@unbrained/pm-cli 2026.8.20 → 2026.8.22

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 (228) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +38 -0
  3. package/dist/cli/error-guidance.d.ts +29 -4
  4. package/dist/cli/error-guidance.js +43 -43
  5. package/dist/cli/main.d.ts +3 -0
  6. package/dist/cli/main.js +40 -7
  7. package/dist/cli-bundle/bundle-manifest.json +150 -150
  8. package/dist/cli-bundle/chunks/{chunk-L4LGPBJU.js → chunk-BWX4SK46.js} +58 -58
  9. package/dist/cli-bundle/chunks/chunk-EMWDM5FI.js +13 -0
  10. package/dist/cli-bundle/chunks/chunk-HYG6LRL4.js +200 -0
  11. package/dist/cli-bundle/chunks/{chunk-TSMWLCHS.js → chunk-MYYI3ZOA.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-4GB2LTOQ.js → chunk-MZTZQTMS.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-7BRF2BX2.js → chunk-QI2CT3IX.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-SMWXHMVB.js +35 -0
  15. package/dist/cli-bundle/chunks/{chunk-US2ZQW2M.js → chunk-U6GQ4VMV.js} +47 -47
  16. package/dist/cli-bundle/chunks/{chunk-K3EN3LK2.js → chunk-VMMIL3SI.js} +2 -2
  17. package/dist/cli-bundle/chunks/chunk-WG4STC36.js +5 -0
  18. package/dist/cli-bundle/chunks/{chunk-XYDDWBZN.js → chunk-YBPJAOQQ.js} +3 -3
  19. package/dist/cli-bundle/chunks/{register-list-query-JSAQCVOC.js → register-list-query-HZKBQNWW.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-mutation-XJPAW63D.js → register-mutation-HTKEEGRD.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-operations-DSOSB2XQ.js → register-operations-6EMRWJJY.js} +2 -2
  22. package/dist/cli-bundle/chunks/{register-setup-QUR6QL2C.js → register-setup-QK4OTOXN.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-TDR5OGG3.js → chunk-2ARQGDDW.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-AZBACT5T.js → chunk-2AZT5WXZ.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-M32HFIQB.js → chunk-2POVTNLY.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/chunk-3LKU6PTJ.js +4 -0
  27. package/dist/cli-bundle/focused-chunks/chunk-5SHSBMX2.js +2 -0
  28. package/dist/cli-bundle/focused-chunks/{chunk-UGSS4F5X.js → chunk-6S2MO3Q3.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-5L7M4AI7.js → chunk-A2BC5PQL.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/chunk-C4S4A4JJ.js +5 -0
  31. package/dist/cli-bundle/focused-chunks/{chunk-OM65KHGF.js → chunk-D6RBZEJJ.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/chunk-E2EWYPY6.js +16 -0
  33. package/dist/cli-bundle/focused-chunks/{chunk-G3C5ERXG.js → chunk-GMYPD4FX.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/chunk-L5LDSRO2.js +155 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-BLJCGGID.js → chunk-MB37AYN6.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/chunk-MCOR37QK.js +2 -0
  37. package/dist/cli-bundle/focused-chunks/{chunk-FUREQLQN.js → chunk-PH2OXXVZ.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-325UXIO7.js → chunk-PMGJUFNQ.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/chunk-R6SR45XU.js +50 -0
  40. package/dist/cli-bundle/focused-chunks/chunk-WZE4LIPW.js +8 -0
  41. package/dist/cli-bundle/main.js +13 -13
  42. package/dist/cli-bundle/sdk-authoring.js +1 -1
  43. package/dist/cli-bundle/sdk-contracts.js +2 -2
  44. package/dist/cli-bundle/sdk-core.js +40 -40
  45. package/dist/cli-bundle/sdk-governance.js +1 -1
  46. package/dist/cli-bundle/sdk-graph.js +1 -1
  47. package/dist/cli-bundle/sdk-merge.js +32 -32
  48. package/dist/cli-bundle/sdk-query.js +1 -1
  49. package/dist/cli-bundle/sdk-runtime.js +1 -1
  50. package/dist/cli-bundle/sdk-testing.js +1 -1
  51. package/dist/cli-bundle/sdk.js +5 -5
  52. package/dist/core/extensions/extension-hook-runtime.js +22 -20
  53. package/dist/core/extensions/extension-types.d.ts +8 -1
  54. package/dist/core/extensions/extension-types.js +2 -2
  55. package/dist/core/extensions/loader.js +7 -3
  56. package/dist/core/extensions/service-ownership.d.ts +8 -0
  57. package/dist/core/extensions/service-ownership.js +20 -0
  58. package/dist/core/item/id.js +20 -5
  59. package/dist/core/item/item-format.js +27 -2
  60. package/dist/core/shared/errors.d.ts +20 -0
  61. package/dist/core/shared/errors.js +2 -2
  62. package/dist/core/store/item-store.js +6 -91
  63. package/dist/core/store/tracker-preflight.d.ts +7 -0
  64. package/dist/core/store/tracker-preflight.js +142 -0
  65. package/dist/sdk/agent/refusal-reachability.d.ts +1 -1
  66. package/dist/sdk/agent/tracker-preflight-contracts.d.ts +63 -0
  67. package/dist/sdk/agent/tracker-preflight-contracts.js +127 -0
  68. package/dist/sdk/annotations.js +6 -7
  69. package/dist/sdk/authoring.d.ts +1 -1
  70. package/dist/sdk/authoring.js +2 -2
  71. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +77 -0
  72. package/dist/sdk/cli-contracts/agent-output-contracts.js +324 -2
  73. package/dist/sdk/cli-contracts/commander-mutation-options.js +3 -3
  74. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +3 -1
  75. package/dist/sdk/cli-contracts/runtime-contracts.js +4 -3
  76. package/dist/sdk/cli-contracts.d.ts +1 -1
  77. package/dist/sdk/cli-contracts.js +3 -3
  78. package/dist/sdk/config.d.ts +5 -0
  79. package/dist/sdk/config.js +5 -5
  80. package/dist/sdk/context-intent-runtime.js +7 -4
  81. package/dist/sdk/contracts.d.ts +1 -0
  82. package/dist/sdk/contracts.js +3 -2
  83. package/dist/sdk/dependencies.js +5 -7
  84. package/dist/sdk/dependency-flag-validation.d.ts +1 -1
  85. package/dist/sdk/dependency-flag-validation.js +10 -4
  86. package/dist/sdk/environment/tracker-preflight.d.ts +6 -0
  87. package/dist/sdk/environment/tracker-preflight.js +10 -0
  88. package/dist/sdk/eval.js +5 -7
  89. package/dist/sdk/extension/install-sources.d.ts +1 -1
  90. package/dist/sdk/extension/install-sources.js +6 -3
  91. package/dist/sdk/extension/output-ownership.d.ts +1 -0
  92. package/dist/sdk/extension/output-ownership.js +3 -2
  93. package/dist/sdk/files.js +6 -10
  94. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +75 -15
  95. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +81 -8
  96. package/dist/sdk/governance/assurance.d.ts +36 -2
  97. package/dist/sdk/governance/assurance.js +184 -10
  98. package/dist/sdk/governance/gc.js +5 -6
  99. package/dist/sdk/governance/health.d.ts +3 -0
  100. package/dist/sdk/governance/health.js +42 -11
  101. package/dist/sdk/governance/hierarchy-validation.d.ts +29 -0
  102. package/dist/sdk/governance/hierarchy-validation.js +109 -0
  103. package/dist/sdk/governance/reindex.js +5 -6
  104. package/dist/sdk/governance/validate.d.ts +2 -9
  105. package/dist/sdk/governance/validate.js +51 -109
  106. package/dist/sdk/graph/assembly.d.ts +6 -1
  107. package/dist/sdk/graph/assembly.js +16 -22
  108. package/dist/sdk/graph/governance-contracts.d.ts +1 -1
  109. package/dist/sdk/graph/governance-contracts.js +8 -2
  110. package/dist/sdk/graph/governance.d.ts +7 -5
  111. package/dist/sdk/graph/governance.js +76 -16
  112. package/dist/sdk/graph/hierarchy-integrity.d.ts +94 -0
  113. package/dist/sdk/graph/hierarchy-integrity.js +311 -0
  114. package/dist/sdk/graph/index.d.ts +2 -1
  115. package/dist/sdk/graph/index.js +3 -2
  116. package/dist/sdk/graph/remediation.js +32 -2
  117. package/dist/sdk/graph/run.d.ts +31 -2
  118. package/dist/sdk/graph/run.js +83 -36
  119. package/dist/sdk/graph/traversal.js +14 -5
  120. package/dist/sdk/graph/workspace-relationship-kind-registry.d.ts +8 -0
  121. package/dist/sdk/graph/workspace-relationship-kind-registry.js +28 -0
  122. package/dist/sdk/history-compact.js +6 -9
  123. package/dist/sdk/history-read.js +5 -7
  124. package/dist/sdk/history-redact.js +5 -6
  125. package/dist/sdk/history-repair.js +6 -9
  126. package/dist/sdk/improvement-ledger.js +7 -10
  127. package/dist/sdk/index.d.ts +4 -2
  128. package/dist/sdk/index.js +5 -3
  129. package/dist/sdk/item-children.js +21 -8
  130. package/dist/sdk/lifecycle/append.d.ts +0 -5
  131. package/dist/sdk/lifecycle/append.js +5 -6
  132. package/dist/sdk/lifecycle/claim.d.ts +0 -5
  133. package/dist/sdk/lifecycle/claim.js +6 -9
  134. package/dist/sdk/lifecycle/close-many.d.ts +0 -5
  135. package/dist/sdk/lifecycle/close-many.js +5 -6
  136. package/dist/sdk/lifecycle/close.d.ts +0 -5
  137. package/dist/sdk/lifecycle/close.js +5 -6
  138. package/dist/sdk/lifecycle/copy.d.ts +0 -5
  139. package/dist/sdk/lifecycle/copy.js +5 -6
  140. package/dist/sdk/lifecycle/create.d.ts +0 -5
  141. package/dist/sdk/lifecycle/create.js +127 -102
  142. package/dist/sdk/lifecycle/delete.js +5 -6
  143. package/dist/sdk/lifecycle/focus.d.ts +0 -5
  144. package/dist/sdk/lifecycle/focus.js +5 -6
  145. package/dist/sdk/lifecycle/hierarchy-mutation-lock.d.ts +15 -0
  146. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +25 -0
  147. package/dist/sdk/lifecycle/plan.d.ts +0 -5
  148. package/dist/sdk/lifecycle/plan.js +5 -6
  149. package/dist/sdk/lifecycle/restore.js +5 -6
  150. package/dist/sdk/lifecycle/update-many.d.ts +0 -5
  151. package/dist/sdk/lifecycle/update-many.js +5 -6
  152. package/dist/sdk/lifecycle/update.d.ts +2 -5
  153. package/dist/sdk/lifecycle/update.js +211 -84
  154. package/dist/sdk/linked-artifacts.js +6 -7
  155. package/dist/sdk/merge/install.js +5 -6
  156. package/dist/sdk/mutation-events.js +5 -7
  157. package/dist/sdk/package-import-adapters.js +6 -8
  158. package/dist/sdk/profile.js +6 -7
  159. package/dist/sdk/query/activity.js +5 -6
  160. package/dist/sdk/query/calendar.js +5 -6
  161. package/dist/sdk/query/complete-list.d.ts +3 -3
  162. package/dist/sdk/query/complete-list.js +46 -3
  163. package/dist/sdk/query/get.d.ts +0 -5
  164. package/dist/sdk/query/get.js +5 -6
  165. package/dist/sdk/query/history.d.ts +0 -5
  166. package/dist/sdk/query/history.js +5 -6
  167. package/dist/sdk/query/list.d.ts +4 -3
  168. package/dist/sdk/query/list.js +92 -54
  169. package/dist/sdk/query/search.js +5 -7
  170. package/dist/sdk/read-output-contracts.d.ts +5 -1
  171. package/dist/sdk/read-output-contracts.js +87 -22
  172. package/dist/sdk/relationship-context.js +3 -4
  173. package/dist/sdk/relationship-kinds/contract.d.ts +8 -0
  174. package/dist/sdk/relationship-kinds/contract.js +13 -13
  175. package/dist/sdk/relationships.d.ts +1 -1
  176. package/dist/sdk/relationships.js +27 -2
  177. package/dist/sdk/runtime.d.ts +3 -2
  178. package/dist/sdk/runtime.js +3 -2
  179. package/dist/sdk/schema-migration.js +6 -7
  180. package/dist/sdk/schema.js +5 -6
  181. package/dist/sdk/stats.js +5 -8
  182. package/dist/sdk/templates.js +5 -6
  183. package/dist/sdk/test/batch.js +15 -9
  184. package/dist/sdk/test/execution.js +12 -5
  185. package/dist/sdk/test/runs.js +5 -7
  186. package/dist/types.d.ts +11 -0
  187. package/dist/types.js +2 -2
  188. package/docs/AGENT_UX_CONTRACTS.md +24 -1
  189. package/docs/COMMANDS.md +29 -14
  190. package/docs/DEPENDENCY_KIND_CONTRACT.md +40 -1
  191. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +98 -0
  192. package/docs/EXTENSIONS.md +2 -1
  193. package/docs/README.md +1 -0
  194. package/docs/READ_OUTPUT_CONTRACTS.md +9 -2
  195. package/docs/RECURRENCE_RECOVERY_CONTRACTS.md +37 -0
  196. package/docs/RELATIONSHIP_GRAPH.md +97 -12
  197. package/docs/SDK_PRIMITIVE_INVENTORY.md +15 -1
  198. package/docs/TESTING.md +15 -0
  199. package/marketplace.json +2 -2
  200. package/package.json +1 -1
  201. package/packages/pm-beads/package.json +1 -1
  202. package/packages/pm-calendar/package.json +1 -1
  203. package/packages/pm-command-kit/package.json +1 -1
  204. package/packages/pm-digital-twin/package.json +1 -1
  205. package/packages/pm-governance-audit/package.json +1 -1
  206. package/packages/pm-guide-shell/package.json +1 -1
  207. package/packages/pm-kanban/package.json +1 -1
  208. package/packages/pm-lifecycle-hooks/package.json +1 -1
  209. package/packages/pm-linked-test-adapters/package.json +1 -1
  210. package/packages/pm-search-advanced/package.json +1 -1
  211. package/packages/pm-templates/package.json +1 -1
  212. package/packages/pm-todos/package.json +1 -1
  213. package/packages/pm-vcs/package.json +1 -1
  214. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  215. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  216. package/sdk/public-surface.json +848 -56
  217. package/dist/cli-bundle/chunks/chunk-2RDVGYWE.js +0 -13
  218. package/dist/cli-bundle/chunks/chunk-BLVQHFSY.js +0 -35
  219. package/dist/cli-bundle/chunks/chunk-CU25EQVV.js +0 -5
  220. package/dist/cli-bundle/chunks/chunk-RS3IV2R6.js +0 -197
  221. package/dist/cli-bundle/focused-chunks/chunk-6AHG2YW7.js +0 -50
  222. package/dist/cli-bundle/focused-chunks/chunk-GXWQBE3T.js +0 -8
  223. package/dist/cli-bundle/focused-chunks/chunk-JWKEDZJI.js +0 -4
  224. package/dist/cli-bundle/focused-chunks/chunk-KYZ6JGPL.js +0 -155
  225. package/dist/cli-bundle/focused-chunks/chunk-Q47EX4DI.js +0 -2
  226. package/dist/cli-bundle/focused-chunks/chunk-RIHDMCUM.js +0 -2
  227. package/dist/cli-bundle/focused-chunks/chunk-T4ZFY7ZJ.js +0 -16
  228. package/dist/cli-bundle/focused-chunks/chunk-Z3PLWSGM.js +0 -2
@@ -1,55 +1,55 @@
1
- import{n as ym,o as ps,p as Sm,q as Em,r as Mi,s as hs,t as Tm,u as Di,v as gs,y as jm,z as qm}from"./focused-chunks/chunk-BLJCGGID.js";import{a as Hm,f as Vm,h as qt,m as Xm,o as Qm,r as Zm,s as eu,w as tu}from"./focused-chunks/chunk-Z3PLWSGM.js";import{$ as _a,$a as Vp,Aa as Rp,Ba as Ip,Bb as Xp,Ca as xp,Cb as nf,Da as Op,Db as rf,Ea as Cn,Fa as Pp,G as rp,Ga as Np,I as w,Ia as er,J as sp,Ja as Lp,K as op,Ka as Fp,L as Fe,La as $p,M as ip,Ma as Mp,N as da,Na as Dp,O as ap,Oa as Up,P as la,Q as Vs,R as ma,Ra as Gp,S as Ht,Sa as Ys,T as ua,Ta as Tw,U as ye,Ua as jp,V as pa,Va as qp,W as $e,Wa as ha,X as cp,Xa as Kp,Y as dp,Ya as zp,Z as fa,Za as Bp,_ as lp,_a as Hp,a as Hi,ab as Wp,b as Uu,bb as tr,cb as ga,db as ya,eb as Js,fb as ba,gb as Yp,ha as mp,hb as wa,i as Qu,ib as Xs,j as Zu,ja as Ws,jb as Rn,ka as up,kb as va,la as pp,lb as ka,ma as fp,mb as Jp,na as _p,oa as hp,pa as gp,pb as Qs,qa as yp,ra as bp,sa as wp,ta as vp,ua as kp,va as Sp,wa as Ep,xa as Tp,ya as Ap,za as Cp}from"./focused-chunks/chunk-6AHG2YW7.js";import{e as _m,g as hm,h as gm,k as bm,q as km}from"./focused-chunks/chunk-OM65KHGF.js";import{b as Km,c as ys,e as zm,f as Bm,g as uw}from"./focused-chunks/chunk-325UXIO7.js";import{H as Bi,L as Gm,a as ol,b as il,c as al,d as cl,f as dl}from"./focused-chunks/chunk-AZBACT5T.js";import{a as $u,b as Mu,c as to}from"./focused-chunks/chunk-GXWQBE3T.js";import{Z as np,b as Du,e as ep,f as Qn,g as Zn,i as ca,t as tp}from"./focused-chunks/chunk-RIHDMCUM.js";import{Ba as Aw,Ca as Ea,D as Zs,Da as Ta,E as Zp,Ea as eo,F as rr,Fa as Cw,G as ef,Ga as Rw,O as It,Q as Sa,Ya as Aa,bb as sr,c as ra,db as tf,e as sa,g as Pu,h as xs,hb as Ca,i as oa,j as Nu,k as Os,l as Ps,m as Ns,n as Lu,o as Fu,s as Hu,t as Vu,u as Wu,v as Yu,w as Ju,wb as or,x as Xu,xb as Ra,y as nr}from"./focused-chunks/chunk-T4ZFY7ZJ.js";import{a as nu,b as ru,c as su}from"./focused-chunks/chunk-5L7M4AI7.js";import{A as ia,B as Hs,Ca as Bu,D as ju,E as qu,Ea as no,F as Xn,Ia as In,a as Ls,b as Fs,c as $s,d as Ms,h as Ds,j as Us,k as Gs,l as Gu,m as js,n as qs,o as Rt,p as kn,q as Ks,r as Sn,s as zs,t as ne,u as Bs,v as Ke,va as An,w as Le,wa as Ku,x as ie,xa as aa,y as En,ya as zu,z as Tn}from"./focused-chunks/chunk-FUREQLQN.js";import{c as um,f as pm,g as fm,i as us,j as kt,k as Am,l as Cm,m as Rm}from"./focused-chunks/chunk-M32HFIQB.js";import{$ as Dl,A as qr,Aa as om,B as yl,Ba as Qr,C as bl,Ca as im,D as wl,Da as am,E as Kr,Ea as cm,F as vl,Fa as Zr,G as kl,Ga as es,H as Sl,Ha as ts,I as zr,Ia as ns,J as Br,Ja as Hn,K as El,Ka as rs,L as Hr,La as dm,Ma as Vn,N as Tl,Na as ss,O as Bn,Oa as os,P as Al,Pa as is,Q as Cl,Qa as as,R as Rl,Ra as lm,S as Il,Sa as vt,T as xl,Ta as cs,U as Ol,Ua as ds,V as Pl,Va as ls,W as Nl,Wa as ms,X as Ll,Y as Fl,Z as $l,Za as mm,_ as Ml,aa as Ul,ab as F,ba as Gl,ca as jl,d as Li,da as ql,e as ll,ea as Kl,fa as Vr,ga as Wr,h as ml,ha as zl,i as Fi,ia as Bl,j as jt,ja as Hl,ka as Vl,l as ul,la as Wl,ma as Yl,na as Jl,oa as Xl,q as $i,qa as Ql,ra as Zl,s as Ur,sa as em,t as Gr,ta as tm,u as jr,ua as nm,v as pl,va as rm,w as fl,wa as Yr,x as _l,xa as Jr,y as hl,ya as Xr,z as gl,za as sm}from"./focused-chunks/chunk-TDR5OGG3.js";import{c as Qp}from"./focused-chunks/chunk-G3C5ERXG.js";import{$a as Cu,Ab as Ou,Bb as Te,Da as qe,Ea as Tt,F as ks,G as au,Ga as As,H as cu,Ha as Ne,I as hn,Ia as zt,J as Yn,Ja as wu,K as gw,Ka as Bt,L as yw,La as vu,M as bw,N as ww,Na as ku,O as vw,Oa as bn,P as Ss,Pa as Su,Q as kw,Qa as Cs,R as Sw,Ra as st,S as Ew,T as gn,U as R,V as S,Wa as Eu,X as yn,Xa as Tu,Ya as At,Z as Q,_ as Pe,_a as Au,a as ou,ab as A,ba as du,bb as Ee,c as iu,ca as Es,cb as Ru,da as lu,db as Iu,e as Vi,ea as mu,eb as Ct,f as Wi,fa as uu,fb as na,g as Yi,ga as pu,gb as ge,h as Ji,ha as fu,hb as Jn,i as Xi,j as Qi,ja as W,k as Zi,l as I,la as se,m as fn,ma as Ts,n as Kt,na as ea,nb as wn,o as z,oa as _u,p as ws,pa as je,pb as vn,q as _n,qa as We,ra as Et,rb as D,sa as hu,sb as K,t as vs,ta as gu,ua as ta,ub as oe,v as Ge,vb as Rs,w as pw,wa as yu,wb as Is,x as fw,xa as bu,xb as ot,y as _w,yb as xu,z as hw,zb as Z}from"./focused-chunks/chunk-KYZ6JGPL.js";import{$ as Hd,B as Pi,C as Kn,D as he,G as x,Ga as Mr,H as pe,Ha as sl,I as Lr,Ia as Dr,J as mn,K as zn,L as zd,La as nt,M as T,N as Bd,Na as fs,O as et,Oa as rt,P as C,Pa as St,Q as Gt,Qa as wm,S as Se,Sa as M,T as Fr,Ta as _s,Ua as Ve,Wa as vm,Z as un,ba as Ni,ca as Vd,ea as Wd,ga as $r,h as bt,i as Pr,ia as Yd,j as Nr,ja as Jd,la as Xd,ma as Qd,na as Zd,oa as el,pa as tl,q as k,qa as nl,r as Ut,ra as rl,s as wt,t as q,u as ue,w as ln}from"./focused-chunks/chunk-JWKEDZJI.js";import{b as bs,h as Wm,i as Ym,l as pn,p as Jm}from"./focused-chunks/chunk-UGSS4F5X.js";import{A as Ud,B as Gd,C as jd,D as qd,Da as Qb,E as Ti,Ea as Zb,F as Ai,Fa as ew,G as Ci,Ga as tw,H as Ri,Ha as Dm,I as Ii,J as xi,L as Or,Na as qi,Pa as nw,Qa as rw,R as Oi,T as Kd,W as yt,Y as d,Z as l,_a as sw,aa as J,ab as ow,ba as tt,bb as iw,cb as Ki,db as aw,ea as Wn,eb as zi,hb as Um,ia as Im,ib as cw,ja as xm,ka as Om,kb as dw,l as Rr,la as Pm,lb as lw,m as $d,ma as Nm,mb as mw,n as Ir,na as Lm,o as Ei,oa as Ui,pa as Fm,qa as $m,s as Dt,t as Ze,ta as Gi,u as cn,ua as Mm,v as dn,va as ji,w as xr,y as Md,z as Dd}from"./focused-chunks/chunk-Q47EX4DI.js";import{AsyncLocalStorage as eF}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27dd77f6-e53d-55b7-be15-db0e60eaec4e")}catch{}})();function sf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Iw(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function Ia(e,t){let n=Iw(t),r=n==="brief"?n:sf(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:sf(e.filters)?e.filters:{},projection:r}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ede8efb-54ec-5b13-a1bf-216b525acc12")}catch{}})();async function of(e,t){let n=T(t??process.cwd(),e),r=await A(n);return oe(n,r.item_format,x(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9eae1a3-3eb6-5415-86c3-a8e8e1fedd1f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c898a52-eba4-5626-8207-5ffefd4990ba")}catch{}})();var xw=new Map;function xa(){xw.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f62939a-7b99-5687-93ae-834e0032f1d5")}catch{}})();var Ow={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function af(e){return Object.fromEntries($m.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var cf={ctx:{action:"context"},...Ow,...af("extension"),...af("package")};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="41012e87-ed61-56b2-8505-8f786b3952b2")}catch{}})();var Oa="PmCliError";function Pw(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=d.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function df(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new l(e,Pw(t.exitCode??d.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function ro(e){if(!(e instanceof Error)||e.name!==Oa)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ff13ec2a-64a8-5512-973f-5447be945978")}catch{}})();function Pa(e){let t=Wd();for(let n of e)t.register(n);return t}function lf(e,t){return{client:t,isItemNotFoundError:n=>ro(n)&&n.exitCode===d.NOT_FOUND,getItemAt:(n,r)=>Fu(n,r,{pmRoot:e}),openRelationshipEventStore:n=>Mu.open({pmRoot:e,nodes:n.nodes,registry:Pa(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new Jd(n.nodes,n.edges,Pa(n.definitions)),analyzeRelationshipImpact:(n,r,s)=>Du(n,r,s),validateRelationshipEvents:n=>{let r=new $u(n.nodes,{registry:Pa(n.definitions)});return n.events.map(s=>r.append({...s,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>Uu({...n,pmRoot:e})}}import{readFile as Nw}from"node:fs/promises";import Lw from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ba0243e-98d1-5aef-bd47-54f0b630be58")}catch{}})();var Na="context-intents.json";function so(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fw(e,t,n){if(!so(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(s=>typeof s=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function mf(e,t){let n=Array.isArray(e)?e:so(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,s)=>Fw(r,t,s))}async function $w(e){let t=Lw.join(e,Na),n;try{n=await Nw(t,"utf8")}catch(s){if(Ut(s))return[];throw s}let r;try{r=JSON.parse(n)}catch(s){let o=s instanceof Error?s.message:String(s);throw new TypeError(`Invalid ${Na}: ${o}`,{cause:s})}return mf(r,Na)}function Mw(e){if(!so(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return so(n)?n.contextIntents??n.context_intents:void 0}function Dw(e){return e.flatMap(t=>{let n=Mw(t.module);return n===void 0?[]:mf(n,`package ${t.name}`)})}async function Uw(e){let t=await $w(e.pmRoot),n=Dw(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function La(e,t){let n=await Uw(e);return await Ym(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e3ba7e9-8822-53ba-981e-e177be5219f3")}catch{}})();async function uf(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=Le(),s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=R(t.author,o.author_default),c=(await r.resolveValue(t.body,"--body")).trim();if(c.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",d.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let m=await Z({pmRoot:s,settings:o,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
1
+ import{n as Tm,o as ys,p as Om,q as Pm,r as Hi,s as vs,t as Nm,u as Vi,v as ks,y as Jm,z as Xm}from"./focused-chunks/chunk-MB37AYN6.js";import{a as tu,f as nu,h as Bt,m as iu,o as au,r as cu,s as du,w as lu}from"./focused-chunks/chunk-5SHSBMX2.js";import{$ as Sa,$a as rf,Aa as Dp,Ba as Up,Bb as cf,Ca as Gp,Cb as pf,Da as jp,Db as ff,Ea as xn,Fa as qp,G as pp,Ga as Kp,I as w,Ia as rr,J as fp,Ja as zp,K as _p,Ka as Bp,L as Me,La as Hp,M as hp,Ma as Vp,N as ga,Na as Wp,O as gp,Oa as Yp,P as ya,Q as Zs,R as ba,Ra as Jp,S as Yt,Sa as to,T as wa,Ta as Nw,U as we,Ua as Xp,V as va,Va as Qp,W as $e,Wa as Ea,X as yp,Xa as Zp,Y as bp,Ya as ef,Z as ka,Za as tf,_ as wp,_a as nf,a as ta,ab as sf,b as Yu,bb as sr,cb as Aa,db as Ta,eb as no,fb as Ca,gb as of,ha as vp,hb as Ra,i as cp,ib as ro,j as dp,ja as eo,jb as On,ka as kp,kb as Ia,la as Sp,lb as xa,ma as Ep,mb as af,na as Ap,oa as Tp,pa as Cp,pb as so,qa as Rp,ra as Ip,sa as xp,ta as Op,ua as Pp,va as Np,wa as Lp,xa as Fp,ya as Mp,za as $p}from"./focused-chunks/chunk-R6SR45XU.js";import{e as Sm,g as Em,h as Am,k as Cm,q as xm}from"./focused-chunks/chunk-D6RBZEJJ.js";import{b as Qm,c as Ss,e as Zm,f as eu,g as ww}from"./focused-chunks/chunk-PMGJUFNQ.js";import{H as ea,L as Ym,a as pl,b as fl,c as _l,d as hl,f as gl}from"./focused-chunks/chunk-2AZT5WXZ.js";import{a as Hu,b as Vu,c as ao}from"./focused-chunks/chunk-WZE4LIPW.js";import{P as up,b as Wu,j as mp}from"./focused-chunks/chunk-MCOR37QK.js";import{Ba as Lw,Ca as Pa,D as oo,Da as Na,E as lf,Ea as io,F as ir,Fa as Fw,G as mf,Ga as Mw,O as Pt,Q as Oa,Ya as La,bb as ar,c as ua,db as uf,e as pa,g as qu,h as Fs,hb as Fa,i as fa,j as Ku,k as Ms,l as $s,m as Ds,n as zu,o as Bu,s as np,t as rp,u as sp,v as op,w as ip,wb as cr,x as ap,xb as Ma,y as or}from"./focused-chunks/chunk-E2EWYPY6.js";import{a as mu,b as uu,c as pu}from"./focused-chunks/chunk-A2BC5PQL.js";import{A as _a,B as Xs,Ca as tp,D as Xu,E as Qu,Ea as co,F as er,Ia as Pn,a as Us,b as Gs,c as js,d as qs,h as Ks,j as zs,k as Bs,l as Ju,m as Hs,n as Vs,o as xt,p as An,q as Ws,r as Tn,s as Ys,t as se,u as Js,v as ze,va as In,w as Fe,wa as Zu,x as ce,xa as ha,y as Cn,ya as ep,z as Rn}from"./focused-chunks/chunk-PH2OXXVZ.js";import{c as wm,f as vm,g as km,i as gs,j as Et,k as Lm,l as Fm,m as Mm}from"./focused-chunks/chunk-2POVTNLY.js";import{$ as Hl,A as Vr,Aa as pm,B as Tl,Ba as rs,C as Cl,Ca as fm,D as Rl,Da as _m,E as Wr,Ea as hm,F as Il,Fa as ss,G as xl,Ga as os,H as Ol,Ha as is,I as Yr,Ia as as,J as Jr,Ja as Yn,K as Pl,Ka as cs,L as Xr,La as gm,Ma as Jn,N as Nl,Na as ds,O as Wn,Oa as ls,P as Ll,Pa as ms,Q as Fl,Qa as us,R as Ml,Ra as ym,S as $l,Sa as St,T as Dl,Ta as ps,U as Ul,Ua as fs,V as Gl,Va as _s,W as jl,Wa as hs,X as ql,Y as Kl,Z as zl,Za as bm,_ as Bl,aa as Vl,ab as M,ba as Wl,ca as Yl,d as Ki,da as Jl,e as yl,ea as Xl,fa as Qr,ga as Zr,h as bl,ha as Ql,i as zi,ia as Zl,j as zt,ja as em,ka as tm,l as wl,la as nm,ma as rm,na as sm,oa as om,q as Bi,qa as im,ra as am,s as zr,sa as cm,t as Br,ta as dm,u as Hr,ua as lm,v as vl,va as mm,w as kl,wa as es,x as Sl,xa as ts,y as El,ya as ns,z as Al,za as um}from"./focused-chunks/chunk-2ARQGDDW.js";import{c as df}from"./focused-chunks/chunk-GMYPD4FX.js";import{$a as Mu,Ab as Gu,Bb as ne,Cb as ju,Da as Ke,Db as Re,Ea as Ct,Eb as lp,F as Cs,Fb as tr,G as hu,Ga as Os,Gb as nr,H as gu,Ha as Le,Hb as Ot,I as bn,Ia as Vt,J as Qn,Ja as Iu,K as Aw,Ka as Wt,L as Tw,La as xu,M as Cw,Mb as Qs,N as Rw,Na as Ou,O as Iw,Oa as kn,P as Rs,Pa as Pu,Q as xw,Qa as Ps,R as Ow,Ra as it,S as Pw,T as wn,U as T,V as k,Wa as Nu,X as vn,Xa as Lu,Ya as Rt,Z as te,_ as ye,_a as Fu,a as fu,ab as A,ba as yu,bb as Ce,c as _u,ca as Is,cb as $u,da as bu,db as Du,e as na,ea as wu,eb as It,f as ra,fa as vu,fb as ma,g as sa,ga as ku,gb as be,h as oa,ha as Su,hb as Zn,i as ia,j as aa,ja as Y,k as ca,l as R,la as Z,m as gn,ma as xs,n as Ht,na as da,nb as Sn,o as z,oa as Eu,p as As,pa as qe,pb as En,q as yn,qa as Je,ra as Tt,rb as Uu,sa as Au,sb as C,t as Ts,ta as Tu,tb as D,ua as la,ub as K,v as je,w as vw,wa as Cu,wb as ae,x as kw,xa as Ru,xb as Ns,y as Sw,yb as Ls,z as Ew,zb as at}from"./focused-chunks/chunk-L5LDSRO2.js";import{$ as el,B as ji,C as Hn,D as he,G as I,Ga as qr,H as fe,Ha as ul,I as Ur,Ia as Kr,J as fn,K as Vn,L as Qd,La as st,M as E,N as Zd,Na as bs,O as nt,Oa as ot,P as ge,Pa as At,Q as Kt,Qa as Rm,S as Te,Sa as $,T as Gr,Ta as ws,Ua as Ye,Wa as Im,Z as _n,ba as qi,ca as tl,ea as nl,ga as jr,h as vt,i as $r,ia as rl,j as Dr,ja as sl,la as ol,ma as il,na as al,oa as cl,pa as dl,q as P,qa as ll,r as qt,ra as ml,s as kt,t as q,u as pe,w as pn}from"./focused-chunks/chunk-3LKU6PTJ.js";import{b as Es,h as ru,i as su,l as hn,p as ou}from"./focused-chunks/chunk-6S2MO3Q3.js";import{A as Vd,B as Wd,C as Yd,D as Jd,Da as iw,E as Li,Ea as aw,F as Fi,Fa as cw,G as Mi,Ga as dw,H as $i,Ha as Hm,I as Di,J as Ui,L as Mr,La as Vm,Qa as Xi,R as Gi,T as Xd,Va as lw,W as wt,Wa as mw,Y as l,Z as m,aa as Q,ba as rt,ea as Xn,eb as uw,gb as pw,hb as fw,ia as $m,ib as Qi,ja as Dm,jb as _w,ka as Um,kb as Zi,l as Nr,la as Gm,m as zd,ma as jm,n as Lr,na as qm,nb as Wm,o as Ni,oa as Wi,ob as hw,pa as Km,qa as zm,qb as gw,rb as yw,s as jt,sb as bw,t as tt,ta as Yi,u as mn,ua as Bm,v as un,va as Ji,w as Fr,y as Bd,z as Hd}from"./focused-chunks/chunk-C4S4A4JJ.js";import{AsyncLocalStorage as uF}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27dd77f6-e53d-55b7-be15-db0e60eaec4e")}catch{}})();function _f(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $w(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function $a(e,t){let n=$w(t),r=n==="brief"?n:_f(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:_f(e.filters)?e.filters:{},projection:r}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ede8efb-54ec-5b13-a1bf-216b525acc12")}catch{}})();async function hf(e,t){let n=E(t??process.cwd(),e),r=await A(n);return ae(n,r.item_format,I(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9eae1a3-3eb6-5415-86c3-a8e8e1fedd1f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c898a52-eba4-5626-8207-5ffefd4990ba")}catch{}})();var Dw=new Map;function Da(){Dw.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f62939a-7b99-5687-93ae-834e0032f1d5")}catch{}})();var Uw={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function gf(e){return Object.fromEntries(zm.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var yf={ctx:{action:"context"},...Uw,...gf("extension"),...gf("package")};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="41012e87-ed61-56b2-8505-8f786b3952b2")}catch{}})();var Ua="PmCliError";function Gw(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=l.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function bf(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new m(e,Gw(t.exitCode??l.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function lo(e){if(!(e instanceof Error)||e.name!==Ua)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ff13ec2a-64a8-5512-973f-5447be945978")}catch{}})();function Ga(e){let t=nl();for(let n of e)t.register(n);return t}function wf(e,t){return{client:t,isItemNotFoundError:n=>lo(n)&&n.exitCode===l.NOT_FOUND,getItemAt:(n,r)=>Bu(n,r,{pmRoot:e}),openRelationshipEventStore:n=>Vu.open({pmRoot:e,nodes:n.nodes,registry:Ga(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new sl(n.nodes,n.edges,Ga(n.definitions)),analyzeRelationshipImpact:(n,r,s)=>Wu(n,r,s),validateRelationshipEvents:n=>{let r=new Hu(n.nodes,{registry:Ga(n.definitions)});return n.events.map(s=>r.append({...s,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>Yu({...n,pmRoot:e})}}import{readFile as jw}from"node:fs/promises";import qw from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a7548f2-93a0-5dfc-9d9a-c5aef4656c7c")}catch{}})();var ja="context-intents.json";function mo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kw(e,t,n){if(!mo(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(s=>typeof s=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function vf(e,t){let n=Array.isArray(e)?e:mo(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,s)=>Kw(r,t,s))}async function zw(e){let t=qw.join(e,ja),n;try{n=await jw(t,"utf8")}catch(s){if(qt(s))return[];throw await Uu(e),s}let r;try{r=JSON.parse(n)}catch(s){let o=s instanceof Error?s.message:String(s);throw new TypeError(`Invalid ${ja}: ${o}`,{cause:s})}return vf(r,ja)}function Bw(e){if(!mo(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return mo(n)?n.contextIntents??n.context_intents:void 0}function Hw(e){return e.flatMap(t=>{let n=Bw(t.module);return n===void 0?[]:vf(n,`package ${t.name}`)})}async function Vw(e){let t=await zw(e.pmRoot),n=Hw(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function qa(e,t){let n=await Vw(e);return await su(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="73184370-6517-533e-90db-536893402616")}catch{}})();async function kf(e,t,n){if(t.body===void 0)throw new m("Missing required --body text",l.USAGE);let r=Fe(),s=E(process.cwd(),n.path);await C(s);let o=await A(s),i=T(t.author,o.author_default),c=(await r.resolveValue(t.body,"--body")).trim();if(c.length===0)throw new m("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",l.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let d=await ne({pmRoot:s,settings:o,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
2
2
 
3
3
  `:"";return u.body=`${u.body.trimEnd()}${p}${c}
4
- `,{changedFields:["body"]}}});return{item:m.item,appended:c,changed_fields:m.changedFields}}import{readFile as Gw}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0af9967c-ca72-563a-9518-2e68da0c0fe0")}catch{}})();function io(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,t}function pf(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,d.USAGE,{code:"structured_event_immutable"})}function Fa(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Vt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function xn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let o=ne(n,"--add");return Object.keys(o).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:o.text?.trim()||n}catch{return n}}function $a(e){return typeof e=="object"&&e!==null&&"code"in e}async function jw(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,d.USAGE);let r=Le();if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add")??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new l("--file path cannot be empty",d.USAGE);try{return{value:await Gw(s,"utf8"),emptyFlag:"--file"}}catch(o){if($a(o)&&Ut(o))throw new l(`--file path not found: ${s}`,d.USAGE);let i=o instanceof Error?o.message:String(o);throw new l(`Failed to read --file path "${s}": ${i}`,d.USAGE)}}async function ao(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",d.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",d.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",d.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",d.USAGE);let n=await jw(e,t);if(e.edit!==void 0){if(!n)throw new l("--edit requires replacement text from --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function ar(e,t){throw e instanceof l&&e.exitCode===d.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function _f(e){return e==="comments"?"--stdin":"--add -"}function qw(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let s=_f(t.collectionKey),o=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new l(`--add value "${r}" looks like an option, not annotation text. Use ${s} to read stdin, or use text=${r} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${s} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${o} ${s}`,`${o} --add text=${r}`]})}function Kw(e,t){if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,d.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${_f(e.collectionKey)}`]})}async function On(e,t,n,r){Kw(r,t);let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=x(o,I()),a=Xn(t.limit);if(r.input.mode==="list"){let _=await D(s,e,o.id_prefix,o.item_format,i.type_to_folder);if(!_)throw new l(`Item ${e} not found`,d.NOT_FOUND);let h=await K(_,{schema:o.schema}),y=Vt(h.document.metadata,r.collectionKey);return oo(_.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=R(t.author,o.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,h;try{h=await Z({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Vt(g.metadata,r.collectionKey),v=ff(r.input.index,b.length,r.collectionKey);return pf(b[v],"deleted"),b.splice(v,1),g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){ar(g,r.conflictGuidance)}let y=Vt(h.item,r.collectionKey);return oo(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";qw(m,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,d.USAGE);if(r.input.mode==="edit"){let _=r.editOp??r.op,h;try{h=await Z({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Vt(g.metadata,r.collectionKey),v=ff(r.input.index,b.length,r.collectionKey),E=b[v];return pf(E,"edited"),b[v]={...E,text:u,edited_at:S()},g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){ar(g,r.conflictGuidance)}let y=Vt(h.item,r.collectionKey);return oo(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:y[r.input.index-1]},t.fullHistory===!0)}let p;try{p=await Z({pmRoot:s,settings:o,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(_){let h=Vt(_.metadata,r.collectionKey),y={created_at:S(),author:c,text:u};return h.push(r.createEntry(y)),_.metadata[r.collectionKey]=h,{changedFields:[r.collectionKey]}}})}catch(_){ar(_,r.conflictGuidance)}let f=Vt(p.item,r.collectionKey);return oo(p.item.id,r.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:f.length,entry:f.at(-1)},t.fullHistory===!0)}function ff(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),s=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,o=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${s} index ${e??"(missing)"} out of range (item has ${o})`,d.USAGE)}return e-1}function oo(e,t,n,r,s,o,i=!1){let a=o===void 0||i?Fa(n,o!==void 0&&i?void 0:r):o.entry===void 0?[]:[o.entry],c=o!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...[s,o!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...o===void 0?{}:{mutation_receipt:{action:o.action,entry_index:o.entryIndex,changed_count:1,full_history_included:!c},omission_receipt:{has_omissions:c,omitted_field_group_count:c?1:0,omitted_field_groups:c?[{name:`${t}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0579277-f123-5f96-8664-dfe05ade1b24")}catch{}})();async function hf(e,t,n){return[...await Et(Se(e,t),t).catch(()=>[])].reverse().find(o=>o.patch.some(i=>i.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f70f1329-4dfb-5625-ae0a-66c858d88f7b")}catch{}})();var gf="no_available_next_item";function yf(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function co(e,t,n,r={}){let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=M(o.schema),a=R(r.author,o.author_default),c=gn(a),m=null,u=!1,p=[],f=await Z({pmRoot:s,settings:o,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,vm(_.metadata.status,i)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&g!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let v=await hf(s,_.metadata.id,y);throw new l(`Item ${_.metadata.id} is already ${v}. Use --force to take over, or --if-available to skip without failing.`,d.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}p.push(`claim_takeover:${m}->${a}`)}return _.metadata.assignee=a,_.metadata.claim_principal=c,{changedFields:["assignee","claim_principal"],warnings:p}}});return u||await Ea({pmRoot:s,settings:o,principal:c,itemId:f.item.id}),{item:f.item,claimed_by:u&&m!==null?m:a,previous_assignee:m,forced:t,...u?{skipped:!0}:{},...p.length>0?{warnings:p}:{}}}async function bf(e,t,n={},r={}){let s=zw(n.maxAttempts),o=await A(T(process.cwd(),t.path)),i={...n,author:R(n.author,o.author_default)},a=await sr({...r,callerAuthor:i.author,limit:String(s)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return Bw(c.slice(0,s),e,t,i)}function zw(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new l("--max-attempts must be an integer from 1 to 100",d.USAGE);return t}async function Bw(e,t,n,r={},s=co){let o=0;for(let a of e){o+=1;try{let c=await s(a.id,t,n,r),m={...c,recommendation:a,attempts:o,available:!0};if(!c.skipped)return m}catch(c){if(!yf(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:R(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:o,warnings:[gf]};let i=o===0;throw new l(i?"No actionable items matched the selection filters":"No actionable item remained available to claim",i?d.NOT_FOUND:d.CONFLICT,{code:gf,why:i?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[i?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function lo(e,t,n,r={}){let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=R(r.author,o.author_default),a=gn(i),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await Z({pmRoot:s,settings:o,id:e,op:"release",author:i,message:r.message,force:t,bypassAssigneeConflict:c,mutate(p){return m=p.metadata.assignee??null,!m&&!p.metadata.claim_principal?{changedFields:[]}:(delete p.metadata.assignee,delete p.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(p){ar(p,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}return await Ta({pmRoot:s,principal:a,itemId:u.item.id}),{item:u.item,released_by:i,previous_assignee:m,forced:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7ae3c89-b50b-5e4f-8273-8318bc976d84")}catch{}})();var Hw=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function wf(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function Ma(e,t){return Da(e,t,{operation:"close"})}function Da(e,t,n){let r=wf(e);if(!t||r.closeReason!==void 0)return r;let s=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",d.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:s,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function Ua(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,s=e.dependencies??[],o=s.filter(m=>m.kind==="blocked_by"),i=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),i&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&o.length>0){let m=s.filter(u=>u.kind!=="blocked_by");m.length>0?e.dependencies=m:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...o.map(m=>m.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[t.orderingEdges==="preserve"?`closed_preserved_predecessors:${e.id}:${c.join(",")}`:`closed_removed_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="83affe54-a56c-5d84-b6b0-9634d4238ff5")}catch{}})();var Vw=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function Ww(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new l(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,d.USAGE)}function Yw(e){let t=[];for(let n of Vw){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function Jw(e,t,n){let r=new Set,s=t;for(;typeof s=="string"&&s.trim().length>0;){let o=s.trim();if(o===n)return!0;if(r.has(o))return!1;r.add(o),s=(await e(o))?.duplicate_of}return!1}function Xw(e){return typeof e!="string"||e.trim().length===0}async function Qw(e,t,n,r){let s=n?.trim();if(!s)return;if(s===r)throw new l("An item cannot be closed as a duplicate of itself.",d.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let o=x(t,I()),i=new Map,a=async m=>{if(i.has(m))return i.get(m)??null;let u=await D(e,m,t.id_prefix,t.item_format,o.type_to_folder);if(!u)return i.set(m,null),null;let{document:p}=await K(u,{schema:t.schema});return i.set(m,p.metadata),p.metadata},c=await a(s);if(!c)throw new l(`Duplicate target "${s}" was not found. Create or locate the canonical item first.`,d.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${s}" --duplicate-of ${s}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await Jw(a,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${s}" points back to "${r}".`,d.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new l(`Duplicate target "${s}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,d.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function Zw(e,t,n){return e.filter(r=>r.parent===t&&!se(r.status,n)).map(r=>r.id).sort((r,s)=>r.localeCompare(s))}function ev(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),s=Qp(e),o=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:s.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(o)).filter(({blockerIds:a})=>a.every(c=>{if(c===o)return!0;let m=r.get(c);return m!==void 0&&se(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function tv(e,t,n,r,s,o){let i=ev(n,r,o),a=[];for(let c of i)try{let m=await Z({pmRoot:e,settings:t,id:c.id,op:"update",author:s,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(h=>{let y=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=o.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let u=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${u}`)}return a}function nv(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:s,key:o}of r){if(typeof s!="string")continue;let i=s.trim();i.length!==0&&(e[o]=i,n.push(o))}return n}function rv(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:s,value:o}of r)Xw(e[s])&&(e[s]=o,n.push(s));return n}function sv(e,t,n,r){let s=[];if(t!=="off"){let o=Yw(e);if(o.length>0){let i=o.map(a=>a.label);if(t==="strict"){let a=o.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(m=>[m,"<value>"])];throw new l(`Cannot close item ${e.id}: missing ${i.join(", ")}. Populate fields or use --validate-close warn.`,d.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:bs(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}s.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new l(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,d.USAGE);s.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return s}return n.length>0&&s.push(`closed_with_active_children:${e.id}:${n.join(",")}`),s}function ov(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function iv(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function av(e,t){if(se(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use --force to close again.`,d.CONFLICT);let n=nv(e,t.options),r=rv(e,t.duplicateOf),s=sv(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let o=t.options.completedAt!==void 0||e.completed_at===void 0;o&&(e.completed_at=t.completedAt);let i=["status","closed_at",...o?["completed_at"]:[],...ov(e,t.closeReason),...n];if(zu(e)&&(e.plan_mode="completed",i.push("plan_mode")),t.duplicateOf!==void 0){i.push("duplicate_of");for(let c of r)i.includes(c)||i.push(c)}i.push(...iv(e));let a=Ua(e,t.lifecyclePolicy);return i.push(...a.changedFields),s.push(...a.warnings),{changedFields:i,...s.length>0?{warnings:s}:{}}}async function vf(e,t,n,r){let s=T(process.cwd(),r.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=M(o.schema),a=R(n.author,o.author_default),c=x(o,I()).type_to_folder,m=await D(s,e,o.id_prefix,o.item_format,c);if(!m)throw await ot(s,e,o.id_prefix,c);let u=await Qw(s,o,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Ma({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=Ww(n.validateClose)??o.governance.close_validation_default,h=await oe(s,o.item_format,c,void 0,o.schema),y=Zw(h,m.id,i),g=new Date().toISOString(),b=n.completedAt===void 0?g:Q(n.completedAt,new Date(g),"completed-at"),v=await Z({pmRoot:s,settings:o,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(E){return av(E.metadata,{pmRoot:s,statusRegistry:i,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:g,completedAt:b,lifecyclePolicy:p})}});return{item:v.item,changed_fields:v.changedFields,warnings:[...v.warnings,...await tv(s,o,h,m.id,a,i)]}}function it(e,t,n,r){return vf(e,t,n,r)}import cv from"fast-json-patch";import Ga from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="353be665-9f67-5d0e-99c9-6bbb7e927e0b")}catch{}})();function dv(e,t){return Pu(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function lv(e){let t=oa(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:We(zt(t))}async function mv(e,t,n,r){let s=await D(e,t,n.id_prefix,n.item_format,r);if(s){let c=Se(e,s.id),m=await Ru({pmRoot:e,settings:n,itemId:s.id,commandLabel:"restore"});return{id:s.id,historyPath:c,located:s,historyPolicyWarnings:m.warnings}}let o=ge(t,n.id_prefix),i=na(t),a=o===i?[o]:[o,i];for(let c of a){let m=Se(e,c);if(await k(m))return{id:c,historyPath:m,located:null,historyPolicyWarnings:[]}}throw new l(`Item ${t} not found`,d.NOT_FOUND)}function uv(e,t){let n=Bt(e),r=Bt(t),s=cv.compare(n,r),o=new Set;for(let i of s){if(i.path==="/body"||i.path.startsWith("/body/")){o.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];o.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(o).sort((i,a)=>i.localeCompare(a))}async function pv(e){if(await q(e.subject.historyPath)!==e.historyRawBeforeLock)throw new l(`History for ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);let n=await D(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),r=n?await K(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==e.currentItemRawBeforeLock)throw new l(`Item ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);return{loadedItemUnderLock:r,existingItemPath:n?.itemPath??null}}function fv(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:lv(t),originalRaw:null}}function _v(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new l(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,d.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function hv(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await ue(e.existingItemPath,e.resolvedOriginalRaw),await Ga.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await ue(e.existingItemPath,e.resolvedOriginalRaw);return}await Ga.rm(e.restoredItemPath,{force:!0})}async function gv(e){return[...await z({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await z({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function Wt(e,t,n,r){let s=T(process.cwd(),r.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=x(o,I()),a=await mv(s,e,o,i.type_to_folder),c=a.id,m=await q(a.historyPath),u=await Et(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let p=dv(t,u),f=Nu(oa(u,p.historyIndex),p),_=wu(f,{schema:o.schema});if(_.metadata.id!==c)throw new l(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let y=(a.located?await K(a.located,{schema:o.schema}):null)?.raw??null,g=R(n.author,o.author_default),b=await Pe(s,c,o.locks.ttl_seconds,g,!!n.force,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let{loadedItemUnderLock:v,existingItemPath:E}=await pv({pmRoot:s,resolvedId:c,subject:a,settings:o,typeToFolder:i.type_to_folder,historyRawBeforeLock:m,currentItemRawBeforeLock:y}),N="toon",O=fv(v,u),j=_v({document:O.document,author:g,force:n.force,enforcement:o.governance.ownership_enforcement,resolvedId:c}),$=uv(O.document,_);await ws({pm_root:s,operation:"restore",before:O.document,after:_,changed_fields:$,sdk:Is({pmRoot:s,settings:o,typeToFolder:i.type_to_folder})});let xe=je(_,{format:N,schema:o.schema}),te=Gt(s,_.metadata.type,c,N,i.type_to_folder),_e=await wn(s,g),ce=[];try{await ue(te,xe),E&&te!==E&&await Ga.rm(E);let pt=qe({nowIso:S(),author:g,op:"restore",before:O.document,after:_,message:n.message});try{await Tt(a.historyPath,pt)}catch(ft){throw await hv({existingItemPath:E,resolvedOriginalRaw:O.originalRaw,restoredItemPath:te}),ft}ce=await vn({pmRoot:s,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:te,previousItemPath:E??void 0,document:_})}finally{await _e()}let Qe=await gv({restoredItemPath:te,historyPath:a.historyPath,before:O.document,after:_});fn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:O.document.metadata.status,status:_.metadata.status,previous:Kt(O.document.metadata,$),current:Kt(_.metadata,$),changed_fields:$});let ut=u[p.historyIndex];return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,entry_ts:ut.ts,entry_op:ut.op},changed_fields:$,warnings:[...a.historyPolicyWarnings,...j,...ce,...Qe]}}finally{await b()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4da07a98-855e-59cf-a6a4-2f59a8b3c0bd")}catch{}})();var Sf=1,ja="close-many",yv=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function bv(e,t){return nr(e,t,{includePagination:!1})}function wv(e,t){return nr(e,t)}function vv(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)}function kv(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(s=>s.trim().length>0)||(t[n]=r);return t}function Sv(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new l("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",d.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function Ev(e,t){let n=M(t.schema),r=x(t,I()),s=await oe(e,t.item_format,r.type_to_folder,void 0,t.schema),o=new Map,i=new Map;for(let a of s){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),se(a.status,n)))continue;let c=o.get(a.parent);c?c.push(a.id):o.set(a.parent,[a.id])}for(let a of o.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:o,parentByChild:i}}function kf(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let s=0,o=t.get(e),i=[],a=new Set,c=!1;for(;o!==void 0&&!a.has(o);){let m=n?.get(o);if(m!==void 0){s+=m+1;break}a.add(o),i.push(o),s+=1,o=t.get(o)}if(o!==void 0&&a.has(o)&&(c=!0),!c){n?.set(e,s);for(let[m,u]of i.entries())n?.set(u,s-m-1)}return s}async function Tv(e){let t=await $s(e.pmRoot,ja,e.rollbackId,Sf),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Ms(t.items,(s,o)=>Wt(s,o,{author:e.options.author,message:n,force:!0},e.global));return{...qt({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function Av(e,t,n,r,s){return e.map(o=>{let i=(t.get(o.id)??[]).filter(c=>!n.has(c)),a=!Ef(o,r,s);return{id:o.id,title:typeof o.title=="string"?o.title:"",status:o.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function Cv(e){let t=await Fs(e.pmRoot,ja,e.checkpointId,{schema_version:Sf,id:e.checkpointId,created_at:e.nowValue,author:R(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function Rv(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let s=await it(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:s.changed_fields,...s.warnings&&s.warnings.length>0?{warnings:s.warnings}:{}}),n.push(r.id)}catch(s){t.push({id:r.id,status:"failed",error:un(s)})}}return{rows:t,closedIds:n}}function Iv(e){return typeof e.rollback=="string"?e.rollback:void 0}function xv(e,t){if(t.trim().length===0)throw new l("--rollback requires a checkpoint id",d.USAGE);if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(wv(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function Ov(e){if(!bv(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${yv}). Refusing to match every item.`,d.USAGE)}function Pv(e,t){let n=new Map;return[...e].sort((r,s)=>{let o=kf(s.id,t,n)-kf(r.id,t,n);return o!==0?o:r.id.localeCompare(s.id)})}function Ef(e,t,n){return n||!se(e.status,t)}function Nv(e,t,n){return new Set(e.filter(r=>Ef(r,t,n)).map(r=>r.id))}async function Lv(e){Ov(e.options);let t=M(e.settings.schema),n=Sv(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,s=await It(e.options.status,kv(e.options.list),e.global),{childrenByParent:o,parentByChild:i}=await Ev(e.pmRoot,e.settings),a=Pv(s.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(p=>p.trim()).filter(p=>p.length>0))],m=new Set(a.map(p=>p.id)),u=Nv(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:s,matched:a,unmatchedIds:c.filter(p=>!m.has(p)),planRows:Av(a,o,u,t,r)}}function Fv(e){return{outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds.length>0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function $v(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return Cv({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function Tf(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=e.dryRun===!0,o=Iv(e);if(vv(e.list),o!==void 0)return xv(e,o),Tv({pmRoot:n,rollbackId:o,options:e,global:t});let i=await Lv({pmRoot:n,settings:r,options:e,global:t});if(s)return Fv(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=S(),m=Ls(ja,c),u=await $v({context:i,options:e,closableIds:a,checkpointId:m,nowValue:c}),p={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:i.validateCloseMode,force:i.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await Rv({matched:i.matched,closableIds:a,reason:i.reason,closeOptions:p,global:t}),h=f.filter(b=>b.status==="closed").length,y=f.filter(b=>b.status==="skipped").length,g=f.filter(b=>b.status==="failed").length;return{...qt({applied:h,skipped:y,failed:g,unmatched:i.unmatchedIds.length}),mode:"apply",matched_count:i.matched.length,dry_run:!1,...i.reason!==void 0?{reason:i.reason}:{},filters:i.listed.filters,...i.validateCloseMode?{validate_close:i.validateCloseMode}:{},...u?{checkpoint:u}:{},closed_count:h,skipped_count:y,failed_count:g,rows:f,ids:_,...i.unmatchedIds.length>0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}import{readFile as Mv}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7687052-a04e-536e-ace5-a665ebd477e3")}catch{}})();async function qa(e,t){let n=e.add!==void 0,r=e.stdin===!0,s=typeof e.file=="string",o=Number(n)+Number(r)+Number(s);if(o===0)return;if(o>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",d.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add")??"",emptyFlag:"--add"};if(r)return{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);try{return{value:await Mv(i,"utf8"),emptyFlag:"--file"}}catch(a){if($a(a)&&Ut(a))throw new l(`--file path not found: ${i}`,d.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${i}": ${c}`,d.USAGE)}}async function Dv(e,t){let n=e.edit,r=e.delete,s=n!==void 0,o=r!==void 0;if(s&&o)throw new l("Specify only one of --edit or --delete",d.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",d.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",d.USAGE);if(o){if(await qa(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(s){let c=await qa(e,t);if(c===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let i=await qa(e,t);return i===void 0?{mode:"list"}:{mode:i.emptyFlag==="--add"?"add":i.emptyFlag==="--stdin"?"stdin":"file",value:i.value,emptyFlag:i.emptyFlag}}async function Af(e,t,n){let r=Le(),s=await Dv(t,r),o=s.mode==="add"||s.mode==="edit",i=s.value??"";return On(e,t,n,{input:{...s,rawValue:t.add??i,value:o?xn(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(s.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm comments pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="93184f29-f215-5413-9628-fb5b34523995")}catch{}})();async function Cf(e,t,n){return On(e,t,n,{input:await ao(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>xn(r),createEntry:r=>r,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm learnings pm-a1b2 --add "review learning" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebd9f151-593f-5081-97da-d78f83de4914")}catch{}})();function Uv(e){if(e===void 0)return;if(e.trim().length===0)throw new l("--add-json must contain a JSON value",d.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new l("--add-json must be valid JSON",d.USAGE,{code:"structured_event_json_invalid"})}return t}function Gv(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function jv(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new l("--since must be a valid ISO timestamp",d.USAGE,{code:"structured_event_since_invalid"});return t}async function Rf(e,t,n){let r=Uv(t.addJson),s=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&s)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let o=r===void 0?void 0:J(r),i=[t.since,t.eventType].some(h=>h!==void 0),a=jv(t.since),c=Xn(t.limit),m=await On(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await ao(o===void 0?t:{add:o},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>xn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:Gv(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm notes pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}}),u=t.eventType?.trim(),p=m.notes.filter(h=>{let y=[h.format==="json",h.data!==void 0].every(Boolean),g=[a===void 0,Date.parse(h.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),b=[!u,h.event_type===u].includes(!0);return[!i,[y,g,b].every(Boolean)].includes(!0)}),f=i?Fa(p,c):p,_=f.filter(h=>h.format==="json").length;return{...m,notes:f,count:f.length,...i?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f9c9b926-c912-548e-a9c7-64c2c69767cd")}catch{}})();function mo(e,t){if(!t&&/[:,=]/.test(e))throw new l(`Invalid --dep value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE)}function cr(e,t,n=ca()){for(let r of t??[])try{Yd(e,r.id,r.kind,n)}catch(s){throw new l(un(s),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function If(e,t){return(await K(e,{schema:t})).document.metadata.created_at}async function qv(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await D(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:If(n,t.schema)}function Kv(e){let t=e.registry.require(e.dependency.kind);return new l(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,d.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function zv(e){let t=e.dependencies.filter(s=>e.registry.resolve(s.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(s.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:s,located:o})=>o===null?[]:[[s,o]])),r=new Map(await Promise.all([...new Set(t.map(({id:s})=>s))].map(async s=>[s,await If(n.get(s),e.context.schema)])));for(let s of e.holders){let o=await qv(s,e.context);if(o!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(o),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw Kv({holder:s,dependency:i,sourceCreatedAt:o,targetCreatedAt:a,registry:e.registry})}}}async function Yt(e){let t=e.registry??ca(),n=(e.dependencies??[]).filter(i=>!ep(i.source_kind)),r=[...new Set(n.map(i=>i.id))],s=await Promise.all(r.map(async i=>({target:i,located:await D(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),o=s.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(o.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${o.length===1?"":"s"} not found: ${o.join(", ")}`,d.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:o,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${o.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:o,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${o[0]}" --limit 10`}});return await zv({dependencies:n,missingTargets:o,resolutions:s,holders:e.holders??[],registry:t,context:e}),o.map(i=>`dependency_target_unresolved:${i}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcbb6070-7457-5454-abf1-fa8153c8efd6")}catch{}})();function uo(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function po(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function fo(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(xr.includes(t))return t;let n=ie(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new l("Confidence must be an integer 0..100 or one of low|med|medium|high",d.USAGE);return n}function _o(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new l("Regression must be one of true|false|1|0",d.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="afc4f3d5-ba5e-5dd7-abc9-531b319cdb4e")}catch{}})();var Bv=new Set(["none","null"]);function ho(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function ze(e){return e===void 0?!1:Bv.has(e.trim().toLowerCase())}function go(e,t,n){if(!ze(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function be(e,t,n){if(!e||e.length===0||!e.some(o=>ze(o)))return;let s=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${s}`.trim(),d.USAGE)}function yo(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new l(`${n.valueFlag} entries must be strings.`,d.USAGE);let s=r;if(!s.some(a=>ze(a)))continue;if(s.filter(a=>!ze(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2fcfbe50-039b-5031-8b18-a208908a0d87")}catch{}})();function Of(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,d.USAGE)}function Ka(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function we(e,t,n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE);return e}var Pf=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Hv(e,t){return t==="defined"?e!==void 0:!!e}function xf(e,t,n){if(!Hv(e,n))return;let r=ie(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function Vv(e,t,n){let r=e?Q(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new l("--event recur_until must be at or after start",d.USAGE);return r}function Wv(e){return Array.from(new Set(Ka(e).map(t=>we(t.toLowerCase(),qd,"event weekday")))).sort((t,n)=>Ti(t)-Ti(n))}function Yv(e){return Array.from(new Set(Ka(e).map(t=>{let n=ie(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new l("--event recur_by_month_day values must be integers 1..31",d.USAGE);return n}))).sort((t,n)=>t-n)}function Jv(e,t){return Array.from(new Set(Ka(e).map(n=>Q(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Nf(e,t,n,r){let s=e.recur_freq?.trim(),o=e.recur_interval?.trim(),i=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![s,o,i,a,c,m,u].some(E=>E!==void 0))return;if(!s)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let f=we(s.toLowerCase(),jd,"event recurrence frequency"),_=xf(o,"recur_interval",r),h=xf(i,"recur_count",r),y=Vv(a,t,n),g=Wv(c),b=Yv(m),v=Jv(u,n);return{freq:f,interval:_,count:h,until:y,by_weekday:g.length>0?g:void 0,by_month_day:b.length>0?b:void 0,exdates:v.length>0?v:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8248687e-ba97-5e1b-afbf-a322a72eb1aa")}catch{}})();var Lf="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",Xv="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",Qv=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,Zv=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,$f=1e3,za=60*$f,ek=60*za;function Ff(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new l(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,d.USAGE);return n.toISOString()}function tk(e,t){let n=new Date(e),r=t.trim(),s=Qv.exec(r);if(s){let a=s[1]==="-"?-1:1,c=Number.parseInt(s[2],10)*a;return Ff(n.getTime()+c*za,r)}let o=Zv.exec(r);if(o){let[,a,c,m,u]=o;if(c||m||u){let f=a==="-"?-1:1,_=Number.parseInt(c??"0",10),h=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),g=_*ek+h*za+y*$f;return Ff(n.getTime()+f*g,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return Q(i,n,"event.duration")}function Mf(e,t,n,r){if(t&&n)throw new l(Xv,d.USAGE);if(n){let o=tk(e,n);if(o<e)throw new l(Lf,d.USAGE);return o===e?void 0:o}if(!t)return;let s=Q(t,r,"event.end");if(s<e)throw new l(Lf,d.USAGE);if(s!==e)return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var nk=["at","date","text","title"],rk=["start","date","end","duration","title","description","location","timezone","all_day",...Pf],sk=["key","value"];function Df(e,t){return t==="trimmed"?e?.trim():e}function ok(e,t){return t==="defined"?e!==void 0:!!e}function bo(e,t,n){return e.map(r=>{let s=ne(r,"--reminder");Ke(s,"--reminder",nk);let o=Df(s.at??s.date,n.valueMode),i=Df(s.text??s.title,n.valueMode);if(!o||!i)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let a=i.trim();if(!a)throw new l("--reminder text must not be empty",d.USAGE);return{at:Q(o,t,"reminder.at"),text:a}})}function wo(e,t,n){return e.map(r=>{let s=ne(r,"--event");Ke(s,"--event",rk);let o=(s.start??s.date)?.trim();if(!o)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let i=Q(o,t,"event.start"),a=s.end?.trim(),c=s.duration?.trim(),m=Mf(i,a,c,t),u=s.title,p=s.description,f=s.location,_=s.timezone,h=u?.trim(),y=p?.trim(),g=f?.trim(),b=_?.trim(),v=[["title",u,h],["description",p,y],["location",f,g],["timezone",_,b]];for(let[j,$,xe]of v)if($!==void 0&&!xe)throw new l(`--event ${j} must not be empty`,d.USAGE);let E=s.all_day?.trim(),N=Nf(s,i,t,n.recurrenceEmptyNumericGuard),O=ok(E,n.allDayEmptyGuard)?Of(E,"--event all_day"):void 0;return{start_at:i,end_at:m,title:h,description:y,location:g,all_day:O,timezone:b,recurrence:N}})}function vo(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new l("--type-option values must not be empty",d.USAGE);let s,o;if(r.includes(",")||r.includes(`
5
- `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=ne(r,"--type-option");Ke(a,"--type-option",sk),s=a.key?.trim(),o=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),m=a;if(a<=0&&c>0&&(m=c),m<=0||m===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);s=r.slice(0,m).trim(),o=r.slice(m+1).trim()}if(!s||!o)throw new l("--type-option requires key and value",d.USAGE);t[s]=o}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var ik=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Uf(e,t,n,r){if(ik.has(t.trim().toLowerCase())||n!==r.open_status)return;let s=_s("in_progress",r);if(!(s===void 0||s===r.open_status))return{command:`pm start-task ${e}`,to_status:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b20ab37-ffbe-5c65-ac0f-800abf876e16")}catch{}})();var Jt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],ak=new Set(Jt),ck=Jt.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),dk=new RegExp(`^(?:[-*+]\\s+)?(?:${ck})\\s*[:=]`,"i");function ko(e){return e.startsWith("```")||e.includes(`
6
- `)?!0:dk.test(e)}function So(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!ak.has(i)){r.push(s);continue}if(Object.hasOwn(n,i))throw new l(`${t} provides key "${s}" more than once after case normalization`,d.USAGE);n[i]=o}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(s=>`"${s}"`).join(", ")}. Allowed keys: ${Jt.join(", ")}.`,d.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new l(`${t} command and cmd must match when both are provided`,d.USAGE);let{cmd:s,...o}=n;return{...o,command:o.command??s}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="74163bed-a473-543e-ae6a-0d5091b3b3a9")}catch{}})();var Qt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Ws,up,"FORCE_COLOR"]),Ao=/^[A-Za-z_][A-Za-z0-9_]*$/,Xt=["schema","tracker","auto"];function dr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1);if(!Ao.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(Qt.has(i.toUpperCase()))throw new l(`${t} env_set key "${i}" is reserved for sandbox safety`,d.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function lr(e,t){if(!e)return;let n=An(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,d.USAGE);for(let r of n){if(!Ao.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(Qt.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function Co(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,d.USAGE)}function Ro(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Xt.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${Xt.join(", ")}`,d.USAGE)}function Zt(e){if(!e)return;let t=An(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Nn(e,t,n){let r=Zt(e);if(!(!r||r.length===0)){for(let s of r)try{new RegExp(s,"m")}catch(o){throw new l(`${t} ${n} includes invalid regex "${s}": ${o instanceof Error?o.message:String(o)}`,d.USAGE)}return r}}function Io(e,t){if(!e)return;let n=ie(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,d.USAGE);return n}function xo(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function Oo(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,d.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${i}" must be numeric`,d.USAGE);r[i]=c}return Object.keys(r).length>0?r:void 0}var lk=new Set(Jt);function Po(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mk(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!lk.has(i)){r.push(s);continue}if(Object.hasOwn(n,i))throw t(`provides key "${s}" more than once after case normalization`);n[i]=o}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(s=>`"${s}"`).join(", ")}. Allowed keys: ${Jt.join(", ")}.`);return n}function Pn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function Eo(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let s=typeof r=="string"?[r]:r;if(!Array.isArray(s)||s.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let o=s.filter(i=>i.length>0);return o.length>0?o:void 0}function Gf(e,t,n){let r=Eo(e,t,n);if(r){for(let s of r)try{new RegExp(s,"m")}catch(o){throw n(`field "${t}" includes invalid regex "${s}": ${o instanceof Error?o.message:String(o)}`)}return r}}function To(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function uk(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let s=n===void 0?void 0:To(n,"timeout_seconds",t),o=r===void 0?void 0:To(r,"timeout",t);if(s!==void 0&&o!==void 0&&s!==o)throw t("timeout and timeout_seconds must match when both are provided");let i=s??o;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function pk(e,t){let n=Pn(e,"scope",t);if(n===void 0)return"project";if(!Ze.includes(n))throw t(`field "scope" must be one of: ${Ze.join(", ")}`);return n}function fk(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Po(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[s,o]of Object.entries(n)){if(typeof o!="string")throw t(`field "env_set" value for "${s}" must be a string`);if(!Ao.test(s))throw t(`field "env_set" key "${s}" is invalid`);if(Qt.has(s.toUpperCase()))throw t(`field "env_set" key "${s}" is reserved for sandbox safety`);r[s]=o}return Object.keys(r).length>0?r:void 0}function _k(e,t){let n=Eo(e,"env_clear",t);if(n){for(let r of n){if(!Ao.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(Qt.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function hk(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function gk(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=To(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function yk(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Po(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[s,o]of Object.entries(n)){if(s.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean")throw t(`field "assert_json_field_equals" value for "${s}" must be a string, number, or boolean`);r[s]=String(o)}return Object.keys(r).length>0?r:void 0}function bk(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Po(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[s,o]of Object.entries(n)){if(s.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[s]=To(o,`assert_json_field_gte.${s}`,t)}return Object.keys(r).length>0?r:void 0}function wk(e,t,n){let r=p=>new l(`${n} ${t} ${p}`,d.USAGE);if(!Po(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Jt.join(", ")}.`);let s=mk(e,r),o=Pn(s,"command",r),i=Pn(s,"cmd",r);if(o!==void 0&&i!==void 0&&o!==i)throw r("command and cmd must match when both are provided");let a=o??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=Pn(s,"path",r),m=Pn(s,"pm_context_mode",r);if(m!==void 0&&!Xt.includes(m))throw r(`field "pm_context_mode" must be one of: ${Xt.join(", ")}`);let u=Pn(s,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:pk(s,r),timeout_seconds:uk(s,r),pm_context_mode:m,env_set:fk(s,r),env_clear:_k(s,r),shared_host_safe:hk(s,"shared_host_safe",r),assert_stdout_contains:Eo(s,"assert_stdout_contains",r),assert_stdout_regex:Gf(s,"assert_stdout_regex",r),assert_stderr_contains:Eo(s,"assert_stderr_contains",r),assert_stderr_regex:Gf(s,"assert_stderr_regex",r),assert_stdout_min_lines:gk(s,r),assert_json_field_equals:yk(s,r),assert_json_field_gte:bk(s,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function jf(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,d.USAGE);let r;try{r=JSON.parse(n)}catch(o){throw new l(`${t} value is not valid JSON: ${o instanceof Error?o.message:String(o)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let s=Array.isArray(r)?r:[r];if(s.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return s.map((o,i)=>wk(o,s.length>1?`entry ${i+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0062e981-158a-5e6a-b028-6c7cef0f59ba")}catch{}})();var Ba=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Ha=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],qf=[...Ba,...Ha],No=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function Lo(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let s=r.trim().toLowerCase();if(!s)throw new l("--unset values must not be empty",d.USAGE);if(ze(s))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let o=e.resolveDefinition(s);if(!o)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(o.metadataKey),n.add(o.optionKey)}return{metadataKeys:t,optionKeys:n}}function Fo(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let s=n.command_to_fields?.get(t)??[];for(let o of s){if(o.allow_unset===!1)continue;let i=new Set;if(typeof o.key=="string"&&o.key.length>0&&i.add(o.key.toLowerCase()),typeof o.metadata_key=="string"&&o.metadata_key.length>0&&i.add(o.metadata_key.toLowerCase()),typeof o.cli_flag=="string"&&o.cli_flag.length>0&&(i.add(o.cli_flag.replaceAll("-","_").toLowerCase()),i.add(o.cli_flag.toLowerCase())),Array.isArray(o.cli_aliases))for(let a of o.cli_aliases)typeof a!="string"||a.length===0||(i.add(a.replaceAll("-","_").toLowerCase()),i.add(a.toLowerCase()));if(i.has(r))return{optionKey:o.key,metadataKey:o.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="002f45a2-edc3-5aa0-9af8-d9b1dfecc097")}catch{}})();var vk={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function kk(e){return vk[e]}function Va(e){return kk(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7d69bb56-9fab-5059-9357-5b6bea2078b9")}catch{}})();var Sk=["strict","progressive"],Ek=["lightweight"],Hf=new Set(["Reminder","Meeting","Event"]),Tk=new Set(["author","created_at","text"]),Ya=[...qf,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...No],Ak=(()=>{let e=new Map;for(let t of Ya)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),$o=new Map(Ya.map(e=>[e.optionKey,e.canonical])),Ck=Ya.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function Rk(e,t){let n=W(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function Ik(e,t){let n=e.default_status;if(n!==void 0){let r=W(n,t);if(r)return r}return t.open_status}function Wa(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}var xk=ho();function Vf(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=s=>{let o=t.unset?[...t.unset]:[];o.includes(s)||o.push(s),t.unset=o};ze(t.template)&&(t.template=void 0);let r=new Set([...$o.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!ze(o))continue;let i=s==="rank"?"order":$o.get(s)??s;n(i),t[s]=void 0}return yo(t,xk)}function de(e){if(e!==void 0)return e}function Ok(e,t){return Lo({raw:e,supportedFields:Ck,resolveDefinition:n=>Ak.get(n)??Fo(n,"create",t)})}var Kf=["id","kind","type","author","created_at","source_kind"],Mo=["path","scope","note"];function Pk(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let i=o.trim(),a=Ja(i,Kf);mo(i,a);let c=a?ne(o,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",Kf);let m=de(c.id),u=Nk(de(c.kind??c.type));if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",d.USAGE);if(m.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=Qn(de(c.source_kind)),f=de(c.author);return{id:Zn(m,n,p),kind:we(u,Dt,"dependency kind"),created_at:Wa(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function Nk(e){return typeof e=="string"?$r(e)??e.trim():e}function Ja(e,t){if(e.startsWith("```")||e.includes(`
7
- `))return!0;let n=t.map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${n})\\s*[:=]`,"i").test(e)?!0:Bs(e)}function tn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(be(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(i=>{let a=i.trim(),c=()=>{if(a.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:a}},m;try{m=ne(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!Tk.has(f)).length>0)return{created_at:Wa(m.created_at,n),author:de(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:Wa(m.created_at,n),author:de(m.author)??r,text:p}}),explicitEmpty:!1})}function Xa(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),s=Ja(r,Mo),o=s?ne(n,"--file"):{path:r};if(s&&Ke(o,"--file",Mo),!o.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:o.path,scope:we(o.scope??"project",Ze,"file scope"),note:de(o.note)}}),explicitEmpty:!1})}function Qa(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),s=ko(r)?So(ne(n,"--test"),"--test"):{command:r},o=de(s.command),i=de(s.path);if(!o)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let a=de(s.timeout_seconds),c=de(s.timeout);if(a&&c&&a!==c)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let m=a??c;return{command:o,path:i,scope:we(s.scope??"project",Ze,"test scope"),timeout_seconds:m?ie(m,"timeout_seconds"):void 0,pm_context_mode:Ro(s.pm_context_mode,"--test"),env_set:dr(s.env_set,"--test"),env_clear:lr(s.env_clear,"--test"),shared_host_safe:Co(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Zt(s.assert_stdout_contains),assert_stdout_regex:Nn(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Zt(s.assert_stderr_contains),assert_stderr_regex:Nn(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Io(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:xo(s.assert_json_field_equals,"--test"),assert_json_field_gte:Oo(s.assert_json_field_gte,"--test"),note:de(s.note)}}),explicitEmpty:!1})}function Za(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),s=Ja(r,Mo),o=s?ne(n,"--doc"):{path:r};if(s&&Ke(o,"--doc",Mo),!o.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:o.path,scope:we(o.scope??"project",Ze,"doc scope"),note:de(o.note)}}),explicitEmpty:!1})}function Lk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--reminder","Use --clear-reminders to clear reminders."),{values:bo(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function Fk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--event","Use --clear-events to clear linked events."),{values:wo(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function $k(e,t,n,r=[]){let s=[...Or.filter(o=>e[o]!==void 0),...r.filter(o=>e[o]!==void 0),...t.length>0?["body"]:[],...n.map(o=>`unset:${o}`)];return Array.from(new Set(s))}function Mk(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function zf(e,t,n){let r=Kn("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function Dk(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function Wf(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function Uk(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(zf(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(zf(r,e.name,"required_create_repeatables"));return n}function Gk(e,t,n,r){for(let s of e)if(!(!Wf(t,s)&&!n.has(s)))throw new l(`Option ${he("create",s)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function jk(e,t,n){if(t!=="strict")return;let r=e.filter(o=>n.has(o)&&!Va(o));if(r.length===0)return;let s=[...new Set(r.map(o=>he("create",o)))].sort((o,i)=>o.localeCompare(i));throw new l(`Strict create mode requires concrete values for ${s.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function qk(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:vo(e),explicitEmpty:!1})}async function Kk(e){let t=Le();return{...e,body:await t.resolveValue(e.body,"--body"),dep:await t.resolveList(e.dep,"--dep"),comment:await t.resolveList(e.comment,"--comment"),note:await t.resolveList(e.note,"--note"),learning:await t.resolveList(e.learning,"--learning"),file:await t.resolveList(e.file,"--file"),test:await t.resolveList(e.test,"--test"),doc:await t.resolveList(e.doc,"--doc"),reminder:await t.resolveList(e.reminder,"--reminder"),event:await t.resolveList(e.event,"--event"),typeOption:await t.resolveList(e.typeOption,"--type-option"),field:await t.resolveList(e.field,"--field")}}function zk(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${Sk.join(", ")}`,d.USAGE)}function Bk(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new l("--schedule-preset must not be empty",d.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new l(`Invalid --schedule-preset value "${e}". Allowed: ${Ek.join(", ")}`,d.USAGE)}function Hk(e,t,n){let r=zk(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",d.USAGE);return"progressive"}function Vk(e,t,n,r){let s=e.name,o=Dk(t),i=Uk(e,n),a=mn(e,"create",i);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);Gk(a.disabled,o,r,s),jk(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&Va(u)?!0:Wf(o,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>he("create",u)))].sort((u,p)=>u.localeCompare(p))}var Yf=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function Wk(e,t){let n=[];for(let r of e){let s=r.match(Yf);s&&s[2]===t&&n.push(s[1])}return[...new Set(n)].sort((r,s)=>r.localeCompare(s))}function Yk(e,t){return e.filter(n=>{let r=n.match(Yf);return!r||r[2]!==t})}function Jk(e,t,n,r){let s=Yk(e,t);if(s.length===0)return;let o=Jf(n,[],[],r.open_status);throw new l(s.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[o],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function Xk(e,t){let r=e.options.find(s=>s.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function Qk(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function Jf(e,t,n,r){let s=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],o=["--status","--priority","--message"],i=[...new Set([...o,...t])],a=new Set(["--title","--description","--type"]);for(let c of i)a.has(c)||(s.push(...Qk(c,e.name,r)),a.add(c));for(let c of n){let m=Xk(e,c);s.push("--type-option",`${c}=${m}`)}return s.join(" ")}function ec(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new l("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",d.USAGE):new l('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',d.USAGE):new l(`Missing required option ${t}`,d.USAGE);return n}function Zk(e){return Tn(e)}function eS(e,t){let n={};for(let[r,s]of Object.entries(e))n[r]=Array.isArray(s)?[...s]:s;for(let[r,s]of Object.entries(t))s!==void 0&&(n[r]=Array.isArray(s)?[...s]:s);return n}function tS(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function nS(){let e=I();return e?e.commands.some(t=>t.action==="templates-show"||tS(t.command)==="templates show"):!1}function rS(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new l(`Templates package returned invalid payload for template "${t}". Expected an options object.`,d.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Templates package returned invalid options for template "${t}".`,d.GENERIC_FAILURE);let r={};for(let[s,o]of Object.entries(n)){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"){r[s]=o;continue}if(Array.isArray(o)&&o.every(i=>typeof i=="string")){r[s]=[...o];continue}throw new l(`Templates package returned unsupported option value for "${s}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function sS(e,t,n){if(!nS())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await vs({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let s=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${s}`,d.USAGE)}return rS(r.result,e)}function oS(e){return k(C(e)).then(t=>{if(!t)throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)})}function B(e,t,n){return e.has(t)||n===void 0?void 0:de(n)}function en(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var iS=new Set(["milestone","meeting","reminder","event"]);function Xf(e,t,n,r){let s=t!==void 0,o=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return iS.has(e.toLowerCase())&&!s&&!o&&!i}function aS(e,t,n,r,s){let o=[];return e.toLowerCase()==="event"&&(s===void 0||s.length===0)&&o.push(`event_without_schedule:${t}:no_time_set`),Xf(e,n,r,s)&&o.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),o}async function cS(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let s=await ks(r);return s===void 0?{parent:e,parentSource:void 0}:{parent:s,parentSource:"focus"}}async function dS(e,t,n,r,s,o){let i=Gs(s);if(qs(r,i,t.id_prefix),await D(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let c=ge(i,t.id_prefix);return{parent:i,warnings:js(c,o).warnings}}async function lS(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await dS(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function mS(e){if(e.explicitId===void 0)return Jn(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||Gu(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=ge(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",d.USAGE);return n}function Bf(e,t,n,r,s){let o=B(e,t,n);if(o===void 0)return{value:void 0,warnings:[]};let i=Hs(r,o,s);return{value:i.value,warnings:i.warnings}}async function uS(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:s,blockedBy:o,status:i,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(o===void 0)return{dependencyValues:u,status:i};let p=ge(o,n.id_prefix),f=await D(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:i};if((u??[]).some(y=>y.id===f.id&&y.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:i};let h=s.blocked_statuses.has("blocked")?"blocked":[...s.blocked_statuses].sort((y,g)=>y.localeCompare(g))[0]??s.open_status;return{dependencyValues:u,status:h}}function pS(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let s=t.governance.create_default_type?.trim();if(s&&s.length>0&&pe(s,n)){e.type=s;return}pe("Task",n)&&(e.type="Task")}function fS(e,t){return e.options.filter(n=>Kn("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function _S(e,t,n,r,s){let o=e,i=[];if(o.template!==void 0){let h=o.template.trim();if(h.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let y=await sS(h,t,n);o=Vf(eS(y,o))}if(o.type===void 0&&pS(o,r,s),o.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let a=pe(o.type,s);if(!a){let h=qu(o.type),y=h?pe(h,s):void 0;if(y)i.push(`type_coercion:${o.type.trim()}:${y}`),o.type=y,a=y;else throw new l(kt(o.type,s.types,St(n,r.schema)),d.USAGE)}let c=Lr(a,s);if(!c)throw new l(`Invalid type value "${o.type}"`,d.USAGE);let m=c.name,u=fS(c,o),p=u.map(h=>`${h.key}=${String(o[h.key])}`);if(p.length>0){o.typeOption=[...p,...o.typeOption??[]];for(let h of u)delete o[h.key]}let f=Bk(o.schedulePreset);if(f!==void 0&&!Hf.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=Hk(o.createMode,f,r.governance.create_mode_default);return{resolvedOptions:o,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function hS(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),s=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let o of s)if(o.enabled){if(o.values&&o.values.length>0)throw new l(`Cannot combine ${o.clearFlag} with ${o.valueFlag}`,d.USAGE);n.add(o.metadataKey),r.add(o.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function gS(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=$o.get(r)??r;throw new l(`Cannot combine --unset ${o} with ${he("create",r)}`,d.USAGE)}}function yS(e){let t=(n,r)=>{let s=$o.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;go(n,he("create",r),o)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function bS(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,d.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,d.USAGE)}function wS(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:s,openStatus:o,type:i,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(_=>{let h=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${h}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),u=[Jf(n,r,s,o),...m.map(_=>_.example)].join(" "),p=[`Run "pm create --help --type ${i}" for type-aware required option guidance.`];t.includes("--title")&&p.push('Title can also be passed as the first positional argument (example: pm create "Your title" --type '+i+")."),a==="strict"&&(p.push('For staged onboarding, retry with "--create-mode progressive".'),Hf.has(i)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&p.push(`Required custom field formats: ${m.map(_=>_.description).join("; ")}.`);let f=t.length===1?`Missing required option ${t[0]} for type "${i}"`:`Missing required options ${t.join(", ")} for type "${i}"`;throw new l(f,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${i}" in one invocation.`,examples:[u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:["--create-mode progressive",...t]}:void 0})}function vS(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Rt(t.tags):[];return Sn(n,t.addTags)}function kS(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new l("--order and --rank must match when both are provided",d.USAGE);let n=t.order??t.rank,r=en(e,"order",n,s=>ie(s,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function SS(e,t,n,r,s,o){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",d.USAGE);let i=e!==t.close_status?void 0:r.completedAt===void 0?o:Q(r.completedAt,new Date(o),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:i,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:s}:{explicit:r.closeReason};return{closeReason:Da(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function ES(e){let{pmRoot:t,type:n,id:r,settings:s,typeRegistry:o,author:i,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=Gt(t,n,r,s.item_format,o.type_to_folder),g=Se(t,r),b=await Pe(t,r,s.locks.ttl_seconds,i,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),v=[];try{let E=c.metadata.dependencies&&c.metadata.dependencies.length>0?await oe(t,s.item_format,o.type_to_folder,void 0,s.schema):void 0;if(await D(t,r,s.id_prefix,s.item_format,o.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);await ws({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:Is({pmRoot:t,settings:s,typeToFolder:o.type_to_folder})});let O=await wn(t,i,{required:s.governance.duplicate_detection_mode==="strict"&&h!==!0}),j=[];try{s.governance.duplicate_detection_mode==="strict"&&h!==!0&&await In(_,{pmRoot:t,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1}),await ue(y,je(c,{format:s.item_format,schema:s.schema,extensionFieldNames:a}));try{let $=qe({nowIso:f,author:i,op:"create",before:m,after:c,message:u});await Tt(g,$)}catch($){throw await ln(y),$}j=await vn({pmRoot:t,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:y,document:c})}finally{await O()}v=[...E?to(E,[...E,c.metadata],r):[],...j,...await z({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await z({path:g,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],fn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Kt(c.metadata,p),changed_fields:p})}finally{await b()}return v}async function xt(e,t){let n=Vf(await Kk(e)),r=T(process.cwd(),t.path);await oS(r);let s=await A(r),o=M(s.schema),i=Ve(s.schema),a=x(s,I()),c=await _S(n,t,r,s,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=Ok(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=hS(n,f);gS(n,f),yS(n);let y=Vk(m,n,p,h),g=S(),b=R(de(n.author),s.author_default),v=Pk(n.dep,g,s.id_prefix,b),E=tn("--comment",n.comment,g,b),N=tn("--note",n.note,g,b),O=tn("--learning",n.learning,g,b),j=Xa(n.file),$=Qa(n.test),xe=Za(n.doc),te=Lk(n.reminder,g),_e=Fk(n.event,g),ce=qk(n.typeOption),Qe=zn(u,ce.values,a),ut=I(),pt=bt(ut),ft=Pr(n.field,ut),_t=du(n,i,u),hi=new Set(_t.missing_required_flags),gi=i.definitions.filter(H=>hi.has(`--${H.cli_flag}`));bS(ft,_t,f);let jn=Wk(Qe.errors,u),ht=jn.map(H=>`--type-option ${H}=<value>`),Sd=[...new Set([...y,...ht,..._t.missing_required_flags])].sort((H,Si)=>H.localeCompare(Si));wS({combinedMissingFlags:Sd,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:jn,openStatus:o.open_status,type:u,createMode:p,missingRequiredRuntimeFields:gi}),Jk(Qe.errors,u,m,o);let ke=await mS({pmRoot:r,settings:s,typeRegistry:a,explicitId:n.id}),Oe=n.status!==void 0?Rk(n.status,o):Ik(m,o),$t=n.priority!==void 0?Zk(n.priority):2,P=f.metadataKeys,gt=vS(P,n),qn=en(P,"deadline",n.deadline,H=>Q(H,new Date(g),"deadline")),Ue=en(P,"estimated_minutes",n.estimatedMinutes,H=>En(H,"estimated-minutes")),Tr=B(P,"acceptance_criteria",n.acceptanceCriteria),pb=B(P,"definition_of_ready",n.definitionOfReady),fb=kS(P,n),_b=B(P,"goal",n.goal),hb=B(P,"objective",n.objective),gb=B(P,"value",n.value),yb=B(P,"impact",n.impact),bb=B(P,"outcome",n.outcome),wb=B(P,"why_now",n.whyNow),vb=B(P,"assignee",n.assignee),kb=P.has("author")?void 0:de(n.author)??b,Sb=B(P,"parent",n.parent),Ed=await cS(Sb,n,P,r),yi=Ed.parent,Eb=Ed.parentSource,Tb=B(P,"reviewer",n.reviewer),Ab=en(P,"risk",n.risk,H=>we(uo(H),cn,"risk")),Cb=en(P,"confidence",n.confidence,H=>fo(H)),Rb=n.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,Td=s.validation.sprint_release_format,Mt=[...c.warnings,...aS(u,ke,qn,te.values,_e.values)],Ad=await lS({itemId:ke,parent:yi,pmRoot:r,settings:s,typeRegistry:a,policy:Rb});yi=Ad.parent,Mt.push(...Ad.warnings);let Cd=Bf(P,"sprint",n.sprint,"sprint",Td),Ib=Cd.value;Mt.push(...Cd.warnings);let Rd=Bf(P,"release",n.release,"release",Td),xb=Rd.value;Mt.push(...Rd.warnings);let Id=B(P,"blocked_by",n.blockedBy),xd=await uS({pmRoot:r,settings:s,typeRegistry:a,statusRegistry:o,blockedBy:Id,dependencyValues:v.values,status:Oe,statusExplicit:n.status!==void 0,nowValue:g,author:b}),bi=xd.dependencyValues;cr(ke,bi),Mt.push(...await Yt({pmRoot:r,dependencies:bi,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:ke,createdAt:g}],schema:s.schema})),Oe=xd.status;let Ob=B(P,"blocked_reason",n.blockedReason),Pb=B(P,"unblock_note",n.unblockNote),Nb=B(P,"reporter",n.reporter),Lb=en(P,"severity",n.severity,H=>we(po(H),dn,"severity")),Fb=B(P,"environment",n.environment),$b=B(P,"repro_steps",n.reproSteps),Od=B(P,"resolution",n.resolution),Mb=B(P,"expected_result",n.expectedResult),Db=B(P,"actual_result",n.actualResult),Ub=B(P,"affected_version",n.affectedVersion),Gb=B(P,"fixed_version",n.fixedVersion),jb=B(P,"component",n.component),qb=en(P,"regression",n.regression,H=>_o(H)),Kb=B(P,"customer_impact",n.customerImpact),wi=ec(n.title,"--title"),vi=n.description??"",Ar=n.body??"",Pd=await In({title:wi,description:vi,body:Ar},{pmRoot:r,mode:s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Mt.push(...no(Pd));let ki=SS(Oe,o,s,n,Od,g),zb=ki.closeReason,Bb=Oe===o.close_status?g:void 0,Hb=ki.completedAt;Mt.push(...ki.warnings);let Cr=ea({id:ke,title:wi,description:vi,type:u,type_options:Qe.normalized,status:Oe,closed_at:Bb,completed_at:Hb,close_reason:zb,priority:$t,tags:gt,created_at:g,updated_at:g,deadline:qn,assignee:vb,author:kb,estimated_minutes:Ue,acceptance_criteria:Tr,definition_of_ready:pb,order:fb,goal:_b,objective:hb,value:gb,impact:yb,outcome:bb,why_now:wb,parent:yi,reviewer:Tb,risk:Ab,confidence:Cb,sprint:Ib,release:xb,blocked_by:Id,blocked_reason:Ob,unblock_note:Pb,reporter:Nb,severity:Lb,environment:Fb,repro_steps:$b,resolution:Od,expected_result:Mb,actual_result:Db,affected_version:Ub,fixed_version:Gb,component:jb,regression:qb,customer_impact:Kb,dependencies:bi,comments:E.values,notes:N.values,learnings:O.values,files:j.values,tests:$.values,docs:xe.values,reminders:te.values,events:_e.values,...ft,..._t.values});try{Nr(Cr,ut)}catch(H){throw new l(H instanceof Error?H.message:"Invalid extension item field values",d.USAGE)}let Vb=We({metadata:Cr,body:Ar},{schema:s.schema,extensionFieldNames:pt}),Wb={metadata:{},body:""},Nd=[..._].sort((H,Si)=>H.localeCompare(Si)),Yb=Mk(n.message,Nd),Ld=$k(Cr,Ar,Nd,[...Object.keys(ft),...Object.keys(_t.values??{})]),Jb=await ES({pmRoot:r,type:u,id:ke,settings:s,typeRegistry:a,author:b,extensionFieldNames:pt,afterDocument:Vb,beforeDocument:Wb,historyMessage:Yb,changedFields:Ld,nowValue:g,similarityCandidate:{title:wi,description:vi,body:Ar},allowDuplicate:n.allowDuplicate}),Fd=structuredClone(Cr);p==="strict"&&_.has("dependencies")&&(Fd.dependencies=[]);let Xb=Uf(ke,u,Oe,o);return Xf(u,qn,te.values,_e.values)&&yu(`[pm] warning: ${u} '${ke}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${ke} --deadline <ISO>' or 'pm update ${ke} --event "start=<ISO>,end=<ISO>"'.`),{item:Fd,changed_fields:Ld,warnings:[...Mt,...Jb],...Object.fromEntries([["parent_source",Eb],["next_transition",Xb],["similarity_advisory",Pd]].filter(H=>H[1]!==void 0))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ab4f16d-ce37-546e-a2f6-0495fd1967c7")}catch{}})();var sc=[...Ba,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Ha,...No],TS=(()=>{let e=new Map;for(let t of sc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Do=new Map(sc.map(e=>[e.optionKey,e.canonical])),AS=sc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),CS=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),RS=ho({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function IS(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=s=>{let o=t.unset?[...t.unset]:[];o.includes(s)||o.push(s),t.unset=o},r=new Set([...Do.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!ze(o))continue;let i=s==="rank"?"order":Do.get(s)??s;n(i),t[s]=void 0}return yo(t,RS)}function i_(e,t,n=[]){return Lo({raw:e,supportedFields:AS,resolveDefinition:r=>{let s=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return TS.get(r)??Fo(r,"update",t)??(s?{optionKey:"field",metadataKey:s}:void 0)}})}var Qf=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function Zf(e){let t=e.disallowedFlags.flatMap(r=>{let s=Qf.get(r);return s?[s(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let s=Qf.get(r);return s?[`Replace ${r} with: ${s(e.id)}`]:[]});return new l(e.message,d.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function xS(e,t,n){let r=t.ownershipMetadataBypass===!0,s=t.ownershipDependencyBypass===!0;if(!r&&!s)return;if(r&&s)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let o=(c,m,u)=>{c&&u.push(m)};if(s){let c=[];if(o(t.title!==void 0,"--title",c),o(t.description!==void 0,"--description",c),o(t.body!==void 0,"--body",c),o(t.status!==void 0,"--status",c),o(t.closeReason!==void 0,"--close-reason",c),o(t.priority!==void 0,"--priority",c),o(t.type!==void 0,"--type",c),o(t.tags!==void 0,"--tags",c),o(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),o(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),o(t.deadline!==void 0,"--deadline",c),o(t.estimatedMinutes!==void 0,"--estimate",c),o(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),o(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),o(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),o(t.definitionOfReady!==void 0,"--definition-of-ready",c),o(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),o(t.goal!==void 0,"--goal",c),o(t.objective!==void 0,"--objective",c),o(t.value!==void 0,"--value",c),o(t.impact!==void 0,"--impact",c),o(t.outcome!==void 0,"--outcome",c),o(t.whyNow!==void 0,"--why-now",c),o(t.assignee!==void 0,"--assignee",c),o(t.parent!==void 0,"--parent",c),o(t.reviewer!==void 0,"--reviewer",c),o(t.risk!==void 0,"--risk",c),o(t.confidence!==void 0,"--confidence",c),o(t.sprint!==void 0,"--sprint",c),o(t.release!==void 0,"--release",c),o(t.blockedBy!==void 0,"--blocked-by",c),o(t.blockedReason!==void 0,"--blocked-reason",c),o(t.unblockNote!==void 0,"--unblock-note",c),o(t.reporter!==void 0,"--reporter",c),o(t.severity!==void 0,"--severity",c),o(t.environment!==void 0,"--environment",c),o(t.reproSteps!==void 0,"--repro-steps",c),o(t.resolution!==void 0,"--resolution",c),o(t.expectedResult!==void 0,"--expected-result",c),o(t.actualResult!==void 0,"--actual-result",c),o(t.affectedVersion!==void 0,"--affected-version",c),o(t.fixedVersion!==void 0,"--fixed-version",c),o(t.component!==void 0,"--component",c),o(t.regression!==void 0,"--regression",c),o(t.customerImpact!==void 0,"--customer-impact",c),o(t.depRemove!==void 0,"--dep-remove",c),o(t.replaceDeps===!0,"--replace-deps",c),o(t.replaceTests===!0,"--replace-tests",c),o(t.replaceFiles===!0,"--replace-files",c),o(t.replaceDocs===!0,"--replace-docs",c),o(t.comment!==void 0,"--comment",c),o(t.note!==void 0,"--note",c),o(t.learning!==void 0,"--learning",c),o(t.file!==void 0,"--file",c),o(t.test!==void 0,"--test",c),o(t.doc!==void 0,"--doc",c),o(t.reminder!==void 0,"--reminder",c),o(t.event!==void 0,"--event",c),o(t.typeOption!==void 0,"--type-option",c),o(t.clearDeps===!0,"--clear-deps",c),o(t.clearComments===!0,"--clear-comments",c),o(t.clearNotes===!0,"--clear-notes",c),o(t.clearLearnings===!0,"--clear-learnings",c),o(t.clearFiles===!0,"--clear-files",c),o(t.clearTests===!0,"--clear-tests",c),o(t.clearDocs===!0,"--clear-docs",c),o(t.clearReminders===!0,"--clear-reminders",c),o(t.clearEvents===!0,"--clear-events",c),o(t.clearTypeOptions===!0,"--clear-type-options",c),o(t.force===!0,"--force",c),o(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw Zf({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let i=[];o(t.status!==void 0,"--status",i),o(t.closeReason!==void 0,"--close-reason",i),o(t.assignee!==void 0,"--assignee",i),o(t.parent!==void 0,"--parent",i),o(t.blockedBy!==void 0,"--blocked-by",i),o(t.blockedReason!==void 0,"--blocked-reason",i),o(t.unblockNote!==void 0,"--unblock-note",i),o(t.dep!==void 0,"--dep",i),o(t.depRemove!==void 0,"--dep-remove",i),o(t.replaceDeps===!0,"--replace-deps",i),o(t.replaceTests===!0,"--replace-tests",i),o(t.replaceFiles===!0,"--replace-files",i),o(t.replaceDocs===!0,"--replace-docs",i),o(t.note!==void 0,"--note",i),o(t.learning!==void 0,"--learning",i),o(t.test!==void 0,"--test",i),o(t.reminder!==void 0,"--reminder",i),o(t.event!==void 0,"--event",i),o(t.clearDeps===!0,"--clear-deps",i),o(t.clearComments===!0,"--clear-comments",i),o(t.clearNotes===!0,"--clear-notes",i),o(t.clearLearnings===!0,"--clear-learnings",i),o(t.clearFiles===!0,"--clear-files",i),o(t.clearTests===!0,"--clear-tests",i),o(t.clearDocs===!0,"--clear-docs",i),o(t.clearReminders===!0,"--clear-reminders",i),o(t.clearEvents===!0,"--clear-events",i);let a=[...n].filter(c=>CS.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw Zf({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${i.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:i})}function OS(e,t){let n=W(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function PS(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Cm({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=W(e.fromStatus,e.statusRegistry)??e.fromStatus,r=W(e.toStatus,e.statusRegistry)??e.toStatus,s=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Rm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(s,d.USAGE);return`workflow_transition_not_allowed: ${s}`}function NS(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}function Uo(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var LS=["id","kind","type","author","created_at","source_kind"],FS=["id","kind","type","source_kind"];function $S(e){return e.startsWith("```")||e.includes(`
8
- `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Bs(e)}function a_(e){return typeof e=="string"?$r(e)??e.trim():e}function Go(e,t,n,r){return e?(be(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=$S(i);mo(i,a);let c=a?ne(o,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",LS);let m=c.id?.trim(),u=a_((c.kind??c.type)?.trim());if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",d.USAGE);if(m.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=Qn(Uo(c.source_kind)),f=Uo(c.author);return{id:Zn(m,t,p),kind:we(u,Dt,"dependency kind"),created_at:NS(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function MS(e,t){return e?(be(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new l("--dep-remove requires id or key/value selectors",d.USAGE);if(r.includes("=")||/^(?:[-*+]\s+)?(?:id|kind|type|source_kind)\s*[:=]/i.test(r)||r.startsWith("```")){let s=ne(r,"--dep-remove");Ke(s,"--dep-remove",FS);let o=s.id?.trim();if(!o)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(o.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${o}"`,d.USAGE);let i=a_(Uo(s.kind??s.type)),a=Qn(Uo(s.source_kind));return{id:Zn(o,t,a),kind:i?we(i,Dt,"dependency kind"):void 0,source_kind:a}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:ge(r,t)}})):[]}function e_(e){let t=e.source_kind?.trim().toLowerCase()??"";return`${e.id.trim().toLowerCase()}::${e.kind}::${t}`}function DS(e,t,n,r){let s=[...e??[]],o=!1;if(t===void 0){let i=s.filter(a=>a.kind!=="blocked_by");return i.length!==s.length&&(s=i,o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}return s.some(i=>i.kind==="blocked_by"&&i.id===t)||(s.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}async function US(e,t,n,r,s,o){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await D(n,ge(i,r),r,s,o);return a?{id:a.id}:{unresolved:i}}function GS(e,t,n,r,s){let o=DS(e.dependencies,t,n,r);o.changed&&(o.dependencies===void 0?delete e.dependencies:e.dependencies=o.dependencies,s.includes("dependencies")||s.push("dependencies"))}function jS(e){return`${e.path}::${e.scope}`}function qS(e){return`${e.path}::${e.scope}`}function KS(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}`}function zS(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase())}function BS(e){return Tn(e)}function t_(e,t){let n=Kn("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function HS(e,t,n){let r=new Set,s=(o,i)=>{i&&r.add(o)};if(s("title",e.title!==void 0),s("description",e.description!==void 0),s("body",e.body!==void 0),s("status",e.status!==void 0),s("closeReason",e.closeReason!==void 0),s("priority",e.priority!==void 0),s("type",e.type!==void 0),s("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),s("deadline",e.deadline!==void 0),s("estimatedMinutes",e.estimatedMinutes!==void 0),s("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),s("definitionOfReady",e.definitionOfReady!==void 0),s("order",e.order!==void 0||e.rank!==void 0),s("goal",e.goal!==void 0),s("objective",e.objective!==void 0),s("value",e.value!==void 0),s("impact",e.impact!==void 0),s("outcome",e.outcome!==void 0),s("whyNow",e.whyNow!==void 0),s("author",e.author!==void 0),s("message",e.message!==void 0),s("assignee",e.assignee!==void 0),s("parent",e.parent!==void 0),s("reviewer",e.reviewer!==void 0),s("risk",e.risk!==void 0),s("confidence",e.confidence!==void 0),s("sprint",e.sprint!==void 0),s("release",e.release!==void 0),s("blockedBy",e.blockedBy!==void 0),s("blockedReason",e.blockedReason!==void 0),s("unblockNote",e.unblockNote!==void 0),s("reporter",e.reporter!==void 0),s("severity",e.severity!==void 0),s("environment",e.environment!==void 0),s("reproSteps",e.reproSteps!==void 0),s("resolution",e.resolution!==void 0),s("expectedResult",e.expectedResult!==void 0),s("actualResult",e.actualResult!==void 0),s("affectedVersion",e.affectedVersion!==void 0),s("fixedVersion",e.fixedVersion!==void 0),s("component",e.component!==void 0),s("regression",e.regression!==void 0),s("customerImpact",e.customerImpact!==void 0),s("dep",e.dep!==void 0),s("depRemove",e.depRemove!==void 0),s("dep",e.replaceDeps===!0),s("comment",e.comment!==void 0),s("note",e.note!==void 0),s("learning",e.learning!==void 0),s("file",e.file!==void 0),s("test",e.test!==void 0),s("test",e.replaceTests===!0),s("file",e.replaceFiles===!0),s("doc",e.replaceDocs===!0),s("doc",e.doc!==void 0),s("reminder",e.reminder!==void 0),s("event",e.event!==void 0),s("typeOption",e.typeOption!==void 0),s("field",e.field!==void 0),s("force",e.force===!0),s("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),s("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),s("dep",e.clearDeps===!0),s("comment",e.clearComments===!0),s("note",e.clearNotes===!0),s("learning",e.clearLearnings===!0),s("file",e.clearFiles===!0),s("test",e.clearTests===!0),s("doc",e.clearDocs===!0),s("reminder",e.clearReminders===!0),s("event",e.clearEvents===!0),s("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let o=i_(e.unset,t,n);for(let i of o.optionKeys)s(i,!0)}return r}function VS(e,t,n,r,s){let o=Lr(e,n);if(!o)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=mn(o,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let a=HS(t,r,s);for(let c of i.disabled)if(a.has(t_(c,e)))throw new l(`Option ${he("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of i.required)if(!a.has(t_(c,e)))throw new l(`Missing required option ${he("update",c)} for type "${e}"`,d.USAGE)}var WS=new Set(["order","rank"]),YS=Pi.filter(e=>!WS.has(e)),c_=["tags","closeReason",...YS],JS=["title","description","body","status","closeReason","completedAt","priority","type",...Pi,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],XS=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>Q(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>En(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],QS=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>we(uo(e),cn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>fo(e)}],ZS=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>we(po(e),dn,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>_o(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function rc(e,t,n){for(let r of e){let s=t[r.optionKey],o=n.clearItemMetadataKeys.has(r.metadataKey);if(!(s===void 0&&!o)){if(o){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof s!="string")throw new l(`${he("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(s,n):s.trim(),n.changedFields.push(r.metadataKey)}}}async function eE(e){let t=Le();return IS({...e,body:await t.resolveValue(e.body,"--body"),dep:await t.resolveList(e.dep,"--dep"),depRemove:await t.resolveList(e.depRemove,"--dep-remove"),comment:await t.resolveList(e.comment,"--comment"),note:await t.resolveList(e.note,"--note"),learning:await t.resolveList(e.learning,"--learning"),file:await t.resolveList(e.file,"--file"),test:await t.resolveList(e.test,"--test"),doc:await t.resolveList(e.doc,"--doc"),reminder:await t.resolveList(e.reminder,"--reminder"),event:await t.resolveList(e.event,"--event"),typeOption:await t.resolveList(e.typeOption,"--type-option"),field:await t.resolveList(e.field,"--field")})}function tE(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function tc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new l(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,d.USAGE);if(e.enabled&&e.clearEnabled)throw new l(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,d.USAGE)}function oc(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new l("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",d.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new l("--replace-deps requires at least one --dep entry",d.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new l("--replace-deps cannot be combined with --dep-remove",d.USAGE);tc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),tc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),tc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function nE(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new l(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,d.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function rE(e){let t={};for(let n of c_)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function sE(e,t){let n=rE(e);for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=Do.get(r)??r;throw new l(`Cannot combine --unset ${o} with ${he("update",r)}`,d.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --add-ac",d.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --remove-ac",d.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new l("Cannot combine --unset tags with --remove-tags",d.USAGE)}}function oE(e){let t=(n,r)=>{let s=Do.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;go(n,he("update",r),o)};for(let n of c_)t(e[n],String(n));t(e.order??e.rank,"order"),be(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),be(e.event,"--event","Use --clear-events to clear linked events.")}function iE(e,t){let n={};for(let r of JS)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.runtimeFields=Object.keys(t).length>0,n}async function aE(e){let t=await D(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await ot(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await K(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function cE(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function dE(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new l("--order and --rank must match when both are provided",d.USAGE)}async function lE(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Gs(e.options.parent);if(qs(e.id,t,e.settings.id_prefix),await D(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=ge(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:js(r,e.parentReferencePolicy).warnings}}function mE(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function uE(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await D(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await ot(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await K(t,{schema:e.settings.schema}),r=e.options.type!==void 0?pe(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",s=PS({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return s?[s]:[]}async function pE(e){if(!e.fieldFlags.status||W(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],s=[];if(n.length>0){let a=await at(e.id,{...e.options,status:void 0,closeReason:void 0,message:void 0},e.global);s=a.changed_fields,r.push(...a.warnings)}let o=await it(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...e.workflowTransitionWarnings,...r,...o.warnings,"auto_routed_from_update_to_close"];return{item:o.item,changed_fields:[...s,...o.changed_fields],warnings:i}}function fE(e,t,n,r){return t.title!==void 0&&(e.metadata.title=ec(t.title,"--title"),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),W(e.metadata.status,n)??e.metadata.status}function _E(e,t,n,r,s){let o=OS(n,t.statusRegistry);if(e.metadata.status=o,s.push("status"),o===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,s.push("closed_at","completed_at");return}!se(o,t.statusRegistry)&&se(r,t.statusRegistry)&&e.metadata.closed_at!==void 0&&(delete e.metadata.closed_at,s.push("closed_at"),e.metadata.completed_at!==void 0&&(delete e.metadata.completed_at,s.push("completed_at")))}function hE(e,t,n,r){if(t.options.status!==void 0&&_E(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!se(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=Q(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function gE(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let s=t.options.closeReason?.trim()??"";if(s.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=s}r.push("close_reason");return}t.options.status!==void 0&&se(n,t.statusRegistry)&&!se(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function yE(e,t,n,r){hE(e,t,n,r),gE(e,t,n,r)}function bE(e,t,n){let r=pe(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=BS(t.options.priority),n.push("priority")),t.options.type!==void 0){let s=pe(t.options.type,t.typeRegistry);if(!s)throw new l(kt(t.options.type,t.typeRegistry.types,St(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=s,r=s,n.push("type")}return VS(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),wE(e,t,r,n),r}function wE(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let o=vo(t.options.typeOption??[]),i=zn(n,o,t.typeRegistry);if(i.errors.length>0)throw new l(i.errors.join("; "),d.USAGE);e.metadata.type_options=i.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let s=zn(n,e.metadata.type_options,t.typeRegistry);if(s.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${s.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=s.normalized}function vE(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){let s=new Set(r.map(o=>e_(o)));for(let o of t.dependencyUpdates.additions){let i=e_(o);s.has(i)||(r.push(o),s.add(i))}}t.dependencyRemovals.length>0&&(r=r.filter(s=>!t.dependencyRemovals.some(o=>zS(s,o)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function kE(e,t,n){nc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),nc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),nc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function nc(e,t,n,r,s,o){n===void 0&&!s.has(t)||(s.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],o.push(t))}function SE(e,t,n){n_(e,"files",t.options.file,t.fileUpdates.values,jS,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),EE(e,t,n),n_(e,"docs",t.options.doc,t.docUpdates.values,qS,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function n_(e,t,n,r,s,o,i,a){if(!(n===void 0&&!i.has(t))){if(o)e.metadata[t]=r;else if(i.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(u=>s(u)));for(let u of r){let p=s(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function EE(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=r_(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=r_([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function r_(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let s=KS(r);n.has(s)||(t.push(r),n.add(s))}return t}function TE(e,t,n){let r=t.options.addTags,s=t.options.removeTags,o=Array.isArray(r)&&r.length>0||Array.isArray(s)&&s.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||o){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Rt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=zs(Sn(i,r),s),n.changedFields.push("tags")}rc(XS,t.options,n),CE(e,t,n.changedFields)}function AE(e,t,n){let r=t.options.addAc,s=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(s)&&s.length>0))return;let o=Ks(kn(e.metadata.acceptance_criteria),r,s);if(o.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${o.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:o.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let i=o.criteria.join("; ");e.metadata.acceptance_criteria!==i&&(i===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=i,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function CE(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let s=ie(r??"","order");if(!Number.isInteger(s))throw new l("Order must be an integer",d.USAGE);e.metadata.order=s}n.push("order")}}function RE(e,t,n,r){IE(e,t,n.changedFields),xE(e,t,n.changedFields),rc(QS,t.options,n),s_(e,t,"sprint",r,n.changedFields),s_(e,t,"release",r,n.changedFields),OE(e,t,n.changedFields),rc(ZS,t.options,n)}function IE(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new l("--assignee must not be empty. Use --unset assignee to clear it.",d.USAGE);e.metadata.assignee=r}n.push("assignee")}}function xE(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function s_(e,t,n,r,s){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let o=Hs(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=o.value,r.push(...o.warnings)}s.push(n)}}function OE(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&GS(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function PE(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=bo(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=wo(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function NE(e,t,n){o_(e,t.runtimeFieldRegistry.definitions.map(s=>s.metadata_key),t.clearItemMetadataKeys,n),o_(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[s,o]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(s)){let i=s.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===s)?.cli_flag??i;throw new l(`Cannot combine --unset ${i} with --${c}`,d.USAGE)}tt(e[s],o)||(e[s]=o,n.push(s))}let r=Pr(t.options.field,t.extensionRegistrations);for(let s of Object.keys(r))if(t.clearItemMetadataKeys.has(s))throw new l(`Cannot combine --unset ${s.replaceAll("_","-")} with --field ${s}=...`,d.USAGE);for(let[s,o]of Object.entries(r))tt(e[s],o)||(e[s]=o,n.push(s))}function o_(e,t,n,r){for(let s of t)!n.has(s)||e[s]===void 0||(delete e[s],r.push(s))}function LE(e,t){let n=structuredClone(e.metadata),r=e.body,s=[],o=[],i=fE(e,t.options,t.statusRegistry,s),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:s,nowValue:t.nowValue};yE(e,t,i,s),bE(e,t,s),vE(e,t,s),kE(e,t,s),SE(e,t,s),TE(e,t,c),AE(e,t,c),RE(e,t,c,o),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&cr(e.metadata.id,e.metadata.dependencies),W(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,s.includes("assignee")||s.push("assignee")),PE(e,t,s),NE(a,t,s);try{Nr(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(p){throw new l(p instanceof Error?p.message:"Invalid extension item field values",d.USAGE)}let m=e.metadata,u=[...new Set(s)].filter(p=>p==="body"?e.body!==r:!tt(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&o.push(`acceptance_criteria_replaced:${kn(n.acceptance_criteria).length}:${kn(m.acceptance_criteria).length}`),{changedFields:u,warnings:o}}async function d_(e,t,n,r={}){t=await eE(t);let s=T(process.cwd(),n.path);await cE(s);let o=await A(s),i=M(o.schema),a=Ve(o.schema),c=I(),m=bt(c),u=x(o,c),p=o.governance.workflow_enforcement??"off",f=p==="off"?[]:Am(o.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][o.validation.parent_reference],h=i_(t.unset,a,m),y=new Set(h.optionKeys),g=new Set(h.metadataKeys);oc(t),nE({definitions:tE(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:g}),xS(e,t,g),sE(t,h),oE(t);let b=R(t.author,o.author_default),v=new Date,E=v.toISOString(),N=Go(t.dep,o.id_prefix,E,b);cr(e,N.additions);let O=await Yt({pmRoot:s,dependencies:N.additions,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:o.schema}),j=MS(t.depRemove,o.id_prefix),$=tn("--comment",t.comment,E,b),xe=t.ownershipMetadataBypass===!0&&$.values?{...$,values:$.values.map(Ue=>({...Ue,author:b}))}:$,te=tn("--note",t.note,E,b),_e=tn("--learning",t.learning,E,b),ce=Xa(t.file),Qe=Qa(t.test),ut=Za(t.doc),pt=[],ft=await lE({id:e,options:t,unsetTargets:h,pmRoot:s,settings:o,typeRegistry:u,parentReferencePolicy:_}),_t=await US(t.blockedBy,g.has("blocked_by"),s,o.id_prefix,o.item_format,u.type_to_folder),hi=_t.id,gi=[...ft.warnings,...mE(_t)],jn=Es(t,a,t.runtimeFieldCommands),ht=iE(t,jn);if(!Object.values(ht).some(Boolean))return aE({pmRoot:s,id:e,settings:o,typeRegistry:u});pt.push(...await uE({options:t,fieldFlags:ht,workflowEnforcement:p,typeWorkflows:f,statusRegistry:i,typeRegistry:u,pmRoot:s,id:e,settings:o}));let ke=await pE({options:t,fieldFlags:ht,statusRegistry:i,workflowTransitionWarnings:pt,global:n,id:e});if(ke)return ke;dE(t);let Oe=ht.dep||ht.depRemove||ht.blockedBy?await oe(s,o.item_format,u.type_to_folder,void 0,o.schema):void 0,$t,P,gt=await xu({pmRoot:s,settings:o,typeToFolder:u.type_to_folder,id:e,op:FE(t,r),author:b,message:t.message,resolveHistoryContext:()=>P,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(Ue){return $t=$E({document:Ue,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),P=$t?{recurrence:$t}:void 0,Oe=Oe?.map(Tr=>Tr.id===Ue.metadata.id?structuredClone(Ue.metadata):Tr),LE(Ue,{options:t,settings:o,typeRegistry:u,statusRegistry:i,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:g,dependencyUpdates:N,dependencyRemovals:j,commentUpdates:xe,noteUpdates:te,learningUpdates:_e,fileUpdates:ce,testUpdates:Qe,docUpdates:ut,resolvedParentValue:ft.resolvedParentValue,resolvedBlockedByDependencyId:hi,runtimeFieldUpdates:jn,nowValue:v,nowIso:E,author:b,pmRoot:s})}}),qn=Oe?to(Oe,Oe.map(Ue=>Ue.id===gt.item.id?gt.item:Ue),gt.item.id):[];return{item:gt.item,changed_fields:gt.changedFields,warnings:[...pt,...gi,...O,...qn,...gt.warnings],...$t===void 0?{}:{lifecycle_transition:$t}}}function FE(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function $E(e){if(e.recurrenceReason===void 0)return;let t=W(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!se(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,d.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=W(n,e.statusRegistry)??n,s=e.document.metadata,o=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(i=>{let a=s[i];return typeof a=="string"?[[i,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:o}}async function at(e,t,n){return d_(e,t,n)}async function l_(e,t,n,r){let s=await d_(e,t,n,{recurrenceReason:r});if(s.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,d.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...s,lifecycle_transition:s.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e797d654-df89-554b-876b-cb2faa350bd0")}catch{}})();var u_=1,ac="update-many",ME=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),DE=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),UE={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},GE=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],jE={close_reason:"close_reason","close-reason":"close_reason",deadline:"deadline",estimate:"estimated_minutes",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",ac:"acceptance_criteria",definition_of_ready:"definition_of_ready","definition-of-ready":"definition_of_ready",order:"order",rank:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",why_now:"why_now","why-now":"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blocked_by:"blocked_by","blocked-by":"blocked_by",blocked_reason:"blocked_reason","blocked-reason":"blocked_reason",unblock_note:"unblock_note","unblock-note":"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",repro_steps:"repro_steps","repro-steps":"repro_steps",resolution:"resolution",expected_result:"expected_result","expected-result":"expected_result",actual_result:"actual_result","actual-result":"actual_result",affected_version:"affected_version","affected-version":"affected_version",fixed_version:"fixed_version","fixed-version":"fixed_version",component:"component",regression:"regression",customer_impact:"customer_impact","customer-impact":"customer_impact",type_options:"type_options","type-options":"type_options",tags:"tags"},p_=e=>{let t={};for(let[n,r]of Object.entries(e))ME.has(n)||r!==void 0&&(t[n]=r);return t},qE=e=>Object.keys(p_(e)).length>0,f_=e=>typeof e=="string"?e.trim():e,KE=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},ic=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},zE=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??f_(e)},BE={priority:KE,estimatedMinutes:ic,order:ic,rank:ic,regression:zE},HE=(e,t)=>{if(t!==void 0)return(BE[e]??f_)(t)},VE=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return jE[t]??t},jo=(e,t)=>tt(e,t),WE=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],YE=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,JE=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",m_=(e,t)=>t===void 0?void 0:e[t],Ln=e=>Array.isArray(e)?e.length:0,XE=(e,t,n)=>{let r=n[e.addKey],s=m_(n,e.removeKey),o=Ln(r),i=Ln(s),a=n[e.clearKey]===!0,c=m_(n,e.replaceKey)===!0;if(![a,c,o>0,i>0].includes(!0))return;let m=WE(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:JE({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:o,remove_count:i,before_count:YE(e.field,m)}}},QE=(e,t)=>{let n=[];for(let r of GE){let s=XE(r,e,t);s!==void 0&&n.push(s)}return n},ZE=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],eT=(e,t)=>{if(![t.tags!==void 0,Ln(t.addTags)>0,Ln(t.removeTags)>0].includes(!0))return;let n=ZE(e.tags),r=t.tags===void 0?n:Rt(t.tags),s=Sn(r,t.addTags),o=zs(s,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!jo(i,o))return{field:"tags",before:n,after:o}},tT=(e,t)=>{let n=e.acceptance_criteria,r=Ks(kn(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let s=r.criteria.join("; ");if(!jo(typeof n=="string"?n:"",s))return{field:"acceptance_criteria",before:n,after:s}},nT=(e,t,n)=>{for(let[r,s]of Object.entries(UE)){let o=n[r];if(o===void 0)continue;let i=t[s],a=HE(r,o);jo(i,a)||e.push({field:s,before:i,after:a})}},rT=(e,t,n,r)=>{let s=Es(n,r,["update_many"]);for(let[o,i]of Object.entries(s)){let a=t[o];jo(a,i)||e.push({field:o,before:a,after:i})}},sT=(e,t,n)=>{for(let r of n??[]){let s=VE(r),o=t[s];o!==void 0&&e.push({field:s,before:o,after:null})}},oT=(e,t,n={})=>{let r=e,s=[],o=eT(r,n);if(o&&s.push(o),nT(s,r,n),Ln(n.addAc)>0||Ln(n.removeAc)>0){let i=tT(r,n);i!==void 0&&s.push(i)}return s.push(...QE(r,n)),rT(s,r,n,t),sT(s,r,n.unset),{id:e.id,changes:s}},iT=(e,t)=>ju(e,t,{strict:!0,flagLabel:"--filter-status"}),aT=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)},cT=[({update:e})=>{e.priority!==void 0&&Tn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,I());if(!pe(e.type,r))throw new l(kt(e.type,r.types,St(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!W(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,d.USAGE)}},({update:e})=>{e.deadline!==void 0&&Q(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&En(e.estimatedMinutes,"estimated-minutes")}],dT=(e,t,n,r)=>{let s={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let o of cT)o(s)},lT=async e=>{let t=await $s(e.pmRoot,ac,e.rollbackId,u_),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Ms(t.items,(s,o)=>Wt(s,o,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...qt({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},mT=async e=>{let t={schema_version:u_,id:e.checkpointId,created_at:e.nowValue,author:R(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Fs(e.pmRoot,ac,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},uT=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(s=>s.trim()).filter(s=>s.length>0))],r=new Set(t.map(s=>s.id));return n.filter(s=>!r.has(s))},cc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},pT=async e=>{let t=T(process.cwd(),e.path);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:M(n.schema),runtimeFieldRegistry:Ve(n.schema)}},fT=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(nr(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",d.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",d.USAGE);return lT({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},_T=async e=>{iT(e.options.status,e.runtime.statusRegistry);let t=await It(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(s=>{let o=oT(s,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?o:{...o,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await It(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(s=>s.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:uT(e.options.list?.ids,r)}},hT=e=>({outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...cc(e)}),gT=e=>({...qt({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...cc(e)}),yT=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,s=new Set(e.plans.filter(o=>o.changes.length>0).map(o=>o.id));for(let o of e.items){if(!s.has(o.id)){t.push({id:o.id,status:"skipped"});continue}try{let i=await at(o.id,{...e.options.update,message:r,runtimeFieldCommands:["update_many"]},e.global);t.push({id:o.id,status:"updated",changed_fields:i.changed_fields,warnings:i.warnings}),n.push(o.id)}catch(i){t.push({id:o.id,status:"failed",error:un(i)})}}return{rows:t,updatedIds:n}},bT=async e=>{if(e.plan.actionable.length===0)return gT(e.plan);let t=S(),n=Ls(ac,t),r=new Set(e.plan.actionable.map(p=>p.id)),s=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),o=e.options.checkpoint===!1?void 0:await mT({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:s}),i=await yT({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=p=>i.rows.filter(f=>f.status===p).length,c=a("updated"),m=a("skipped"),u=a("failed");return{...qt({applied:c,skipped:m,failed:u,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...o?{checkpoint:o}:{},updated_count:c,skipped_count:m,failed_count:u,rows:i.rows,ids:i.updatedIds,...cc(e.plan)}},__=async(e,t)=>{let n=await pT(t),r=typeof e.rollback=="string"?e.rollback:void 0,s=p_(e.update);if(aT(e.list),r!==void 0)return fT({runtime:n,rollbackId:r,options:e,global:t,updateSummary:s});if(!qE(e.update))throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${DE}).`,d.USAGE);dT(e.update,n.settings,n.statusRegistry,n.pmRoot),oc(e.update);let o=await Yt({pmRoot:n.pmRoot,dependencies:Go(e.update.dep,n.settings.id_prefix,S(),R(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await _T({options:e,global:t,runtime:n,updateSummary:s,dependencyWarnings:o});return await Yt({pmRoot:n.pmRoot,dependencies:Go(e.update.dep,n.settings.id_prefix,S(),R(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:i.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:n.settings.schema}),e.dryRun===!0?hT(i):bT({runtime:n,options:e,global:t,plan:i})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d5ea029-26ef-51bc-bacc-b1d4d807a024")}catch{}})();var wT=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],h_=["brief","standard","deep"],b_="plan-step-",fc="draft",pc=["bug-investigation","feature-implementation","refactoring-sprint"],g_={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function vT(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(g_,t)?g_[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${pc.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${pc[0]}`]});return n.map(r=>({...r}))}function kT(e,t){return t>0?Math.round(e/t*100):0}function w_(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function Me(e){return Array.isArray(e)?e.flatMap(t=>An(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?An(e,{unique:!1}):[]}function ve(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function v_(e,t=fc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ai.find(s=>s===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${Ai.join(", ")}`,d.USAGE);return r}function _c(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ci.find(s=>s===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${Ci.join(", ")}`,d.USAGE);return r}function k_(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ii.find(s=>s===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${Ii.join(", ")}`,d.USAGE);return r}function ST(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ri.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${Ri.join(", ")}`,d.USAGE);return n}function ET(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=h_.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${h_.join(", ")}`,d.USAGE);return n}function TT(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new l("Plan --fields requires a comma-separated list of plan field names",d.USAGE);return t}var dc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function AT(e,t){let n=e,r={},s=[];for(let o of t){let i=o.startsWith("plan.")?o.slice(5):o;if(i.length!==0){if(!dc.has(i)){s.push(o);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(s.length>0)throw new l(`Unknown Plan --fields value(s): ${s.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...dc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:s,suggested_retry:`pm plan show <id> --fields ${[...dc].join(",")}`}});return r}function hc(e,t){let n={};for(let r of e.split(",")){let s=r.trim();if(s.length===0)continue;let o=s.indexOf("=");if(o<=0)throw new l(`Invalid ${t} entry "${s}"; expected key=value`,d.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[s.slice(0,o).trim().toLowerCase()]=s.slice(o+1).trim()}return n}function gc(e){let t=hc(e,"--file");if(!t.path)throw new l("--file requires path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function yc(e){let t=hc(e,"--test");if(!t.command&&!t.path)throw new l("--test requires at least command=<value> or path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function bc(e){let t=hc(e,"--doc");if(!t.path)throw new l("--doc requires path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function CT(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=kT(t.completed,t.total),t}function RT(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${b_}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new l("Could not allocate step id (limit reached)",d.GENERIC_FAILURE)}function Fn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(s=>s.id===n);if(r)return r;if(/^\d+$/.test(n)){let s=Number.parseInt(n,10),o=e.find(i=>i.order===s);if(o)return o}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function y_(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function IT(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],s=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",d.USAGE);for(let i of e.slice().sort((a,c)=>a.order-c.order)){let a=y_(i);if(a){s.push({from_step:i.id,...a});continue}r.push(i)}return{targets:r,skipped:s}}let o=new Set;for(let i of t){let a=Fn(e,i);if(o.has(a.id))continue;o.add(a.id);let c=y_(a);if(c){s.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:s}}function xT(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function OT(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function PT(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function Ae(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=CT(n),s=OT(n),o={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??fc,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:s?{id:s.id,order:s.order,title:s.title,status:s.status}:void 0,blocked_steps:PT(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(o.steps=n),t==="deep"&&(o.decisions=e.plan_decisions??[],o.discoveries=e.plan_discoveries??[],o.validation=e.plan_validation??[]),o}function Ce(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!aa(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function S_(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new l(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,d.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function NT(e){let t=T(process.cwd(),e.path);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=await A(t);return{pmRoot:t,settings:n}}async function E_(e,t){let n=x(e.settings,I()),r=await D(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,d.NOT_FOUND);let s=await K(r,{schema:e.settings.schema});return S_(s.document.metadata),{document:s.document,itemId:r.id}}function LT(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of Me(e.related))t.push(`id=${n},kind=related`);for(let n of Me(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of Me(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function FT(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function $T(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||Me(e.dependsOn).length>0||Me(e.link).length>0}function MT(e){let t=e.stepTitle?.trim()||void 0,n=w_(e.step),r=e.template?.trim()?vT(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(s=>s.title)],templateSteps:r}}function DT(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",d.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${pc[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",d.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function UT(e,t){let n=_c(e.stepStatus,"pending"),r=wc(e,"depends_on"),s=ve(e.file).map(gc),o=ve(e.test).map(yc),i=ve(e.doc).map(bc),a=S();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:s.length>0?s:void 0,tests:o.length>0?o:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function GT(e){let t=MT(e),n=$T(e);if(DT(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[UT(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=S();return{steps:t.stepTitles.map((s,o)=>({id:`${b_}${String(o+1).padStart(3,"0")}`,order:o+1,title:s,body:t.templateSteps[o]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}async function jT(e,t,n){let r=e.title?.trim();if(!r)throw new l("pm plan create requires --title",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let s=v_(e.mode,fc),o=ST(e.harness),i=e.fromSearch?.trim(),a=FT(e),{steps:c,hasPerStepDetailOptions:m}=GT(e);if(c.length===0&&m)throw new l("pm plan create step options require --step-title (or a single --step)",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?R(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:ve(e.file),test:ve(e.test),doc:ve(e.doc),field:ve(e.field),assignee:R(e.author,n.settings.author_default),blockedBy:void 0,dep:LT(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")},_=await xt(f,t),h=await Z({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:R(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let b=["plan_mode"];g.metadata.plan_mode=s,o&&(g.metadata.plan_harness=o,b.push("plan_harness"));let v=e.scope?.trim();v&&(g.metadata.plan_scope=v,b.push("plan_scope"));let E=e.resumeContext?.trim();return E&&(g.metadata.plan_resume_context=E,b.push("plan_resume_context")),g.metadata.plan_steps=c,b.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],b.push("plan_validation")),p&&(g.metadata.assignee=p,b.push("assignee")),{changedFields:b}}}),y=Ae(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Ce(_.item.id,y),warnings:[..._.warnings],generated_at:S()}}async function qT(e,t,n){let r=ET(t.depth),s=TT(t.fields),{document:o,itemId:i}=await E_(n,e),a=Ae(o.metadata,s===null?r:"deep");return{action:"show",plan:s===null?a:AT(a,s),next_actions:Ce(i,a),warnings:[],generated_at:S()}}function KT(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,s])=>[r,JSON.stringify(s)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function Ye(e){let t=R(e.options.author,e.ctx.settings.author_default),n,r=await Z({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(s){S_(s.metadata);let o=M(e.ctx.settings.schema);if(se(s.metadata.status,o)||aa(s.metadata.plan_mode))throw new l(`Plan ${s.metadata.id} is terminal (status=${s.metadata.status}, plan_mode=${s.metadata.plan_mode??"unset"}) and cannot be mutated.`,d.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let i=(s.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(s.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,s);n=c.resultStep;let m=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));s.metadata.plan_steps=m;let u=KT(a,s.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function zT(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let s=_c(t.stepStatus,"pending"),o=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await Ye({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;T_(u,void 0,s,o);let f=BT(u,t,{order:p,title:r,status:s});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Ae(i.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Ce(c,m),warnings:[],generated_at:S()}}function T_(e,t,n,r){if(n!=="in_progress"||r)return;let s=e.find(o=>o.id!==t&&o.status==="in_progress");if(s)throw new l(`Plan already has step ${s.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function BT(e,t,n){let r=wc(t,"depends_on"),s=ve(t.file).map(gc),o=ve(t.test).map(yc),i=ve(t.doc).map(bc),a=S();return{id:RT(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:s.length>0?s:void 0,tests:o.length>0?o:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function wc(e,t){let n=Me(e.dependsOn).map(u=>({id:u,kind:t})),r=Me(e.related).map(u=>({id:u,kind:"related"})),s=Me(e.blocks).map(u=>({id:u,kind:"blocks"})),o=Me(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=Me(e.link),a=k_(e.linkKind,t),c=e.linkNote?.trim(),m=i.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...s,...o,...m]}async function lc(e,t,n,r){let{document:s,resultStep:o,itemId:i}=await Ye({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=Fn(c,r.stepRef),p=S(),f=r.finalStatus??_c(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return T_(c,u.status==="in_progress"?u.id:void 0,f,_),HT(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Ae(s.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:o,next_actions:Ce(i,a),warnings:[],generated_at:S()}}function HT(e,t,n,r){VT(e,t,n),WT(e,t),e.status=n,e.updated_at=r,YT(e,n,r)}function VT(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new l("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",d.USAGE)}function WT(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=t.stepOwner.trim()||void 0),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let r=ve(t.file).map(gc),s=ve(t.test).map(yc),o=ve(t.doc).map(bc);r.length>0&&(e.files=mc(e.files,r)),s.length>0&&(e.tests=mc(e.tests,s)),o.length>0&&(e.docs=mc(e.docs,o))}function mc(e,t){let n=[...e??[]],r=new Set(n.map(s=>JSON.stringify(s)));for(let s of t){let o=JSON.stringify(s);r.has(o)||(r.add(o),n.push(s))}return n}function YT(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function JT(e,t,n,r,s){let{document:o,itemId:i}=await Ye({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${s}`,mutator(c){let m=Fn(c,r),u=c.filter(f=>f.id!==m.id),p=Math.max(1,Math.min(s,u.length+1));return u.splice(p-1,0,m),u.forEach((f,_)=>{f.order=_+1,f.updated_at=S()}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=Ae(o.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Ce(i,a),warnings:[],generated_at:S()}}async function XT(e,t,n,r){let{document:s,itemId:o}=await Ye({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=Fn(a,r),m=a.filter(u=>u.id!==c.id);return m.forEach((u,p)=>{u.order=p+1}),a.length=0,a.push(...m),{changedSteps:[c.id]}}}),i=Ae(s.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Ce(o,i),warnings:[],generated_at:S()}}async function QT(e,t,n,r){let s=wc(t,k_(t.linkKind,"related"));if(s.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let o=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await Ye({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Fn(u,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of s){let b=h(g);y.has(b)||(_.push(g),y.add(b))}if(f.linked_items=_,f.updated_at=S(),o){let g=p.metadata.dependencies??[],b=E=>`${E.kind}:${E.id}`,v=new Set(g.map(b));for(let E of s){let N=E.kind==="depends_on"?"blocked_by":E.kind,O={id:E.id,kind:N,created_at:S(),author:R(t.author,n.settings.author_default)};v.has(b(O))||(g.push(O),v.add(b(O)))}p.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),m=Ae(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ce(a,m),warnings:[],generated_at:S()}}async function ZT(e,t,n,r){let s=Me(t.link);if(s.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:o,itemId:i,resultStep:a}=await Ye({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=Fn(m,r),p=(u.linked_items??[]).filter(f=>!s.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=S(),{changedSteps:[u.id],resultStep:u}}}),c=Ae(o.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Ce(i,c),warnings:[],generated_at:S()}}async function uc(e,t,n,r){let s=xT(r,t);if(!s){let m=`--${r}-text`,u=`--${r}`;throw new l(`pm plan ${r} requires ${m}`,d.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${m} "..."`,`pm plan ${r} <plan-id> ${u} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${m} <value>`}})}let o=R(t.author,n.settings.author_default),{document:i,itemId:a}=await Ye({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,u){let p=S();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:o,decision:s,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:o,text:s}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:s,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Ae(i.metadata,"deep");return{action:r,plan:c,next_actions:Ce(a,c),warnings:[],generated_at:S()}}async function eA(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:s,itemId:o}=await Ye({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Ae(s.metadata,"brief");return{action:"resume",plan:i,next_actions:Ce(o,i),warnings:[],generated_at:S()}}async function tA(e,t,n){let r=v_(t.mode??"approved","approved"),{document:s,itemId:o}=await Ye({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(a,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Ae(s.metadata,"brief");return{action:"approve",plan:i,next_actions:Ce(o,i),warnings:[],generated_at:S()}}function A_(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function nA(e,t){let n=Ae(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ce(e.itemId,n),warnings:A_(t),generated_at:S()}}function rA(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let s of n.linked_items??[]){let o=s.kind==="blocked_by"||s.kind==="blocks"||s.kind==="related"||s.kind==="discovered_from"?s.kind:"related";r.push(`id=${s.id},kind=${o}`)}return r}async function sA(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let s of ve(e.options.field)){let o=s.indexOf("=");if(o<=0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.USAGE);let c=i.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.USAGE);let[m,...u]=c,p=`${m}${u.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(p))throw new l(`Invalid --field entry "${s}"; "${p}" is reserved by materialize and cannot be overridden`,d.USAGE);n[p]=a}for(let s of e.targets){let o=await xt({...n,title:s.title,description:s.body?.trim()||s.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${s.id}`,dep:rA(e.parent,e.planItemId,s)},{path:e.pmRoot});t.push({id:o.item.id,title:o.item.title,type:e.resolvedTypeName,parent:o.item.parent,tags:o.item.tags??[],from_step:s.id})}return t}function oA(e,t,n){for(let r of t){let s=n.find(a=>a.from_step===r.id);if(!s)continue;let o=e.find(a=>a.id===r.id);if(!o)continue;let i=o.linked_items??[];i.push({id:s.id,kind:"implements",note:`materialized as ${s.type}`}),o.linked_items=i,o.updated_at=S()}}async function iA(e,t,n){let r=Me(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let s=t.materializeType?.trim()||"Task",o=x(n.settings,I()),i=pe(s,o);if(!i)throw new l(`Invalid --materialize-type "${s}"`,d.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await E_(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=IT(u,r);if(p.length===0){if(f.length>0)return nA(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await sA({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await Ye({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(b){return oA(b,p,_),{changedSteps:p.map(v=>v.id)}}}),g=Ae(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ce(y,g),warnings:A_(f),generated_at:S()}}function aA(e){if(e.subcommand==="create")return e;let t=w_(e.options.step);if(t.length>1)throw new l(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,d.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:{...e.options,stepTitle:t[0]}}:e}function ct(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function nn(e,t){let n=ct(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function cA(e){let t=nn(e,"reorder-step");if(e.reorderTo===void 0)throw new l("pm plan reorder-step requires <plan-id> <step> <new-order>",d.USAGE);return{...t,reorderTo:e.reorderTo}}var dA={create:(e,t)=>jT(e.options,e.global,t),show:(e,t)=>qT(ct(e,"show"),e.options,t),"add-step":(e,t)=>zT(ct(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=nn(e,"update-step");return lc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=nn(e,"complete-step");return lc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=nn(e,"block-step");return lc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=cA(e);return JT(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=nn(e,"remove-step");return XT(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=nn(e,"link");return QT(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=nn(e,"unlink");return ZT(n.id,e.options,t,n.stepRef)},decision:(e,t)=>uc(ct(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>uc(ct(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>uc(ct(e,"validation"),e.options,t,"validation"),resume:(e,t)=>eA(ct(e,"resume"),e.options,t),approve:(e,t)=>tA(ct(e,"approve"),e.options,t),materialize:(e,t)=>iA(ct(e,"materialize"),e.options,t)};function lA(e){let t=dA[e];if(!t)throw Te({command_path:"plan",token:e,allowed:wT});return t}async function C_(e){let t=await NT(e.global),n=aA(e);return lA(n.subcommand)(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4eb2056a-4444-514a-a0db-79b8875c3d65")}catch{}})();function mA(e,t){return[...new Set([...Or.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,s)=>r.localeCompare(s))}function uA(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function vc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await D(r,e,s.id_prefix,s.item_format,o.type_to_folder);if(!i)throw await ot(r,e,s.id_prefix,o.type_to_folder);let a=await K(i,{schema:s.schema}),c=a.document.metadata,m=S(),u=R(t.author,s.author_default),p=await Jn(r,s.id_prefix,{tokenLength:s.ids.token_length,typeToFolder:o.type_to_folder,probeExisting:!1}),f=M(s.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let h={...c,id:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let y=bt(I()),g=We({metadata:h,body:a.document.body},{schema:s.schema,extensionFieldNames:y}),b=await In({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=mA(g.metadata,g.body),E=Gt(r,g.metadata.type,p,s.item_format,o.type_to_folder),N=Se(r,p),O=await Pe(r,p,s.locks.ttl_seconds,u,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),j={metadata:{},body:""},$,xe;try{let te=await wn(r,u,{required:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await In({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1});let _e=await D(r,p,s.id_prefix,s.item_format,o.type_to_folder);if(_e)throw new l(`Cannot copy to ${p}: an item with that id already exists at ${_e.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${_e.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await ue(E,je(g,{format:s.item_format,schema:s.schema,extensionFieldNames:y}));try{let ce=qe({nowIso:m,author:u,op:"create",before:j,after:g,message:uA(i.id,t.message)});await Tt(N,ce)}catch(ce){throw await ln(E),ce}xe=await vn({pmRoot:r,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:E,document:g})}finally{await te()}$=[...await z({path:E,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:j,after:g,changed_fields:v}),...await z({path:N,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:j,after:g,changed_fields:v})],fn({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Kt(g.metadata,v),changed_fields:v})}finally{await O()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:v,warnings:[...no(b),...xe,...$],...b===void 0?{}:{similarity_advisory:b}}}import qo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="14aa55e1-cb5f-55ea-bf4c-412217d87449")}catch{}})();async function kc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=R(t.author,s.author_default),i=await Ou({pmRoot:r,settings:s,id:e,author:o,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?qo.relative(r,i.targetPath).split(qo.sep).join("/"):void 0;return{item:i.item,changed_fields:i.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:i.item.status,...a?{target_path:a}:{},history_retained:qo.relative(r,Se(r,i.item.id)).split(qo.sep).join("/"),tombstone_retention:"retain_append_only",warnings:i.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f43df79-0b27-53b3-b8bd-9f2a35561733")}catch{}})();async function pA(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}async function Sc(e,t,n){let r=T(process.cwd(),n.path);if(await pA(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",d.USAGE);let p=await A(r),f=gn(R(void 0,p.author_default));return await cu(r),await eo({pmRoot:r,settings:p,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await ks(r);if(p===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let f=await fA(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let o=await A(r),i=x(o,I()),a=await D(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await ot(r,e,o.id_prefix,i.type_to_folder);let c=ge(a.id,o.id_prefix),m=await K(a,{schema:o.schema}),u=R_(m.document.metadata.title);return await au(r,c),await eo({pmRoot:r,settings:o,principal:gn(R(void 0,o.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function fA(e,t){let n=await A(e),r=x(n,I()),s=await D(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!s)return null;let o=await K(s,{schema:n.schema});return R_(o.document.metadata.title)}function R_(e){return e.trim().length>0?e:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f4f5f10-793d-5baa-8985-c0ec855b16c4")}catch{}})();var I_=new Set(["item_format"]),x_=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),_A=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","telemetry_tracking"]),hA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","telemetry_tracking"]),gA={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function yA(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(I_.has(t)||x_.has(t)||_A.has(t)||t==="context")return t}function bA(e){let t=e.trim().toLowerCase();return gA[t]??e}function O_(e,t){let n=yA(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:I_.has(n)?{routable:!0,flag:"format",value:t}:x_.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:hA.has(n)?bA(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9a8d99c-df4e-55b3-81f5-27124d598c5f")}catch{}})();var P_=["project","global"],dt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],context:["context"]},wA=Object.keys(dt).map(e=>dt[e][0]),vA=Object.fromEntries(Object.keys(dt).flatMap(e=>dt[e].map(t=>[t,e]))),kA={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",telemetry_tracking:"Telemetry usage reporting policy.",context:"Context command settings (depth, section toggles, limits)."},SA=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],EA=new Set(["metadata_required_fields",...SA]),TA=new Set(["test_result_tracking","telemetry_tracking"]),AA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),CA=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),RA=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),IA=new Set(["governance_preset","governance_create_default_type"]),M_=e=>EA.has(e),xA=e=>CA.has(e),OA=e=>RA.has(e),PA=e=>IA.has(e);function Ec(e){return e==="definition_of_done"||M_(e)}function NA(e){if(P_.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${P_.join(", ")}`,d.USAGE)}function LA(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Te({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function FA(e){let t=vA[e];if(t)return t;let n=Mi.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${wA.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function $A(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,s)=>r.localeCompare(s));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",d.USAGE);return n}function MA(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",d.USAGE):new l("Config set item-format requires --format toon",d.USAGE)}function D_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",d.USAGE)}function U_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set test-result-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function G_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function Ac(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",d.USAGE)}function j_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",d.USAGE)}function q_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",d.USAGE)}function K_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",d.USAGE)}function z_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",d.USAGE)}function B_(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-workflow-enforcement requires one of: off, warn, strict",d.USAGE)}function H_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",d.USAGE)}function V_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",d.USAGE)}function N_(e,t){switch(e){case"history_missing_stream_policy":return D_(t);case"sprint_release_format_policy":return ia(t);case"parent_reference_policy":case"governance_parent_reference_policy":return Us(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Ac(t);case"governance_preset":return j_(t);case"governance_ownership_enforcement":return q_(t);case"governance_create_mode_default":return K_(t);case"governance_close_validation_default":return z_(t);case"governance_require_close_reason":return V_(t);case"governance_workflow_enforcement":return B_(t);case"governance_force_required_for_stale_lock":return H_(t);case"test_result_tracking":return U_(t);case"telemetry_tracking":return G_(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var L_={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},DA=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function UA(e,t){let n=[...new Set((e??[]).map(o=>o.trim()).filter(o=>o.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",d.USAGE);let r=n.map(o=>o.toLowerCase().replaceAll("-","_")),s=r.filter(o=>L_[o]===void 0);if(s.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${s.join(", ")}. Supported values: ${DA.join(", ")}`,d.USAGE);return[...new Set(r.map(o=>L_[o]))].sort((o,i)=>o.localeCompare(i))}function GA(e,t,n){let r=[...new Set((t??[]).map(s=>s.trim().toLowerCase()).filter(s=>s.length>0))].sort((s,o)=>s.localeCompare(o));if(n){if(r.length>0)throw new l(`Config set ${dt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${dt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function jA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function qA(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,d.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,d.USAGE);return FA(t)}function W_(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var KA={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function Cc(e,t){return KA[t](e)}function De(e,t){return t.length===0?e:{...e,warnings:t}}async function zA(e,t){let n=process.cwd(),r=e==="project"?T(n,t.path):et(n),s=C(r);if(e==="project"&&!await k(s))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);return{pmRoot:r,settingsPath:s}}function BA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,d.USAGE)}function F_(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new l(`Context ${t} must be a positive integer`,d.USAGE)}async function HA(e,t,n,r,s){let o=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!xi.includes(c))throw new l(`Context --default-depth must be one of ${xi.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,o=!0)}if(t.activityLimit!==void 0){let c=F_(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,o=!0)}if(t.staleThresholdDays!==void 0){let c=F_(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,o=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of a){let u=BA(m);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,o=!0)}}return o&&await Ee(n.pmRoot,e,"config:set:context"),De({scope:r,key:"context",context_settings:{default_depth:i.default_depth,activity_limit:i.activity_limit,stale_threshold_days:i.stale_threshold_days,sections:{...i.sections}},settings_path:n.settingsPath,changed:o},s)}function VA(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,d.USAGE);return{...n,value:t}}function WA(e,t,n,r,s,o){if(s===void 0)return o;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,d.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',d.USAGE);if(r)return VA(t,s,o);W_(n);let i=O_(n,s);if(!i.routable)throw new l(i.reason,d.USAGE);if(i.flag==="criterion"){if(o.criterion!==void 0&&o.criterion.length>0)throw new l(`Config set ${t} received both positional value "${s}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...o,criterion:i.values}}if(i.flag==="format")return{...o,format:i.value};if(o.policy!==void 0&&N_(n,o.policy)!==N_(n,i.value))throw new l(`Config set ${t} received both positional value "${s}" and --policy "${o.policy}". Pass only one.`,d.USAGE);return{...o,policy:i.value}}function YA(e){let t=Object.keys(dt).map(r=>({key:r,aliases:dt[r],value_kind:r==="context"?"object":Ec(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:Ec(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:kA[r],value:Cc(e.settings,r)})),n=Mi.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Di(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return De({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function JA(e){let t=Object.fromEntries(Object.keys(dt).map(n=>[n,Cc(e.settings,n)]));return De({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function XA(e,t){let n=Cc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?De({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?De({...r,context_settings:n},e.warnings):Array.isArray(n)?De({...r,criteria:n},e.warnings):De({...r,policy:n},e.warnings)}async function QA(e,t,n,r){if(t==="get"){let a=Di(e.settings,n);return De({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let s=r.value;if(typeof s!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let o=Tm(n,s);if(!o.ok)throw new l(o.error.message,d.USAGE);let i=gs(e.settings,n,o.parsed.value);return i&&await Ee(e.target.pmRoot,e.settings,`config:set:${n.path}`),De({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:o.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function X(e,t,n){t&&await Ee(e.target.pmRoot,e.settings,n)}function $_(e,t,n){return e!==n||t!==n}function ae(e,t,n,r){return De({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Tc(e,t,n,r){return De({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function ZA(e,t){let n=MA(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,s;if(r){let o=x(e.settings,I()),i=await Ku(e.target.pmRoot,n,"config:set:item_format:migrate",o.type_to_folder,e.settings.schema);s={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await Ee(e.target.pmRoot,e.settings,"config:set:item_format")}return De({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:s,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function eC(e,t,n){if(t==="history_missing_stream_policy"){let o=D_(n.policy),i=e.settings.history.missing_stream!==o;return e.settings.history.missing_stream=o,await X(e,i,"config:set:history_missing_stream_policy"),ae(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let o=ia(n.policy),i=e.settings.validation.sprint_release_format!==o;return e.settings.validation.sprint_release_format=o,await X(e,i,"config:set:sprint_release_format_policy"),ae(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let o=Us(n.policy),i=e.settings.validation.parent_reference!==o||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==o;return e.settings.validation.parent_reference=o,e.settings.governance.preset="custom",e.settings.governance.parent_reference=o,await X(e,i,"config:set:parent_reference_policy"),ae(e,t,e.settings.validation.parent_reference,i)}let r=Ac(n.policy),s=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await X(e,s,"config:set:metadata_validation_profile"),ae(e,t,e.settings.validation.metadata_profile,s)}async function tC(e,t,n){if(t==="metadata_required_fields"){let a=UA(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((m,u)=>m!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await X(e,c,"config:set:metadata_required_fields"),Tc(e,t,[...e.settings.validation.metadata_required_fields],c)}let s={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],o=GA(t,n.criterion,n.clearCriteria),i=o.length!==s.length||o.some((a,c)=>a!==s[c]);return s.splice(0,s.length,...o),await X(e,i,`config:set:${t}`),Tc(e,t,[...s],i)}async function nC(e,t,n){if(t==="governance_preset"){let c=j_(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await X(e,m,"config:set:governance_preset"),ae(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",s=r?n.policy.trim():"";if(r&&s.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await X(e,c,"config:set:governance_create_default_type"),ae(e,t,e.settings.governance.create_default_type??"",c)}if(s.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let o=x(e.settings,I()),i=pe(s,o);if(!i)throw new l(kt(s,o.types,St(e.target.pmRoot,e.settings.schema)),d.USAGE);let a=e.settings.governance.create_default_type!==i;return e.settings.governance.create_default_type=i,await X(e,a,"config:set:governance_create_default_type"),ae(e,t,e.settings.governance.create_default_type,a)}async function rC(e,t,n){if(t==="governance_ownership_enforcement"){let o=q_(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==o;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=o,await X(e,i,"config:set:governance_ownership_enforcement"),ae(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let o=K_(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==o;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=o,await X(e,i,"config:set:governance_create_mode_default"),ae(e,t,e.settings.governance.create_mode_default,i)}let r=z_(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await X(e,s,"config:set:governance_close_validation_default"),ae(e,t,e.settings.governance.close_validation_default,s)}async function sC(e,t,n){if(t==="governance_parent_reference_policy"){let o=Us(n.policy),i=e.settings.governance.preset!=="custom"||$_(e.settings.governance.parent_reference,e.settings.validation.parent_reference,o);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=o,e.settings.validation.parent_reference=o,await X(e,i,"config:set:governance_parent_reference_policy"),ae(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let o=Ac(n.policy),i=e.settings.governance.preset!=="custom"||$_(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,o);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=o,e.settings.validation.metadata_profile=o,await X(e,i,"config:set:governance_metadata_validation_profile"),ae(e,t,e.settings.governance.metadata_profile,i)}let r=B_(n.policy),s=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await X(e,s,"config:set:governance_workflow_enforcement"),ae(e,t,e.settings.governance.workflow_enforcement,s)}async function oC(e,t,n){if(t==="governance_require_close_reason"){let a=V_(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await X(e,c,"config:set:governance_require_close_reason"),ae(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let s=H_(n.policy)==="enabled",o=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==s;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=s,await X(e,o,"config:set:governance_force_required_for_stale_lock"),ae(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function iC(e,t,n){if(t==="test_result_tracking"){let a=U_(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await X(e,c,"config:set:test_result_tracking"),ae(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}let s=G_(n.policy)==="enabled",o=e.settings.telemetry.enabled!==s||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=s,e.settings.telemetry.first_run_prompt_completed=!0,await X(e,o,"config:set:telemetry_tracking"),ae(e,t,e.settings.telemetry.enabled?"enabled":"disabled",o)}async function aC(e,t,n){let r=$A(n.criterion,n.clearCriteria),s=r.length!==e.settings.workflow.definition_of_done.length||r.some((o,i)=>o!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await X(e,s,"config:set:definition_of_done"),Tc(e,t,[...e.settings.workflow.definition_of_done],s)}async function cC(e,t,n){if(n.clearCriteria===!0&&!Ec(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?ZA(e,n):t==="context"?HA(e.settings,n,e.target,e.scope,e.warnings):t==="definition_of_done"?aC(e,t,n):M_(t)?tC(e,t,n):TA.has(t)?iC(e,t,n):AA.has(t)?oC(e,t,n):xA(t)?rC(e,t,n):OA(t)?sC(e,t,n):PA(t)?nC(e,t,n):eC(e,t,n)}async function Y_(e,t,n,r,s,o){let i=NA(e),a=LA(t),c=a==="get"||a==="set"?hs(n):void 0,m=c?void 0:qA(a,n),u=WA(a,n,m,c,o,r),p=await zA(i,s),{settings:f,metadata:_,warnings:h}=await Cu(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:jA(h)};return c?QA(y,a,c,u):a==="list"?YA(y):a==="export"?JA(y):(W_(m),a==="get"?XA(y,m):cC(y,m,u))}import UC from"node:fs/promises";import V from"node:path";import GC from"node:readline/promises";import{stdin as jC,stdout as Re}from"node:process";import Ic from"node:fs/promises";import re from"node:path";import dC from"node:readline/promises";import{stdin as lC,stdout as Ko}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e404796d-439b-5f4c-9330-5b12ff41d7b2")}catch{}})();var X_=["ask","add","skip","status"],mC=["AGENTS.md","CLAUDE.md"],uC=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],pC=8,xc=1,fC="<!-- pm-cli:agent-guidance:start:",_C=`<!-- pm-cli:agent-guidance:start:v${xc} -->`,Rc="<!-- pm-cli:agent-guidance:end -->",pr="Add workflow guidance later: pm init --agent-guidance add";var hC=()=>dC.createInterface({input:lC,output:Ko});function mr(e,t){let n=re.relative(e,t);return n.length===0?re.basename(t):n.split(re.sep).join("/")}function J_(e){return e.endsWith(`
4
+ `,{changedFields:["body"]}}});return{item:d.item,appended:c,changed_fields:d.changedFields}}import{readFile as Ww}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eac75dc5-80b4-50d2-b615-4f96edca7346")}catch{}})();function po(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,t}function Sf(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new m(`Structured context events are append-only and cannot be ${t}.`,l.USAGE,{code:"structured_event_immutable"})}function Ka(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Jt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Nn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let o=se(n,"--add");return Object.keys(o).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:o.text?.trim()||n}catch{return n}}function za(e){return typeof e=="object"&&e!==null&&"code"in e}async function Yw(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new m(`Specify ${t} text using only one input source: --add, --stdin, or --file`,l.USAGE);let r=Fe();if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add")??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new m("--file path cannot be empty",l.USAGE);try{return{value:await Ww(s,"utf8"),emptyFlag:"--file"}}catch(o){if(za(o)&&qt(o))throw new m(`--file path not found: ${s}`,l.USAGE);let i=o instanceof Error?o.message:String(o);throw new m(`Failed to read --file path "${s}": ${i}`,l.USAGE)}}async function fo(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new m("Specify only one of --edit or --delete",l.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new m("--delete cannot be combined with replacement text",l.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new m("--delete must be a positive integer",l.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new m("--edit must be a positive integer",l.USAGE);let n=await Yw(e,t);if(e.edit!==void 0){if(!n)throw new m("--edit requires replacement text from --add, --stdin, or --file",l.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function lr(e,t){throw e instanceof m&&e.exitCode===l.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new m(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Af(e){return e==="comments"?"--stdin":"--add -"}function Jw(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let s=Af(t.collectionKey),o=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new m(`--add value "${r}" looks like an option, not annotation text. Use ${s} to read stdin, or use text=${r} for literal dash-leading text.`,l.USAGE,{code:"annotation_flag_like_value",required:`Use ${s} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${o} ${s}`,`${o} --add text=${r}`]})}function Xw(e,t){if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new m(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,l.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${Af(e.collectionKey)}`]})}async function Ln(e,t,n,r){Xw(r,t);let s=E(process.cwd(),n.path);await C(s);let o=await A(s),i=I(o,R()),a=er(t.limit);if(r.input.mode==="list"){let _=await D(s,e,o.id_prefix,o.item_format,i.type_to_folder);if(!_)throw new m(`Item ${e} not found`,l.NOT_FOUND);let h=await K(_,{schema:o.schema}),y=Jt(h.document.metadata,r.collectionKey);return uo(_.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=T(t.author,o.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,h;try{h=await ne({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Jt(g.metadata,r.collectionKey),v=Ef(r.input.index,b.length,r.collectionKey);return Sf(b[v],"deleted"),b.splice(v,1),g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){lr(g,r.conflictGuidance)}let y=Jt(h.item,r.collectionKey);return uo(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let d=r.input.rawValue??r.input.value??"";Jw(d,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new m(`${r.input.emptyFlag??"--add"} text cannot be empty`,l.USAGE);if(r.input.mode==="edit"){let _=r.editOp??r.op,h;try{h=await ne({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Jt(g.metadata,r.collectionKey),v=Ef(r.input.index,b.length,r.collectionKey),S=b[v];return Sf(S,"edited"),b[v]={...S,text:u,edited_at:k()},g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){lr(g,r.conflictGuidance)}let y=Jt(h.item,r.collectionKey);return uo(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:y[r.input.index-1]},t.fullHistory===!0)}let p;try{p=await ne({pmRoot:s,settings:o,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(_){let h=Jt(_.metadata,r.collectionKey),y={created_at:k(),author:c,text:u};return h.push(r.createEntry(y)),_.metadata[r.collectionKey]=h,{changedFields:[r.collectionKey]}}})}catch(_){lr(_,r.conflictGuidance)}let f=Jt(p.item,r.collectionKey);return uo(p.item.id,r.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:f.length,entry:f.at(-1)},t.fullHistory===!0)}function Ef(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),s=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,o=t===1?`1 ${r}`:`${t} ${n}`;throw new m(`${s} index ${e??"(missing)"} out of range (item has ${o})`,l.USAGE)}return e-1}function uo(e,t,n,r,s,o,i=!1){let a=o===void 0||i?Ka(n,o!==void 0&&i?void 0:r):o.entry===void 0?[]:[o.entry],c=o!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...[s,o!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...o===void 0?{}:{mutation_receipt:{action:o.action,entry_index:o.entryIndex,changed_count:1,full_history_included:!c},omission_receipt:{has_omissions:c,omitted_field_group_count:c?1:0,omitted_field_groups:c?[{name:`${t}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0579277-f123-5f96-8664-dfe05ade1b24")}catch{}})();async function Tf(e,t,n){return[...await Tt(Te(e,t),t).catch(()=>[])].reverse().find(o=>o.patch.some(i=>i.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a61bf25-e320-5adc-8f5a-a427bc89af1a")}catch{}})();var Cf="no_available_next_item";function Rf(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function _o(e,t,n,r={}){let s=E(process.cwd(),n.path);await C(s);let o=await A(s),i=$(o.schema),a=T(r.author,o.author_default),c=wn(a),d=null,u=!1,p=[],f=await ne({pmRoot:s,settings:o,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||y;if(d=y.trim().length>0?y:null,Im(_.metadata.status,i)&&!t)throw new m(`Cannot claim terminal item ${_.metadata.id} without --force`,l.CONFLICT);if(d!==null&&g!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${d}`),{changedFields:[]};if(!t){let v=await Tf(s,_.metadata.id,y);throw new m(`Item ${_.metadata.id} is already ${v}. Use --force to take over, or --if-available to skip without failing.`,l.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}p.push(`claim_takeover:${d}->${a}`)}return _.metadata.assignee=a,_.metadata.claim_principal=c,{changedFields:["assignee","claim_principal"],warnings:p}}});return u||await Pa({pmRoot:s,settings:o,principal:c,itemId:f.item.id}),{item:f.item,claimed_by:u&&d!==null?d:a,previous_assignee:d,forced:t,...u?{skipped:!0}:{},...p.length>0?{warnings:p}:{}}}async function If(e,t,n={},r={}){let s=Qw(n.maxAttempts),o=await A(E(process.cwd(),t.path)),i={...n,author:T(n.author,o.author_default)},a=await ar({...r,callerAuthor:i.author,limit:String(s)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return Zw(c.slice(0,s),e,t,i)}function Qw(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new m("--max-attempts must be an integer from 1 to 100",l.USAGE);return t}async function Zw(e,t,n,r={},s=_o){let o=0;for(let a of e){o+=1;try{let c=await s(a.id,t,n,r),d={...c,recommendation:a,attempts:o,available:!0};if(!c.skipped)return d}catch(c){if(!Rf(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:T(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:o,warnings:[Cf]};let i=o===0;throw new m(i?"No actionable items matched the selection filters":"No actionable item remained available to claim",i?l.NOT_FOUND:l.CONFLICT,{code:Cf,why:i?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[i?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function ho(e,t,n,r={}){let s=E(process.cwd(),n.path);await C(s);let o=await A(s),i=T(r.author,o.author_default),a=wn(i),c=r.ownershipReleaseBypass===!0,d=null,u;try{u=await ne({pmRoot:s,settings:o,id:e,op:"release",author:i,message:r.message,force:t,bypassAssigneeConflict:c,mutate(p){return d=p.metadata.assignee??null,!d&&!p.metadata.claim_principal?{changedFields:[]}:(delete p.metadata.assignee,delete p.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(p){lr(p,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}return await Na({pmRoot:s,principal:a,itemId:u.item.id}),{item:u.item,released_by:i,previous_assignee:d,forced:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7ae3c89-b50b-5e4f-8273-8318bc976d84")}catch{}})();var ev=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function xf(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function Ba(e,t){return Ha(e,t,{operation:"close"})}function Ha(e,t,n){let r=xf(e);if(!t||r.closeReason!==void 0)return r;let s=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new m("Close reason text is required because governance.require_close_reason is enabled",l.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:s,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function Va(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,s=e.dependencies??[],o=s.filter(d=>d.kind==="blocked_by"),i=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),i&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&o.length>0){let d=s.filter(u=>u.kind!=="blocked_by");d.length>0?e.dependencies=d:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...o.map(d=>d.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[t.orderingEdges==="preserve"?`closed_preserved_predecessors:${e.id}:${c.join(",")}`:`closed_removed_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="781b5118-7b07-53c7-802f-c889cb797a96")}catch{}})();var tv=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function nv(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new m(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,l.USAGE)}function rv(e){let t=[];for(let n of tv){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function sv(e,t,n){let r=new Set,s=t;for(;typeof s=="string"&&s.trim().length>0;){let o=s.trim();if(o===n)return!0;if(r.has(o))return!1;r.add(o),s=(await e(o))?.duplicate_of}return!1}function ov(e){return typeof e!="string"||e.trim().length===0}async function iv(e,t,n,r){let s=n?.trim();if(!s)return;if(s===r)throw new m("An item cannot be closed as a duplicate of itself.",l.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let o=I(t,R()),i=new Map,a=async d=>{if(i.has(d))return i.get(d)??null;let u=await D(e,d,t.id_prefix,t.item_format,o.type_to_folder);if(!u)return i.set(d,null),null;let{document:p}=await K(u,{schema:t.schema});return i.set(d,p.metadata),p.metadata},c=await a(s);if(!c)throw new m(`Duplicate target "${s}" was not found. Create or locate the canonical item first.`,l.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${s}" --duplicate-of ${s}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await sv(a,c.duplicate_of,r))throw new m(`Circular duplicate reference detected. Target "${s}" points back to "${r}".`,l.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new m(`Duplicate target "${s}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,l.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function av(e,t,n){return e.filter(r=>r.parent===t&&!Z(r.status,n)).map(r=>r.id).sort((r,s)=>r.localeCompare(s))}function cv(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),s=df(e),o=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:s.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(o)).filter(({blockerIds:a})=>a.every(c=>{if(c===o)return!0;let d=r.get(c);return d!==void 0&&Z(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function dv(e,t,n,r,s,o){let i=cv(n,r,o),a=[];for(let c of i)try{let d=await ne({pmRoot:e,settings:t,id:c.id,op:"update",author:s,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(h=>{let y=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=o.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${d.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(d){let u=d instanceof Error?d.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${u}`)}return a}function lv(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:s,key:o}of r){if(typeof s!="string")continue;let i=s.trim();i.length!==0&&(e[o]=i,n.push(o))}return n}function mv(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:s,value:o}of r)ov(e[s])&&(e[s]=o,n.push(s));return n}function uv(e,t,n,r){let s=[];if(t!=="off"){let o=rv(e);if(o.length>0){let i=o.map(a=>a.label);if(t==="strict"){let a=o.map(d=>`--${d.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(d=>[d,"<value>"])];throw new m(`Cannot close item ${e.id}: missing ${i.join(", ")}. Populate fields or use --validate-close warn.`,l.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:Es(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}s.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new m(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,l.USAGE);s.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return s}return n.length>0&&s.push(`closed_with_active_children:${e.id}:${n.join(",")}`),s}function pv(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function fv(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function _v(e,t){if(Z(e.status,t.statusRegistry)&&!t.force)throw new m(`Item ${e.id} is already terminal; use --force to close again.`,l.CONFLICT);let n=lv(e,t.options),r=mv(e,t.duplicateOf),s=uv(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let o=t.options.completedAt!==void 0||e.completed_at===void 0;o&&(e.completed_at=t.completedAt);let i=["status","closed_at",...o?["completed_at"]:[],...pv(e,t.closeReason),...n];if(ep(e)&&(e.plan_mode="completed",i.push("plan_mode")),t.duplicateOf!==void 0){i.push("duplicate_of");for(let c of r)i.includes(c)||i.push(c)}i.push(...fv(e));let a=Va(e,t.lifecyclePolicy);return i.push(...a.changedFields),s.push(...a.warnings),{changedFields:i,...s.length>0?{warnings:s}:{}}}async function Of(e,t,n,r){let s=E(process.cwd(),r.path);await C(s);let o=await A(s),i=$(o.schema),a=T(n.author,o.author_default),c=I(o,R()).type_to_folder,d=await D(s,e,o.id_prefix,o.item_format,c);if(!d)throw await at(s,e,o.id_prefix,c);let u=await iv(s,o,n.duplicateOf,d.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Ba({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=nv(n.validateClose)??o.governance.close_validation_default,h=await ae(s,o.item_format,c,void 0,o.schema),y=av(h,d.id,i),g=new Date().toISOString(),b=n.completedAt===void 0?g:te(n.completedAt,new Date(g),"completed-at"),v=await ne({pmRoot:s,settings:o,id:d.id,op:"close",author:a,message:n.message,force:n.force,mutate(S){return _v(S.metadata,{pmRoot:s,statusRegistry:i,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:g,completedAt:b,lifecyclePolicy:p})}});return{item:v.item,changed_fields:v.changedFields,warnings:[...v.warnings,...await dv(s,o,h,d.id,a,i)]}}function ct(e,t,n,r){return Of(e,t,n,r)}import hv from"fast-json-patch";import Wa from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="db5f3a6d-9ae5-5f9b-bedf-766b2b79324c")}catch{}})();function gv(e,t){return qu(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function yv(e){let t=fa(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Je(Vt(t))}async function bv(e,t,n,r){let s=await D(e,t,n.id_prefix,n.item_format,r);if(s){let c=Te(e,s.id),d=await $u({pmRoot:e,settings:n,itemId:s.id,commandLabel:"restore"});return{id:s.id,historyPath:c,located:s,historyPolicyWarnings:d.warnings}}let o=be(t,n.id_prefix),i=ma(t),a=o===i?[o]:[o,i];for(let c of a){let d=Te(e,c);if(await P(d))return{id:c,historyPath:d,located:null,historyPolicyWarnings:[]}}throw new m(`Item ${t} not found`,l.NOT_FOUND)}function wv(e,t){let n=Wt(e),r=Wt(t),s=hv.compare(n,r),o=new Set;for(let i of s){if(i.path==="/body"||i.path.startsWith("/body/")){o.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];o.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(o).sort((i,a)=>i.localeCompare(a))}async function vv(e){if(await q(e.subject.historyPath)!==e.historyRawBeforeLock)throw new m(`History for ${e.resolvedId} changed while waiting for lock; retry restore.`,l.CONFLICT);let n=await D(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),r=n?await K(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==e.currentItemRawBeforeLock)throw new m(`Item ${e.resolvedId} changed while waiting for lock; retry restore.`,l.CONFLICT);return{loadedItemUnderLock:r,existingItemPath:n?.itemPath??null}}function kv(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:yv(t),originalRaw:null}}function Sv(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new m(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,l.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function Ev(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await pe(e.existingItemPath,e.resolvedOriginalRaw),await Wa.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await pe(e.existingItemPath,e.resolvedOriginalRaw);return}await Wa.rm(e.restoredItemPath,{force:!0})}async function Av(e){return[...await z({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await z({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function Xt(e,t,n,r){let s=E(process.cwd(),r.path);await C(s);let o=await A(s),i=I(o,R()),a=await bv(s,e,o,i.type_to_folder),c=a.id,d=await q(a.historyPath),u=await Tt(a.historyPath,c);if(u.length===0)throw new m(`No history exists for ${c}; restore is unavailable.`,l.NOT_FOUND);let p=gv(t,u),f=Ku(fa(u,p.historyIndex),p),_=Iu(f,{schema:o.schema});if(_.metadata.id!==c)throw new m(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,l.GENERIC_FAILURE);let y=(a.located?await K(a.located,{schema:o.schema}):null)?.raw??null,g=T(n.author,o.author_default),b=await ye(s,c,o.locks.ttl_seconds,g,!!n.force,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let{loadedItemUnderLock:v,existingItemPath:S}=await vv({pmRoot:s,resolvedId:c,subject:a,settings:o,typeToFolder:i.type_to_folder,historyRawBeforeLock:d,currentItemRawBeforeLock:y}),x="toon",O=kv(v,u),j=Sv({document:O.document,author:g,force:n.force,enforcement:o.governance.ownership_enforcement,resolvedId:c}),L=wv(O.document,_);await As({pm_root:s,operation:"restore",before:O.document,after:_,changed_fields:L,sdk:Ls({pmRoot:s,settings:o,typeToFolder:i.type_to_folder})});let Ee=qe(_,{format:x,schema:o.schema}),X=Kt(s,_.metadata.type,c,x,i.type_to_folder),ie=await Sn(s,g),V=[];try{await pe(X,Ee),S&&X!==S&&await Wa.rm(S);let _t=Ke({nowIso:k(),author:g,op:"restore",before:O.document,after:_,message:n.message});try{await Ct(a.historyPath,_t)}catch(ht){throw await Ev({existingItemPath:S,resolvedOriginalRaw:O.originalRaw,restoredItemPath:X}),ht}V=await En({pmRoot:s,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:X,previousItemPath:S??void 0,document:_})}finally{await ie()}let Ge=await Av({restoredItemPath:X,historyPath:a.historyPath,before:O.document,after:_});gn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:O.document.metadata.status,status:_.metadata.status,previous:Ht(O.document.metadata,L),current:Ht(_.metadata,L),changed_fields:L});let ft=u[p.historyIndex];return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,entry_ts:ft.ts,entry_op:ft.op},changed_fields:L,warnings:[...a.historyPolicyWarnings,...j,...V,...Ge]}}finally{await b()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7113374-b169-5f92-9c20-075a47520440")}catch{}})();var Nf=1,Ya="close-many",Tv=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function Cv(e,t){return or(e,t,{includePagination:!1})}function Rv(e,t){return or(e,t)}function Iv(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new m("--ids requires at least one non-empty item ID",l.USAGE)}function xv(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(s=>s.trim().length>0)||(t[n]=r);return t}function Ov(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new m("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",l.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function Pv(e,t){let n=$(t.schema),r=I(t,R()),s=await ae(e,t.item_format,r.type_to_folder,void 0,t.schema),o=new Map,i=new Map;for(let a of s){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),Z(a.status,n)))continue;let c=o.get(a.parent);c?c.push(a.id):o.set(a.parent,[a.id])}for(let a of o.values())a.sort((c,d)=>c.localeCompare(d));return{childrenByParent:o,parentByChild:i}}function Pf(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let s=0,o=t.get(e),i=[],a=new Set,c=!1;for(;o!==void 0&&!a.has(o);){let d=n?.get(o);if(d!==void 0){s+=d+1;break}a.add(o),i.push(o),s+=1,o=t.get(o)}if(o!==void 0&&a.has(o)&&(c=!0),!c){n?.set(e,s);for(let[d,u]of i.entries())n?.set(u,s-d-1)}return s}async function Nv(e){let t=await js(e.pmRoot,Ya,e.rollbackId,Nf),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await qs(t.items,(s,o)=>Xt(s,o,{author:e.options.author,message:n,force:!0},e.global));return{...Bt({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function Lv(e,t,n,r,s){return e.map(o=>{let i=(t.get(o.id)??[]).filter(c=>!n.has(c)),a=!Lf(o,r,s);return{id:o.id,title:typeof o.title=="string"?o.title:"",status:o.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function Fv(e){let t=await Gs(e.pmRoot,Ya,e.checkpointId,{schema_version:Nf,id:e.checkpointId,created_at:e.nowValue,author:T(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function Mv(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let s=await ct(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:s.changed_fields,...s.warnings&&s.warnings.length>0?{warnings:s.warnings}:{}}),n.push(r.id)}catch(s){t.push({id:r.id,status:"failed",error:_n(s)})}}return{rows:t,closedIds:n}}function $v(e){return typeof e.rollback=="string"?e.rollback:void 0}function Dv(e,t){if(t.trim().length===0)throw new m("--rollback requires a checkpoint id",l.USAGE);if(e.dryRun===!0)throw new m("--dry-run cannot be combined with --rollback",l.USAGE);if(Rv(e.list,e.status))throw new m("Rollback mode does not accept filter options",l.USAGE)}function Uv(e){if(!Cv(e.list,e.status))throw new m(`close-many requires at least one filter to scope the close (for example: ${Tv}). Refusing to match every item.`,l.USAGE)}function Gv(e,t){let n=new Map;return[...e].sort((r,s)=>{let o=Pf(s.id,t,n)-Pf(r.id,t,n);return o!==0?o:r.id.localeCompare(s.id)})}function Lf(e,t,n){return n||!Z(e.status,t)}function jv(e,t,n){return new Set(e.filter(r=>Lf(r,t,n)).map(r=>r.id))}async function qv(e){Uv(e.options);let t=$(e.settings.schema),n=Ov(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,s=await Pt(e.options.status,xv(e.options.list),e.global),{childrenByParent:o,parentByChild:i}=await Pv(e.pmRoot,e.settings),a=Gv(s.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(p=>p.trim()).filter(p=>p.length>0))],d=new Set(a.map(p=>p.id)),u=jv(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:s,matched:a,unmatchedIds:c.filter(p=>!d.has(p)),planRows:Lv(a,o,u,t,r)}}function Kv(e){return{outcome:"effect",exit_code:l.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds.length>0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function zv(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return Fv({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function Ff(e,t){let n=E(process.cwd(),t.path);await C(n);let r=await A(n),s=e.dryRun===!0,o=$v(e);if(Iv(e.list),o!==void 0)return Dv(e,o),Nv({pmRoot:n,rollbackId:o,options:e,global:t});let i=await qv({pmRoot:n,settings:r,options:e,global:t});if(s)return Kv(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=k(),d=Us(Ya,c),u=await zv({context:i,options:e,closableIds:a,checkpointId:d,nowValue:c}),p={author:e.author,message:e.message??`close-many apply ${d}`,completedAt:e.completedAt,validateClose:i.validateCloseMode,force:i.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await Mv({matched:i.matched,closableIds:a,reason:i.reason,closeOptions:p,global:t}),h=f.filter(b=>b.status==="closed").length,y=f.filter(b=>b.status==="skipped").length,g=f.filter(b=>b.status==="failed").length;return{...Bt({applied:h,skipped:y,failed:g,unmatched:i.unmatchedIds.length}),mode:"apply",matched_count:i.matched.length,dry_run:!1,...i.reason!==void 0?{reason:i.reason}:{},filters:i.listed.filters,...i.validateCloseMode?{validate_close:i.validateCloseMode}:{},...u?{checkpoint:u}:{},closed_count:h,skipped_count:y,failed_count:g,rows:f,ids:_,...i.unmatchedIds.length>0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}import{readFile as Bv}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7687052-a04e-536e-ace5-a665ebd477e3")}catch{}})();async function Ja(e,t){let n=e.add!==void 0,r=e.stdin===!0,s=typeof e.file=="string",o=Number(n)+Number(r)+Number(s);if(o===0)return;if(o>1)throw new m("Specify comment text using only one input source: --add, --stdin, or --file",l.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add")??"",emptyFlag:"--add"};if(r)return{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new m("--file path cannot be empty",l.USAGE);try{return{value:await Bv(i,"utf8"),emptyFlag:"--file"}}catch(a){if(za(a)&&qt(a))throw new m(`--file path not found: ${i}`,l.USAGE);let c=a instanceof Error?a.message:String(a);throw new m(`Failed to read --file path "${i}": ${c}`,l.USAGE)}}async function Hv(e,t){let n=e.edit,r=e.delete,s=n!==void 0,o=r!==void 0;if(s&&o)throw new m("Specify only one of --edit or --delete",l.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new m("--edit must be a positive integer",l.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new m("--delete must be a positive integer",l.USAGE);if(o){if(await Ja(e,t)!==void 0)throw new m("--delete does not take comment text",l.USAGE);return{mode:"delete",index:r}}if(s){let c=await Ja(e,t);if(c===void 0)throw new m("--edit requires replacement text via positional [text], --add, --stdin, or --file",l.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let i=await Ja(e,t);return i===void 0?{mode:"list"}:{mode:i.emptyFlag==="--add"?"add":i.emptyFlag==="--stdin"?"stdin":"file",value:i.value,emptyFlag:i.emptyFlag}}async function Mf(e,t,n){let r=Fe(),s=await Hv(t,r),o=s.mode==="add"||s.mode==="edit",i=s.value??"";return Ln(e,t,n,{input:{...s,rawValue:t.add??i,value:o?Nn(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(s.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm comments pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="93184f29-f215-5413-9628-fb5b34523995")}catch{}})();async function $f(e,t,n){return Ln(e,t,n,{input:await fo(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Nn(r),createEntry:r=>r,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm learnings pm-a1b2 --add "review learning" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebd9f151-593f-5081-97da-d78f83de4914")}catch{}})();function Vv(e){if(e===void 0)return;if(e.trim().length===0)throw new m("--add-json must contain a JSON value",l.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new m("--add-json must be valid JSON",l.USAGE,{code:"structured_event_json_invalid"})}return t}function Wv(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function Yv(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new m("--since must be a valid ISO timestamp",l.USAGE,{code:"structured_event_since_invalid"});return t}async function Df(e,t,n){let r=Vv(t.addJson),s=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&s)throw new m("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",l.USAGE,{code:"structured_event_input_conflict"});let o=r===void 0?void 0:Q(r),i=[t.since,t.eventType].some(h=>h!==void 0),a=Yv(t.since),c=er(t.limit),d=await Ln(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await fo(o===void 0?t:{add:o},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>Nn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:Wv(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm notes pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}}),u=t.eventType?.trim(),p=d.notes.filter(h=>{let y=[h.format==="json",h.data!==void 0].every(Boolean),g=[a===void 0,Date.parse(h.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),b=[!u,h.event_type===u].includes(!0);return[!i,[y,g,b].every(Boolean)].includes(!0)}),f=i?Ka(p,c):p,_=f.filter(h=>h.format==="json").length;return{...d,notes:f,count:f.length,...i?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d6f359cb-2bc9-5f96-8789-db91512d0bd5")}catch{}})();function mr(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new m(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,l.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function ur(e,t,n=Ot()){for(let r of t??[])try{rl(e,r.id,r.kind,n)}catch(s){throw new m(_n(s),l.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Uf(e,t){return(await K(e,{schema:t})).document.metadata.created_at}async function Jv(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await D(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Uf(n,t.schema)}function Xv(e){let t=e.registry.require(e.dependency.kind);return new m(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,l.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function Qv(e){let t=e.dependencies.filter(s=>e.registry.resolve(s.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(s.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:s,located:o})=>o===null?[]:[[s,o]])),r=new Map(await Promise.all([...new Set(t.map(({id:s})=>s))].map(async s=>[s,await Uf(n.get(s),e.context.schema)])));for(let s of e.holders){let o=await Jv(s,e.context);if(o!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(o),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw Xv({holder:s,dependency:i,sourceCreatedAt:o,targetCreatedAt:a,registry:e.registry})}}}async function Qt(e){let t=e.registry??Ot(),n=(e.dependencies??[]).filter(i=>!lp(i.source_kind)),r=[...new Set(n.map(i=>i.id))],s=await Promise.all(r.map(async i=>({target:i,located:await D(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),o=s.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(o.length>0&&e.allowUnresolved!==!0)throw new m(`Dependency target${o.length===1?"":"s"} not found: ${o.join(", ")}`,l.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:o,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${o.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:o,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${o[0]}" --limit 10`}});return await Qv({dependencies:n,missingTargets:o,resolutions:s,holders:e.holders??[],registry:t,context:e}),o.map(i=>`dependency_target_unresolved:${i}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcbb6070-7457-5454-abf1-fa8153c8efd6")}catch{}})();function go(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function yo(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function bo(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Fr.includes(t))return t;let n=ce(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new m("Confidence must be an integer 0..100 or one of low|med|medium|high",l.USAGE);return n}function wo(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new m("Regression must be one of true|false|1|0",l.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="afc4f3d5-ba5e-5dd7-abc9-531b319cdb4e")}catch{}})();var Zv=new Set(["none","null"]);function vo(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function Be(e){return e===void 0?!1:Zv.has(e.trim().toLowerCase())}function ko(e,t,n){if(!Be(e))return;let r=n?` ${n}`:"";throw new m(`${t} no longer accepts "none" or "null".${r}`.trim(),l.USAGE)}function ve(e,t,n){if(!e||e.length===0||!e.some(o=>Be(o)))return;let s=n?` ${n}`:"";throw new m(`${t} no longer accepts "none" or "null".${s}`.trim(),l.USAGE)}function So(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new m(`${n.valueFlag} entries must be strings.`,l.USAGE);let s=r;if(!s.some(a=>Be(a)))continue;if(s.filter(a=>!Be(a)).length>0)throw new m(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,l.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2fcfbe50-039b-5031-8b18-a208908a0d87")}catch{}})();function jf(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new m(`${t} must be one of true|false|1|0|yes|no`,l.USAGE)}function Xa(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function ke(e,t,n){if(!t.includes(e))throw new m(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,l.USAGE);return e}var qf=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function ek(e,t){return t==="defined"?e!==void 0:!!e}function Gf(e,t,n){if(!ek(e,n))return;let r=ce(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new m(`--event ${t} must be an integer >= 1`,l.USAGE);return r}function tk(e,t,n){let r=e?te(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new m("--event recur_until must be at or after start",l.USAGE);return r}function nk(e){return Array.from(new Set(Xa(e).map(t=>ke(t.toLowerCase(),Jd,"event weekday")))).sort((t,n)=>Li(t)-Li(n))}function rk(e){return Array.from(new Set(Xa(e).map(t=>{let n=ce(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new m("--event recur_by_month_day values must be integers 1..31",l.USAGE);return n}))).sort((t,n)=>t-n)}function sk(e,t){return Array.from(new Set(Xa(e).map(n=>te(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Kf(e,t,n,r){let s=e.recur_freq?.trim(),o=e.recur_interval?.trim(),i=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![s,o,i,a,c,d,u].some(S=>S!==void 0))return;if(!s)throw new m("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",l.USAGE);let f=ke(s.toLowerCase(),Yd,"event recurrence frequency"),_=Gf(o,"recur_interval",r),h=Gf(i,"recur_count",r),y=tk(a,t,n),g=nk(c),b=rk(d),v=sk(u,n);return{freq:f,interval:_,count:h,until:y,by_weekday:g.length>0?g:void 0,by_month_day:b.length>0?b:void 0,exdates:v.length>0?v:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8248687e-ba97-5e1b-afbf-a322a72eb1aa")}catch{}})();var zf="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",ok="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",ik=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,ak=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Hf=1e3,Qa=60*Hf,ck=60*Qa;function Bf(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new m(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,l.USAGE);return n.toISOString()}function dk(e,t){let n=new Date(e),r=t.trim(),s=ik.exec(r);if(s){let a=s[1]==="-"?-1:1,c=Number.parseInt(s[2],10)*a;return Bf(n.getTime()+c*Qa,r)}let o=ak.exec(r);if(o){let[,a,c,d,u]=o;if(c||d||u){let f=a==="-"?-1:1,_=Number.parseInt(c??"0",10),h=Number.parseInt(d??"0",10),y=Number.parseInt(u??"0",10),g=_*ck+h*Qa+y*Hf;return Bf(n.getTime()+f*g,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return te(i,n,"event.duration")}function Vf(e,t,n,r){if(t&&n)throw new m(ok,l.USAGE);if(n){let o=dk(e,n);if(o<e)throw new m(zf,l.USAGE);return o===e?void 0:o}if(!t)return;let s=te(t,r,"event.end");if(s<e)throw new m(zf,l.USAGE);if(s!==e)return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var lk=["at","date","text","title"],mk=["start","date","end","duration","title","description","location","timezone","all_day",...qf],uk=["key","value"];function Wf(e,t){return t==="trimmed"?e?.trim():e}function pk(e,t){return t==="defined"?e!==void 0:!!e}function Eo(e,t,n){return e.map(r=>{let s=se(r,"--reminder");ze(s,"--reminder",lk);let o=Wf(s.at??s.date,n.valueMode),i=Wf(s.text??s.title,n.valueMode);if(!o||!i)throw new m("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",l.USAGE);let a=i.trim();if(!a)throw new m("--reminder text must not be empty",l.USAGE);return{at:te(o,t,"reminder.at"),text:a}})}function Ao(e,t,n){return e.map(r=>{let s=se(r,"--event");ze(s,"--event",mk);let o=(s.start??s.date)?.trim();if(!o)throw new m("--event requires start=<iso|relative> or date=<iso|relative>",l.USAGE);let i=te(o,t,"event.start"),a=s.end?.trim(),c=s.duration?.trim(),d=Vf(i,a,c,t),u=s.title,p=s.description,f=s.location,_=s.timezone,h=u?.trim(),y=p?.trim(),g=f?.trim(),b=_?.trim(),v=[["title",u,h],["description",p,y],["location",f,g],["timezone",_,b]];for(let[j,L,Ee]of v)if(L!==void 0&&!Ee)throw new m(`--event ${j} must not be empty`,l.USAGE);let S=s.all_day?.trim(),x=Kf(s,i,t,n.recurrenceEmptyNumericGuard),O=pk(S,n.allDayEmptyGuard)?jf(S,"--event all_day"):void 0;return{start_at:i,end_at:d,title:h,description:y,location:g,all_day:O,timezone:b,recurrence:x}})}function To(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new m("--type-option values must not be empty",l.USAGE);let s,o;if(r.includes(",")||r.includes(`
5
+ `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=se(r,"--type-option");ze(a,"--type-option",uk),s=a.key?.trim(),o=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),d=a;if(a<=0&&c>0&&(d=c),d<=0||d===r.length-1)throw new m("--type-option requires key=value or key=<name>,value=<value> entries",l.USAGE);s=r.slice(0,d).trim(),o=r.slice(d+1).trim()}if(!s||!o)throw new m("--type-option requires key and value",l.USAGE);t[s]=o}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39a36d42-29b1-5f0f-a8b2-f3bfc0ef78c2")}catch{}})();var fk="hierarchy-integrity";async function Co(e){let t=e.required?await ye(e.pmRoot,fk,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var _k=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Yf(e,t,n,r){if(_k.has(t.trim().toLowerCase())||n!==r.open_status)return;let s=ws("in_progress",r);if(!(s===void 0||s===r.open_status))return{command:`pm start-task ${e}`,to_status:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b20ab37-ffbe-5c65-ac0f-800abf876e16")}catch{}})();var Zt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],hk=new Set(Zt),gk=Zt.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),yk=new RegExp(`^(?:[-*+]\\s+)?(?:${gk})\\s*[:=]`,"i");function Ro(e){return e.startsWith("```")||e.includes(`
6
+ `)?!0:yk.test(e)}function Io(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!hk.has(i)){r.push(s);continue}if(Object.hasOwn(n,i))throw new m(`${t} provides key "${s}" more than once after case normalization`,l.USAGE);n[i]=o}if(r.length>0)throw new m(`${t} does not recognize key${r.length>1?"s":""} ${r.map(s=>`"${s}"`).join(", ")}. Allowed keys: ${Zt.join(", ")}.`,l.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new m(`${t} command and cmd must match when both are provided`,l.USAGE);let{cmd:s,...o}=n;return{...o,command:o.command??s}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="74163bed-a473-543e-ae6a-0d5091b3b3a9")}catch{}})();var tn=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",eo,kp,"FORCE_COLOR"]),Po=/^[A-Za-z_][A-Za-z0-9_]*$/,en=["schema","tracker","auto"];function pr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new m(`${t} env_set must include at least one KEY=VALUE assignment`,l.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new m(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,l.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1);if(!Po.test(i))throw new m(`${t} env_set key "${i}" is invalid`,l.USAGE);if(tn.has(i.toUpperCase()))throw new m(`${t} env_set key "${i}" is reserved for sandbox safety`,l.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function fr(e,t){if(!e)return;let n=In(e,{separators:/[;,\n]/});if(n.length===0)throw new m(`${t} env_clear must include at least one environment variable name`,l.USAGE);for(let r of n){if(!Po.test(r))throw new m(`${t} env_clear key "${r}" is invalid`,l.USAGE);if(tn.has(r.toUpperCase()))throw new m(`${t} env_clear key "${r}" is reserved for sandbox safety`,l.USAGE)}return n}function No(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new m(`${t} ${n} must be one of true|false|1|0|yes|no`,l.USAGE)}function Lo(e,t){if(!e)return;let n=e.trim().toLowerCase();if(en.includes(n))return n;throw new m(`${t} pm_context_mode must be one of: ${en.join(", ")}`,l.USAGE)}function nn(e){if(!e)return;let t=In(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Mn(e,t,n){let r=nn(e);if(!(!r||r.length===0)){for(let s of r)try{new RegExp(s,"m")}catch(o){throw new m(`${t} ${n} includes invalid regex "${s}": ${o instanceof Error?o.message:String(o)}`,l.USAGE)}return r}}function Fo(e,t){if(!e)return;let n=ce(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new m(`${t} assert_stdout_min_lines must be an integer >= 0`,l.USAGE);return n}function Mo(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new m(`${t} assert_json_field_equals must include at least one path=value assignment`,l.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new m(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,l.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new m(`${t} assert_json_field_equals entries must include non-empty path and value`,l.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function $o(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new m(`${t} assert_json_field_gte must include at least one path=value assignment`,l.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new m(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,l.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new m(`${t} assert_json_field_gte entries must include non-empty path and value`,l.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new m(`${t} assert_json_field_gte value for "${i}" must be numeric`,l.USAGE);r[i]=c}return Object.keys(r).length>0?r:void 0}var bk=new Set(Zt);function Do(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wk(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!bk.has(i)){r.push(s);continue}if(Object.hasOwn(n,i))throw t(`provides key "${s}" more than once after case normalization`);n[i]=o}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(s=>`"${s}"`).join(", ")}. Allowed keys: ${Zt.join(", ")}.`);return n}function Fn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function xo(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let s=typeof r=="string"?[r]:r;if(!Array.isArray(s)||s.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let o=s.filter(i=>i.length>0);return o.length>0?o:void 0}function Jf(e,t,n){let r=xo(e,t,n);if(r){for(let s of r)try{new RegExp(s,"m")}catch(o){throw n(`field "${t}" includes invalid regex "${s}": ${o instanceof Error?o.message:String(o)}`)}return r}}function Oo(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function vk(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let s=n===void 0?void 0:Oo(n,"timeout_seconds",t),o=r===void 0?void 0:Oo(r,"timeout",t);if(s!==void 0&&o!==void 0&&s!==o)throw t("timeout and timeout_seconds must match when both are provided");let i=s??o;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function kk(e,t){let n=Fn(e,"scope",t);if(n===void 0)return"project";if(!tt.includes(n))throw t(`field "scope" must be one of: ${tt.join(", ")}`);return n}function Sk(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Do(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[s,o]of Object.entries(n)){if(typeof o!="string")throw t(`field "env_set" value for "${s}" must be a string`);if(!Po.test(s))throw t(`field "env_set" key "${s}" is invalid`);if(tn.has(s.toUpperCase()))throw t(`field "env_set" key "${s}" is reserved for sandbox safety`);r[s]=o}return Object.keys(r).length>0?r:void 0}function Ek(e,t){let n=xo(e,"env_clear",t);if(n){for(let r of n){if(!Po.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(tn.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function Ak(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function Tk(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=Oo(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function Ck(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Do(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[s,o]of Object.entries(n)){if(s.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean")throw t(`field "assert_json_field_equals" value for "${s}" must be a string, number, or boolean`);r[s]=String(o)}return Object.keys(r).length>0?r:void 0}function Rk(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Do(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[s,o]of Object.entries(n)){if(s.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[s]=Oo(o,`assert_json_field_gte.${s}`,t)}return Object.keys(r).length>0?r:void 0}function Ik(e,t,n){let r=p=>new m(`${n} ${t} ${p}`,l.USAGE);if(!Do(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Zt.join(", ")}.`);let s=wk(e,r),o=Fn(s,"command",r),i=Fn(s,"cmd",r);if(o!==void 0&&i!==void 0&&o!==i)throw r("command and cmd must match when both are provided");let a=o??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=Fn(s,"path",r),d=Fn(s,"pm_context_mode",r);if(d!==void 0&&!en.includes(d))throw r(`field "pm_context_mode" must be one of: ${en.join(", ")}`);let u=Fn(s,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:kk(s,r),timeout_seconds:vk(s,r),pm_context_mode:d,env_set:Sk(s,r),env_clear:Ek(s,r),shared_host_safe:Ak(s,"shared_host_safe",r),assert_stdout_contains:xo(s,"assert_stdout_contains",r),assert_stdout_regex:Jf(s,"assert_stdout_regex",r),assert_stderr_contains:xo(s,"assert_stderr_contains",r),assert_stderr_regex:Jf(s,"assert_stderr_regex",r),assert_stdout_min_lines:Tk(s,r),assert_json_field_equals:Ck(s,r),assert_json_field_gte:Rk(s,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function Xf(e,t){let n=e.trim();if(n.length===0)throw new m(`${t} requires a JSON object or array of objects describing linked-test entries`,l.USAGE);let r;try{r=JSON.parse(n)}catch(o){throw new m(`${t} value is not valid JSON: ${o instanceof Error?o.message:String(o)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,l.USAGE)}let s=Array.isArray(r)?r:[r];if(s.length===0)throw new m(`${t} array must include at least one linked-test entry object`,l.USAGE);return s.map((o,i)=>Ik(o,s.length>1?`entry ${i+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0062e981-158a-5e6a-b028-6c7cef0f59ba")}catch{}})();var Za=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],ec=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],Qf=[...Za,...ec],Uo=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function Go(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let s=r.trim().toLowerCase();if(!s)throw new m("--unset values must not be empty",l.USAGE);if(Be(s))throw new m('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',l.USAGE);let o=e.resolveDefinition(s);if(!o)throw new m(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,l.USAGE);t.add(o.metadataKey),n.add(o.optionKey)}return{metadataKeys:t,optionKeys:n}}function jo(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let s=n.command_to_fields?.get(t)??[];for(let o of s){if(o.allow_unset===!1)continue;let i=new Set;if(typeof o.key=="string"&&o.key.length>0&&i.add(o.key.toLowerCase()),typeof o.metadata_key=="string"&&o.metadata_key.length>0&&i.add(o.metadata_key.toLowerCase()),typeof o.cli_flag=="string"&&o.cli_flag.length>0&&(i.add(o.cli_flag.replaceAll("-","_").toLowerCase()),i.add(o.cli_flag.toLowerCase())),Array.isArray(o.cli_aliases))for(let a of o.cli_aliases)typeof a!="string"||a.length===0||(i.add(a.replaceAll("-","_").toLowerCase()),i.add(a.toLowerCase()));if(i.has(r))return{optionKey:o.key,metadataKey:o.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="002f45a2-edc3-5aa0-9af8-d9b1dfecc097")}catch{}})();var xk={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function Ok(e){return xk[e]}function tc(e){return Ok(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4dff80ab-acfc-5f81-a546-3f19629d97be")}catch{}})();var Pk=["strict","progressive"],Nk=["lightweight"],n_=new Set(["Reminder","Meeting","Event"]),Lk=new Set(["author","created_at","text"]),rc=[...Qf,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...Uo],Fk=(()=>{let e=new Map;for(let t of rc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),qo=new Map(rc.map(e=>[e.optionKey,e.canonical])),Mk=rc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function $k(e,t){let n=Y(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new m(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n}function Dk(e,t){let n=e.default_status;if(n!==void 0){let r=Y(n,t);if(r)return r}return t.open_status}function nc(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new m(`Invalid created_at timestamp "${e}"`,l.USAGE);return new Date(n).toISOString()}var Uk=vo();function r_(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=s=>{let o=t.unset?[...t.unset]:[];o.includes(s)||o.push(s),t.unset=o};Be(t.template)&&(t.template=void 0);let r=new Set([...qo.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Be(o))continue;let i=s==="rank"?"order":qo.get(s)??s;n(i),t[s]=void 0}return So(t,Uk)}function le(e){if(e!==void 0)return e}function Gk(e,t){return Go({raw:e,supportedFields:Mk,resolveDefinition:n=>Fk.get(n)??jo(n,"create",t)})}var Zf=["id","kind","type","author","created_at","source_kind"],Ko=["path","scope","note"];function jk(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ve(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let i=o.trim(),a=sc(i,Zf);mr(i,a);let c=a?se(o,"--dep"):{id:i,kind:"related"};a&&ze(c,"--dep",Zf);let d=le(c.id),u=qk(le(c.kind??c.type));if(!d||!u)throw new m("--dep requires id and kind, or a bare item id to create a related dependency",l.USAGE);if(d.trim().toLowerCase()==="undefined")throw new m(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,l.USAGE);let p=tr(le(c.source_kind)),f=le(c.author);return{id:nr(d,n,p),kind:ke(u,jt,"dependency kind"),created_at:nc(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function qk(e){return typeof e=="string"?jr(e)??e.trim():e}function sc(e,t){if(e.startsWith("```")||e.includes(`
7
+ `))return!0;let n=t.map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${n})\\s*[:=]`,"i").test(e)?!0:Js(e)}function sn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(ve(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(i=>{let a=i.trim(),c=()=>{if(a.length===0)throw new m(`${e} requires text=<value>`,l.USAGE);return{created_at:n,author:r,text:a}},d;try{d=se(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(d).filter(f=>!Lk.has(f)).length>0)return{created_at:nc(d.created_at,n),author:le(d.author)??r,text:a};let p=d.text??"";if(p==="")throw new m(`${e} requires text=<value>`,l.USAGE);return{created_at:nc(d.created_at,n),author:le(d.author)??r,text:p}}),explicitEmpty:!1})}function oc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ve(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),s=sc(r,Ko),o=s?se(n,"--file"):{path:r};if(s&&ze(o,"--file",Ko),!o.path)throw new m("--file requires path=<value> or a bare file path",l.USAGE);return{path:o.path,scope:ke(o.scope??"project",tt,"file scope"),note:le(o.note)}}),explicitEmpty:!1})}function ic(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ve(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),s=Ro(r)?Io(se(n,"--test"),"--test"):{command:r},o=le(s.command),i=le(s.path);if(!o)throw new m("--test requires command=<value> or a bare command (path=<value> is optional metadata)",l.USAGE);let a=le(s.timeout_seconds),c=le(s.timeout);if(a&&c&&a!==c)throw new m("--test timeout and timeout_seconds must match when both are provided",l.USAGE);let d=a??c;return{command:o,path:i,scope:ke(s.scope??"project",tt,"test scope"),timeout_seconds:d?ce(d,"timeout_seconds"):void 0,pm_context_mode:Lo(s.pm_context_mode,"--test"),env_set:pr(s.env_set,"--test"),env_clear:fr(s.env_clear,"--test"),shared_host_safe:No(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:nn(s.assert_stdout_contains),assert_stdout_regex:Mn(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:nn(s.assert_stderr_contains),assert_stderr_regex:Mn(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Fo(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:Mo(s.assert_json_field_equals,"--test"),assert_json_field_gte:$o(s.assert_json_field_gte,"--test"),note:le(s.note)}}),explicitEmpty:!1})}function ac(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ve(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),s=sc(r,Ko),o=s?se(n,"--doc"):{path:r};if(s&&ze(o,"--doc",Ko),!o.path)throw new m("--doc requires path=<value> or a bare doc path",l.USAGE);return{path:o.path,scope:ke(o.scope??"project",tt,"doc scope"),note:le(o.note)}}),explicitEmpty:!1})}function Kk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ve(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Eo(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function zk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ve(e,"--event","Use --clear-events to clear linked events."),{values:Ao(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function Bk(e,t,n,r=[]){let s=[...Mr.filter(o=>e[o]!==void 0),...r.filter(o=>e[o]!==void 0),...t.length>0?["body"]:[],...n.map(o=>`unset:${o}`)];return Array.from(new Set(s))}function Hk(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function e_(e,t,n){let r=Hn("create",e);if(!r)throw new m(`Unsupported ${n} entry "${e}" for type "${t}"`,l.CONFLICT);return r}function Vk(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function s_(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function Wk(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(e_(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(e_(r,e.name,"required_create_repeatables"));return n}function Yk(e,t,n,r){for(let s of e)if(!(!s_(t,s)&&!n.has(s)))throw new m(`Option ${he("create",s)} is disabled for type "${r}" by command_option_policies`,l.USAGE)}function Jk(e,t,n){if(t!=="strict")return;let r=e.filter(o=>n.has(o)&&!tc(o));if(r.length===0)return;let s=[...new Set(r.map(o=>he("create",o)))].sort((o,i)=>o.localeCompare(i));throw new m(`Strict create mode requires concrete values for ${s.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,l.USAGE)}function Xk(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ve(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:To(e),explicitEmpty:!1})}async function Qk(e){let t=Fe();return{...e,body:await t.resolveValue(e.body,"--body"),dep:await t.resolveList(e.dep,"--dep"),comment:await t.resolveList(e.comment,"--comment"),note:await t.resolveList(e.note,"--note"),learning:await t.resolveList(e.learning,"--learning"),file:await t.resolveList(e.file,"--file"),test:await t.resolveList(e.test,"--test"),doc:await t.resolveList(e.doc,"--doc"),reminder:await t.resolveList(e.reminder,"--reminder"),event:await t.resolveList(e.event,"--event"),typeOption:await t.resolveList(e.typeOption,"--type-option"),field:await t.resolveList(e.field,"--field")}}function Zk(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new m(`Invalid --create-mode value "${e}". Allowed: ${Pk.join(", ")}`,l.USAGE)}function eS(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new m("--schedule-preset must not be empty",l.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new m(`Invalid --schedule-preset value "${e}". Allowed: ${Nk.join(", ")}`,l.USAGE)}function tS(e,t,n){let r=Zk(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new m("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",l.USAGE);return"progressive"}function nS(e,t,n,r){let s=e.name,o=Vk(t),i=Wk(e,n),a=fn(e,"create",i);if(a.errors.length>0)throw new m(a.errors.join("; "),l.CONFLICT);Yk(a.disabled,o,r,s),Jk(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&tc(u)?!0:s_(o,u),d=a.required.filter(u=>!c(u));return[...new Set(d.map(u=>he("create",u)))].sort((u,p)=>u.localeCompare(p))}var o_=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function rS(e,t){let n=[];for(let r of e){let s=r.match(o_);s&&s[2]===t&&n.push(s[1])}return[...new Set(n)].sort((r,s)=>r.localeCompare(s))}function sS(e,t){return e.filter(n=>{let r=n.match(o_);return!r||r[2]!==t})}function oS(e,t,n,r){let s=sS(e,t);if(s.length===0)return;let o=i_(n,[],[],r.open_status);throw new m(s.join("; "),l.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[o],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function iS(e,t){let r=e.options.find(s=>s.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function aS(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function i_(e,t,n,r){let s=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],o=["--status","--priority","--message"],i=[...new Set([...o,...t])],a=new Set(["--title","--description","--type"]);for(let c of i)a.has(c)||(s.push(...aS(c,e.name,r)),a.add(c));for(let c of n){let d=iS(e,c);s.push("--type-option",`${c}=${d}`)}return s.join(" ")}function cc(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new m("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",l.USAGE):new m('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',l.USAGE):new m(`Missing required option ${t}`,l.USAGE);return n}function cS(e){return Rn(e)}function dS(e,t){let n={};for(let[r,s]of Object.entries(e))n[r]=Array.isArray(s)?[...s]:s;for(let[r,s]of Object.entries(t))s!==void 0&&(n[r]=Array.isArray(s)?[...s]:s);return n}function lS(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function mS(){let e=R();return e?e.commands.some(t=>t.action==="templates-show"||lS(t.command)==="templates show"):!1}function uS(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new m(`Templates package returned invalid payload for template "${t}". Expected an options object.`,l.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new m(`Templates package returned invalid options for template "${t}".`,l.GENERIC_FAILURE);let r={};for(let[s,o]of Object.entries(n)){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"){r[s]=o;continue}if(Array.isArray(o)&&o.every(i=>typeof i=="string")){r[s]=[...o];continue}throw new m(`Templates package returned unsupported option value for "${s}" in template "${t}".`,l.GENERIC_FAILURE)}return r}async function pS(e,t,n){if(!mS())throw new m("--template requires the templates package. Install it first (for example: pm install templates --project).",l.USAGE);let r=await Ts({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let s=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new m(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${s}`,l.USAGE)}return uS(r.result,e)}function fS(e){return C(e)}function B(e,t,n){return e.has(t)||n===void 0?void 0:le(n)}function rn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var _S=new Set(["milestone","meeting","reminder","event"]);function a_(e,t,n,r){let s=t!==void 0,o=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return _S.has(e.toLowerCase())&&!s&&!o&&!i}function hS(e,t,n,r,s){let o=[];return e.toLowerCase()==="event"&&(s===void 0||s.length===0)&&o.push(`event_without_schedule:${t}:no_time_set`),a_(e,n,r,s)&&o.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),o}async function gS(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let s=await Cs(r);return s===void 0?{parent:e,parentSource:void 0}:{parent:s,parentSource:"focus"}}async function yS(e,t,n,r,s,o){let i=Bs(s);if(Vs(r,i,t.id_prefix),await D(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let c=be(i,t.id_prefix);return{parent:i,warnings:Hs(c,o).warnings}}async function bS(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await yS(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function wS(e){if(e.explicitId===void 0)return Zn(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new m("--id must be a string",l.USAGE);let t=e.explicitId.trim();if(t.length===0||Ju(t))throw new m("--id must not be empty or use a placeholder token",l.USAGE);let n=be(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new m("--id must contain only letters, numbers, and dashes after normalization",l.USAGE);return n}function t_(e,t,n,r,s){let o=B(e,t,n);if(o===void 0)return{value:void 0,warnings:[]};let i=Xs(r,o,s);return{value:i.value,warnings:i.warnings}}async function vS(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:s,blockedBy:o,status:i,statusExplicit:a,nowValue:c,author:d}=e,u=e.dependencyValues;if(o===void 0)return{dependencyValues:u,status:i};let p=be(o,n.id_prefix),f=await D(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:i};if((u??[]).some(y=>y.id===f.id&&y.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:i};let h=s.blocked_statuses.has("blocked")?"blocked":[...s.blocked_statuses].sort((y,g)=>y.localeCompare(g))[0]??s.open_status;return{dependencyValues:u,status:h}}function kS(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let s=t.governance.create_default_type?.trim();if(s&&s.length>0&&fe(s,n)){e.type=s;return}fe("Task",n)&&(e.type="Task")}function SS(e,t){return e.options.filter(n=>Hn("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new m(`Template custom type option "${n.key}" must be a string, number, or boolean value`,l.USAGE)})}async function ES(e,t,n,r,s){let o=e,i=[];if(o.template!==void 0){let h=o.template.trim();if(h.length===0)throw new m("--template must not be empty. Omit --template to disable template usage.",l.USAGE);let y=await pS(h,t,n);o=r_(dS(y,o))}if(o.type===void 0&&kS(o,r,s),o.type===void 0)throw new m("Missing required option --type <value>",l.USAGE);let a=fe(o.type,s);if(!a){let h=Qu(o.type),y=h?fe(h,s):void 0;if(y)i.push(`type_coercion:${o.type.trim()}:${y}`),o.type=y,a=y;else throw new m(Et(o.type,s.types,At(n,r.schema)),l.USAGE)}let c=Ur(a,s);if(!c)throw new m(`Invalid type value "${o.type}"`,l.USAGE);let d=c.name,u=SS(c,o),p=u.map(h=>`${h.key}=${String(o[h.key])}`);if(p.length>0){o.typeOption=[...p,...o.typeOption??[]];for(let h of u)delete o[h.key]}let f=eS(o.schedulePreset);if(f!==void 0&&!n_.has(d))throw new m(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,l.USAGE);let _=tS(o.createMode,f,r.governance.create_mode_default);return{resolvedOptions:o,typeDefinition:c,type:d,schedulePreset:f,createMode:_,warnings:i}}function AS(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),s=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let o of s)if(o.enabled){if(o.values&&o.values.length>0)throw new m(`Cannot combine ${o.clearFlag} with ${o.valueFlag}`,l.USAGE);n.add(o.metadataKey),r.add(o.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function TS(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=qo.get(r)??r;throw new m(`Cannot combine --unset ${o} with ${he("create",r)}`,l.USAGE)}}function CS(e){let t=(n,r)=>{let s=qo.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;ko(n,he("create",r),o)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function RS(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new m(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,l.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new m(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,l.USAGE)}function IS(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:s,openStatus:o,type:i,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(_=>{let h=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${h}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),u=[i_(n,r,s,o),...d.map(_=>_.example)].join(" "),p=[`Run "pm create --help --type ${i}" for type-aware required option guidance.`];t.includes("--title")&&p.push('Title can also be passed as the first positional argument (example: pm create "Your title" --type '+i+")."),a==="strict"&&(p.push('For staged onboarding, retry with "--create-mode progressive".'),n_.has(i)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&p.push(`Required custom field formats: ${d.map(_=>_.description).join("; ")}.`);let f=t.length===1?`Missing required option ${t[0]} for type "${i}"`:`Missing required options ${t.join(", ")} for type "${i}"`;throw new m(f,l.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${i}" in one invocation.`,examples:[u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:["--create-mode progressive",...t]}:void 0})}function xS(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new m("Cannot combine --unset tags with --add-tags",l.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?xt(t.tags):[];return Tn(n,t.addTags)}function OS(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new m("--order and --rank must match when both are provided",l.USAGE);let n=t.order??t.rank,r=rn(e,"order",n,s=>ce(s,"order"));if(r!==void 0&&!Number.isInteger(r))throw new m("Order must be an integer",l.USAGE);return r}function PS(e,t,n,r,s,o){if(r.completedAt!==void 0&&e!==t.close_status)throw new m("--completed-at requires a terminal create status.",l.USAGE);let i=e!==t.close_status?void 0:r.completedAt===void 0?o:te(r.completedAt,new Date(o),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:i,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:s}:{explicit:r.closeReason};return{closeReason:Ha(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function NS(e){let{pmRoot:t,type:n,id:r,settings:s,typeRegistry:o,author:i,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=Kt(t,n,r,s.item_format,o.type_to_folder),g=Te(t,r),b=Ot(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(j=>b.resolve(j.kind)?.hierarchy),S=await Co({pmRoot:t,author:i,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:v}),x=v,O=[];try{let j=await ye(t,r,s.locks.ttl_seconds,i,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms);try{let L=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await ae(t,s.item_format,o.type_to_folder,void 0,s.schema):void 0;if(await D(t,r,s.id_prefix,s.item_format,o.type_to_folder))throw new m(`Item "${r}" already exists`,l.CONFLICT);if(L){let V=$(s.schema);Qs(L,[...L,c.metadata],r,Ge=>Z(Ge,V),b)}await As({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:Ls({pmRoot:t,settings:s,typeToFolder:o.type_to_folder})});let X=await Sn(t,i,{required:s.governance.duplicate_detection_mode==="strict"&&h!==!0}),ie=[];try{s.governance.duplicate_detection_mode==="strict"&&h!==!0&&await Pn(_,{pmRoot:t,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1}),await pe(y,qe(c,{format:s.item_format,schema:s.schema,extensionFieldNames:a}));try{let V=Ke({nowIso:f,author:i,op:"create",before:d,after:c,message:u});await Ct(g,V)}catch(V){throw await pn(y),V}x&&(await S(),x=!1),ie=await En({pmRoot:t,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:y,document:c})}finally{await X()}O=[...L?ao(L,[...L,c.metadata],r):[],...ie,...await z({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:p}),...await z({path:g,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:p})],gn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Ht(c.metadata,p),changed_fields:p})}finally{await j()}}finally{x&&await S()}return O}async function Nt(e,t){let n=r_(await Qk(e)),r=E(process.cwd(),t.path);await fS(r);let s=await A(r),o=$(s.schema),i=Ye(s.schema),a=I(s,R()),c=await ES(n,t,r,s,a);n=c.resolvedOptions;let{typeDefinition:d,type:u,createMode:p}=c,f=Gk(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=AS(n,f);TS(n,f),CS(n);let y=nS(d,n,p,h),g=k(),b=T(le(n.author),s.author_default),v=jk(n.dep,g,s.id_prefix,b),S=sn("--comment",n.comment,g,b),x=sn("--note",n.note,g,b),O=sn("--learning",n.learning,g,b),j=oc(n.file),L=ic(n.test),Ee=ac(n.doc),X=Kk(n.reminder,g),ie=zk(n.event,g),V=Xk(n.typeOption),Ge=Vn(u,V.values,a),ft=R(),_t=vt(ft),ht=$r(n.field,ft),gt=yu(n,i,u),ki=new Set(gt.missing_required_flags),Si=i.definitions.filter(H=>ki.has(`--${H.cli_flag}`));RS(ht,gt,f);let Bn=rS(Ge.errors,u),Ut=Bn.map(H=>`--type-option ${H}=<value>`),Od=[...new Set([...y,...Ut,...gt.missing_required_flags])].sort((H,Pi)=>H.localeCompare(Pi));IS({combinedMissingFlags:Od,typeDefinition:d,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:Bn,openStatus:o.open_status,type:u,createMode:p,missingRequiredRuntimeFields:Si}),oS(Ge.errors,u,d,o);let Ae=await wS({pmRoot:r,settings:s,typeRegistry:a,explicitId:n.id}),yt=n.status!==void 0?$k(n.status,o):Dk(d,o),Ei=n.priority!==void 0?cS(n.priority):2,N=f.metadataKeys,Ne=xS(N,n),et=rn(N,"deadline",n.deadline,H=>te(H,new Date(g),"deadline")),Ir=rn(N,"estimated_minutes",n.estimatedMinutes,H=>Cn(H,"estimated-minutes")),bt=B(N,"acceptance_criteria",n.acceptanceCriteria),Ai=B(N,"definition_of_ready",n.definitionOfReady),We=OS(N,n),Ti=B(N,"goal",n.goal),xr=B(N,"objective",n.objective),Ab=B(N,"value",n.value),Tb=B(N,"impact",n.impact),Cb=B(N,"outcome",n.outcome),Rb=B(N,"why_now",n.whyNow),Ib=B(N,"assignee",n.assignee),xb=N.has("author")?void 0:le(n.author)??b,Ob=B(N,"parent",n.parent),Pd=await gS(Ob,n,N,r),Ci=Pd.parent,Pb=Pd.parentSource,Nb=B(N,"reviewer",n.reviewer),Lb=rn(N,"risk",n.risk,H=>ke(go(H),mn,"risk")),Fb=rn(N,"confidence",n.confidence,H=>bo(H)),Mb=n.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,Nd=s.validation.sprint_release_format,Gt=[...c.warnings,...hS(u,Ae,et,X.values,ie.values)],Ld=await bS({itemId:Ae,parent:Ci,pmRoot:r,settings:s,typeRegistry:a,policy:Mb});Ci=Ld.parent,Gt.push(...Ld.warnings);let Fd=t_(N,"sprint",n.sprint,"sprint",Nd),$b=Fd.value;Gt.push(...Fd.warnings);let Md=t_(N,"release",n.release,"release",Nd),Db=Md.value;Gt.push(...Md.warnings);let $d=B(N,"blocked_by",n.blockedBy),Dd=await vS({pmRoot:r,settings:s,typeRegistry:a,statusRegistry:o,blockedBy:$d,dependencyValues:v.values,status:yt,statusExplicit:n.status!==void 0,nowValue:g,author:b}),Ri=Dd.dependencyValues;ur(Ae,Ri),Gt.push(...await Qt({pmRoot:r,dependencies:Ri,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ae,createdAt:g}],schema:s.schema})),yt=Dd.status;let Ub=B(N,"blocked_reason",n.blockedReason),Gb=B(N,"unblock_note",n.unblockNote),jb=B(N,"reporter",n.reporter),qb=rn(N,"severity",n.severity,H=>ke(yo(H),un,"severity")),Kb=B(N,"environment",n.environment),zb=B(N,"repro_steps",n.reproSteps),Ud=B(N,"resolution",n.resolution),Bb=B(N,"expected_result",n.expectedResult),Hb=B(N,"actual_result",n.actualResult),Vb=B(N,"affected_version",n.affectedVersion),Wb=B(N,"fixed_version",n.fixedVersion),Yb=B(N,"component",n.component),Jb=rn(N,"regression",n.regression,H=>wo(H)),Xb=B(N,"customer_impact",n.customerImpact),Ii=cc(n.title,"--title"),xi=n.description??"",Or=n.body??"",Gd=await Pn({title:Ii,description:xi,body:Or},{pmRoot:r,mode:s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Gt.push(...co(Gd));let Oi=PS(yt,o,s,n,Ud,g),Qb=Oi.closeReason,Zb=yt===o.close_status?g:void 0,ew=Oi.completedAt;Gt.push(...Oi.warnings);let Pr=da({id:Ae,title:Ii,description:xi,type:u,type_options:Ge.normalized,status:yt,closed_at:Zb,completed_at:ew,close_reason:Qb,priority:Ei,tags:Ne,created_at:g,updated_at:g,deadline:et,assignee:Ib,author:xb,estimated_minutes:Ir,acceptance_criteria:bt,definition_of_ready:Ai,order:We,goal:Ti,objective:xr,value:Ab,impact:Tb,outcome:Cb,why_now:Rb,parent:Ci,reviewer:Nb,risk:Lb,confidence:Fb,sprint:$b,release:Db,blocked_by:$d,blocked_reason:Ub,unblock_note:Gb,reporter:jb,severity:qb,environment:Kb,repro_steps:zb,resolution:Ud,expected_result:Bb,actual_result:Hb,affected_version:Vb,fixed_version:Wb,component:Yb,regression:Jb,customer_impact:Xb,dependencies:Ri,comments:S.values,notes:x.values,learnings:O.values,files:j.values,tests:L.values,docs:Ee.values,reminders:X.values,events:ie.values,...ht,...gt.values});try{Dr(Pr,ft)}catch(H){throw new m(H instanceof Error?H.message:"Invalid extension item field values",l.USAGE)}let tw=Je({metadata:Pr,body:Or},{schema:s.schema,extensionFieldNames:_t}),nw={metadata:{},body:""},jd=[..._].sort((H,Pi)=>H.localeCompare(Pi)),rw=Hk(n.message,jd),qd=Bk(Pr,Or,jd,[...Object.keys(ht),...Object.keys(gt.values??{})]),sw=await NS({pmRoot:r,type:u,id:Ae,settings:s,typeRegistry:a,author:b,extensionFieldNames:_t,afterDocument:tw,beforeDocument:nw,historyMessage:rw,changedFields:qd,nowValue:g,similarityCandidate:{title:Ii,description:xi,body:Or},allowDuplicate:n.allowDuplicate}),Kd=structuredClone(Pr);p==="strict"&&_.has("dependencies")&&(Kd.dependencies=[]);let ow=Yf(Ae,u,yt,o);return a_(u,et,X.values,ie.values)&&Cu(`[pm] warning: ${u} '${Ae}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ae} --deadline <ISO>' or 'pm update ${Ae} --event "start=<ISO>,end=<ISO>"'.`),{item:Kd,changed_fields:qd,warnings:[...Gt,...sw],...Object.fromEntries([["parent_source",Pb],["next_transition",ow],["similarity_advisory",Gd]].filter(H=>H[1]!==void 0))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c1729f8-4a67-5746-a1bf-351f862ceb66")}catch{}})();var uc=[...Za,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...ec,...Uo],LS=(()=>{let e=new Map;for(let t of uc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),zo=new Map(uc.map(e=>[e.optionKey,e.canonical])),FS=uc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),MS=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),$S=vo({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function DS(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=s=>{let o=t.unset?[...t.unset]:[];o.includes(s)||o.push(s),t.unset=o},r=new Set([...zo.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Be(o))continue;let i=s==="rank"?"order":zo.get(s)??s;n(i),t[s]=void 0}return So(t,$S)}function __(e,t,n=[]){return Go({raw:e,supportedFields:FS,resolveDefinition:r=>{let s=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return LS.get(r)??jo(r,"update",t)??(s?{optionKey:"field",metadataKey:s}:void 0)}})}var c_=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function d_(e){let t=e.disallowedFlags.flatMap(r=>{let s=c_.get(r);return s?[s(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let s=c_.get(r);return s?[`Replace ${r} with: ${s(e.id)}`]:[]});return new m(e.message,l.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function US(e,t,n){let r=t.ownershipMetadataBypass===!0,s=t.ownershipDependencyBypass===!0;if(!r&&!s)return;if(r&&s)throw new m("Choose only one package-provided ownership bypass mode.",l.USAGE);let o=(c,d,u)=>{c&&u.push(d)};if(s){let c=[];if(o(t.title!==void 0,"--title",c),o(t.description!==void 0,"--description",c),o(t.body!==void 0,"--body",c),o(t.status!==void 0,"--status",c),o(t.closeReason!==void 0,"--close-reason",c),o(t.priority!==void 0,"--priority",c),o(t.type!==void 0,"--type",c),o(t.tags!==void 0,"--tags",c),o(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),o(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),o(t.deadline!==void 0,"--deadline",c),o(t.estimatedMinutes!==void 0,"--estimate",c),o(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),o(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),o(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),o(t.definitionOfReady!==void 0,"--definition-of-ready",c),o(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),o(t.goal!==void 0,"--goal",c),o(t.objective!==void 0,"--objective",c),o(t.value!==void 0,"--value",c),o(t.impact!==void 0,"--impact",c),o(t.outcome!==void 0,"--outcome",c),o(t.whyNow!==void 0,"--why-now",c),o(t.assignee!==void 0,"--assignee",c),o(t.parent!==void 0,"--parent",c),o(t.reviewer!==void 0,"--reviewer",c),o(t.risk!==void 0,"--risk",c),o(t.confidence!==void 0,"--confidence",c),o(t.sprint!==void 0,"--sprint",c),o(t.release!==void 0,"--release",c),o(t.blockedBy!==void 0,"--blocked-by",c),o(t.blockedReason!==void 0,"--blocked-reason",c),o(t.unblockNote!==void 0,"--unblock-note",c),o(t.reporter!==void 0,"--reporter",c),o(t.severity!==void 0,"--severity",c),o(t.environment!==void 0,"--environment",c),o(t.reproSteps!==void 0,"--repro-steps",c),o(t.resolution!==void 0,"--resolution",c),o(t.expectedResult!==void 0,"--expected-result",c),o(t.actualResult!==void 0,"--actual-result",c),o(t.affectedVersion!==void 0,"--affected-version",c),o(t.fixedVersion!==void 0,"--fixed-version",c),o(t.component!==void 0,"--component",c),o(t.regression!==void 0,"--regression",c),o(t.customerImpact!==void 0,"--customer-impact",c),o(t.depRemove!==void 0,"--dep-remove",c),o(t.replaceDeps===!0,"--replace-deps",c),o(t.replaceTests===!0,"--replace-tests",c),o(t.replaceFiles===!0,"--replace-files",c),o(t.replaceDocs===!0,"--replace-docs",c),o(t.comment!==void 0,"--comment",c),o(t.note!==void 0,"--note",c),o(t.learning!==void 0,"--learning",c),o(t.file!==void 0,"--file",c),o(t.test!==void 0,"--test",c),o(t.doc!==void 0,"--doc",c),o(t.reminder!==void 0,"--reminder",c),o(t.event!==void 0,"--event",c),o(t.typeOption!==void 0,"--type-option",c),o(t.clearDeps===!0,"--clear-deps",c),o(t.clearComments===!0,"--clear-comments",c),o(t.clearNotes===!0,"--clear-notes",c),o(t.clearLearnings===!0,"--clear-learnings",c),o(t.clearFiles===!0,"--clear-files",c),o(t.clearTests===!0,"--clear-tests",c),o(t.clearDocs===!0,"--clear-docs",c),o(t.clearReminders===!0,"--clear-reminders",c),o(t.clearEvents===!0,"--clear-events",c),o(t.clearTypeOptions===!0,"--clear-type-options",c),o(t.force===!0,"--force",c),o(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new m("The dependency ownership bypass requires at least one --dep value",l.USAGE);if(c.length>0)throw d_({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let i=[];o(t.status!==void 0,"--status",i),o(t.closeReason!==void 0,"--close-reason",i),o(t.assignee!==void 0,"--assignee",i),o(t.parent!==void 0,"--parent",i),o(t.blockedBy!==void 0,"--blocked-by",i),o(t.blockedReason!==void 0,"--blocked-reason",i),o(t.unblockNote!==void 0,"--unblock-note",i),o(t.dep!==void 0,"--dep",i),o(t.depRemove!==void 0,"--dep-remove",i),o(t.replaceDeps===!0,"--replace-deps",i),o(t.replaceTests===!0,"--replace-tests",i),o(t.replaceFiles===!0,"--replace-files",i),o(t.replaceDocs===!0,"--replace-docs",i),o(t.note!==void 0,"--note",i),o(t.learning!==void 0,"--learning",i),o(t.test!==void 0,"--test",i),o(t.reminder!==void 0,"--reminder",i),o(t.event!==void 0,"--event",i),o(t.clearDeps===!0,"--clear-deps",i),o(t.clearComments===!0,"--clear-comments",i),o(t.clearNotes===!0,"--clear-notes",i),o(t.clearLearnings===!0,"--clear-learnings",i),o(t.clearFiles===!0,"--clear-files",i),o(t.clearTests===!0,"--clear-tests",i),o(t.clearDocs===!0,"--clear-docs",i),o(t.clearReminders===!0,"--clear-reminders",i),o(t.clearEvents===!0,"--clear-events",i);let a=[...n].filter(c=>MS.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw d_({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${i.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:i})}function GS(e,t){let n=Y(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new m(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n}function jS(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Fm({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Y(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Y(e.toStatus,e.statusRegistry)??e.toStatus,s=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Mm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new m(s,l.USAGE);return`workflow_transition_not_allowed: ${s}`}function qS(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:h_(e)}function h_(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new m(`Invalid dependency created_at timestamp "${e}"`,l.USAGE);return new Date(t).toISOString()}function $n(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var KS=["id","kind","type","author","created_at","source_kind"],zS=["id","kind","type","author","created_at","source_kind"];function g_(e){return e.startsWith("```")||e.includes(`
8
+ `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Js(e)}function y_(e){return typeof e=="string"?jr(e)??e.trim():e}function Ho(e,t,n,r){return e?(ve(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=g_(i);mr(i,a);let c=a?se(o,"--dep"):{id:i,kind:"related"};a&&ze(c,"--dep",KS);let d=c.id?.trim(),u=y_((c.kind??c.type)?.trim());if(!d||!u)throw new m("--dep requires id and kind, or a bare item id to add a related dependency",l.USAGE);if(d.toLowerCase()==="undefined")throw new m(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,l.USAGE);let p=tr($n(c.source_kind)),f=$n(c.author);return{id:nr(d,t,p),kind:ke(u,jt,"dependency kind"),created_at:qS(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function BS(e,t){return e?(ve(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new m("--dep-remove requires id or key/value selectors",l.USAGE);let s=g_(r);if(mr(r,s,"--dep-remove"),s){let o=se(r,"--dep-remove");ze(o,"--dep-remove",zS);let i=o.id?.trim();if(!i)throw new m("--dep-remove key/value form requires id=<value>",l.USAGE);if(i.toLowerCase()==="undefined")throw new m(`--dep-remove id must not use placeholder token "${i}"`,l.USAGE);let a=y_($n(o.kind??o.type)),c=tr($n(o.source_kind)),d=$n(o.author),u=$n(o.created_at);return{id:nr(i,t,c),kind:a?ke(a,jt,"dependency kind"):void 0,source_kind:c,author:d,created_at:u?h_(u):void 0}}if(r.toLowerCase()==="undefined")throw new m(`--dep-remove id must not use placeholder token "${r}"`,l.USAGE);return{id:be(r,t)}})):[]}function Bo(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function HS(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",s=Date.parse(r),o=Number.isFinite(s)?new Date(s).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,o].join("\0")}function VS(e,t,n,r){let s=[...e??[]],o=!1;if(t===void 0){let i=s.filter(a=>a.kind!=="blocked_by");return i.length!==s.length&&(s=i,o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}return s.some(i=>i.kind==="blocked_by"&&i.id===t)||(s.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}async function WS(e,t,n,r,s,o){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await D(n,be(i,r),r,s,o);return a?{id:a.id}:{unresolved:i}}function YS(e,t,n,r,s){let o=VS(e.dependencies,t,n,r);o.changed&&(o.dependencies===void 0?delete e.dependencies:e.dependencies=o.dependencies,s.includes("dependencies")||s.push("dependencies"))}function JS(e){return`${e.path}::${e.scope}`}function XS(e){return`${e.path}::${e.scope}`}function QS(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}`}function b_(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function ZS(e){return Rn(e)}function l_(e,t){let n=Hn("update",e);if(!n)throw new m(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,l.CONFLICT);return n}function eE(e,t,n){let r=new Set,s=(o,i)=>{i&&r.add(o)};if(s("title",e.title!==void 0),s("description",e.description!==void 0),s("body",e.body!==void 0),s("status",e.status!==void 0),s("closeReason",e.closeReason!==void 0),s("priority",e.priority!==void 0),s("type",e.type!==void 0),s("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),s("deadline",e.deadline!==void 0),s("estimatedMinutes",e.estimatedMinutes!==void 0),s("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),s("definitionOfReady",e.definitionOfReady!==void 0),s("order",e.order!==void 0||e.rank!==void 0),s("goal",e.goal!==void 0),s("objective",e.objective!==void 0),s("value",e.value!==void 0),s("impact",e.impact!==void 0),s("outcome",e.outcome!==void 0),s("whyNow",e.whyNow!==void 0),s("author",e.author!==void 0),s("message",e.message!==void 0),s("assignee",e.assignee!==void 0),s("parent",e.parent!==void 0),s("reviewer",e.reviewer!==void 0),s("risk",e.risk!==void 0),s("confidence",e.confidence!==void 0),s("sprint",e.sprint!==void 0),s("release",e.release!==void 0),s("blockedBy",e.blockedBy!==void 0),s("blockedReason",e.blockedReason!==void 0),s("unblockNote",e.unblockNote!==void 0),s("reporter",e.reporter!==void 0),s("severity",e.severity!==void 0),s("environment",e.environment!==void 0),s("reproSteps",e.reproSteps!==void 0),s("resolution",e.resolution!==void 0),s("expectedResult",e.expectedResult!==void 0),s("actualResult",e.actualResult!==void 0),s("affectedVersion",e.affectedVersion!==void 0),s("fixedVersion",e.fixedVersion!==void 0),s("component",e.component!==void 0),s("regression",e.regression!==void 0),s("customerImpact",e.customerImpact!==void 0),s("dep",e.dep!==void 0),s("depRemove",e.depRemove!==void 0),s("dep",e.replaceDeps===!0),s("comment",e.comment!==void 0),s("note",e.note!==void 0),s("learning",e.learning!==void 0),s("file",e.file!==void 0),s("test",e.test!==void 0),s("test",e.replaceTests===!0),s("file",e.replaceFiles===!0),s("doc",e.replaceDocs===!0),s("doc",e.doc!==void 0),s("reminder",e.reminder!==void 0),s("event",e.event!==void 0),s("typeOption",e.typeOption!==void 0),s("field",e.field!==void 0),s("force",e.force===!0),s("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),s("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),s("dep",e.clearDeps===!0),s("comment",e.clearComments===!0),s("note",e.clearNotes===!0),s("learning",e.clearLearnings===!0),s("file",e.clearFiles===!0),s("test",e.clearTests===!0),s("doc",e.clearDocs===!0),s("reminder",e.clearReminders===!0),s("event",e.clearEvents===!0),s("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let o=__(e.unset,t,n);for(let i of o.optionKeys)s(i,!0)}return r}function tE(e,t,n,r,s){let o=Ur(e,n);if(!o)throw new m(`Invalid type value "${e}"`,l.USAGE);let i=fn(o,"update",[]);if(i.errors.length>0)throw new m(i.errors.join("; "),l.CONFLICT);let a=eE(t,r,s);for(let c of i.disabled)if(a.has(l_(c,e)))throw new m(`Option ${he("update",c)} is disabled for type "${e}" by command_option_policies`,l.USAGE);for(let c of i.required)if(!a.has(l_(c,e)))throw new m(`Missing required option ${he("update",c)} for type "${e}"`,l.USAGE)}var nE=new Set(["order","rank"]),rE=ji.filter(e=>!nE.has(e)),w_=["tags","closeReason",...rE],sE=["title","description","body","status","closeReason","completedAt","priority","type",...ji,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],oE=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>te(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Cn(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],iE=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>ke(go(e),mn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>bo(e)}],aE=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>ke(yo(e),un,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>wo(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function mc(e,t,n){for(let r of e){let s=t[r.optionKey],o=n.clearItemMetadataKeys.has(r.metadataKey);if(!(s===void 0&&!o)){if(o){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof s!="string")throw new m(`${he("update",String(r.optionKey))} must be a string value`,l.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(s,n):s.trim(),n.changedFields.push(r.metadataKey)}}}async function cE(e){let t=Fe();return DS({...e,body:await t.resolveValue(e.body,"--body"),dep:await t.resolveList(e.dep,"--dep"),depRemove:await t.resolveList(e.depRemove,"--dep-remove"),comment:await t.resolveList(e.comment,"--comment"),note:await t.resolveList(e.note,"--note"),learning:await t.resolveList(e.learning,"--learning"),file:await t.resolveList(e.file,"--file"),test:await t.resolveList(e.test,"--test"),doc:await t.resolveList(e.doc,"--doc"),reminder:await t.resolveList(e.reminder,"--reminder"),event:await t.resolveList(e.event,"--event"),typeOption:await t.resolveList(e.typeOption,"--type-option"),field:await t.resolveList(e.field,"--field")})}function dE(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function dc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new m(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,l.USAGE);if(e.enabled&&e.clearEnabled)throw new m(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,l.USAGE)}function pc(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new m("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",l.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new m("--replace-deps requires at least one --dep entry",l.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new m("--replace-deps cannot be combined with --dep-remove",l.USAGE);dc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),dc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),dc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function lE(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new m(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,l.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function mE(e){let t={};for(let n of w_)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function uE(e,t){let n=mE(e);for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=zo.get(r)??r;throw new m(`Cannot combine --unset ${o} with ${he("update",r)}`,l.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new m("Cannot combine --unset acceptance-criteria with --add-ac",l.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new m("Cannot combine --unset acceptance-criteria with --remove-ac",l.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new m("Cannot combine --unset tags with --add-tags",l.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new m("Cannot combine --unset tags with --remove-tags",l.USAGE)}}function pE(e){let t=(n,r)=>{let s=zo.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;ko(n,he("update",r),o)};for(let n of w_)t(e[n],String(n));t(e.order??e.rank,"order"),ve(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),ve(e.event,"--event","Use --clear-events to clear linked events.")}function fE(e,t){let n={};for(let r of sE)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.runtimeFields=Object.keys(t).length>0,n}async function _E(e){let t=await D(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await at(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await K(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function hE(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return ae(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function gE(e){e.before&&Qs(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>Z(t,e.statusRegistry),Ot())}async function yE(e){await C(e)}function bE(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new m("--order and --rank must match when both are provided",l.USAGE)}async function wE(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Bs(e.options.parent);if(Vs(e.id,t,e.settings.id_prefix),await D(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=be(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:Hs(r,e.parentReferencePolicy).warnings}}function vE(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function kE(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await D(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await at(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await K(t,{schema:e.settings.schema}),r=e.options.type!==void 0?fe(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",s=jS({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return s?[s]:[]}async function SE(e){if(!e.fieldFlags.status||Y(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],s=[];if(n.length>0){let a=await dt(e.id,{...e.options,status:void 0,closeReason:void 0,message:void 0},e.global);s=a.changed_fields,r.push(...a.warnings)}let o=await ct(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...e.workflowTransitionWarnings,...r,...o.warnings,"auto_routed_from_update_to_close"];return{item:o.item,changed_fields:[...s,...o.changed_fields],warnings:i}}function EE(e,t,n,r){return t.title!==void 0&&(e.metadata.title=cc(t.title,"--title"),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),Y(e.metadata.status,n)??e.metadata.status}function AE(e,t,n,r,s){let o=GS(n,t.statusRegistry);if(e.metadata.status=o,s.push("status"),o===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,s.push("closed_at","completed_at");return}!Z(o,t.statusRegistry)&&Z(r,t.statusRegistry)&&e.metadata.closed_at!==void 0&&(delete e.metadata.closed_at,s.push("closed_at"),e.metadata.completed_at!==void 0&&(delete e.metadata.completed_at,s.push("completed_at")))}function TE(e,t,n,r){if(t.options.status!==void 0&&AE(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!Z(e.metadata.status,t.statusRegistry))throw new m("--completed-at can only be set on a terminal item",l.USAGE);e.metadata.completed_at=te(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function CE(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let s=t.options.closeReason?.trim()??"";if(s.length===0)throw new m("--close-reason must not be empty",l.USAGE);e.metadata.close_reason=s}r.push("close_reason");return}t.options.status!==void 0&&Z(n,t.statusRegistry)&&!Z(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function RE(e,t,n,r){TE(e,t,n,r),CE(e,t,n,r)}function IE(e,t,n){let r=fe(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=ZS(t.options.priority),n.push("priority")),t.options.type!==void 0){let s=fe(t.options.type,t.typeRegistry);if(!s)throw new m(Et(t.options.type,t.typeRegistry.types,At(t.pmRoot,t.settings.schema)),l.USAGE);e.metadata.type=s,r=s,n.push("type")}return tE(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),xE(e,t,r,n),r}function xE(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let o=To(t.options.typeOption??[]),i=Vn(n,o,t.typeRegistry);if(i.errors.length>0)throw new m(i.errors.join("; "),l.USAGE);e.metadata.type_options=i.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let s=Vn(n,e.metadata.type_options,t.typeRegistry);if(s.errors.length>0)throw new m(`Current type options are incompatible with type "${n}". ${s.errors.join("; ")}. Use --clear-type-options to clear them.`,l.USAGE);e.metadata.type_options=s.normalized}function OE(e,t){let n=new Set(t.map(s=>Bo(s))),r=new Set;return e.filter(s=>{if(!n.has(Bo(s)))return!0;let o=HS(s);return r.has(o)?!1:(r.add(o),!0)})}function PE(e,t,n){let r=t.filter(s=>!e.some(o=>b_(o,s)));if(r.length!==0)throw new m(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,l.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(s=>({id:s.id,kind:s.kind,source_kind:s.source_kind,author:s.author,created_at:s.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function NE(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=OE(r,t.dependencyUpdates.additions);let s=new Set(r.map(o=>Bo(o)));for(let o of t.dependencyUpdates.additions){let i=Bo(o);s.has(i)||(r.push(o),s.add(i))}}t.dependencyRemovals.length>0&&(PE(r,t.dependencyRemovals,e.metadata.id),r=r.filter(s=>!t.dependencyRemovals.some(o=>b_(s,o)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function LE(e,t,n){lc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),lc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),lc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function lc(e,t,n,r,s,o){n===void 0&&!s.has(t)||(s.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],o.push(t))}function FE(e,t,n){m_(e,"files",t.options.file,t.fileUpdates.values,JS,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),ME(e,t,n),m_(e,"docs",t.options.doc,t.docUpdates.values,XS,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function m_(e,t,n,r,s,o,i,a){if(!(n===void 0&&!i.has(t))){if(o)e.metadata[t]=r;else if(i.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(u=>s(u)));for(let u of r){let p=s(u);d.has(p)||(c.push(u),d.add(p))}e.metadata[t]=c}a.push(t)}}function ME(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=u_(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=u_([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function u_(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let s=QS(r);n.has(s)||(t.push(r),n.add(s))}return t}function $E(e,t,n){let r=t.options.addTags,s=t.options.removeTags,o=Array.isArray(r)&&r.length>0||Array.isArray(s)&&s.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||o){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?xt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Ys(Tn(i,r),s),n.changedFields.push("tags")}mc(oE,t.options,n),UE(e,t,n.changedFields)}function DE(e,t,n){let r=t.options.addAc,s=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(s)&&s.length>0))return;let o=Ws(An(e.metadata.acceptance_criteria),r,s);if(o.unmatchedRemovals.length>0)throw new m(`Acceptance criteria removal did not match: ${o.unmatchedRemovals.join(", ")}`,l.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:o.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let i=o.criteria.join("; ");e.metadata.acceptance_criteria!==i&&(i===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=i,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function UE(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let s=ce(r??"","order");if(!Number.isInteger(s))throw new m("Order must be an integer",l.USAGE);e.metadata.order=s}n.push("order")}}function GE(e,t,n,r){jE(e,t,n.changedFields),qE(e,t,n.changedFields),mc(iE,t.options,n),p_(e,t,"sprint",r,n.changedFields),p_(e,t,"release",r,n.changedFields),KE(e,t,n.changedFields),mc(aE,t.options,n)}function jE(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new m("--assignee must not be empty. Use --unset assignee to clear it.",l.USAGE);e.metadata.assignee=r}n.push("assignee")}}function qE(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function p_(e,t,n,r,s){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let o=Xs(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=o.value,r.push(...o.warnings)}s.push(n)}}function KE(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&YS(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function zE(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Eo(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=Ao(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function BE(e,t,n){f_(e,t.runtimeFieldRegistry.definitions.map(s=>s.metadata_key),t.clearItemMetadataKeys,n),f_(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[s,o]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(s)){let i=s.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(d=>d.metadata_key===s)?.cli_flag??i;throw new m(`Cannot combine --unset ${i} with --${c}`,l.USAGE)}rt(e[s],o)||(e[s]=o,n.push(s))}let r=$r(t.options.field,t.extensionRegistrations);for(let s of Object.keys(r))if(t.clearItemMetadataKeys.has(s))throw new m(`Cannot combine --unset ${s.replaceAll("_","-")} with --field ${s}=...`,l.USAGE);for(let[s,o]of Object.entries(r))rt(e[s],o)||(e[s]=o,n.push(s))}function f_(e,t,n,r){for(let s of t)!n.has(s)||e[s]===void 0||(delete e[s],r.push(s))}function HE(e,t){let n=structuredClone(e.metadata),r=e.body,s=[],o=[],i=EE(e,t.options,t.statusRegistry,s),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:s,nowValue:t.nowValue};RE(e,t,i,s),IE(e,t,s),NE(e,t,s),LE(e,t,s),FE(e,t,s),$E(e,t,c),DE(e,t,c),GE(e,t,c,o),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&ur(e.metadata.id,e.metadata.dependencies),Y(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,s.includes("assignee")||s.push("assignee")),zE(e,t,s),BE(a,t,s);try{Dr(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(p){throw new m(p instanceof Error?p.message:"Invalid extension item field values",l.USAGE)}let d=e.metadata,u=[...new Set(s)].filter(p=>p==="body"?e.body!==r:!rt(n[p],d[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&o.push(`acceptance_criteria_replaced:${An(n.acceptance_criteria).length}:${An(d.acceptance_criteria).length}`),{changedFields:u,warnings:o}}async function v_(e,t,n,r={}){t=await cE(t);let s=E(process.cwd(),n.path);await yE(s);let o=await A(s),i=$(o.schema),a=Ye(o.schema),c=R(),d=vt(c),u=I(o,c),p=o.governance.workflow_enforcement??"off",f=p==="off"?[]:Lm(o.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][o.validation.parent_reference],h=__(t.unset,a,d),y=new Set(h.optionKeys),g=new Set(h.metadataKeys);pc(t),lE({definitions:dE(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:g}),US(e,t,g),uE(t,h),pE(t);let b=T(t.author,o.author_default),v=new Date,S=v.toISOString(),x=Ho(t.dep,o.id_prefix,S,b);ur(e,x.additions);let O=await Qt({pmRoot:s,dependencies:x.additions,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:o.schema}),j=BS(t.depRemove,o.id_prefix),L=sn("--comment",t.comment,S,b),Ee=t.ownershipMetadataBypass===!0&&L.values?{...L,values:L.values.map(Ne=>({...Ne,author:b}))}:L,X=sn("--note",t.note,S,b),ie=sn("--learning",t.learning,S,b),V=oc(t.file),Ge=ic(t.test),ft=ac(t.doc),_t=[],ht=await wE({id:e,options:t,unsetTargets:h,pmRoot:s,settings:o,typeRegistry:u,parentReferencePolicy:_}),gt=await WS(t.blockedBy,g.has("blocked_by"),s,o.id_prefix,o.item_format,u.type_to_folder),ki=gt.id,Si=[...ht.warnings,...vE(gt)],Bn=Is(t,a,t.runtimeFieldCommands),Ut=fE(t,Bn);if(!Object.values(Ut).some(Boolean))return _E({pmRoot:s,id:e,settings:o,typeRegistry:u});_t.push(...await kE({options:t,fieldFlags:Ut,workflowEnforcement:p,typeWorkflows:f,statusRegistry:i,typeRegistry:u,pmRoot:s,id:e,settings:o}));let Ae=await SE({options:t,fieldFlags:Ut,statusRegistry:i,workflowTransitionWarnings:_t,global:n,id:e});if(Ae)return Ae;bE(t);let yt=Ot(),Ei=Ut.parent&&!g.has("parent")||x.additions.some(Ne=>yt.resolve(Ne.kind)?.hierarchy),N=await Co({pmRoot:s,author:b,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:Ei});try{let Ne=await hE({fieldFlags:Ut,clearedMetadataKeys:g,pmRoot:s,settings:o,typeToFolder:u.type_to_folder}),et,Ir,bt=await Gu({pmRoot:s,settings:o,typeToFolder:u.type_to_folder,id:e,op:VE(t,r),author:b,message:t.message,resolveHistoryContext:()=>Ir,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:d,skipNoop:!0,mutate(We){et=WE({document:We,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),Ir=et?{recurrence:et}:void 0,Ne=Ne?.map(xr=>xr.id===We.metadata.id?structuredClone(We.metadata):xr);let Ti=HE(We,{options:t,settings:o,typeRegistry:u,statusRegistry:i,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:d,clearItemMetadataKeys:g,dependencyUpdates:x,dependencyRemovals:j,commentUpdates:Ee,noteUpdates:X,learningUpdates:ie,fileUpdates:V,testUpdates:Ge,docUpdates:ft,resolvedParentValue:ht.resolvedParentValue,resolvedBlockedByDependencyId:ki,runtimeFieldUpdates:Bn,nowValue:v,nowIso:S,author:b,pmRoot:s});return gE({before:Ne,document:We,statusRegistry:i}),Ti}});await N();let Ai=Ne?ao(Ne,Ne.map(We=>We.id===bt.item.id?bt.item:We),bt.item.id):[];return{item:bt.item,changed_fields:bt.changedFields,warnings:[..._t,...Si,...O,...Ai,...bt.warnings],...et===void 0?{}:{lifecycle_transition:et}}}finally{await N()}}function VE(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function WE(e){if(e.recurrenceReason===void 0)return;let t=Y(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!Z(t,e.statusRegistry))throw new m(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,l.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=Y(n,e.statusRegistry)??n,s=e.document.metadata,o=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(i=>{let a=s[i];return typeof a=="string"?[[i,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:o}}async function dt(e,t,n){return v_(e,t,n)}async function k_(e,t,n,r){let s=await v_(e,t,n,{recurrenceReason:r});if(s.lifecycle_transition===void 0)throw new m(`Item ${e} did not produce the required recurrence receipt.`,l.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...s,lifecycle_transition:s.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a157c2e-e9e6-5bce-b124-0a7d34e3c7dc")}catch{}})();var E_=1,_c="update-many",YE=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),JE=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),XE={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},QE=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],ZE={close_reason:"close_reason","close-reason":"close_reason",deadline:"deadline",estimate:"estimated_minutes",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",ac:"acceptance_criteria",definition_of_ready:"definition_of_ready","definition-of-ready":"definition_of_ready",order:"order",rank:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",why_now:"why_now","why-now":"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blocked_by:"blocked_by","blocked-by":"blocked_by",blocked_reason:"blocked_reason","blocked-reason":"blocked_reason",unblock_note:"unblock_note","unblock-note":"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",repro_steps:"repro_steps","repro-steps":"repro_steps",resolution:"resolution",expected_result:"expected_result","expected-result":"expected_result",actual_result:"actual_result","actual-result":"actual_result",affected_version:"affected_version","affected-version":"affected_version",fixed_version:"fixed_version","fixed-version":"fixed_version",component:"component",regression:"regression",customer_impact:"customer_impact","customer-impact":"customer_impact",type_options:"type_options","type-options":"type_options",tags:"tags"},A_=e=>{let t={};for(let[n,r]of Object.entries(e))YE.has(n)||r!==void 0&&(t[n]=r);return t},eA=e=>Object.keys(A_(e)).length>0,T_=e=>typeof e=="string"?e.trim():e,tA=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},fc=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},nA=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??T_(e)},rA={priority:tA,estimatedMinutes:fc,order:fc,rank:fc,regression:nA},sA=(e,t)=>{if(t!==void 0)return(rA[e]??T_)(t)},oA=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return ZE[t]??t},Vo=(e,t)=>rt(e,t),iA=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],aA=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,cA=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",S_=(e,t)=>t===void 0?void 0:e[t],Dn=e=>Array.isArray(e)?e.length:0,dA=(e,t,n)=>{let r=n[e.addKey],s=S_(n,e.removeKey),o=Dn(r),i=Dn(s),a=n[e.clearKey]===!0,c=S_(n,e.replaceKey)===!0;if(![a,c,o>0,i>0].includes(!0))return;let d=iA(e.field,t[e.field]);return{field:e.field,before:d,after:{operation:cA({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:o,remove_count:i,before_count:aA(e.field,d)}}},lA=(e,t)=>{let n=[];for(let r of QE){let s=dA(r,e,t);s!==void 0&&n.push(s)}return n},mA=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],uA=(e,t)=>{if(![t.tags!==void 0,Dn(t.addTags)>0,Dn(t.removeTags)>0].includes(!0))return;let n=mA(e.tags),r=t.tags===void 0?n:xt(t.tags),s=Tn(r,t.addTags),o=Ys(s,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!Vo(i,o))return{field:"tags",before:n,after:o}},pA=(e,t)=>{let n=e.acceptance_criteria,r=Ws(An(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new m(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,l.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let s=r.criteria.join("; ");if(!Vo(typeof n=="string"?n:"",s))return{field:"acceptance_criteria",before:n,after:s}},fA=(e,t,n)=>{for(let[r,s]of Object.entries(XE)){let o=n[r];if(o===void 0)continue;let i=t[s],a=sA(r,o);Vo(i,a)||e.push({field:s,before:i,after:a})}},_A=(e,t,n,r)=>{let s=Is(n,r,["update_many"]);for(let[o,i]of Object.entries(s)){let a=t[o];Vo(a,i)||e.push({field:o,before:a,after:i})}},hA=(e,t,n)=>{for(let r of n??[]){let s=oA(r),o=t[s];o!==void 0&&e.push({field:s,before:o,after:null})}},gA=(e,t,n={})=>{let r=e,s=[],o=uA(r,n);if(o&&s.push(o),fA(s,r,n),Dn(n.addAc)>0||Dn(n.removeAc)>0){let i=pA(r,n);i!==void 0&&s.push(i)}return s.push(...lA(r,n)),_A(s,r,n,t),hA(s,r,n.unset),{id:e.id,changes:s}},yA=(e,t)=>Xu(e,t,{strict:!0,flagLabel:"--filter-status"}),bA=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new m("--ids requires at least one non-empty item ID",l.USAGE)},wA=[({update:e})=>{e.priority!==void 0&&Rn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=I(t,R());if(!fe(e.type,r))throw new m(Et(e.type,r.types,At(n,t.schema)),l.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!Y(e.status,t)){let n=t.definitions.map(r=>r.id);throw new m(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,l.USAGE)}},({update:e})=>{e.deadline!==void 0&&te(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&Cn(e.estimatedMinutes,"estimated-minutes")}],vA=(e,t,n,r)=>{let s={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let o of wA)o(s)},kA=async e=>{let t=await js(e.pmRoot,_c,e.rollbackId,E_),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await qs(t.items,(s,o)=>Xt(s,o,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...Bt({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},SA=async e=>{let t={schema_version:E_,id:e.checkpointId,created_at:e.nowValue,author:T(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Gs(e.pmRoot,_c,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},EA=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(s=>s.trim()).filter(s=>s.length>0))],r=new Set(t.map(s=>s.id));return n.filter(s=>!r.has(s))},hc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},AA=async e=>{let t=E(process.cwd(),e.path);await C(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:$(n.schema),runtimeFieldRegistry:Ye(n.schema)}},TA=e=>{if(e.options.dryRun===!0)throw new m("--dry-run cannot be combined with --rollback",l.USAGE);if(or(e.options.list,e.options.status))throw new m("Rollback mode does not accept filter options",l.USAGE);if(Object.keys(e.updateSummary).length>0)throw new m("Rollback mode does not accept update mutation flags",l.USAGE);return kA({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},CA=async e=>{yA(e.options.status,e.runtime.statusRegistry);let t=await Pt(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(s=>{let o=gA(s,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?o:{...o,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await Pt(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(s=>s.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:EA(e.options.list?.ids,r)}},RA=e=>({outcome:"effect",exit_code:l.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...hc(e)}),IA=e=>({...Bt({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...hc(e)}),xA=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,s=new Set(e.plans.filter(o=>o.changes.length>0).map(o=>o.id));for(let o of e.items){if(!s.has(o.id)){t.push({id:o.id,status:"skipped"});continue}try{let i=await dt(o.id,{...e.options.update,message:r,runtimeFieldCommands:["update_many"]},e.global);t.push({id:o.id,status:"updated",changed_fields:i.changed_fields,warnings:i.warnings}),n.push(o.id)}catch(i){t.push({id:o.id,status:"failed",error:_n(i)})}}return{rows:t,updatedIds:n}},OA=async e=>{if(e.plan.actionable.length===0)return IA(e.plan);let t=k(),n=Us(_c,t),r=new Set(e.plan.actionable.map(p=>p.id)),s=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),o=e.options.checkpoint===!1?void 0:await SA({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:s}),i=await xA({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=p=>i.rows.filter(f=>f.status===p).length,c=a("updated"),d=a("skipped"),u=a("failed");return{...Bt({applied:c,skipped:d,failed:u,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...o?{checkpoint:o}:{},updated_count:c,skipped_count:d,failed_count:u,rows:i.rows,ids:i.updatedIds,...hc(e.plan)}},C_=async(e,t)=>{let n=await AA(t),r=typeof e.rollback=="string"?e.rollback:void 0,s=A_(e.update);if(bA(e.list),r!==void 0)return TA({runtime:n,rollbackId:r,options:e,global:t,updateSummary:s});if(!eA(e.update))throw new m(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${JE}).`,l.USAGE);vA(e.update,n.settings,n.statusRegistry,n.pmRoot),pc(e.update);let o=await Qt({pmRoot:n.pmRoot,dependencies:Ho(e.update.dep,n.settings.id_prefix,k(),T(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:I(n.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await CA({options:e,global:t,runtime:n,updateSummary:s,dependencyWarnings:o});return await Qt({pmRoot:n.pmRoot,dependencies:Ho(e.update.dep,n.settings.id_prefix,k(),T(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:I(n.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:i.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:n.settings.schema}),e.dryRun===!0?RA(i):OA({runtime:n,options:e,global:t,plan:i})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="49fd5730-99c2-5a93-a80e-83c806a124bf")}catch{}})();var PA=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],R_=["brief","standard","deep"],O_="plan-step-",kc="draft",vc=["bug-investigation","feature-implementation","refactoring-sprint"],I_={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function NA(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(I_,t)?I_[t]:void 0;if(!n)throw new m(`Unknown plan template "${e}". Allowed: ${vc.join(", ")}`,l.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${vc[0]}`]});return n.map(r=>({...r}))}function LA(e,t){return t>0?Math.round(e/t*100):0}function P_(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function De(e){return Array.isArray(e)?e.flatMap(t=>In(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?In(e,{unique:!1}):[]}function Se(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function N_(e,t=kc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Fi.find(s=>s===n);if(!r)throw new m(`Invalid plan mode "${e}". Allowed: ${Fi.join(", ")}`,l.USAGE);return r}function Sc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Mi.find(s=>s===n);if(!r)throw new m(`Invalid step status "${e}". Allowed: ${Mi.join(", ")}`,l.USAGE);return r}function L_(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Di.find(s=>s===n);if(!r)throw new m(`Invalid step link kind "${e}". Allowed: ${Di.join(", ")}`,l.USAGE);return r}function FA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=$i.find(r=>r===t);if(!n)throw new m(`Invalid plan harness "${e}". Allowed: ${$i.join(", ")}`,l.USAGE);return n}function MA(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=R_.find(r=>r===t);if(!n)throw new m(`Invalid --depth "${e}". Allowed: ${R_.join(", ")}`,l.USAGE);return n}function $A(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new m("Plan --fields requires a comma-separated list of plan field names",l.USAGE);return t}var gc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function DA(e,t){let n=e,r={},s=[];for(let o of t){let i=o.startsWith("plan.")?o.slice(5):o;if(i.length!==0){if(!gc.has(i)){s.push(o);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(s.length>0)throw new m(`Unknown Plan --fields value(s): ${s.join(", ")}`,l.USAGE,{nextSteps:[`Use --fields ${[...gc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:s,suggested_retry:`pm plan show <id> --fields ${[...gc].join(",")}`}});return r}function Ec(e,t){let n={};for(let r of e.split(",")){let s=r.trim();if(s.length===0)continue;let o=s.indexOf("=");if(o<=0)throw new m(`Invalid ${t} entry "${s}"; expected key=value`,l.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[s.slice(0,o).trim().toLowerCase()]=s.slice(o+1).trim()}return n}function Ac(e){let t=Ec(e,"--file");if(!t.path)throw new m("--file requires path=<value>",l.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function Tc(e){let t=Ec(e,"--test");if(!t.command&&!t.path)throw new m("--test requires at least command=<value> or path=<value>",l.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function Cc(e){let t=Ec(e,"--doc");if(!t.path)throw new m("--doc requires path=<value>",l.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function UA(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=LA(t.completed,t.total),t}function GA(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${O_}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new m("Could not allocate step id (limit reached)",l.GENERIC_FAILURE)}function Un(e,t){let n=t.trim();if(n.length===0)throw new m("Step reference cannot be empty",l.USAGE);let r=e.find(s=>s.id===n);if(r)return r;if(/^\d+$/.test(n)){let s=Number.parseInt(n,10),o=e.find(i=>i.order===s);if(o)return o}throw new m(`Step "${t}" not found in plan`,l.NOT_FOUND)}function x_(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function jA(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],s=[];if(n.length>0){if(t.length>n.length)throw new m("pm plan materialize --steps all cannot be combined with other step refs",l.USAGE);for(let i of e.slice().sort((a,c)=>a.order-c.order)){let a=x_(i);if(a){s.push({from_step:i.id,...a});continue}r.push(i)}return{targets:r,skipped:s}}let o=new Set;for(let i of t){let a=Un(e,i);if(o.has(a.id))continue;o.add(a.id);let c=x_(a);if(c){s.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:s}}function qA(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function KA(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function zA(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function Ie(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=UA(n),s=KA(n),o={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??kc,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:s?{id:s.id,order:s.order,title:s.title,status:s.status}:void 0,blocked_steps:zA(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(o.steps=n),t==="deep"&&(o.decisions=e.plan_decisions??[],o.discoveries=e.plan_discoveries??[],o.validation=e.plan_validation??[]),o}function xe(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!ha(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function F_(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new m(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,l.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function BA(e){let t=E(process.cwd(),e.path);await C(t);let n=await A(t);return{pmRoot:t,settings:n}}async function M_(e,t){let n=I(e.settings,R()),r=await D(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new m(`Plan ${t} not found`,l.NOT_FOUND);let s=await K(r,{schema:e.settings.schema});return F_(s.document.metadata),{document:s.document,itemId:r.id}}function HA(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of De(e.related))t.push(`id=${n},kind=related`);for(let n of De(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of De(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function VA(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function WA(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||De(e.dependsOn).length>0||De(e.link).length>0}function YA(e){let t=e.stepTitle?.trim()||void 0,n=P_(e.step),r=e.template?.trim()?NA(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(s=>s.title)],templateSteps:r}}function JA(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new m("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",l.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${vc[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new m("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",l.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function XA(e,t){let n=Sc(e.stepStatus,"pending"),r=Rc(e,"depends_on"),s=Se(e.file).map(Ac),o=Se(e.test).map(Tc),i=Se(e.doc).map(Cc),a=k();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:s.length>0?s:void 0,tests:o.length>0?o:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function QA(e){let t=YA(e),n=WA(e);if(JA(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[XA(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((s,o)=>({id:`${O_}${String(o+1).padStart(3,"0")}`,order:o+1,title:s,body:t.templateSteps[o]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}async function ZA(e,t,n){let r=e.title?.trim();if(!r)throw new m("pm plan create requires --title",l.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let s=N_(e.mode,kc),o=FA(e.harness),i=e.fromSearch?.trim(),a=VA(e),{steps:c,hasPerStepDetailOptions:d}=QA(e);if(c.length===0&&d)throw new m("pm plan create step options require --step-title (or a single --step)",l.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?T(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:Se(e.file),test:Se(e.test),doc:Se(e.doc),field:Se(e.field),assignee:T(e.author,n.settings.author_default),blockedBy:void 0,dep:HA(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")},_=await Nt(f,t),h=await ne({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:T(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let b=["plan_mode"];g.metadata.plan_mode=s,o&&(g.metadata.plan_harness=o,b.push("plan_harness"));let v=e.scope?.trim();v&&(g.metadata.plan_scope=v,b.push("plan_scope"));let S=e.resumeContext?.trim();return S&&(g.metadata.plan_resume_context=S,b.push("plan_resume_context")),g.metadata.plan_steps=c,b.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],b.push("plan_validation")),p&&(g.metadata.assignee=p,b.push("assignee")),{changedFields:b}}}),y=Ie(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:xe(_.item.id,y),warnings:[..._.warnings],generated_at:k()}}async function eT(e,t,n){let r=MA(t.depth),s=$A(t.fields),{document:o,itemId:i}=await M_(n,e),a=Ie(o.metadata,s===null?r:"deep");return{action:"show",plan:s===null?a:DA(a,s),next_actions:xe(i,a),warnings:[],generated_at:k()}}function tT(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,s])=>[r,JSON.stringify(s)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function Xe(e){let t=T(e.options.author,e.ctx.settings.author_default),n,r=await ne({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(s){F_(s.metadata);let o=$(e.ctx.settings.schema);if(Z(s.metadata.status,o)||ha(s.metadata.plan_mode))throw new m(`Plan ${s.metadata.id} is terminal (status=${s.metadata.status}, plan_mode=${s.metadata.plan_mode??"unset"}) and cannot be mutated.`,l.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let i=(s.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(s.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,s);n=c.resultStep;let d=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));s.metadata.plan_steps=d;let u=tT(a,s.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function nT(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new m("pm plan add-step requires --step-title",l.USAGE);let s=Sc(t.stepStatus,"pending"),o=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await Xe({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;$_(u,void 0,s,o);let f=rT(u,t,{order:p,title:r,status:s});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),d=Ie(i.metadata,"standard");return{action:"add-step",plan:d,step:a,next_actions:xe(c,d),warnings:[],generated_at:k()}}function $_(e,t,n,r){if(n!=="in_progress"||r)return;let s=e.find(o=>o.id!==t&&o.status==="in_progress");if(s)throw new m(`Plan already has step ${s.id} in_progress. Pass --allow-multiple-active or update that step first.`,l.CONFLICT)}function rT(e,t,n){let r=Rc(t,"depends_on"),s=Se(t.file).map(Ac),o=Se(t.test).map(Tc),i=Se(t.doc).map(Cc),a=k();return{id:GA(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:s.length>0?s:void 0,tests:o.length>0?o:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function Rc(e,t){let n=De(e.dependsOn).map(u=>({id:u,kind:t})),r=De(e.related).map(u=>({id:u,kind:"related"})),s=De(e.blocks).map(u=>({id:u,kind:"blocks"})),o=De(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=De(e.link),a=L_(e.linkKind,t),c=e.linkNote?.trim(),d=i.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...s,...o,...d]}async function yc(e,t,n,r){let{document:s,resultStep:o,itemId:i}=await Xe({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,d){let u=Un(c,r.stepRef),p=k(),f=r.finalStatus??Sc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return $_(c,u.status==="in_progress"?u.id:void 0,f,_),sT(u,t,f,p),d.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Ie(s.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:o,next_actions:xe(i,a),warnings:[],generated_at:k()}}function sT(e,t,n,r){oT(e,t,n),iT(e,t),e.status=n,e.updated_at=r,aT(e,n,r)}function oT(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new m("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",l.USAGE)}function iT(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=t.stepOwner.trim()||void 0),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let r=Se(t.file).map(Ac),s=Se(t.test).map(Tc),o=Se(t.doc).map(Cc);r.length>0&&(e.files=bc(e.files,r)),s.length>0&&(e.tests=bc(e.tests,s)),o.length>0&&(e.docs=bc(e.docs,o))}function bc(e,t){let n=[...e??[]],r=new Set(n.map(s=>JSON.stringify(s)));for(let s of t){let o=JSON.stringify(s);r.has(o)||(r.add(o),n.push(s))}return n}function aT(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function cT(e,t,n,r,s){let{document:o,itemId:i}=await Xe({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${s}`,mutator(c){let d=Un(c,r),u=c.filter(f=>f.id!==d.id),p=Math.max(1,Math.min(s,u.length+1));return u.splice(p-1,0,d),u.forEach((f,_)=>{f.order=_+1,f.updated_at=k()}),c.length=0,c.push(...u),{changedSteps:[d.id],resultStep:d}}}),a=Ie(o.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:xe(i,a),warnings:[],generated_at:k()}}async function dT(e,t,n,r){let{document:s,itemId:o}=await Xe({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=Un(a,r),d=a.filter(u=>u.id!==c.id);return d.forEach((u,p)=>{u.order=p+1}),a.length=0,a.push(...d),{changedSteps:[c.id]}}}),i=Ie(s.metadata,"standard");return{action:"remove-step",plan:i,next_actions:xe(o,i),warnings:[],generated_at:k()}}async function lT(e,t,n,r){let s=Rc(t,L_(t.linkKind,"related"));if(s.length===0)throw new m("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",l.USAGE);let o=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await Xe({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Un(u,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of s){let b=h(g);y.has(b)||(_.push(g),y.add(b))}if(f.linked_items=_,f.updated_at=k(),o){let g=p.metadata.dependencies??[],b=S=>`${S.kind}:${S.id}`,v=new Set(g.map(b));for(let S of s){let x=S.kind==="depends_on"?"blocked_by":S.kind,O={id:S.id,kind:x,created_at:k(),author:T(t.author,n.settings.author_default)};v.has(b(O))||(g.push(O),v.add(b(O)))}p.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),d=Ie(i.metadata,"standard");return{action:"link",plan:d,step:c,next_actions:xe(a,d),warnings:[],generated_at:k()}}async function mT(e,t,n,r){let s=De(t.link);if(s.length===0)throw new m("pm plan unlink requires --link <id> to remove",l.USAGE);let{document:o,itemId:i,resultStep:a}=await Xe({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(d){let u=Un(d,r),p=(u.linked_items??[]).filter(f=>!s.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=k(),{changedSteps:[u.id],resultStep:u}}}),c=Ie(o.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:xe(i,c),warnings:[],generated_at:k()}}async function wc(e,t,n,r){let s=qA(r,t);if(!s){let d=`--${r}-text`,u=`--${r}`;throw new m(`pm plan ${r} requires ${d}`,l.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${d} "..."`,`pm plan ${r} <plan-id> ${u} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${d} <value>`}})}let o=T(t.author,n.settings.author_default),{document:i,itemId:a}=await Xe({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(d,u){let p=k();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:o,decision:s,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:o,text:s}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:s,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Ie(i.metadata,"deep");return{action:r,plan:c,next_actions:xe(a,c),warnings:[],generated_at:k()}}async function uT(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new m("pm plan resume requires --resume-context <text>",l.USAGE);let{document:s,itemId:o}=await Xe({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=r;let d=t.scope?.trim();return d&&(c.metadata.plan_scope=d),{changedSteps:[]}}}),i=Ie(s.metadata,"brief");return{action:"resume",plan:i,next_actions:xe(o,i),warnings:[],generated_at:k()}}async function pT(e,t,n){let r=N_(t.mode??"approved","approved"),{document:s,itemId:o}=await Xe({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(a,c){c.metadata.plan_mode=r;let d=t.scope?.trim();return d&&(c.metadata.plan_scope=d),{changedSteps:[]}}}),i=Ie(s.metadata,"brief");return{action:"approve",plan:i,next_actions:xe(o,i),warnings:[],generated_at:k()}}function D_(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function fT(e,t){let n=Ie(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:xe(e.itemId,n),warnings:D_(t),generated_at:k()}}function _T(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let s of n.linked_items??[]){let o=s.kind==="blocked_by"||s.kind==="blocks"||s.kind==="related"||s.kind==="discovered_from"?s.kind:"related";r.push(`id=${s.id},kind=${o}`)}return r}async function hT(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let s of Se(e.options.field)){let o=s.indexOf("=");if(o<=0)throw new m(`Invalid --field entry "${s}"; expected name=value`,l.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0)throw new m(`Invalid --field entry "${s}"; expected name=value`,l.USAGE);let c=i.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new m(`Invalid --field entry "${s}"; expected name=value`,l.USAGE);let[d,...u]=c,p=`${d}${u.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(p))throw new m(`Invalid --field entry "${s}"; "${p}" is reserved by materialize and cannot be overridden`,l.USAGE);n[p]=a}for(let s of e.targets){let o=await Nt({...n,title:s.title,description:s.body?.trim()||s.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${s.id}`,dep:_T(e.parent,e.planItemId,s)},{path:e.pmRoot});t.push({id:o.item.id,title:o.item.title,type:e.resolvedTypeName,parent:o.item.parent,tags:o.item.tags??[],from_step:s.id})}return t}function gT(e,t,n){for(let r of t){let s=n.find(a=>a.from_step===r.id);if(!s)continue;let o=e.find(a=>a.id===r.id);if(!o)continue;let i=o.linked_items??[];i.push({id:s.id,kind:"implements",note:`materialized as ${s.type}`}),o.linked_items=i,o.updated_at=k()}}async function yT(e,t,n){let r=De(t.steps);if(r.length===0)throw new m("pm plan materialize requires --steps <ids|orders|all>",l.USAGE);let s=t.materializeType?.trim()||"Task",o=I(n.settings,R()),i=fe(s,o);if(!i)throw new m(`Invalid --materialize-type "${s}"`,l.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,d=await M_(n,e),u=(d.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=jA(u,r);if(p.length===0){if(f.length>0)return fT(d,f);throw new m("No matching plan steps found for --steps",l.NOT_FOUND)}let _=await hT({targets:p,parent:a,planItemId:d.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await Xe({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(b){return gT(b,p,_),{changedSteps:p.map(v=>v.id)}}}),g=Ie(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:xe(y,g),warnings:D_(f),generated_at:k()}}function bT(e){if(e.subcommand==="create")return e;let t=P_(e.options.step);if(t.length>1)throw new m(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,l.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:{...e.options,stepTitle:t[0]}}:e}function lt(e,t){if(!e.id)throw new m(`pm plan ${t} requires a plan id`,l.USAGE);return e.id}function on(e,t){let n=lt(e,t);if(!e.stepRef)throw new m(`pm plan ${t} requires <plan-id> <step>`,l.USAGE);return{id:n,stepRef:e.stepRef}}function wT(e){let t=on(e,"reorder-step");if(e.reorderTo===void 0)throw new m("pm plan reorder-step requires <plan-id> <step> <new-order>",l.USAGE);return{...t,reorderTo:e.reorderTo}}var vT={create:(e,t)=>ZA(e.options,e.global,t),show:(e,t)=>eT(lt(e,"show"),e.options,t),"add-step":(e,t)=>nT(lt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=on(e,"update-step");return yc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=on(e,"complete-step");return yc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=on(e,"block-step");return yc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=wT(e);return cT(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=on(e,"remove-step");return dT(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=on(e,"link");return lT(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=on(e,"unlink");return mT(n.id,e.options,t,n.stepRef)},decision:(e,t)=>wc(lt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>wc(lt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>wc(lt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>uT(lt(e,"resume"),e.options,t),approve:(e,t)=>pT(lt(e,"approve"),e.options,t),materialize:(e,t)=>yT(lt(e,"materialize"),e.options,t)};function kT(e){let t=vT[e];if(!t)throw Re({command_path:"plan",token:e,allowed:PA});return t}async function U_(e){let t=await BA(e.global),n=bT(e);return kT(n.subcommand)(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b59e8e54-f9e0-5cdb-bc59-6dcbf67f278d")}catch{}})();function ST(e,t){return[...new Set([...Mr.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,s)=>r.localeCompare(s))}function ET(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Ic(e,t,n){let r=E(process.cwd(),n.path);await C(r);let s=await A(r),o=I(s,R()),i=await D(r,e,s.id_prefix,s.item_format,o.type_to_folder);if(!i)throw await at(r,e,s.id_prefix,o.type_to_folder);let a=await K(i,{schema:s.schema}),c=a.document.metadata,d=k(),u=T(t.author,s.author_default),p=await Zn(r,s.id_prefix,{tokenLength:s.ids.token_length,typeToFolder:o.type_to_folder,probeExisting:!1}),f=$(s.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new m("Copy --title must not be empty",l.USAGE);let h={...c,id:p,title:_??c.title,status:f.open_status,created_at:d,updated_at:d};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let y=vt(R()),g=Je({metadata:h,body:a.document.body},{schema:s.schema,extensionFieldNames:y}),b=await Pn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=ST(g.metadata,g.body),S=Kt(r,g.metadata.type,p,s.item_format,o.type_to_folder),x=Te(r,p),O=await ye(r,p,s.locks.ttl_seconds,u,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),j={metadata:{},body:""},L,Ee;try{let X=await Sn(r,u,{required:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await Pn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1});let ie=await D(r,p,s.id_prefix,s.item_format,o.type_to_folder);if(ie)throw new m(`Cannot copy to ${p}: an item with that id already exists at ${ie.itemPath}. Retry the copy to allocate a new id.`,l.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${ie.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await pe(S,qe(g,{format:s.item_format,schema:s.schema,extensionFieldNames:y}));try{let V=Ke({nowIso:d,author:u,op:"create",before:j,after:g,message:ET(i.id,t.message)});await Ct(x,V)}catch(V){throw await pn(S),V}Ee=await En({pmRoot:r,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:S,document:g})}finally{await X()}L=[...await z({path:S,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:j,after:g,changed_fields:v}),...await z({path:x,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:j,after:g,changed_fields:v})],gn({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Ht(g.metadata,v),changed_fields:v})}finally{await O()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:v,warnings:[...co(b),...Ee,...L],...b===void 0?{}:{similarity_advisory:b}}}import Wo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7819b53c-b0e4-50b0-a670-f80b36765085")}catch{}})();async function xc(e,t,n){let r=E(process.cwd(),n.path);await C(r);let s=await A(r),o=T(t.author,s.author_default),i=await ju({pmRoot:r,settings:s,id:e,author:o,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?Wo.relative(r,i.targetPath).split(Wo.sep).join("/"):void 0;return{item:i.item,changed_fields:i.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:i.item.status,...a?{target_path:a}:{},history_retained:Wo.relative(r,Te(r,i.item.id)).split(Wo.sep).join("/"),tombstone_retention:"retain_append_only",warnings:i.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5ddb139-9780-50e0-87a5-621913cb0de4")}catch{}})();async function AT(e){await C(e)}async function Oc(e,t,n){let r=E(process.cwd(),n.path);if(await AT(r),t.clear===!0){if(e!==void 0)throw new m("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",l.USAGE);let p=await A(r),f=wn(T(void 0,p.author_default));return await gu(r),await io({pmRoot:r,settings:p,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await Cs(r);if(p===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let f=await TT(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let o=await A(r),i=I(o,R()),a=await D(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await at(r,e,o.id_prefix,i.type_to_folder);let c=be(a.id,o.id_prefix),d=await K(a,{schema:o.schema}),u=G_(d.document.metadata.title);return await hu(r,c),await io({pmRoot:r,settings:o,principal:wn(T(void 0,o.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function TT(e,t){let n=await A(e),r=I(n,R()),s=await D(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!s)return null;let o=await K(s,{schema:n.schema});return G_(o.document.metadata.title)}function G_(e){return e.trim().length>0?e:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f4f5f10-793d-5baa-8985-c0ec855b16c4")}catch{}})();var j_=new Set(["item_format"]),q_=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),CT=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","telemetry_tracking"]),RT=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","telemetry_tracking"]),IT={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function xT(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(j_.has(t)||q_.has(t)||CT.has(t)||t==="context")return t}function OT(e){let t=e.trim().toLowerCase();return IT[t]??e}function K_(e,t){let n=xT(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:j_.has(n)?{routable:!0,flag:"format",value:t}:q_.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:RT.has(n)?OT(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5918331a-46e9-5699-b85d-89f49a27d341")}catch{}})();var z_=["project","global"],mt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],context:["context"]},PT=Object.keys(mt).map(e=>mt[e][0]),NT=Object.fromEntries(Object.keys(mt).flatMap(e=>mt[e].map(t=>[t,e]))),LT={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",telemetry_tracking:"Telemetry usage reporting policy.",context:"Context command settings (depth, section toggles, limits)."},FT=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],MT=new Set(["metadata_required_fields",...FT]),$T=new Set(["test_result_tracking","telemetry_tracking"]),DT=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),UT=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),GT=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),jT=new Set(["governance_preset","governance_create_default_type"]),Y_=e=>MT.has(e),qT=e=>UT.has(e),KT=e=>GT.has(e),zT=e=>jT.has(e);function Pc(e){return e==="definition_of_done"||Y_(e)}function BT(e){if(z_.includes(e))return e;throw new m(`Invalid config scope "${e}". Allowed: ${z_.join(", ")}`,l.USAGE)}function HT(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Re({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function VT(e){let t=NT[e];if(t)return t;let n=Hi.map(r=>r.key).join(", ");throw new m(`Invalid config key "${e}". Supported: ${PT.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,l.USAGE)}function WT(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,s)=>r.localeCompare(s));if(t){if(n.length>0)throw new m("Config set definition-of-done cannot combine --clear-criteria with --criterion values",l.USAGE);return[]}if(n.length===0)throw new m("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",l.USAGE);return n}function YT(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new m("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",l.USAGE):new m("Config set item-format requires --format toon",l.USAGE)}function J_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new m("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",l.USAGE)}function X_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new m("Config set test-result-tracking requires --policy with one of: enabled, disabled",l.USAGE)}function Q_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new m("Config set telemetry-tracking requires --policy with one of: enabled, disabled",l.USAGE)}function Lc(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new m("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",l.USAGE)}function Z_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new m("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",l.USAGE)}function eh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new m("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",l.USAGE)}function th(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new m("Config set governance-create-mode-default requires --policy with one of: progressive, strict",l.USAGE)}function nh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new m("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",l.USAGE)}function rh(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new m("Config set governance-workflow-enforcement requires one of: off, warn, strict",l.USAGE)}function sh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new m("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",l.USAGE)}function oh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new m("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",l.USAGE)}function B_(e,t){switch(e){case"history_missing_stream_policy":return J_(t);case"sprint_release_format_policy":return _a(t);case"parent_reference_policy":case"governance_parent_reference_policy":return zs(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Lc(t);case"governance_preset":return Z_(t);case"governance_ownership_enforcement":return eh(t);case"governance_create_mode_default":return th(t);case"governance_close_validation_default":return nh(t);case"governance_require_close_reason":return oh(t);case"governance_workflow_enforcement":return rh(t);case"governance_force_required_for_stale_lock":return sh(t);case"test_result_tracking":return X_(t);case"telemetry_tracking":return Q_(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var H_={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},JT=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function XT(e,t){let n=[...new Set((e??[]).map(o=>o.trim()).filter(o=>o.length>0))];if(t){if(n.length>0)throw new m("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",l.USAGE);return[]}if(n.length===0)throw new m("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",l.USAGE);let r=n.map(o=>o.toLowerCase().replaceAll("-","_")),s=r.filter(o=>H_[o]===void 0);if(s.length>0)throw new m(`Config set metadata-required-fields received unsupported values: ${s.join(", ")}. Supported values: ${JT.join(", ")}`,l.USAGE);return[...new Set(r.map(o=>H_[o]))].sort((o,i)=>o.localeCompare(i))}function QT(e,t,n){let r=[...new Set((t??[]).map(s=>s.trim().toLowerCase()).filter(s=>s.length>0))].sort((s,o)=>s.localeCompare(o));if(n){if(r.length>0)throw new m(`Config set ${mt[e][0]} cannot combine --clear-criteria with --criterion values`,l.USAGE);return[]}if(r.length===0)throw new m(`Config set ${mt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,l.USAGE);return r}function ZT(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function eC(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new m(`Config action "${e}" does not accept <key>`,l.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new m(`Config action "${e}" requires <key>`,l.USAGE);return VT(t)}function ih(e){if(!e)throw new m("Config action requires <key>",l.USAGE)}var tC={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function Fc(e,t){return tC[t](e)}function Ue(e,t){return t.length===0?e:{...e,warnings:t}}async function nC(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):nt(n),s=ge(r);return e==="project"&&await C(r),{pmRoot:r,settingsPath:s}}function rC(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new m(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,l.USAGE)}function V_(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new m(`Context ${t} must be a positive integer`,l.USAGE)}async function sC(e,t,n,r,s){let o=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!Ui.includes(c))throw new m(`Context --default-depth must be one of ${Ui.join("|")}`,l.USAGE);i.default_depth!==c&&(i.default_depth=c,o=!0)}if(t.activityLimit!==void 0){let c=V_(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,o=!0)}if(t.staleThresholdDays!==void 0){let c=V_(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,o=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,d]of a){let u=rC(d);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,o=!0)}}return o&&await Ce(n.pmRoot,e,"config:set:context"),Ue({scope:r,key:"context",context_settings:{default_depth:i.default_depth,activity_limit:i.activity_limit,stale_threshold_days:i.stale_threshold_days,sections:{...i.sections}},settings_path:n.settingsPath,changed:o},s)}function oC(e,t,n){if(n.value!==void 0&&n.value!==t)throw new m(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,l.USAGE);return{...n,value:t}}function iC(e,t,n,r,s,o){if(s===void 0)return o;if(e!=="set")throw new m(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,l.USAGE);if(typeof t!="string"||t.trim().length===0)throw new m('Config action "set" requires <key> before a positional <value>.',l.USAGE);if(r)return oC(t,s,o);ih(n);let i=K_(n,s);if(!i.routable)throw new m(i.reason,l.USAGE);if(i.flag==="criterion"){if(o.criterion!==void 0&&o.criterion.length>0)throw new m(`Config set ${t} received both positional value "${s}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,l.USAGE);return{...o,criterion:i.values}}if(i.flag==="format")return{...o,format:i.value};if(o.policy!==void 0&&B_(n,o.policy)!==B_(n,i.value))throw new m(`Config set ${t} received both positional value "${s}" and --policy "${o.policy}". Pass only one.`,l.USAGE);return{...o,policy:i.value}}function aC(e){let t=Object.keys(mt).map(r=>({key:r,aliases:mt[r],value_kind:r==="context"?"object":Pc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:Pc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:LT[r],value:Fc(e.settings,r)})),n=Hi.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Vi(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Ue({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function cC(e){let t=Object.fromEntries(Object.keys(mt).map(n=>[n,Fc(e.settings,n)]));return Ue({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function dC(e,t){let n=Fc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Ue({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Ue({...r,context_settings:n},e.warnings):Array.isArray(n)?Ue({...r,criteria:n},e.warnings):Ue({...r,policy:n},e.warnings)}async function lC(e,t,n,r){if(t==="get"){let a=Vi(e.settings,n);return Ue({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let s=r.value;if(typeof s!="string")throw new m(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,l.USAGE);let o=Nm(n,s);if(!o.ok)throw new m(o.error.message,l.USAGE);let i=ks(e.settings,n,o.parsed.value);return i&&await Ce(e.target.pmRoot,e.settings,`config:set:${n.path}`),Ue({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:o.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function ee(e,t,n){t&&await Ce(e.target.pmRoot,e.settings,n)}function W_(e,t,n){return e!==n||t!==n}function de(e,t,n,r){return Ue({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Nc(e,t,n,r){return Ue({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function mC(e,t){let n=YT(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,s;if(r){let o=I(e.settings,R()),i=await Zu(e.target.pmRoot,n,"config:set:item_format:migrate",o.type_to_folder,e.settings.schema);s={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await Ce(e.target.pmRoot,e.settings,"config:set:item_format")}return Ue({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:s,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function uC(e,t,n){if(t==="history_missing_stream_policy"){let o=J_(n.policy),i=e.settings.history.missing_stream!==o;return e.settings.history.missing_stream=o,await ee(e,i,"config:set:history_missing_stream_policy"),de(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let o=_a(n.policy),i=e.settings.validation.sprint_release_format!==o;return e.settings.validation.sprint_release_format=o,await ee(e,i,"config:set:sprint_release_format_policy"),de(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let o=zs(n.policy),i=e.settings.validation.parent_reference!==o||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==o;return e.settings.validation.parent_reference=o,e.settings.governance.preset="custom",e.settings.governance.parent_reference=o,await ee(e,i,"config:set:parent_reference_policy"),de(e,t,e.settings.validation.parent_reference,i)}let r=Lc(n.policy),s=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await ee(e,s,"config:set:metadata_validation_profile"),de(e,t,e.settings.validation.metadata_profile,s)}async function pC(e,t,n){if(t==="metadata_required_fields"){let a=XT(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((d,u)=>d!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await ee(e,c,"config:set:metadata_required_fields"),Nc(e,t,[...e.settings.validation.metadata_required_fields],c)}let s={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],o=QT(t,n.criterion,n.clearCriteria),i=o.length!==s.length||o.some((a,c)=>a!==s[c]);return s.splice(0,s.length,...o),await ee(e,i,`config:set:${t}`),Nc(e,t,[...s],i)}async function fC(e,t,n){if(t==="governance_preset"){let c=Z_(n.policy),d=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await ee(e,d,"config:set:governance_preset"),de(e,t,e.settings.governance.preset,d)}let r=typeof n.policy=="string",s=r?n.policy.trim():"";if(r&&s.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await ee(e,c,"config:set:governance_create_default_type"),de(e,t,e.settings.governance.create_default_type??"",c)}if(s.length===0)throw new m('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',l.USAGE);let o=I(e.settings,R()),i=fe(s,o);if(!i)throw new m(Et(s,o.types,At(e.target.pmRoot,e.settings.schema)),l.USAGE);let a=e.settings.governance.create_default_type!==i;return e.settings.governance.create_default_type=i,await ee(e,a,"config:set:governance_create_default_type"),de(e,t,e.settings.governance.create_default_type,a)}async function _C(e,t,n){if(t==="governance_ownership_enforcement"){let o=eh(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==o;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=o,await ee(e,i,"config:set:governance_ownership_enforcement"),de(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let o=th(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==o;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=o,await ee(e,i,"config:set:governance_create_mode_default"),de(e,t,e.settings.governance.create_mode_default,i)}let r=nh(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await ee(e,s,"config:set:governance_close_validation_default"),de(e,t,e.settings.governance.close_validation_default,s)}async function hC(e,t,n){if(t==="governance_parent_reference_policy"){let o=zs(n.policy),i=e.settings.governance.preset!=="custom"||W_(e.settings.governance.parent_reference,e.settings.validation.parent_reference,o);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=o,e.settings.validation.parent_reference=o,await ee(e,i,"config:set:governance_parent_reference_policy"),de(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let o=Lc(n.policy),i=e.settings.governance.preset!=="custom"||W_(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,o);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=o,e.settings.validation.metadata_profile=o,await ee(e,i,"config:set:governance_metadata_validation_profile"),de(e,t,e.settings.governance.metadata_profile,i)}let r=rh(n.policy),s=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await ee(e,s,"config:set:governance_workflow_enforcement"),de(e,t,e.settings.governance.workflow_enforcement,s)}async function gC(e,t,n){if(t==="governance_require_close_reason"){let a=oh(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await ee(e,c,"config:set:governance_require_close_reason"),de(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let s=sh(n.policy)==="enabled",o=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==s;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=s,await ee(e,o,"config:set:governance_force_required_for_stale_lock"),de(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function yC(e,t,n){if(t==="test_result_tracking"){let a=X_(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await ee(e,c,"config:set:test_result_tracking"),de(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}let s=Q_(n.policy)==="enabled",o=e.settings.telemetry.enabled!==s||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=s,e.settings.telemetry.first_run_prompt_completed=!0,await ee(e,o,"config:set:telemetry_tracking"),de(e,t,e.settings.telemetry.enabled?"enabled":"disabled",o)}async function bC(e,t,n){let r=WT(n.criterion,n.clearCriteria),s=r.length!==e.settings.workflow.definition_of_done.length||r.some((o,i)=>o!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await ee(e,s,"config:set:definition_of_done"),Nc(e,t,[...e.settings.workflow.definition_of_done],s)}async function wC(e,t,n){if(n.clearCriteria===!0&&!Pc(t))throw new m("--clear-criteria is only supported with config set criteria-list keys",l.USAGE);return t==="item_format"?mC(e,n):t==="context"?sC(e.settings,n,e.target,e.scope,e.warnings):t==="definition_of_done"?bC(e,t,n):Y_(t)?pC(e,t,n):$T.has(t)?yC(e,t,n):DT.has(t)?gC(e,t,n):qT(t)?_C(e,t,n):KT(t)?hC(e,t,n):zT(t)?fC(e,t,n):uC(e,t,n)}async function ah(e,t,n,r,s,o){let i=BT(e),a=HT(t),c=a==="get"||a==="set"?vs(n):void 0,d=c?void 0:eC(a,n),u=iC(a,n,d,c,o,r),p=await nC(i,s),{settings:f,metadata:_,warnings:h}=await Mu(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:ZT(h)};return c?lC(y,a,c,u):a==="list"?aC(y):a==="export"?cC(y):(ih(d),a==="get"?dC(y,d):wC(y,d,u))}import XC from"node:fs/promises";import W from"node:path";import QC from"node:readline/promises";import{stdin as ZC,stdout as Oe}from"node:process";import $c from"node:fs/promises";import oe from"node:path";import vC from"node:readline/promises";import{stdin as kC,stdout as Yo}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e404796d-439b-5f4c-9330-5b12ff41d7b2")}catch{}})();var dh=["ask","add","skip","status"],SC=["AGENTS.md","CLAUDE.md"],EC=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],AC=8,Dc=1,TC="<!-- pm-cli:agent-guidance:start:",CC=`<!-- pm-cli:agent-guidance:start:v${Dc} -->`,Mc="<!-- pm-cli:agent-guidance:end -->",gr="Add workflow guidance later: pm init --agent-guidance add";var RC=()=>vC.createInterface({input:kC,output:Yo});function _r(e,t){let n=oe.relative(e,t);return n.length===0?oe.basename(t):n.split(oe.sep).join("/")}function ch(e){return e.endsWith(`
9
9
  `)?e:`${e}
10
- `}function gC(e){return e.includes(`\r
10
+ `}function IC(e){return e.includes(`\r
11
11
  `)?`\r
12
12
  `:`
13
- `}function Q_(e){let t=e.indexOf(fC);if(t===-1)return null;let n=e.indexOf(Rc,t);return n===-1?null:{start_index:t,end_index:n+Rc.length}}function yC(e){return Q_(e)!==null}function bC(e,t="<your project test command>"){return[_C,"## pm Workflow (Agent Quickstart)","",'- Orient before mutate: `pm context --limit 10`, `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`.',"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, `pm close <id> "<evidence>" --validate-close warn`, `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Rc,""].join(e)}function wC(e,t="<your project test command>"){let n=gC(e),r=bC(n,t),s=Q_(e);if(s){let a=e.slice(s.end_index),c=a.startsWith(`\r
13
+ `}function lh(e){let t=e.indexOf(TC);if(t===-1)return null;let n=e.indexOf(Mc,t);return n===-1?null:{start_index:t,end_index:n+Mc.length}}function xC(e){return lh(e)!==null}function OC(e,t="<your project test command>"){return[CC,"## pm Workflow (Agent Quickstart)","",'- Orient before mutate: `pm context --limit 10`, `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`.',"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, `pm close <id> "<evidence>" --validate-close warn`, `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Mc,""].join(e)}function PC(e,t="<your project test command>"){let n=IC(e),r=OC(n,t),s=lh(e);if(s){let a=e.slice(s.end_index),c=a.startsWith(`\r
14
14
  `)?a.slice(2):a.startsWith(`
15
- `)?a.slice(1):a,m=J_(`${e.slice(0,s.start_index)}${r}${c}`);return{next_content:m,changed:m!==e}}let o=e.length===0?"":e.endsWith(`
15
+ `)?a.slice(1):a,d=ch(`${e.slice(0,s.start_index)}${r}${c}`);return{next_content:d,changed:d!==e}}let o=e.length===0?"":e.endsWith(`
16
16
  `)?`
17
17
  `:`
18
18
 
19
- `,i=J_(`${e}${o}${r}`);return{next_content:i,changed:i!==e}}async function vC(e){if(await k(re.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Ic.readFile(re.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=kC(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await k(re.join(e,"pnpm-lock.yaml"))?"pnpm test":await k(re.join(e,"bun.lock"))||await k(re.join(e,"bun.lockb"))?"bun run test":await k(re.join(e,"yarn.lock"))?"yarn test":"npm test"}function kC(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function SC(e,t){let n=re.dirname(e);return re.basename(e)==="pm"&&re.basename(n)===".agents"?re.dirname(n):re.resolve(t,e)}function EC(e,t){let n=e.find(s=>re.basename(s.file_path)==="AGENTS.md"&&s.exists);if(n)return n.file_path;let r=e.find(s=>s.exists);return r?r.file_path:re.join(t,"AGENTS.md")}function TC(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function AC(e){let t=hC();try{Ko.write(`
19
+ `,i=ch(`${e}${o}${r}`);return{next_content:i,changed:i!==e}}async function NC(e){if(await P(oe.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await $c.readFile(oe.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=LC(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await P(oe.join(e,"pnpm-lock.yaml"))?"pnpm test":await P(oe.join(e,"bun.lock"))||await P(oe.join(e,"bun.lockb"))?"bun run test":await P(oe.join(e,"yarn.lock"))?"yarn test":"npm test"}function LC(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function FC(e,t){let n=oe.dirname(e);return oe.basename(e)==="pm"&&oe.basename(n)===".agents"?oe.dirname(n):oe.resolve(t,e)}function MC(e,t){let n=e.find(s=>oe.basename(s.file_path)==="AGENTS.md"&&s.exists);if(n)return n.file_path;let r=e.find(s=>s.exists);return r?r.file_path:oe.join(t,"AGENTS.md")}function $C(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function DC(e){let t=RC();try{Yo.write(`
20
20
  Agent guidance check
21
- `),Ko.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
22
- `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return Ko.write(`
23
- `),TC(n,!0)}finally{t.close()}}function Z_(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:xc,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function eh(e){let t=[];for(let n of mC){let r=re.join(e,n),s=await k(r);if(!s){t.push({file_path:r,exists:s,has_guidance:!1,has_marker:!1});continue}let o=await Ic.readFile(r,"utf8"),i=o.toLowerCase(),a=uC.filter(m=>i.includes(m)),c=yC(o);t.push({file_path:r,exists:s,has_guidance:c||a.length>=pC,has_marker:c})}return t}function fr(e,t){e.includes(t)||e.push(t)}function CC(e,t){let n=Z_(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function RC(e,t=re.dirname(e)){let r=await k(e)?await Ic.readFile(e,"utf8"):"",s=wC(r,await vC(t));return s.changed?(await ue(e,s.next_content),{changed:!0,warnings:await z({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function IC(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>mr(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>mr(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>mr(e.projectRoot,t.file_path))}}async function xC(e,t,n){return e?await eh(n):t}function ur(e,t,n){e.state={...e.state,...n,template_version:xc,last_checked_files:t}}async function th(e,t){if(t.presentBefore)return;let n=await RC(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function OC(e,t){t||(e.warnings.push("agent_guidance:missing"),fr(e.nextSteps,pr))}function PC(e,t){e.skipped=!0,ur(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),fr(e.nextSteps,pr)}async function NC(e,t){await th(e,t),ur(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function LC(e,t){e.state.declined&&ur(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function FC(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),fr(e.nextSteps,pr)}async function $C(e,t){if(e.prompted=!0,await AC(t.targetRelativePath)){await th(e,t),ur(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,ur(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),fr(e.nextSteps,pr)}function MC(e){e.warnings.push("agent_guidance:missing_non_interactive"),fr(e.nextSteps,pr)}async function DC(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(OC(n,t.presentBefore),n):t.mode==="skip"?(PC(n,t.checkedFiles),n):t.mode==="add"?(await NC(n,t),n):t.presentBefore?(LC(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(FC(n),n):t.interactive?(await $C(n,t),n):(MC(n),n)}async function nh(e){let t=SC(e.pm_root,e.cwd),n=await eh(t),r=EC(n,t),s=mr(t,r),o=n.map(u=>mr(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await DC(Z_(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:s,checkedFiles:o,presentBefore:i,projectRoot:t}),c=CC(e.settings,a.state);return n=await xC(a.applied,n,t),{summary:IC({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:s,prompted:a.prompted,applied:a.applied,skipped:a.skipped,state:a.state}),warnings:a.warnings,next_steps:a.nextSteps,settings_changed:c.changed}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="75c0d2d2-6a89-508f-b7dd-b43d55978b44")}catch{}})();var qC=()=>GC.createInterface({input:jC,output:Re});function KC(){return structuredClone(yt)}var zC=["minimal","default","strict"];function sh(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--preset must not be empty",d.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new l(`Invalid --preset value "${e}". Allowed: ${zC.join(", ")}`,d.USAGE)}function BC(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return hm(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${_m.join(", ")}`,d.USAGE)}}}function HC(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new l("--author must not be empty",d.USAGE);return t}function Oc(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:V.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function VC(e,t,n,r){let s=r?.trim();if(r!==void 0&&s?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(s!==void 0){if(t.path!==void 0||Oc(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=V.resolve(e,s),u=V.join(m,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:m}}}if(t.path===void 0&&Oc(n)){let m=V.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let o=T(e,t.path),i=V.join(V.resolve(e),".agents","pm"),a=V.dirname(V.dirname(o)),c=V.resolve(o)===i?"current":"ancestor";return{pmRoot:o,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:o,workspace_root:a,discovery:c,requested_cwd:V.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:o}}}function WC(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new l("--id-prefix must not be empty",d.USAGE);if(Oc(t))throw new l(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,d.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&Ct(e)!==Ct(t))throw new l(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,d.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Ct(e)}`,`pm init --id-prefix ${Ct(t)}`]});return t}function YC(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--agent-guidance must not be empty",d.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new l(`Invalid --agent-guidance value "${e}". Allowed: ${X_.join(", ")}`,d.USAGE)}function JC(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function oh(e,t){let n=Kd[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function XC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function QC(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(XC).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function ZC(e,t,n){let r=fs(t.schema),s=rt(e,r.files.types,nt.types),i=pm(await q(s)),a=[],c=[];for(let m of gm(n)){let u=fm(i,m);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await At({pmRoot:e,filePath:s,raw:us(i),op:"init:type-preset",author:R(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:s}}async function eR(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",V.join(".agents","pm")];for(let n of t)if(await k(V.join(e,n)))return!0;return!1}async function tR(e,t,n){if(!t||n||await k(V.join(e,"settings.json"))||!await eR(e))return;let r=V.join(e,".agents","pm");throw new l(`Refusing to initialize tracker files directly in workspace root "${e}".`,d.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function ih(e,t){let n=[],r=[];for(let s of t){let o=s?V.join(e,s):e,i=await k(o);await UC.mkdir(o,{recursive:!0}),i?r.push(`already_exists:${o}`):n.push(o),r.push(...await z({path:o,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function nR(e,t){let n=qC();try{Re.write(`pm init setup wizard (agent-optimized)
24
- `),Re.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
21
+ `),Yo.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
22
+ `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return Yo.write(`
23
+ `),$C(n,!0)}finally{t.close()}}function mh(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:Dc,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function uh(e){let t=[];for(let n of SC){let r=oe.join(e,n),s=await P(r);if(!s){t.push({file_path:r,exists:s,has_guidance:!1,has_marker:!1});continue}let o=await $c.readFile(r,"utf8"),i=o.toLowerCase(),a=EC.filter(d=>i.includes(d)),c=xC(o);t.push({file_path:r,exists:s,has_guidance:c||a.length>=AC,has_marker:c})}return t}function yr(e,t){e.includes(t)||e.push(t)}function UC(e,t){let n=mh(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function GC(e,t=oe.dirname(e)){let r=await P(e)?await $c.readFile(e,"utf8"):"",s=PC(r,await NC(t));return s.changed?(await pe(e,s.next_content),{changed:!0,warnings:await z({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function jC(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>_r(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>_r(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>_r(e.projectRoot,t.file_path))}}async function qC(e,t,n){return e?await uh(n):t}function hr(e,t,n){e.state={...e.state,...n,template_version:Dc,last_checked_files:t}}async function ph(e,t){if(t.presentBefore)return;let n=await GC(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function KC(e,t){t||(e.warnings.push("agent_guidance:missing"),yr(e.nextSteps,gr))}function zC(e,t){e.skipped=!0,hr(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),yr(e.nextSteps,gr)}async function BC(e,t){await ph(e,t),hr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function HC(e,t){e.state.declined&&hr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function VC(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),yr(e.nextSteps,gr)}async function WC(e,t){if(e.prompted=!0,await DC(t.targetRelativePath)){await ph(e,t),hr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,hr(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),yr(e.nextSteps,gr)}function YC(e){e.warnings.push("agent_guidance:missing_non_interactive"),yr(e.nextSteps,gr)}async function JC(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(KC(n,t.presentBefore),n):t.mode==="skip"?(zC(n,t.checkedFiles),n):t.mode==="add"?(await BC(n,t),n):t.presentBefore?(HC(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(VC(n),n):t.interactive?(await WC(n,t),n):(YC(n),n)}async function fh(e){let t=FC(e.pm_root,e.cwd),n=await uh(t),r=MC(n,t),s=_r(t,r),o=n.map(u=>_r(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await JC(mh(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:s,checkedFiles:o,presentBefore:i,projectRoot:t}),c=UC(e.settings,a.state);return n=await qC(a.applied,n,t),{summary:jC({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:s,prompted:a.prompted,applied:a.applied,skipped:a.skipped,state:a.state}),warnings:a.warnings,next_steps:a.nextSteps,settings_changed:c.changed}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="75c0d2d2-6a89-508f-b7dd-b43d55978b44")}catch{}})();var eR=()=>QC.createInterface({input:ZC,output:Oe});function tR(){return structuredClone(wt)}var nR=["minimal","default","strict"];function hh(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new m("--preset must not be empty",l.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new m(`Invalid --preset value "${e}". Allowed: ${nR.join(", ")}`,l.USAGE)}function rR(e){if(e!==void 0){if(e.trim().length===0)throw new m("--type-preset must not be empty",l.USAGE);try{return Em(e)}catch{throw new m(`Invalid --type-preset value "${e}". Allowed: ${Sm.join(", ")}`,l.USAGE)}}}function sR(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new m("--author must not be empty",l.USAGE);return t}function Uc(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:W.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function oR(e,t,n,r){let s=r?.trim();if(r!==void 0&&s?.length===0)throw new m("--workspace must not be empty",l.USAGE);if(s!==void 0){if(t.path!==void 0||Uc(n))throw new m("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",l.USAGE);let d=W.resolve(e,s),u=W.join(d,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:d}}}if(t.path===void 0&&Uc(n)){let d=W.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let o=E(e,t.path),i=W.join(W.resolve(e),".agents","pm"),a=W.dirname(W.dirname(o)),c=W.resolve(o)===i?"current":"ancestor";return{pmRoot:o,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:o,workspace_root:a,discovery:c,requested_cwd:W.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:o}}}function iR(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new m("--id-prefix must not be empty",l.USAGE);if(Uc(t))throw new m(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,l.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&It(e)!==It(t))throw new m(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,l.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${It(e)}`,`pm init --id-prefix ${It(t)}`]});return t}function aR(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new m("--agent-guidance must not be empty",l.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new m(`Invalid --agent-guidance value "${e}". Allowed: ${dh.join(", ")}`,l.USAGE)}function cR(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function gh(e,t){let n=Xd[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function dR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lR(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(dR).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function mR(e,t,n){let r=bs(t.schema),s=ot(e,r.files.types,st.types),i=vm(await q(s)),a=[],c=[];for(let d of Am(n)){let u=km(i,d);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await Rt({pmRoot:e,filePath:s,raw:gs(i),op:"init:type-preset",author:T(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:s}}async function uR(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",W.join(".agents","pm")];for(let n of t)if(await P(W.join(e,n)))return!0;return!1}async function pR(e,t,n){if(!t||n||await P(W.join(e,"settings.json"))||!await uR(e))return;let r=W.join(e,".agents","pm");throw new m(`Refusing to initialize tracker files directly in workspace root "${e}".`,l.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function yh(e,t){let n=[],r=[];for(let s of t){let o=s?W.join(e,s):e,i=await P(o);await XC.mkdir(o,{recursive:!0}),i?r.push(`already_exists:${o}`):n.push(o),r.push(...await z({path:o,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function fR(e,t){let n=eR();try{Oe.write(`pm init setup wizard (agent-optimized)
24
+ `),Oe.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
25
25
 
26
- `),Re.write(`1/3 Item ID prefix
27
- `),Re.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
28
- `);let r=await n.question(`Item ID prefix [${e}]: `),s=r.trim().length>0?Ct(r):e;Re.write(`
26
+ `),Oe.write(`1/3 Item ID prefix
27
+ `),Oe.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
28
+ `);let r=await n.question(`Item ID prefix [${e}]: `),s=r.trim().length>0?It(r):e;Oe.write(`
29
29
  2/3 Governance preset
30
- `),Re.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
31
- `),Re.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
32
- `),Re.write(`strict: ownership blocking, strict create defaults, close validation strict.
33
- `);let o=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),i=o.trim().length>0?o.trim():"minimal",a="minimal";try{a=sh(i)}catch{Re.write(`Unrecognized governance preset "${i}"; using minimal.
34
- `)}Re.write(`
30
+ `),Oe.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
31
+ `),Oe.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
32
+ `),Oe.write(`strict: ownership blocking, strict create defaults, close validation strict.
33
+ `);let o=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),i=o.trim().length>0?o.trim():"minimal",a="minimal";try{a=hh(i)}catch{Oe.write(`Unrecognized governance preset "${i}"; using minimal.
34
+ `)}Oe.write(`
35
35
  3/3 Project telemetry
36
- `),Re.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
37
- `);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=JC(m,t);return Re.write(`
38
- `),{prefix:s,preset:a,telemetry_enabled:u}}finally{n.close()}}function rR(e){return{presetFromOption:sh(e.preset),useDefaults:e.defaults===!0,authorFromOption:HC(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:YC(e.agentGuidance),typePreset:BC(e.typePreset)}}function sR(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function oR(e,t,n,r){if(t.length===0||n)return;let s=r.discovery==="ancestor";throw new l(`${s?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:s?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...s?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...s?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function iR(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(oh(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function aR(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=sR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return oR(e.settingsPath,n,e.options.force===!0,e.target),iR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Ee(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function cR(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,s=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await nR(t,yt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,s=!0}let o=n??"minimal",i=KC();i.id_prefix=t,oh(i,o);let a=Ss()?.trim()||void 0;return i.author_default=e.normalizedOptions.authorFromOption??a??"",r!==void 0&&(i.telemetry.enabled=r,i.telemetry.first_run_prompt_completed=!0),await Ee(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:s}}async function rh(e){return e.settingsExists?await aR(e):await cR({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function dR(e){let t=await nh({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await Ee(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function lR(e,t){let n=[],r=[],s=await wm(e,t.schema);for(let o of s.created_paths)n.push(o),r.push(...await z({path:o,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function mR(e){if(e.typePreset===void 0)return;let t=await ZC(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await z({path:t.file,scope:"project",op:"init:type_preset"})),t}async function uR(e){let n=x(e.settings,I()).folders.filter(s=>!Oi.includes(s)),r=await ih(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function pR(e){let t=V.resolve(e.tracker_root),n=V.dirname(t);return V.basename(t)==="pm"&&V.basename(n)===".agents"?V.dirname(n):e.workspace_root}async function fR(e,t,n,r){if(!e)return;let s=await Cn("all",{install:!0,project:!0},{...t,path:n});r.push(...s.warnings);let o=QC(s),i=o.packages.filter(a=>!a.ok).map(a=>a.alias);if(!o.installed_all||i.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${i.length>0?`: ${i.join(", ")}`:"."}`,d.GENERIC_FAILURE);return o}function _R(e){let t=r=>bs([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let s=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(s)||n.push(s)}return n}async function hR(e,t,n,r=_p){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let s=await r({pmRoot:e,workspaceRoot:t});s.gitattributes.changed&&n.push(`updated:merge_fence:${s.gitattributes.path}`)}catch(s){if(!(s instanceof l))throw s;n.push(`merge_fence_skipped:install_failed:${s.context.code??"pm_error"}:${s.message}:run pm merge install after resolving the Git repository error`)}}async function _r(e,t,n={}){let r=process.cwd(),s=VC(r,t,e,n.workspace),o=s.pmRoot;e=WC(s.prefixArg,n.idPrefix);let i=rR(n);await tR(o,s.target.mode==="tracker-path",n.force===!0);let a=[],c=[],m=V.join(o,"settings.json"),u=await k(m),p;u&&(p=await rh({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:Ct(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target}));let f=await ih(o,Oi);a.push(...f.createdDirs),c.push(...f.warnings),p??=await rh({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:Ct(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target});let{settings:_}=p,h=pR(s.target),y=await pp(h??V.dirname(o)),g=h??y,b=await dR({pmRoot:o,cwd:g??r,agentGuidanceMode:i.agentGuidanceMode,settings:_,warnings:c}),v=await lR(o,_);a.push(...v.createdDirs),c.push(...v.warnings);let E=await mR({pmRoot:o,settings:_,typePreset:i.typePreset,warnings:c});if(E&&(_=await A(o)),await uR({pmRoot:o,settings:_,createdDirs:a,warnings:c}),g&&i.agentGuidanceMode!=="status"){let j=await Hi(g,{pmRoot:o});j.changed&&c.push(`updated:gitignore:${j.path}`)}!u&&n.mergeFence!==!1&&i.agentGuidanceMode!=="status"&&await hR(o,y,c);let N=await fR(i.installBundledPackages,t,o,c),O=_R({installBundledPackages:i.installBundledPackages,registeredTypePreset:E,agentGuidanceNextSteps:b.next_steps,target:s.target});return{ok:!0,path:o,target:s.target,settings:_,created_dirs:a,warnings:c,governance_preset:_.governance.preset,wizard_used:p.wizardUsed,...E?{registered_type_preset:E}:{},...N?{installed_packages:N}:{},next_steps:O,agent_guidance:b}}import SR from"node:fs/promises";import Lc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="70e06a73-6602-5384-a25b-fd3df5f6438e")}catch{}})();var ch=10,rn="https://schema.unbrained.dev/pm/eval-query-set/v1";var zo={schema:rn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Be=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},gR=new Set(["keyword","semantic","hybrid"]);function ah(e,t){let n=0,r=Math.min(t,e.length);for(let s=0;s<r;s+=1)n+=e[s]/Math.log2(s+2);return n}function yR(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),s=ah(r,n),o=Array.from({length:t.size},()=>1),i=ah(o,n);return i===0?0:s/i}function bR(e,t,n){let r=Math.min(n,e.length);for(let s=0;s<r;s+=1)if(t.has(e[s]))return 1/(s+1);return 0}function Pc(e,t,n){let r=Math.min(n,e.length),s=0;for(let o=0;o<r;o+=1)t.has(e[o])&&(s+=1);return s}function wR(e,t,n){return n<=0?0:Pc(e,t,n)/n}function vR(e,t,n){return t.size===0?0:Pc(e,t,n)/t.size}function dh(e,t,n){return{ndcg:yR(e,t,n),mrr:bR(e,t,n),precision:wR(e,t,n),recall:vR(e,t,n),relevant_total:t.size,retrieved_relevant:Pc(e,t,n)}}function lh(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,s)=>({ndcg:r.ndcg+s.ndcg,mrr:r.mrr+s.mrr,precision:r.precision+s.precision,recall:r.recall+s.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function kR(e,t){if(typeof e!="object"||e===null)throw new Be(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new Be(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Be(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(o=>typeof o!="string"))throw new Be(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let s=[...new Set(n.relevant_ids.map(o=>o.trim()).filter(o=>o.length>0))];if(s.length===0)throw new Be(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!gR.has(n.mode)))throw new Be(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:s,...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Nc(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==rn)throw new Be(`Unsupported eval query set schema; expected "${rn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new Be('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Be("Eval query set must contain at least one query");return{schema:rn,queries:n.map((r,s)=>kR(r,s))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b90a064c-f423-5bf7-9fbf-1fb273c7b5af")}catch{}})();var ER=Lc.join("search","eval-queries.json"),Fc={schema:rn,examples:[JSON.stringify(zo)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},TR=new Set(["keyword","semantic","hybrid"]),AR=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!TR.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},CR=e=>{if(e===void 0||e==="")return ch;let t=Hd(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},RR=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new l("Eval --fail-under must be a number in the range [0, 1]",d.USAGE);return n},Ot=e=>Math.round(e*1e4)/1e4,IR=async e=>{try{return await SR.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Fc,examples:[`echo '${JSON.stringify(zo)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},xR=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new l(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,d.USAGE,Fc)}},OR=e=>{try{return Nc(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Fc)}},PR=async e=>OR(xR(await IR(e),e)),NR=(e,t)=>t?Lc.resolve(process.cwd(),t):Lc.join(e,ER),LR=async(e,t,n,r)=>{let s=e.mode??t,i=(await or(e.query,{mode:s,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=dh(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,mode:s,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:Ot(a.ndcg),mrr:Ot(a.mrr),precision:Ot(a.precision),recall:Ot(a.recall)}}},FR=(e,t,n,r)=>{let s=lh(n);return{k:e,query_count:t.length,aggregate:{ndcg:Ot(s.ndcg),mrr:Ot(s.mrr),precision:Ot(s.precision),recall:Ot(s.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||s.ndcg>=r}},mh=async(e,t)=>{let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=CR(e.k),s=AR(e.mode),o=RR(e.failUnder),i=NR(n,e.queries),a=await PR(i),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await LR(u,s,r,t);m.push(f),c.push(p)}return FR(r,c,m,o)};import{readFile as HR,writeFile as VR}from"node:fs/promises";import WR from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c9d6924-ae7c-57c3-a346-1e2189c532fa")}catch{}})();function $c(e,t){let n=Ts(e);if(n)throw new l(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,d.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(i)try{let a=JSON.parse(i);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new l(`History merge input (${t}) contains invalid JSON at line ${s+1}.`,d.GENERIC_FAILURE)}}return r}function Pt(e){return J({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function $R(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Pt(e[r])===Pt(t[r]);)r+=1;return r}function uh(e,t,n){$c(e,"base");let r=$c(t,"ours"),s=$c(n,"theirs"),o=$R(r,s);if(o===r.length&&o===s.length)return{merged:st(r),strategy:"identical",common_entries:o,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===s.length)return{merged:st(r),strategy:"fast_forward_ours",common_entries:o,entries_from_ours:r.length-o,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===r.length)return{merged:st(s),strategy:"fast_forward_theirs",common_entries:o,entries_from_ours:0,entries_from_theirs:s.length-o,entries_total:s.length,reanchored:!1};let i=r.slice(o),a=new Set(i.map(Pt)),c=s.slice(o).filter(p=>!a.has(Pt(p))),m=[...i,...c].sort((p,f)=>{let _=yn(p.ts,f.ts);if(_!==0)return _;let h=a.has(Pt(p)),y=a.has(Pt(f));return h!==y?Number(y)-Number(h):Pt(p).localeCompare(Pt(f))}),u=Cs([...r.slice(0,o),...m]);return{merged:st(u.entries),strategy:"union_reanchor",common_entries:o,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:u.entries.length,reanchored:!0}}function Mc(e,t){let n=Ts(e);if(n)throw new l(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,d.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{throw new l(`Relationship merge input (${t}) contains invalid JSON at line ${s+1}.`,d.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new l(`Relationship merge input (${t}) line ${s+1} is not a relationship event (eventId + sequence required).`,d.GENERIC_FAILURE);r.push(a)}return r}function Bo(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
36
+ `),Oe.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
37
+ `);let c=t?"Y/n":"y/N",d=await n.question(`Enable telemetry for this project? [${c}] `),u=cR(d,t);return Oe.write(`
38
+ `),{prefix:s,preset:a,telemetry_enabled:u}}finally{n.close()}}function _R(e){return{presetFromOption:hh(e.preset),useDefaults:e.defaults===!0,authorFromOption:sR(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:aR(e.agentGuidance),typePreset:rR(e.typePreset)}}function hR(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function gR(e,t,n,r){if(t.length===0||n)return;let s=r.discovery==="ancestor";throw new m(`${s?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,l.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:s?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...s?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...s?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function yR(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(gh(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function bR(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=hR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return gR(e.settingsPath,n,e.options.force===!0,e.target),yR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Ce(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function wR(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,s=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await fR(t,wt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,s=!0}let o=n??"minimal",i=tR();i.id_prefix=t,gh(i,o);let a=Rs()?.trim()||void 0;return i.author_default=e.normalizedOptions.authorFromOption??a??"",r!==void 0&&(i.telemetry.enabled=r,i.telemetry.first_run_prompt_completed=!0),await Ce(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:s}}async function _h(e){return e.settingsExists?await bR(e):await wR({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function vR(e){let t=await fh({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await Ce(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function kR(e,t){let n=[],r=[],s=await Rm(e,t.schema);for(let o of s.created_paths)n.push(o),r.push(...await z({path:o,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function SR(e){if(e.typePreset===void 0)return;let t=await mR(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await z({path:t.file,scope:"project",op:"init:type_preset"})),t}async function ER(e){let n=I(e.settings,R()).folders.filter(s=>!Gi.includes(s)),r=await yh(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function AR(e){let t=W.resolve(e.tracker_root),n=W.dirname(t);return W.basename(t)==="pm"&&W.basename(n)===".agents"?W.dirname(n):e.workspace_root}async function TR(e,t,n,r){if(!e)return;let s=await xn("all",{install:!0,project:!0},{...t,path:n});r.push(...s.warnings);let o=lR(s),i=o.packages.filter(a=>!a.ok).map(a=>a.alias);if(!o.installed_all||i.length>0)throw new m(`pm init --with-packages did not install all bundled packages successfully${i.length>0?`: ${i.join(", ")}`:"."}`,l.GENERIC_FAILURE);return o}function CR(e){let t=r=>Es([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let s=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(s)||n.push(s)}return n}async function RR(e,t,n,r=Ap){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let s=await r({pmRoot:e,workspaceRoot:t});s.gitattributes.changed&&n.push(`updated:merge_fence:${s.gitattributes.path}`)}catch(s){if(!(s instanceof m))throw s;n.push(`merge_fence_skipped:install_failed:${s.context.code??"pm_error"}:${s.message}:run pm merge install after resolving the Git repository error`)}}async function br(e,t,n={}){let r=process.cwd(),s=oR(r,t,e,n.workspace),o=s.pmRoot;e=iR(s.prefixArg,n.idPrefix);let i=_R(n);await pR(o,s.target.mode==="tracker-path",n.force===!0);let a=[],c=[],d=W.join(o,"settings.json"),u=await P(d),p;u&&(p=await _h({pmRoot:o,settingsPath:d,settingsExists:u,normalizedPrefix:It(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target}));let f=await yh(o,Gi);a.push(...f.createdDirs),c.push(...f.warnings),p??=await _h({pmRoot:o,settingsPath:d,settingsExists:u,normalizedPrefix:It(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target});let{settings:_}=p,h=AR(s.target),y=await Sp(h??W.dirname(o)),g=h??y,b=await vR({pmRoot:o,cwd:g??r,agentGuidanceMode:i.agentGuidanceMode,settings:_,warnings:c}),v=await kR(o,_);a.push(...v.createdDirs),c.push(...v.warnings);let S=await SR({pmRoot:o,settings:_,typePreset:i.typePreset,warnings:c});if(S&&(_=await A(o)),await ER({pmRoot:o,settings:_,createdDirs:a,warnings:c}),g&&i.agentGuidanceMode!=="status"){let j=await ta(g,{pmRoot:o});j.changed&&c.push(`updated:gitignore:${j.path}`)}!u&&n.mergeFence!==!1&&i.agentGuidanceMode!=="status"&&await RR(o,y,c);let x=await TR(i.installBundledPackages,t,o,c),O=CR({installBundledPackages:i.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:b.next_steps,target:s.target});return{ok:!0,path:o,target:s.target,settings:_,created_dirs:a,warnings:c,governance_preset:_.governance.preset,wizard_used:p.wizardUsed,...S?{registered_type_preset:S}:{},...x?{installed_packages:x}:{},next_steps:O,agent_guidance:b}}import FR from"node:fs/promises";import qc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="70e06a73-6602-5384-a25b-fd3df5f6438e")}catch{}})();var wh=10,an="https://schema.unbrained.dev/pm/eval-query-set/v1";var Jo={schema:an,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},He=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},IR=new Set(["keyword","semantic","hybrid"]);function bh(e,t){let n=0,r=Math.min(t,e.length);for(let s=0;s<r;s+=1)n+=e[s]/Math.log2(s+2);return n}function xR(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),s=bh(r,n),o=Array.from({length:t.size},()=>1),i=bh(o,n);return i===0?0:s/i}function OR(e,t,n){let r=Math.min(n,e.length);for(let s=0;s<r;s+=1)if(t.has(e[s]))return 1/(s+1);return 0}function Gc(e,t,n){let r=Math.min(n,e.length),s=0;for(let o=0;o<r;o+=1)t.has(e[o])&&(s+=1);return s}function PR(e,t,n){return n<=0?0:Gc(e,t,n)/n}function NR(e,t,n){return t.size===0?0:Gc(e,t,n)/t.size}function vh(e,t,n){return{ndcg:xR(e,t,n),mrr:OR(e,t,n),precision:PR(e,t,n),recall:NR(e,t,n),relevant_total:t.size,retrieved_relevant:Gc(e,t,n)}}function kh(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,s)=>({ndcg:r.ndcg+s.ndcg,mrr:r.mrr+s.mrr,precision:r.precision+s.precision,recall:r.recall+s.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function LR(e,t){if(typeof e!="object"||e===null)throw new He(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new He(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new He(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(o=>typeof o!="string"))throw new He(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let s=[...new Set(n.relevant_ids.map(o=>o.trim()).filter(o=>o.length>0))];if(s.length===0)throw new He(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!IR.has(n.mode)))throw new He(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:s,...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function jc(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==an)throw new He(`Unsupported eval query set schema; expected "${an}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new He('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new He("Eval query set must contain at least one query");return{schema:an,queries:n.map((r,s)=>LR(r,s))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cc9405b-d2b8-59aa-893f-54892595788a")}catch{}})();var MR=qc.join("search","eval-queries.json"),Kc={schema:an,examples:[JSON.stringify(Jo)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},$R=new Set(["keyword","semantic","hybrid"]),DR=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!$R.has(t))throw new m("Eval --mode must be one of keyword|semantic|hybrid",l.USAGE);return t},UR=e=>{if(e===void 0||e==="")return wh;let t=el(e);if(t===null)throw new m("Eval --k must be a positive integer",l.USAGE);return t},GR=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new m("Eval --fail-under must be a number in the range [0, 1]",l.USAGE);return n},Lt=e=>Math.round(e*1e4)/1e4,jR=async e=>{try{return await FR.readFile(e,"utf8")}catch{throw new m(`Eval query set not found at ${e}`,l.NOT_FOUND,{...Kc,examples:[`echo '${JSON.stringify(Jo)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},qR=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new m(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,l.USAGE,Kc)}},KR=e=>{try{return jc(e)}catch(t){throw new m(t instanceof Error?t.message:String(t),l.USAGE,Kc)}},zR=async e=>KR(qR(await jR(e),e)),BR=(e,t)=>t?qc.resolve(process.cwd(),t):qc.join(e,MR),HR=async(e,t,n,r)=>{let s=e.mode??t,i=(await cr(e.query,{mode:s,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=vh(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,mode:s,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:Lt(a.ndcg),mrr:Lt(a.mrr),precision:Lt(a.precision),recall:Lt(a.recall)}}},VR=(e,t,n,r)=>{let s=kh(n);return{k:e,query_count:t.length,aggregate:{ndcg:Lt(s.ndcg),mrr:Lt(s.mrr),precision:Lt(s.precision),recall:Lt(s.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||s.ndcg>=r}},Sh=async(e,t)=>{let n=E(process.cwd(),t.path);await C(n);let r=UR(e.k),s=DR(e.mode),o=GR(e.failUnder),i=BR(n,e.queries),a=await zR(i),c=[],d=[];for(let u of a.queries){let{report:p,metrics:f}=await HR(u,s,r,t);d.push(f),c.push(p)}return VR(r,c,d,o)};import{readFile as sI,writeFile as oI}from"node:fs/promises";import iI from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c9d6924-ae7c-57c3-a346-1e2189c532fa")}catch{}})();function zc(e,t){let n=xs(e);if(n)throw new m(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,l.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(i)try{let a=JSON.parse(i);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new m(`History merge input (${t}) contains invalid JSON at line ${s+1}.`,l.GENERIC_FAILURE)}}return r}function Ft(e){return Q({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function WR(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Ft(e[r])===Ft(t[r]);)r+=1;return r}function Eh(e,t,n){zc(e,"base");let r=zc(t,"ours"),s=zc(n,"theirs"),o=WR(r,s);if(o===r.length&&o===s.length)return{merged:it(r),strategy:"identical",common_entries:o,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===s.length)return{merged:it(r),strategy:"fast_forward_ours",common_entries:o,entries_from_ours:r.length-o,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===r.length)return{merged:it(s),strategy:"fast_forward_theirs",common_entries:o,entries_from_ours:0,entries_from_theirs:s.length-o,entries_total:s.length,reanchored:!1};let i=r.slice(o),a=new Set(i.map(Ft)),c=s.slice(o).filter(p=>!a.has(Ft(p))),d=[...i,...c].sort((p,f)=>{let _=vn(p.ts,f.ts);if(_!==0)return _;let h=a.has(Ft(p)),y=a.has(Ft(f));return h!==y?Number(y)-Number(h):Ft(p).localeCompare(Ft(f))}),u=Ps([...r.slice(0,o),...d]);return{merged:it(u.entries),strategy:"union_reanchor",common_entries:o,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:u.entries.length,reanchored:!0}}function Bc(e,t){let n=xs(e);if(n)throw new m(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,l.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{throw new m(`Relationship merge input (${t}) contains invalid JSON at line ${s+1}.`,l.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new m(`Relationship merge input (${t}) line ${s+1} is not a relationship event (eventId + sequence required).`,l.GENERIC_FAILURE);r.push(a)}return r}function Xo(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
39
39
  `)}
40
- `}function MR(e){return e.map((t,n)=>({...t,sequence:n+1}))}function ph(e,t,n){Mc(e,"base");let r=Mc(t,"ours"),s=Mc(n,"theirs"),o=Math.min(r.length,s.length),i=0;for(;i<o&&r[i].eventId===s[i].eventId;)i+=1;if(i===r.length&&i===s.length)return{merged:Bo(r),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===s.length)return{merged:Bo(r),strategy:"fast_forward_ours",common_entries:i,entries_from_ours:r.length-i,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===r.length)return{merged:Bo(s),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:s.length-i,entries_total:s.length,reanchored:!1};let a=r.slice(i),c=new Set(a.map(f=>f.eventId)),m=s.slice(i).filter(f=>!c.has(f.eventId)),u=[...a,...m].sort((f,_)=>{if(f.timestamp!==void 0&&_.timestamp!==void 0){let g=yn(f.timestamp,_.timestamp);if(g!==0)return g}else{if(f.timestamp===void 0&&_.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let h=c.has(f.eventId),y=c.has(_.eventId);return h!==y?Number(y)-Number(h):0}),p=MR([...r.slice(0,i),...u]);return{merged:Bo(p),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:m.length,entries_total:p.length,reanchored:!0}}var DR=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],UR=["updated_at"];function sn(e,t){return J(e??null)===J(t??null)}function GR(e,t,n){let r=u=>Array.isArray(u)?u:[],s=new Set(r(e).map(u=>J(u))),o=r(t),i=new Set(o.map(u=>J(u))),a=r(n),c=new Set(a.map(u=>J(u))),m=o.filter(u=>{let p=J(u);return!s.has(p)||c.has(p)});for(let u of a){let p=J(u);!i.has(p)&&!s.has(p)&&m.push(u)}return m}function jR(e,t){return yn(String(e),String(t))>=0?e:t}function fh(e,t,n,r){return sn(t,n)?{value:t,from_theirs:!1,conflict:!1}:sn(e,t)?{value:n,from_theirs:!0,conflict:!1}:sn(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function _h(e,t,n,r,s){let o=fh(e,t,n,r);if(!o.conflict||s==="preferred_side")return o;let i=J(n).localeCompare(J(t))<0;return{value:i?n:t,from_theirs:i,conflict:!0}}function Dc(e){return{...e.metadata}}function Uc(e,t,n){try{return We(_u(e,n),n)}catch(r){throw new l(`Item merge input (${t}) is not a readable item document: ${String(r)}`,d.GENERIC_FAILURE)}}function qR(e,t,n,r,s){let o=new Set(DR),i=new Set(UR),a=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((m,u)=>m.localeCompare(u)),c={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let m of a){let u=e[m],p=t[m],f=n[m];if(o.has(m)){let h=GR(u,p,f);c.merged[m]=h,sn(h,p)||c.unionFields.push(m);continue}if(i.has(m)){c.merged[m]=jR(p,f);continue}let _=_h(u,p,f,r,s);_.value!==void 0&&(c.merged[m]=_.value),_.conflict?(c.conflictFields.push(m),c.conflictDecisions.push({field:m,base:u,ours:p,theirs:f,retained:_.value,discarded:_.from_theirs?p:f})):_.from_theirs&&c.fieldsFromTheirs.push(m)}return c}function hh(e,t,n,r={}){let s=r.preferred??"ours",o=r.conflictResolution??"preferred_side",i=e.trim().length>0,a=Uc(t,"ours",r),c=Uc(n,"theirs",r),m=i?Uc(e,"base",r):a,u=i?Dc(m):{},p=Dc(a),f=Dc(c),{merged:_,conflictFields:h,fieldsFromTheirs:y,unionFields:g,conflictDecisions:b}=qR(u,p,f,s,o),v=_h(i?m.body:"",a.body,c.body,s,o);return v.conflict?(h.push("body"),b.push({field:"body",base:i?m.body:"",ours:a.body,theirs:c.body,retained:v.value,discarded:v.from_theirs?a.body:c.body})):v.from_theirs&&y.push("body"),{merged:je({metadata:_,body:v.value},r),conflict_fields:h,fields_from_theirs:y,union_fields:g,conflict_decisions:b,requested_preference:s,conflict_resolution:o}}function Gc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jc(e,t){let n=Ts(e);if(n)throw new l(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,d.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new l(`JSON merge input (${t}) is not valid JSON.`,d.GENERIC_FAILURE)}}function KR(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=m=>{let u=new Map;for(let p of m){let f=J(p);u.set(f,(u.get(f)??0)+1)}return u},s=r(e),o=r(t),i=r(n);for(let[m,u]of s)if((o.get(m)??0)<u||(i.get(m)??0)<u)return null;let a=new Map(o),c=[];for(let m of n){let u=J(m),p=a.get(u)??0;p>0?a.set(u,p-1):c.push(m)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function zR(e,t,n,r,s,o,i){if(!Gc(t)||!Gc(n))return null;let a=Gc(e)?e:{},c={},m=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,p)=>u.localeCompare(p));for(let u of m){let p=s.length>0?`${s}.${u}`:u,f=BR(a,t,n,u,r,p,o,i);f!==void 0&&(c[u]=f)}return c}function gh(e,t,n,r,s,o,i){if(sn(t,n))return t;let a=KR(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(s),a.merged;let c=zR(e,t,n,r,s,o,i);if(c!==null)return c;let m=fh(e,t,n,r);return m.conflict?o.push(s):m.from_theirs&&i.push(s),m.value}function BR(e,t,n,r,s,o,i,a){let c=Object.prototype.hasOwnProperty.call(t,r),m=Object.prototype.hasOwnProperty.call(n,r),u=Object.prototype.hasOwnProperty.call(e,r);if(c&&m)return gh(e[r],t[r],n[r],s,o,i,a);if(c){if(u&&sn(e[r],t[r])){a.push(o);return}return u?(i.push(o),s==="theirs"?void 0:t[r]):t[r]}if(!(u&&sn(e[r],n[r])))return u?(i.push(o),s==="theirs"?n[r]:void 0):(a.push(o),n[r])}function yh(e,t,n,r={}){let s=r.preferred??"ours",o=jc(e,"base"),i=jc(t,"ours"),a=jc(n,"theirs"),c=[],m=[],u=gh(o,i,a,s,"",c,m);return{merged:`${JSON.stringify(u??null,null,2)}
41
- `,conflict_paths:c,paths_from_theirs:m,preferred:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d79e3a4-6104-5855-837f-69a041b87b27")}catch{}})();var bh=["item","history","relationship","json"];function YR(e){let t=e.trim().toLowerCase();if(bh.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${bh.join(", ")}.`,d.USAGE)}function JR(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new l(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,d.USAGE)}async function qc(e,t){try{return await HR(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function XR(e){let t=T(process.cwd(),e.path);return await k(C(t))?A(t):null}function QR(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function wh(e,t){let n=YR(e.artifact),r=JR(e.prefer),s=WR.resolve(e.outputPath??e.oursPath),[o,i,a]=await Promise.all([qc(e.basePath,"base"),qc(e.oursPath,"ours"),qc(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=uh(o,i,a);c=_.merged,p.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=ph(o,i,a);c=_.merged,p.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await XR(t),h=hh(o,i,a,{format:QR(e.itemPath??s,_),schema:_?.schema,extensionFieldNames:bt(I()),preferred:r,conflictResolution:"stable_value_order"});c=h.merged,u.push(...h.conflict_fields),p.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0&&(m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,decisions:h.conflict_decisions})}else{let _=yh(o,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await VR(s,c,"utf8"),m!==void 0){let _=await Lp(m);_!==null&&(p.receipt=er(_))}let f=[];if(u.length>0){let _=p.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${p.receipt.receipt_id} with item ${p.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${u.join(", ")}; the item driver kept the direction-independent stable value. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&p.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:u.length===0,artifact:n,output_path:s,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:S()}}import Sh from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de9b7f82-0f51-599d-b1fa-2d54e3acbdbc")}catch{}})();function vh(e,t){return t==="body"?e.body:e.metadata[t]}function Kc(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(s=>{let o=t.findIndex((i,a)=>!r.has(a)&&Kc(s,i));return o<0?!1:(r.add(o),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,s])=>Object.hasOwn(n,r)&&Kc(s,n[r]))}function kh(e,t){let n=new Set(t),r=[];for(let s=e.length-1;s>=0&&n.size>0;s-=1){let o=e[s],i=new Set;for(let c of vu(o.patch))i.add(Ds(c.path)),c.from&&i.add(Ds(c.from));let a=[...n].filter(c=>i.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:s+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,m)=>c.localeCompare(m))})}}return r.reverse()}function ZR(e,t,n){let r=Sh.compare(t,n);if(r.length===0)return;let s=new Set;for(let h of r)s.add(Ds(h.path));let o=new Set([...s].filter(h=>Kc(vh(t,h),vh(n,h)))),i=new Set([...s].filter(h=>!o.has(h))),a=kh(e,i),c=kh(e,o),m=[...s].sort((h,y)=>h.localeCompare(y)),u=[...i].sort((h,y)=>h.localeCompare(y)),p=[...o].sort((h,y)=>h.localeCompare(y)),f=[...new Set(a.map(h=>h.author))].sort((h,y)=>h.localeCompare(y)),_=[...new Set(c.map(h=>h.author))].sort((h,y)=>h.localeCompare(y));return{reconciled_field_count:s.size,reconciled_fields:m,reverted_field_count:i.size,reverted_fields:u,discarded_events:a,discarded_authors:f,preserved_field_count:o.size,preserved_fields:p,preserved_events:c,preserved_authors:_,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function eI(e,t,n,r){let s=e.located?.itemPath??null,o=e.located?await K(e.located,{schema:t.schema}):null;if(!o)return{currentItemReplay:null,currentItemPath:s,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let i=Bt(o.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:i,currentItemPath:s,matchedChainBefore:Ne(i,r)===a,currentItemRawBeforeLock:o.raw,loadedItem:o}}function tI(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function nI(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:S(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Sh.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Ne(e.finalReplay,e.itemHashVersion),after_hash:Ne(n,e.itemHashVersion),message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function rI(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function sI(e){return Ps({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Os({historyPath:e.historyPath,nextHistoryRaw:st(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function hr(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await Ns(r,e,s,o.type_to_folder);if(!await k(i.historyPath))throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let a=await q(i.historyPath),c=await Et(i.historyPath,i.id);if(c.length===0)throw new l(`No history entries exist for ${i.id}; nothing to repair.`,d.USAGE);let m=bn(c),u=ku(c),p=t.normalizeProvenance?Pp(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=Su(p.entries),_=new Set(p.entries.map(ce=>ce.item_hash_version).filter(ce=>ce!==void 0)),h=Cs(p.entries,f),y=await eI(i,s,c,f),g=h.finalDocument,b=y.currentItemReplay!==null&&Ne(g,f)!==Ne(y.currentItemReplay,f),v=b&&y.currentItemReplay?ZR(h.entries,g,y.currentItemReplay):void 0,E=[h.entriesRehashed>0,h.entriesPatchRepaired>0,b,t.forceAuditEntry===!0,p.receipt.changed].some(Boolean),N=R(t.author,s.author_default),O=!!t.dryRun,j=tI({message:t.message,entriesRehashed:h.entriesRehashed,entriesPatchRepaired:h.entriesPatchRepaired,reconcileNeeded:b}),{rewrittenEntries:$,auditEntryAdded:xe}=nI({reanchorEntries:h.entries,changed:E,reconcileNeeded:b,currentItemReplay:y.currentItemReplay,finalReplay:g,author:N,message:j,auditOperation:t.auditOperation??"history_repair",auditContext:p.receipt.changed?{...t.auditContext,provenance_normalization:p.receipt}:t.auditContext,itemHashVersion:f,explicitItemHashVersion:h.explicitItemHashVersion}),te=bn($);if(!te.ok)throw new l(`history-repair produced an invalid rewritten chain (${te.errors.join(", ")}).`,d.GENERIC_FAILURE);let _e=rI(E,h.skippedOps,v);return E&&!O&&_e.push(...await sI({pmRoot:r,subject:i,settings:s,typeRegistry:o,historyRawBeforeLock:a,currentItemRawBeforeLock:y.currentItemRawBeforeLock,author:N,force:t.force,loadedItem:y.loadedItem,historyPath:i.historyPath,rewrittenEntries:$})),{id:i.id,dry_run:O,changed:E,history:{path:i.historyPath,entries_scanned:c.length,chain_drift_before:!m.ok,entries_rehashed:h.entriesRehashed,entries_patch_repaired:h.entriesPatchRepaired,converted_replace_to_add:h.convertedReplaceToAdd,skipped_ops:h.skippedOps,reconciled_with_item:b,audit_entry_added:xe,verify_ok:te.ok,verify_errors:te.errors,item_hash_version_before:u.item_hash_version??null,item_hash_version_after:f,version_disposition:_.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:y.currentItemPath!==null,path:y.currentItemPath,matched_chain_before:y.matchedChainBefore},provenance_normalization:{requested:t.normalizeProvenance===!0,...p.receipt},...v?{reconciliation:v}:{},warnings:[...new Set(_e)].sort((ce,Qe)=>ce.localeCompare(Qe)),generated_at:S()}}function Eh(e,t){if(t&&e!==void 0)throw new l("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",d.USAGE);if(!t&&e===void 0)throw new l("history-repair: provide an item <id> or pass --all to repair every drifted stream.",d.USAGE)}async function Ho(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=x(r,I()),o=[],i=await Rs(n,r.item_format,s.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await rp(n,i),c=e.normalizeProvenance?await Np(n):[],m=[...new Set([...a.driftedItems,...c])].sort((_,h)=>_.localeCompare(h)),u=[],p=[],f={repaired:0,skipped_clean:0,failed:0};for(let _ of m)try{let h=await hr(_,{...e,auditContext:e.auditContextById?.[_],auditContextById:void 0},t),y=h.changed?"repaired":"skipped_clean";f[y]+=1,p.push(...h.warnings.map(g=>`${_}:${g}`)),u.push({id:_,outcome:y,entries_rehashed:h.history.entries_rehashed,entries_patch_repaired:h.history.entries_patch_repaired,reconciled_with_item:h.history.reconciled_with_item,...h.reconciliation?{reconciliation:h.reconciliation}:{},warnings:h.warnings})}catch(h){f.failed+=1,u.push({id:_,outcome:"failed",error:h instanceof Error?h.message:String(h)})}return e.dryRun||await bu(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:i.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:u,totals:f,warnings:[...new Set([...o,...p])].sort((_,h)=>_.localeCompare(h)),generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c5620467-6c8c-5702-b742-57fba9e302c5")}catch{}})();async function Th(e,t){let n=e.dryRun===!0,r=await Fp(process.cwd(),{includeLossless:!0}),{pendingDecisions:s}=$p(r);if(!n&&e.force!==!0&&s.length>0)throw new l(`Merge reconciliation would accept ${s.length} receipt(s) containing discarded scalar values. Review pm merge report and rerun with --force only after deciding which values to retain or re-apply.`,d.CONFLICT,{code:"merge_reconcile_discards_require_acceptance",required:"Explicitly review every discarded field before accepting reconciliation.",nextSteps:s.map(g=>`Review receipt ${g.id} for ${g.item_id}: ${g.decisions.map(b=>b.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let o=r.reduce((g,b)=>((g[b.item_id]??=[]).push(b),g),{}),i=Object.fromEntries(Object.entries(o).map(([g,b])=>[g,{merge:{receipts:b.map(er)}}])),a=await Ho({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:i},t),c=new Set(a.streams.map(g=>g.id)),m=Object.keys(o).filter(g=>!c.has(g));(await Promise.allSettled(m.map(g=>hr(g,{dryRun:n,author:e.author??t.author,message:e.message??"record field-aware branch merge provenance",force:e.force,auditOperation:"merge_reconcile",auditContext:i[g],forceAuditEntry:!0},t)))).forEach((g,b)=>{let v=m[b];if(g.status==="fulfilled"){let E=g.value.changed?"repaired":"skipped_clean";a.streams.push({id:v,outcome:E,entries_rehashed:g.value.history.entries_rehashed,entries_patch_repaired:g.value.history.entries_patch_repaired,reconciled_with_item:g.value.history.reconciled_with_item,warnings:g.value.warnings}),a.totals[E]+=1}else a.streams.push({id:v,outcome:"failed",error:g.reason instanceof Error?g.reason.message:String(g.reason)}),a.totals.failed+=1});let p=0;!n&&a.totals.failed===0&&(await Promise.all(r.map(g=>Mp(process.cwd(),g))),p=r.length);let f=await Qs({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),_=f.checks.every(g=>g.status==="ok"),h=a.totals.failed===0&&_,y=n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.","No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:h?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:h,dry_run:n,repair:a,receipts:{pending_before:r.length,reconciled:p,summaries:r.map(er)},validation:f,guidance:y,generated_at:f.generated_at}}import{createHash as oI}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e8cd5790-eacf-5ef7-bc0a-11ea3fe17d2d")}catch{}})();var Rh=1,Ih=/^[A-Za-z0-9_-]+$/,iI=100,Ah=1e3;var zG=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function He(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,s)=>r.localeCompare(s));return n.length===0?void 0:n}function aI(e){return oI("sha256").update(J({type:He(e.type),author:He(e.author),item:He(e.item),harness:He(e.harness),agent_instance:He(e.agentInstance),provenance:He(e.provenanceFilter)})).digest("hex").slice(0,24)}function Ch(e,t){let n={version:Rh,fingerprint:t,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function cI(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Rh,n.fingerprint===t,typeof n.ts=="string",typeof n.stream_id=="string",typeof n.stream_offset=="number",Number.isSafeInteger(n.stream_offset),Number(n.stream_offset)>=0].every(Boolean)}function dI(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Ih.test(n))throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"})}if(!cI(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function lI(e){let t=e??iI;if(!Number.isSafeInteger(t)||t<0||t>Ah)throw new l(`Mutation event limit must be an integer from 0 to ${Ah}.`,d.USAGE,{code:"invalid_event_limit"});return t}function mI(e,t){let n=e?.trim();if(!n)return{};if(Ih.test(n))return{cursor:dI(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new l("Mutation event --since must be an event cursor or ISO timestamp.",d.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function uI(e,t){let n=await ta(e,t);if(n===null){if(!await hu(e))return{...await gu(e,t),source:"authoritative_history"};n=await ta(e,t)}if(n===null)throw new l("Mutation event index could not be opened after rebuild.",d.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function pI(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Vo(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=lI(e.limit),r=pI(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new l("Mutation event projections are mutually exclusive. Use --provenance or --full.",d.USAGE);let s=await A(t),o=s.agent_identity.identity_vocabulary,i=Hu(s.agent_identity.harness_signals),a=Vu({provenance:e.provenanceFilter},i),c=He(e.harness),m=aI(e),{cursor:u,sinceTimestamp:p}=mI(e.since,m),f={...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:He(e.type),authors:He(e.author),harnesses:c,harness_alias_authors:c?Object.entries(o.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:He(e.agentInstance),provenance:[...a].map(([y,g])=>({dimension:y,values:[...g]})),stream_ids:He(e.item),limit:n},_=await uI(t,f),h=_.events.map(y=>({...r==="row"?{cursor:Ch(y,m)}:{},item_id:y.stream_id,version:y.stream_offset+1,ts:y.entry.ts,author:y.entry.author,type:y.entry.op,...y.entry.message===void 0?{}:{message:y.entry.message},patch_count:y.entry.patch.length,...e.full===!0?{entry:y.entry}:{},...e.provenance===!0?{provenance:Wu(y.entry,o,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:Ch(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Yu(_.events.map(y=>y.entry),o,i)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32223457-5f57-5049-99cf-c5d766413fb6")}catch{}})();var fI="1h",_I="now",hI="+1d";function Nt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function xh(e,t,n){return{type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message}}async function Oh(e,t,n,r){let s=xh(e,t,n),o=[];return Nt(o,"start",n.start??_I),n.end!==void 0?Nt(o,"end",n.end):Nt(o,"duration",n.duration??fI),Nt(o,"location",n.location),Nt(o,"timezone",n.timezone),n.allDay===!0&&Nt(o,"all_day","true"),s.event=[o.join(",")],xt(s,r)}function Ph(e,t,n){return Oh("Meeting",e,t,n)}function Nh(e,t,n){return Oh("Event",e,t,n)}function Lh(e,t,n){let r=xh("Reminder",e,t),s=[];return Nt(s,"at",t.at??hI),Nt(s,"text",t.text??e),r.reminder=[s.join(",")],xt(r,n)}import yr from"node:crypto";import{cp as $h,lstat as kI,mkdir as on,readFile as $n,readdir as Bc,rename as Uh,rm as Vc,writeFile as Yo}from"node:fs/promises";import L from"node:path";import{constants as Lt}from"node:os";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1c74b5a9-67b8-597c-98de-a4487691081f")}catch{}})();var Fh=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),gI=/^[a-z][a-z0-9_]{0,63}$/u,yI=new Map([[Lt.errno.EACCES,"EACCES"],[Lt.errno.EDQUOT,"EDQUOT"],[Lt.errno.EMFILE,"EMFILE"],[Lt.errno.ENFILE,"ENFILE"],[Lt.errno.ENOMEM,"ENOMEM"],[Lt.errno.ENOSPC,"ENOSPC"],[Lt.errno.EPERM,"EPERM"],[Lt.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),bI={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function wI(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&Fh.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:yI.get(Math.abs(t.errno))??null}function vI(e,t,n={}){let r=wI(e);if(r===null)return null;if(!gI.test(t))throw new l("Host environment operation labels must be bounded identifiers.",d.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let s=Fh.get(r);return new l(`Host filesystem operation ${t} ${s.summary}.`,d.GENERIC_FAILURE,{code:n.codes?.[s.category]??bI[s.category].code,reason:r,required:s.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[s.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function Wo(e,t,n={}){try{return await t()}catch(r){throw vI(r,e,n)??r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2580e043-8675-5070-b57e-30cae333228c")}catch{}})();var Gh="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var jh=L.join("runtime","workspace-snapshots"),SI=new Set(["checkpoints","locks","runtime","search","transactions"]),EI=/^[a-z0-9][a-z0-9._-]*$/,gr="sdk-workspace-transaction",zc={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},qh={renameEntry:Uh,removeEntry:async e=>{await Vc(e,{recursive:!0,force:!0})}},Hc=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await $n(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==gr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await ue(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
42
- `)}};async function Kh(e,t=""){let n=await Bc(L.join(e,t),{withFileTypes:!0}),r=[];for(let s of n.sort((o,i)=>o.name.localeCompare(i.name))){if(t.length===0&&SI.has(s.name))continue;let o=L.posix.join(t.replaceAll(L.sep,"/"),s.name);if(s.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${o}`);if(s.isDirectory())r.push(...await Kh(e,o));else if(s.isFile())r.push(o);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${o}`)}return r}async function zh(e){let t=await Kh(e),n=yr.createHash("sha256"),r=[],s=0;for(let i of t){let a=await $n(L.join(e,i));r.push(a),s+=a.byteLength,n.update(i),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let o=n.digest("hex");return{manifest:{schema:Gh,fingerprint:o,files:t,bytes:s},contents:r}}function Mh(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
43
- `).filter(t=>t.trim().length>0).length}async function TI(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let s=t.slice(r,r+32),o=await Promise.all(s.map(async i=>[i,await $n(L.join(e,i))]));for(let[i,a]of o)n.set(i,a)}return n}function Wc(e){if(!EI.test(e))throw new l("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",d.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Bh(e,t){return Wo(`workspace_snapshot_${e}`,t,{codes:{capacity:zc.capacity.code,permission:zc.permission.code,resource:zc.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function an(e){return L.join(e,jh)}function Hh(e){return new l(`Unknown workspace snapshot: ${e}`,d.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Vh(e,t){try{return JSON.parse(await $n(e,"utf8"))}catch(n){throw wt(n)?Hh(t):n}}async function Dh(e,t,n){try{await Vc(e,{recursive:n})}catch(r){throw wt(r)?Hh(t):r}}async function AI(e,t,n=qh){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function CI(e,t,n,r,s){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await s?.()}catch(o){throw await r.renameEntry(n,t),await r.removeEntry(e),o}await r.removeEntry(n)}async function RI(e,t){return Wc(t),/^[a-f0-9]{64}$/.test(t)?t:(await Vh(L.join(an(e),"refs",`${t}.json`),t)).fingerprint}async function Yc(e,t={}){if(t.name!==void 0&&(Wc(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new l("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",d.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await zh(e),s=an(e),o=L.join(s,"objects",n.fingerprint),i=!1;try{i=(await kI(o)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&wt(a)))throw a}if(!i){let a=L.join(s,"objects",`.create-${process.pid}-${yr.randomUUID()}`);await Bh("create_object",async()=>{await on(L.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=L.join(a,"files",m);await on(L.dirname(u),{recursive:!0}),await Yo(u,r[c])}await Yo(L.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
44
- `,"utf8"),await on(L.dirname(o),{recursive:!0})}),i=await AI(a,o)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=L.join(s,"refs");await on(c,{recursive:!0});let m=L.join(c,`.ref-${process.pid}-${yr.randomUUID()}`);await Yo(m,`${JSON.stringify(a,null,2)}
45
- `,"utf8"),await Uh(m,L.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function br(e,t){let n=await RI(e,t),r=await Vh(L.join(an(e),"objects",n,"manifest.json"),t);if(r.schema!==Gh||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,d.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function Jc(e){let t=an(e),n=await Bc(L.join(t,"objects")).catch(s=>{if(s instanceof Error&&"code"in s&&wt(s))return[];throw s}),r=await Bc(L.join(t,"refs")).catch(s=>{if(s instanceof Error&&"code"in s&&wt(s))return[];throw s});return{objects:await Promise.all(n.filter(s=>/^[a-f0-9]{64}$/.test(s)).sort().map(s=>br(e,s))),references:await Promise.all(r.filter(s=>s.endsWith(".json")).sort().map(async s=>JSON.parse(await $n(L.join(t,"refs",s),"utf8"))))}}async function Xc(e,t){let n=await br(e,t),{manifest:r,contents:s}=await zh(e),o=new Map(r.files.map((p,f)=>[p,s[f]])),i=await TI(L.join(an(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),m=new Set([...a,...c]);for(let p of m){let f=o.get(p),_=i.get(p);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=Mh(o.get(p)),_=Mh(i.get(p));return{path:p,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(p=>p.removed_entries>0).sort((p,f)=>p.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:m.size,removed_file_count:[...a].filter(p=>!c.has(p)).length,added_file_count:[...c].filter(p=>!a.has(p)).length,removed_item_count:[...a].filter(p=>p.endsWith(".toon")&&!c.has(p)).length,affected_history_stream_count:u.length,removed_history_entry_count:u.reduce((p,f)=>p+f.removed_entries,0),affected_history_streams:u,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function Wh(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",d.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",s=n.lockTtlSeconds??60,o=n.lockWaitMs??5e3,i=await Pe(e,gr,s,r,!1,!1,o),a=new Hc(Fr(e,gr),r,s);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await Xc(e,t),f=await br(e,t),_=await Yc(e),h=f.fingerprint,y=an(e),g=L.join(y,"objects",h,"files"),b=L.dirname(e),v=L.basename(e);c=L.join(b,`.${v}.restore-${yr.randomUUID()}`);let E=L.join(b,`.${v}.backup-${yr.randomUUID()}`);await Bh("restore_stage",async()=>{await on(c,{recursive:!0}),await $h(g,c,{recursive:!0,force:!1}),await on(L.join(c,"runtime"),{recursive:!0}),await $h(y,L.join(c,jh),{recursive:!0,force:!1})});let N=await Eu({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:p.changed_file_count,removed_file_count:p.removed_file_count,removed_item_count:p.removed_item_count,affected_history_stream_count:p.affected_history_stream_count,removed_history_entry_count:p.removed_history_entry_count},lockTtlSeconds:s,lockWaitMs:o}),O=L.relative(c,N.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let j=Fr(c,gr);return await on(L.dirname(j),{recursive:!0}),await Yo(j,await $n(Fr(e,gr)),{flag:"wx"}),m=!0,await CI(c,e,E,qh,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:O,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([Vc(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function Yh(e,t){Wc(t);let n=an(e);if(!/^[a-f0-9]{64}$/.test(t))return await Dh(L.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Jc(e);if(r.some(s=>s.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Dh(L.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0492d773-2af2-5072-8164-9f8aab536191")}catch{}})();function wr(e){return{...e.args,...e.options}}function lt(e,t){let n=w(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Mn(e){return typeof e=="string"?[e]:ye(e)}function Jh(e){return mh(wr(e),e.global)}function Xh(e){let t=wr(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Vo({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Mn(t.type),author:Mn(t.author),item:Mn(t.item),limit:t.limit===void 0?void 0:Fe(t.limit,"limit"),full:t.full===!0,cursorMode:r,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Mn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Mn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Mn(t.provenanceFilter)}})}function Qh(e){let t=wr(e),n=lt(t,"subcommand");if(n==="install")return fp({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return Th({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return Dp({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return wh({artifact:lt(t,"artifact"),basePath:lt(t,"basePath"),oursPath:lt(t,"oursPath"),theirsPath:lt(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw Te({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Zh(e){let t=wr(e),n=lt(t,"subcommand");if(n!=="snapshot")throw Te({command_path:"workspace",token:n,allowed:["snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??lt(t,"snapshot_action"),s=T(process.cwd(),e.global.path);if(r==="create")return Yc(s,{name:w(t,"name")});if(r==="list")return Jc(s);let o=lt(t,"target");if(r==="inspect")return br(s,o);if(r==="delete")return Yh(s,o);if(r==="restore")return t.dryRun===!0?Xc(s,o):Wh(s,o,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Fe(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Fe(t.lockWaitMs,"lockWaitMs")});throw Te({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Jo(e){let t=wr(e),n=lt(t,"title");return e.action==="meet"?Ph(n,t,e.global):e.action==="event"?Nh(n,t,e.global):Lh(n,t,e.global)}import jI from"node:path";import II from"node:fs/promises";import eg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f232e106-54f4-572e-8f6e-054f52290267")}catch{}})();var xI="templates",OI=".json",PI=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,NI=ys.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),LI=new Set(NI);function FI(e){let t=e.trim();if(!PI.test(t))throw new l(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,d.USAGE);return t}function tg(e){return eg.join(e,xI)}function ng(e,t){return eg.join(tg(e),`${t}${OI}`)}async function $I(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function rg(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function MI(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(LI.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let s=r.filter(o=>typeof o=="string");s.length>0&&(t[n]=s);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(s=>typeof s=="string")&&(t[n]=[...r])}return rg(t)}function DI(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new l(`Template "${t}" has invalid options payload.`,d.GENERIC_FAILURE);let n=e,r={};for(let[s,o]of Object.entries(n)){let i=s.trim();if(i.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof o=="string"){r[i]=o;continue}if(Array.isArray(o)&&o.every(a=>typeof a=="string")){r[i]=[...o];continue}throw new l(`Template "${t}" contains invalid value for option "${i}".`,d.GENERIC_FAILURE)}return rg(r)}function UI(e,t){let n;try{n=JSON.parse(e)}catch{throw new l(`Template "${t}" contains invalid JSON.`,d.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Template "${t}" has invalid document shape.`,d.GENERIC_FAILURE);let r=n,s=DI(r.options,t),o=S();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:o,updated_at:typeof r.updated_at=="string"?r.updated_at:o,options:s}}async function GI(e,t){let n=await q(ng(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return UI(n,t)}async function Qc(e,t,n){let r=T(process.cwd(),n.path);await $I(r);let s=FI(e),o=MI(t);if(Object.keys(o).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let i=S(),a=ng(r,s),c=i;await k(a)&&(c=(await GI(r,s)).created_at);let m={name:s,created_at:c,updated_at:i,options:o},u=await A(r);return await II.mkdir(tg(r),{recursive:!0}),await At({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
46
- `,op:"templates:save",author:R(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:a,options:m.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1e34cfb-3d4e-5b79-8585-3162e71e574c")}catch{}})();var ag=["list","show","apply","lint"],qI="schema-types",KI="schema-statuses",zI="schema-fields";function Xo(){let e=I();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function cg(){let{profiles:e,warnings:t}=ym(Xo());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:Sm(n.definition)})),warnings:t,generated_at:S()}}function dg(e){let t;try{t=ps(e,Xo())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...Em(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function lg(e){let t;try{t=ps(e,Xo())}catch(s){throw new l(s instanceof Error?s.message:String(s),d.USAGE)}let{resolved:n}=t,r=jm(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:S()}}function BI(e,t){return jI.join(e,"templates",`${t}.json`)}async function HI(e,t){let n=await q(BI(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let s=r.options;if(s!==null&&typeof s=="object"&&!Array.isArray(s))return s}}catch{}}async function sg(e,t,n,r){let s=new Map;for(let o of r.templates){let i=await HI(e,o.name);i!==void 0&&s.set(o.name,i)}return{typesRaw:await q(rt(e,t.files.types,nt.types)),statusesRaw:await q(rt(e,t.files.statuses,nt.statuses)),fieldsRaw:await q(rt(e,t.files.fields,nt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:s,installedPackages:new Set}}function Dn(e){let t=[],n=[],r=[];for(let s of e)(s.status==="add"?t:s.status==="update"?n:r).push(s.key);return{added:t,updated:n,unchanged:r}}function og(e,t,n,r,s){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Dn(t.types.changes),statuses:Dn(t.statuses.changes),fields:Dn(t.fields.changes),workflows:Dn(t.workflows.changes.map(o=>({key:o.type,status:o.status}))),config:Dn(t.config.changes),templates:Dn(t.templates.changes.map(o=>({key:o.name,status:o.status}))),packages:t.packages,warnings:[...new Set(s)].sort((o,i)=>o.localeCompare(i)),generated_at:S()}}async function VI(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function WI(e){try{let t=ps(e,Xo());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function mg(e,t,n){let r=T(process.cwd(),n.path);await VI(r);let s=WI(e),o=s.profile,i=s.warnings,a=t.dryRun===!0,c=await A(r),m=fs(c.schema);if(a){let b=await sg(r,m,c,o),v=ig(o,b);return og(o,v,!1,!0,[...i])}let u=R(t.author,c.author_default),p=Au(c),f=!!t.force,_=[...i],h=[],y=async b=>{h.push(await Pe(r,b,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(qI),await y(KI),await y(zI);let b=await sg(r,m,c,o);if(g=ig(o,b),g.types.changed){let v=rt(r,m.files.types,nt.types);await At({pmRoot:r,filePath:v,raw:us(g.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let E=new Set(o.types.map(O=>um(O).name)),N=g.types.file.definitions.filter(O=>E.has(O.name));await wp(r,N,_,"profile:apply-type-folder"),_.push(...await z({path:v,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let v=rt(r,m.files.statuses,nt.statuses);await At({pmRoot:r,filePath:v,raw:km(g.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let v=rt(r,m.files.fields,nt.fields);await At({pmRoot:r,filePath:v,raw:bm(g.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let v of g.config.changes){if(v.status==="unchanged")continue;let E=hs(v.key);E!==void 0&&gs(c,E,v.value)}c.schema.type_workflows=g.workflows.result,await Ee(r,c,"profile:apply-config")}for(let v of g.templates.changes)v.status!=="unchanged"&&await Qc(v.name,{...v.options},n)}finally{for(let b of h.reverse())try{await b()}catch{}}return og(o,g,g.changed,!1,_)}function ig(e,t){try{return qm(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import pg from"node:fs/promises";import fg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7e0f84f6-9528-55c5-8976-6f85cd920486")}catch{}})();function YI(e,t,n){let r=new Set,s=[];for(let o of e){let i=o.trim();if(i.length===0||r.has(i))continue;r.add(i);let a=t.get(i);if(a===void 0){s.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){s.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}s.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return s}function JI(e,t){let n=[...e].sort((s,o)=>o.entries-s.entries||s.id.localeCompare(o.id)),r=[];for(let s of n){if(t.scope==="closed"&&s.bucket!=="closed"){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(s.entries<=t.minEntries){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&s.entries<=t.allOver){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:s.id,entries:s.entries,selected:!0,skip_reason:null})}return r}function ug(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return YI(t.ids,n,t.minEntries)}return JI(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6609492-75a9-5111-b9b3-1b81908f3084")}catch{}})();function XI(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(n)){let o=Number.parseInt(n,10);if(!Number.isSafeInteger(o)||o<1||o>t.length+1)throw new l(`history-compact --before version must be between 1 and ${t.length+1}.`,d.USAGE);let i=Math.max(0,Math.min(t.length,o-1));return{kind:"version",raw:n,compactCount:i,retainedCount:t.length-i}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let s=0;for(let[o,i]of t.entries()){let a=Date.parse(i.ts);if(!Number.isFinite(a))throw new l(`History for this item contains invalid timestamp at entry ${o+1}.`,d.GENERIC_FAILURE);if(a>=r)break;s+=1}return{kind:"timestamp",raw:n,compactCount:s,retainedCount:t.length-s}}function QI(e,t){let n=As(),r=As();for(let s=0;s<e.length;s+=1){let o=e[s];if(Ne(n)!==o.before_hash)throw new l(`history-compact detected before-hash drift at entry ${s+1}; run pm history-repair first.`,d.CONFLICT);if(n=xs(n,o.patch,s+1,o.op),Ne(n)!==o.after_hash)throw new l(`history-compact detected after-hash drift at entry ${s+1}; run pm history-repair first.`,d.CONFLICT);s+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function ZI(e,t,n){let r=structuredClone(t),s=[];for(let[o,i]of e.entries()){let a=Ne(r);r=xs(r,i.patch,n+o+1,i.op),s.push({...i,before_hash:a,after_hash:Ne(r)})}return{entries:s,finalReplay:r}}async function ex(e,t,n){let r=e.located?await K(e.located,{schema:t.schema}):null;return r?{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:Ne(Bt(r.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function tx(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function nx(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function rx(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=QI(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),s=ZI(r,t,e.boundary.compactCount),i=[qe({nowIso:S(),author:e.author,op:"history_compact_baseline",before:zt(As()),after:zt(t),message:nx(e.boundary)}),...s.entries];return e.dryRun||i.push(qe({nowIso:S(),author:e.author,op:"history_compact",before:zt(n),after:zt(n),message:tx(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function sx(e){return Ps({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-compact",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Os({historyPath:e.historyPath,nextHistoryRaw:st(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function Zc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await Ns(r,e,s,o.type_to_folder),a=i.historyPath,c=await q(a);if(c===null)throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let m=await Et(a,i.id);if(m.length===0)throw new l(`No history entries exist for ${i.id}; nothing to compact.`,d.USAGE);let u=bn(m);if(!u.ok)throw new l(`history-compact requires a valid history chain (${u.errors.join(", ")}). Run pm history-repair ${i.id} first.`,d.CONFLICT);let p=XI(t.before,m),f=p.compactCount>0,_=!!t.dryRun,h=R(t.author,s.author_default),y=[];f||y.push("history_compact_noop_before_boundary");let g=await ex(i,s,m);g.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:E}=rx({historyEntries:m,boundary:p,changed:f,dryRun:_,author:h,options:t}),N=bn(b);if(!N.ok)throw new l(`history-compact produced an invalid rewritten chain (${N.errors.join(", ")}).`,d.GENERIC_FAILURE);f&&!_&&y.push(...await sx({pmRoot:r,subject:i,settings:s,typeRegistry:o,historyRawBeforeLock:c,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:h,force:t.force,loadedItem:g.loadedItem,historyPath:a,rewrittenEntries:b}));let O=p.retainedCount>0?p.compactCount+1:null;return{id:i.id,dry_run:_,changed:f,compact_boundary:{kind:p.kind,before:p.raw,entries_compacted:p.compactCount,entries_retained:p.retainedCount,first_retained_entry:O},history:{path:a,entries_scanned:m.length,entries_after:b.length,baseline_entry_added:v,audit_entry_added:E,verify_ok:N.ok,verify_errors:N.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:g.matchedChainBefore},warnings:[...new Set(y)].sort((j,$)=>j.localeCompare($)),generated_at:S()}}var ox=3;function _g(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function ix(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function ax(e){let t=M(e.settings.schema),n=Zs(t),r=await oe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),s=new Map(r.map(m=>[m.id,n.classify(m.status)])),o=fg.join(e.pmRoot,"history"),i=[],a=[];if(!await k(o))return{candidates:i,preselectionErrors:a};let c=(await pg.readdir(o)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=fg.join(o,m),p=m.slice(0,-6);try{let f=await pg.readFile(u,"utf8");await _n({path:u,scope:"project"}),i.push({id:p,entries:ix(f),bucket:s.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:i,preselectionErrors:a}}async function cx(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await Zc(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function hg(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=x(r,I()),{candidates:o,preselectionErrors:i}=await ax({pmRoot:n,settings:r,typeToFolder:s.type_to_folder}),a=e.ids!==void 0&&e.ids.length>0?"ids":"scan",c=e.minEntries??ox,m=r.history.compact_policy,u=a==="scan"&&e.allOver===void 0&&m.enabled,p=e.allOver??(u?m.max_entries:void 0),f=ug(o,{ids:e.ids,scope:e.scope,minEntries:c,allOver:p}),_=!!e.dryRun,h=[...i],y={streams_considered:o.length+i.length,selected:0,items_compacted:0,items_skipped:0,items_errored:i.length};for(let g of f){let b=await cx({row:g,options:e,dryRun:_,global:t});if(h.push(b.result),!b.selected){y.items_skipped+=1;continue}y.selected+=1,b.compacted&&(y.items_compacted+=1),b.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:_,mode:a,scope:e.scope??null,criteria:{min_entries:c,all_over:p??null,policy_threshold_applied:u},totals:y,results:h,generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f762b5e6-8224-531f-9dd1-f71dc18c3ddf")}catch{}})();function gg(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return Eh(n,t),t?Ho(e.options,e.global):hr(n,e.options,e.global)}function yg(e){let t=e.options.ids,n=Array.isArray(t)?t.map(String).filter(m=>m.trim().length>0):typeof t=="string"?t.split(",").map(m=>m.trim()).filter(Boolean):void 0,r=Fe(e.options.allOver??e.options.all_over,"history-compact allOver"),s=Fe(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),o=w(e.options,"scope"),i=[];e.options.closed===!0&&i.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&i.push("all-streams"),(o==="closed"||o==="all-streams")&&i.push(o);let a=[...new Set(i)];if(a.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let c=a[0];return _g(e.id,{ids:n,allOver:r,scope:c}),e.id!==void 0?Zc(e.id,{before:w(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global):hg({ids:n,scope:c,allOver:r,minEntries:s,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function Qo(e){return _s("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08dcee99-5572-5133-b76a-6a50e4e292e7")}catch{}})();async function ed(e,t,n,r){let s=t.trim();if(s.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",d.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let o=T(process.cwd(),r.path),i=M((await A(o)).schema),a=i.open_status,c=Qo(i),m=n.status??a,u=W(m,i)??m;if(u!==a&&u!==c)throw new l(`Reopen target status must be ${a} or ${c}; received ${m}.`,d.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([a,c])],suggested_retry:`pm item reopen ${e} "${s}" --status ${a}`,suggested_retry_args:["item","reopen",e,s,"--status",a]}});let p=await l_(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,s);return{item:p.item,changed_fields:p.changed_fields,warnings:p.warnings,recurrence:p.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="55869854-565d-52d2-8dca-b66aade074bb")}catch{}})();function bg(e,t){let n=e.id??w(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function wg(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function vg(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await it(bg(e,r),wg(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function kg(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await ed(bg(e,r),wg(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2ef0de1-bc44-5550-862c-f3929334fbef")}catch{}})();function Sg(e,t,n){let r;if(typeof e.lines=="string")r=Ys(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");r=Ys(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="90896fb6-ee3e-575d-b103-bbc1a83c6672")}catch{}})();var dx=Bi("list").properties.outputSession,lx={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...dx},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Eg={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},ee={type:"string",description:"pm item id, for example pm-abc1."},mx=`Operation name (one of): ${ji.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,ux={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},px={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function U(e,t=[]){return{...Eg,properties:{...Eg.properties,...e},required:t}}var fx=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:U({action:{type:"string",enum:[...ji],description:mx},id:ee,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...lx},["action"])},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:U({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:U({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid, options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:U({query:{type:"string"},options:{type:"object"},...px},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:U({options:{type:"object"},...ux})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:U({id:ee,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:U({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:U({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:ee,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:ee,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:U({id:ee,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:U({id:ee,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:ee,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:U({id:ee,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:U({id:ee,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:ee,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:U({id:ee,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:U({id:ee,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:U({id:ee,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List or add structured notes on a pm item. Use options.add to append a note; omit it to list existing notes.",inputSchema:U({id:ee,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List or add learnings on a pm item. Use options.add to capture a learning/insight; omit it to list existing learnings.",inputSchema:U({id:ee,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:U({id:ee,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:U({subcommand:{type:"string",enum:[...Fm]},id:ee,target:ee,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:U({id:ee,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:U({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:U({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:U({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Schema mutations write workspace config files, not item history.",inputSchema:U({subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset"],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or custom field key (show-field/add-field/remove-field). Required for those subcommands."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...Ei]},description:`Lifecycle roles for add-status: ${Ei.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys."}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:U({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:U({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:U({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],_x={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},hx=fx.map(e=>{let t=_x[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Bi(t,{properties:n,required:r})}});function Tg(){return hx.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,s)=>r.localeCompare(s)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b07d8f62-6c75-52fd-9956-52cec211303c")}catch{}})();var Ag=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),gx=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],$g=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ei=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),vr=new Set(["cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),Mg=new Map([["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),Dg=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),Ug=new Map([...Dg.entries()].flatMap(([e,t])=>mt(t).map(n=>[n,e]))),Gg=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],jg=new Map(Gg.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),yx=10,bx=20,Cg=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate work through typed operations."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage portable workspace primitives."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),qg=[["init",Tl],["install",Cl],["uninstall",Rl],["explore",Il],["manage",Fl],["describe",xl],["reload",$l],["doctor",Ml],["catalog",Dl],["adopt",Ul],["adopt-all",Ol],["activate",Pl],["deactivate",Nl],["migrate",Ll]],wx=qg.map(([e,t])=>e==="init"?[e,Al]:[e,t]),vx=[...qg.map(([e,t])=>[`extension ${e}`,t]),...wx.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Br],["config",El],["extension",Hr],["package",Bn],["packages",Bn],["install",Gl],["create",Qr],["item mutate",im],["item complete",am],["item reopen",cm],["copy",Zr],["focus",es],["update",ts],["update-many",ns],["upgrade",jl],["calendar",Hn],["cal",Hn],["context",Vn],["ctx",Vn],["get",ss],["search",ds],["eval",lm],["workspace",vt],["workspace snapshot",vt],["workspace snapshot create",vt],["workspace snapshot list",vt],["workspace snapshot inspect",vt],["workspace snapshot restore",vt],["workspace snapshot delete",vt],["next",cs],["aggregate",jr],["deps",is],["graph",as],["guide",os],["reindex",ql],["history",qr],["history-compact",vl],["history-redact",bl],["history-repair",wl],["history-author-acknowledge",Kr],["merge",yl],["schema",kl],["profile",Sl],["plan",zr],["restore",Bl],["delete",Hl],["close",Kl],["close-many",Vr],["append",Wr],["claim",zl],["release",Vl],["start-task",Wl],["pause-task",Yl],["close-task",Jl],["comments",pl],["notes",fl],["learnings",_l],["files",hl],["docs",gl],["test",Zl],["test-all",em],["telemetry",tm],["test-runs",nm],["gc",rm],["stats",Yr],["duplicates",Jr],["validate",sm],["health",Xr],["assurance",om],...mm,["contracts",ls],["completion",ms],["activity",rs],...[...$g].map(e=>[e,Gr])],sd=new Map(vx);function kx(e){let t=Ug.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Rg(e){return Ui.includes(e)?fe(e):e.startsWith("extension-")?fe(`extension ${e.slice(10)}`):e.startsWith("package-")?fe(`package ${e.slice(8)}`):e.startsWith("item-")?fe(`item ${e.slice(5)}`):e.startsWith("test-runs-")?fe(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?fe(`templates ${e.slice(10)}`):ei.has(e)?Dg.get(e)??fe(e):null}function Sx(e,t){return e.command_path===null?!1:mt(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `)||t.startsWith(`${n} `))}function mt(e){return e.split("|").map(t=>fe(t)).filter(t=>t.length>0)}function Ex(e,t){let n=new Set(t),r=new Set;for(let s of e)if(s.command_path)for(let o of mt(s.command_path)){let i=o.split(" ").filter(a=>a.length>0);if(i.length!==0)for(let a=i.length;a>0;a-=1){let c=i.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((s,o)=>s.localeCompare(o))}function Zo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function kr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function Tx(e,t){if(!t)return{...e};let r=kr(e).filter(s=>{let o=s.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:r}}function td(e,t){let r=kr(e).filter(s=>{let o=s.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function fe(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Kg(e){return e.replace(/\s+/g,"-")}function Je(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ig(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=Je(r);!s||n.has(s)||(n.add(s),t.push(s))}return t}function nd(e,t,n){n&&(e[t]=!0)}function xg(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function Ax(e){let t=xg(e.long,"long"),n=xg(e.short,"short"),r=t??n;if(!r)return null;let s={flag:r};n&&t&&(s.short=n),nd(s,"required",e.required===!0),nd(s,"repeatable",e.repeatable===!0),nd(s,"list",e.list===!0);let o=Je(e.description);o&&(s.description=o);let i=Je(e.value_name);i&&(s.value_name=i);let a=[Je(e.value_type),Je(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(s.value_type=a),s}function zg(e){let t=new Map;for(let r of e){let s=fe(r.target_command);if(s.length===0)continue;let o=t.get(s)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;o.sourceDedupe.has(i)||(o.sourceDedupe.add(i),o.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=Ax(a);if(!c)continue;let m=`${c.flag}|${c.short??""}`;o.dedupe.has(m)||(o.dedupe.add(m),o.flags.push(c))}t.set(s,o)}let n=new Map;for(let[r,s]of t.entries())n.set(r,{flags:s.flags,sources:s.sources.sort((o,i)=>{let a=o.layer.localeCompare(i.layer);return a!==0?a:(o.name??"").localeCompare(i.name??"")})});return n}function Cx(e){let t=zg(e.flagRegistrations),n=new Map;for(let o of e.commandDefinitions){let i=fe(o.command);if(i.length===0)continue;let a=Je(o.action)??Kg(i),c=Array.isArray(o.arguments)?o.arguments.map(m=>{let u=Je(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:Je(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{command:i,action:a,source:{layer:o.layer,name:o.name},description:Je(o.description),intent:Je(o.intent),arguments:c,flags:t.get(i)?.flags??[],examples:Ig(o.examples),failure_hints:Ig(o.failure_hints)})}let r=new Set;for(let o of e.handlers)r.add(fe(o));for(let o of n.keys())r.add(o);for(let o of t.keys())r.add(o);let s=[];for(let o of[...r].sort((i,a)=>i.localeCompare(a))){let i=n.get(o);s.push(Rx(o,i,t.get(o)?.flags??[]))}return s}function Rx(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Kg(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function Ix(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(s,o)=>o.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function xx(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function Ox(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",s=e.repeatable===!0||e.list===!0;return{type:s?"array":r,...s?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function Px(e){let t=e.command.split("|").map(s=>s.trim()).filter(s=>s.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let s of e.arguments)n[s.name]=xx(s,e.action),s.required&&r.push(s.name);for(let s of e.flags){let o=Ix(s);!o||n[o]!==void 0||(n[o]=Ox(s,e.action),s.required===!0&&r.push(o))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function Nx(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function Lx(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((o,i)=>o.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let s=new Set(r.flags.map(o=>`${o.flag}|${o.short??""}`));for(let o of n.flags){let i=`${o.flag}|${o.short??""}`;if(!s.has(i))s.add(i),r.flags.push(o);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);a&&Nx(a,o)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function Fx(e,t=A){let n={mode:yt.extensions.policy.mode,trust_mode:yt.extensions.policy.trust_mode,default_sandbox_profile:yt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=T(process.cwd(),e.path);if(!await k(C(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let s=await t(r),o=await Mr({pmRoot:r,settings:s,cwd:process.cwd(),noExtensions:!1}),i=await Dr({...o,loaded:o.loaded});return{handlers:new Set(i.commands.handlers.map(c=>fe(c.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:o.policy.mode,trust_mode:o.policy.trust_mode,default_sandbox_profile:o.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function $x(e,t={}){let n=new Map;for(let r of Gi){let s=ei.has(r);if(s&&!t.includePackageOwnedActions)continue;let o=Rg(r);n.set(r,{action:r,provider:s?"extension":"core",requires_extension:s,command_path:o})}if(t.includePackageOwnedActions)for(let r of ei)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Rg(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:fe(r.command)});return[...n.values()].sort((r,s)=>(r.action??"").localeCompare(s.action??""))}function Mx(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null};let n=e.command_path?mt(e.command_path):[],r=n.some(i=>t.handlers.has(i)),s=n.map(i=>Mg.get(i)).find(i=>typeof i=="string"),o=t.disabledReason===null&&r;return{action:e.action,invocable:o,available:o,requires_extension:!0,provider:"extension",disabled_reason:o?null:t.disabledReason??(s?`optional_package_not_installed:${s}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function Bg(e){return sd.get(e)??Ur}function Dx(e){return vr.has(e)?!1:sd.has(e)}function Ux(e){return $g.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Og(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function Gx(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function jx(e){let t=new Map;for(let r of e.definitions){let s=Og(r.cli_flag);if(!s)continue;let o=r.cli_aliases.map(a=>Gx(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>Og(a)).filter(a=>a!==null&&a!==s);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=o?{flag:s,short:o}:{flag:s},u=`${m.flag}|${m.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(m));for(let p of i){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,s]of t.entries())n.set(r,$i(s.flags));return n}function Pg(e,t){let n=[],r=new Set;for(let s of[...e,...t]){let o=`${s.flag}|${s.short??""}`;r.has(o)||(r.add(o),n.push(s))}return $i(n)}function qx(e,t,n,r){return e.map(s=>{let o=Dx(s),i=o?Bg(s):[],a=n.get(Ux(s))??[],c=t.get(s),m=Pg(i,a),u=Pg(m,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":o?"core":"extension";return{command:s,flags:u,...r?{canonical_command:rd(s),visibility:Zm(rd(s)),positionals:ll(s)?.slots??[],flag_invocations:Qm(s,u)}:{},provider:p,extension_sources:c?.sources}}).sort((s,o)=>s.command.localeCompare(o.command))}function Kx(e,t=Wn){let n=new Set(e),r=new Map;for(let s of Gg){let o=s.aliases.filter(i=>n.has(i));r.set(s.canonical,{canonical:s.canonical,aliases:o,contracts:[]})}for(let s of t){if(!n.has(s.canonical)||s.registration==="commander"&&!n.has(s.alias))continue;let o=r.get(s.canonical)??{canonical:s.canonical,aliases:[],contracts:[]};o.aliases.includes(s.alias)||o.aliases.push(s.alias),o.contracts.push(s),r.set(s.canonical,o)}return[...r.values()].map(({contracts:s,...o})=>s.length===0?o:{...o,contracts:s}).sort((s,o)=>s.canonical.localeCompare(o.canonical))}function zx(){return{create_string_options:Km,create_repeatable_options:ys,update_string_options:zm,update_repeatable_options:Bm,list_string_options:ol,search_string_options:il,calendar_string_options:al,context_string_options:cl,activity_string_options:dl}}function Ng(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=mn(e,"create",n),s=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),o=[...new Set(s.map(a=>he("create",a)))].sort((a,c)=>a.localeCompare(c)),i=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:s,required_flags:o,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function Bx(e){let t={},n={};for(let r of[...e.types].sort((s,o)=>s.localeCompare(o))){let s=e.by_type[r];t[r]=Ng(s,"strict"),n[r]=Ng(s,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Hx(e,t){let n=kr(e);if(n.length===0)return e;let r=!1,s=n.map(o=>{let i=o.properties;if(typeof i!="object"||i===null)return o;let a=i.action;return typeof a!="object"||a===null||a.const!=="create"?o:(r=!0,{...o,"x-create-required-options":t})});return r?{...e,oneOf:s}:e}function Vx(e){let t=Zo(e.action)!==void 0||Zo(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,s=e.schemaOnly===!0,o=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=Zo(e.action),u=Zo(e.command),p=!r&&!c&&!s&&!o&&!i&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:s,flagsOnly:o,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function Wx(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",d.USAGE)}async function Yx(e,t=A){try{return await t(e)}catch{return structuredClone(yt)}}async function Jx(e,t){let n=await Yx(t),r=await Fx(e),s=x(n,r.registrations??I()),o=Ve(n.schema),i=Cx(r);return{settings:n,runtimeProbe:r,typeRegistry:s,statusRegistry:M(n.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:jx(o),createRequiredOptionContracts:Bx(s),extensionContracts:i,mergedExtensionContracts:Lx(i),extensionFlagMap:zg(r.flagRegistrations)}}function Lg(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ei.has(e.selectedAction)||e.selectedCommand!==void 0&&vr.has(e.selectedCommand))}function Xx(e,t){let n=$x(t,{includePackageOwnedActions:Lg(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Mm);return n.filter(s=>!r.has(s.action))}return Lg(e)&&e.selectedCommand!==void 0&&vr.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:kx(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function Qx(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new l(`Unknown action: "${e.selectedAction}".`,d.USAGE)}function Zx(e,t){return[...new Set([...Ui.filter(n=>!vr.has(n)),...[...sd.keys()].filter(n=>!vr.has(n)),...e.flatMap(n=>n.command_path?mt(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>fe(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function eO(e,t){let n=t.slice(0,yx),r=t.length-n.length,s=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),o=t.slice(0,bx),i=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new l(`Command "${e}" is a command namespace. Choose a concrete child command: ${s}.`,d.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:i,nextSteps:[`Retry with a child command, for example: ${i[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:o.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function tO(e,t){return new l(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,d.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function nO(e){return new l(`Unknown command: "${e}".`,d.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function rO(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(o=>o.startsWith(`${e.selectedCommand} `));if(r.length>0)throw eO(e.selectedCommand,r);let s=Mg.get(e.selectedCommand);throw s?tO(e.selectedCommand,s):nO(e.selectedCommand)}function sO(e,t){let n=Xx(e,t.mergedExtensionContracts);Qx(e,n);let r=Zx(n,t.mergedExtensionContracts);rO(e,r);let s=e.selectedCommand?Ug.get(e.selectedCommand):void 0,o=e.selectedCommand?n.filter(m=>s?m.action===s:Sx(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!o.some(m=>m.action===e.selectedAction))throw new l(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,d.USAGE);let i=e.selectedAction?o.filter(m=>m.action===e.selectedAction):o,a=[...new Map(i.map(m=>Mx(m,t.runtimeProbe)).map(m=>[s?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(m=>m.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:o,scopedActionDescriptors:i,selectedPackageOwnedAction:s,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function oO(e){return new Set(kr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let s=r.const;return typeof s=="string"?s:null}).filter(t=>t!==null))}function iO(e){let t=Gm,n=kr(t),r=oO(t),s=e.filter(o=>!r.has(o.action)).map(o=>Px(o));return s.length>0?{...t,oneOf:[...n,...s]}:t}function Fg(e,t,n){let r=new Set(t.actionDescriptors.map(o=>o.action)),s=e.selectedAction?Tx(n,e.selectedAction):e.selectedCommand?td(n,new Set(t.scopedActionDescriptors.map(o=>o.action))):td(n,r);return e.runtimeOnly&&!e.selectedAction?td(s,new Set(t.actions)):s}function aO(e,t,n){let r=iO(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?Hx(Fg(e,n,r),t.createRequiredOptionContracts):Fg(e,n,r);return{mergedSchema:r,filteredSchema:o}}function cO(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?Ex(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function dO(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Wn.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function rd(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":jg.get(t)??t}var lO=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"]]),mO=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function uO(e,t){let n=Cg.get(e)??(e.includes(" ")?void 0:Cg.get(rd(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>mt(m.command).includes(e));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let s=e.split(" "),o=s.at(-1),i=s.slice(0,-1).join(" "),a=lO.get(o),c=mO.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function pO(e,t=[],n={}){let r=n.includeFormatBudgets??!0,s=n.includeIntentProvenance??!0;return[...new Set(e.map(fe))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i)).map(o=>{let i=qi(o,{generateFallback:!0}),a=o.split(" ")[0],c=jg.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),m=new Set([...Bg(o).map(f=>f.flag),...t.filter(f=>mt(f.command).includes(o)).flatMap(f=>f.flags.map(_=>_.flag))]),u=(Ag.get(o)??Ag.get(c)??gx).filter(f=>m.has(f)),p=uO(o,t);return{command:o,intent:p.intent,...s||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:i.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...i.default_max_estimated_tokens_by_format}}:{}}})}function fO(e){return e.map(t=>({budget:qi(t,{generateFallback:!0}),envelope:tu(t)}))}function _O(e){let t=new Map;for(let n of e){let r=Vm(n),s=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,o=s.join(","),i=t.get(o)??{commands:[],exit_codes:s};i.commands.push(n),t.set(o,i)}return[...t.values()]}function hO(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>mt(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(s=>mt(s.command).some(o=>r.has(o)))}return t.extensionContracts}function gO(e,t,n,r){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function yO(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(s=>s.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([s])=>r===void 0||s===r).map(([s,o])=>[s,[...new Set(o.map(i=>`--${i.cli_flag}`))].sort((i,a)=>i.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Im],services:[...xm],policy_modes:[...Om],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Lm],trust_modes:[...Pm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Nm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Md],create_modes:[...Dd],close_validation_modes:[...Ud],workflow_enforcement_modes:[...Gd]},e.relationship_kind_contracts=[...Vd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(s=>s.definitions)].sort((s,o)=>s.kind.localeCompare(o.kind)).map(s=>({canonical:s.kind,aliases:[...s.aliases??[]],...s.inverse===void 0?{}:{inverse:s.inverse},ordering:s.ordering,hierarchy:s.hierarchy})))}function bO(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function wO(e,t,n,r,s){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=qx(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let o=new Set(r);e.list_projections=Object.entries(su).filter(([i])=>o.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...ru],compact_fields:[...nu]}))}e.command_aliases=s}}function vO(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=zx();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function kO(e,t,n,r){e.command_summaries=pO(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Dm],allows_unbounded_opt_out:!0},e.grammar_contracts={nouns:jt.nouns,shared_verbs:jt.shared_verbs,scope_before_verb:jt.scope_before_verb,visible_top_level_ceiling:jt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:jt.ceiling_raise_requires_pm_item,positional_shape_budget:jt.positional_shape_budget,positional_shape_count:new Set(Fi.map(({slots:s})=>ul(s))).size,positional_action_count:Li.length,positional_action_parents:[...new Set(Li.map(({parent:s})=>s))].sort((s,o)=>s.localeCompare(o)),...r.includePositionalSignatures?{positional_signatures:Fi}:{}}}async function Hg(e,t){let n=Vx(e);Wx(n);let r=T(process.cwd(),t.path),s=await Jx(t,r),o=sO(n,s),i=aO(n,s,o),a=cO(n,o),c=dO(n,a),m=gO(n,i,o,c),u=hO(n,s,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&kO(m,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p}),n.summary)return m;let f=Kx(o.commandCatalog);return n.flagsOnly&&!n.fullOutput||yO(m,s,n),bO(m,n,i,u),wO(m,n,s,c,f),vO(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...Zu],gate_triggers:[...Qu]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=ml),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=Tg(),m.context_intents=Wm(),m.read_output_dimensions=Ki,m.error_codes=Xm,m.command_output_contracts=fO(c),m.command_exit_contracts={vocabulary:Hm,command_sets:_O(c)}),m}import oP from"node:fs/promises";import ly from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed44fc89-8b6e-5c83-a4f4-ced4e9031dac")}catch{}})();function ti(e,t,n,r,s,o="min"){let i=s==="min"?e-t:t-e,a=o==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&a<0}function SO(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,s=null,o=null,i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let u;try{u=JSON.parse(m)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(ti(f,i,p,s,"min")&&(i=f,s=p),ti(f,a,p,o,"max","max")&&(a=f,o=p))}return{id:e,bytes:n,lines:r,oldest_ts:s,newest_ts:o}}function Vg(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),s=e.map(({id:_,raw:h})=>SO(_,h)),o=0,i=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of s){if(o+=_.lines,i+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);ti(h,m,_.id,a?.id??null,"min")&&(m=h,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);ti(h,u,_.id,c?.id??null,"max")&&(u=h,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...s].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...s].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:o,total_bytes:i,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as TO}from"node:crypto";import{execFile as AO}from"node:child_process";import Jg from"node:path";import{promisify as CO}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="939d5f93-d287-5c1c-bc78-d013f76735f2")}catch{}})();var Wg=1;function EO(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function od(e){if(e===null)return{format_version:Wg,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Wg||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!EO(r))throw new l("Improvement ledger contains an invalid observation.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aaa927b3-4bc4-561f-aff1-85dc95c12ea1")}catch{}})();var RO=CO(AO),IO=50,Yg=1e3,xO=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Xg(e){let t=e.trim().toLowerCase();if(!xO.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function OO(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function Sr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return n}}function PO(e){let t=e??IO;if(!Number.isSafeInteger(t)||t<0||t>Yg)throw new l(`Improvement observation limit must be an integer from 0 to ${Yg}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Qg(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function NO(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});let r=Xg(n.metric),s=OO(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||s==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let o=await FO(e,n.revision),i=Sr(n.source,"source"),a=Sr(n.itemId,"itemId"),c=Sr(n.unit,"unit"),m=Sr(n.idempotencyKey,"idempotencyKey")??(o.revision_source==="unversioned"?void 0:[o.revision,r,i??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:s,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Qg(n.observedAt??S(),"observedAt"),...o,author:R(n.author,t.author_default),...a===void 0?{}:{item_id:a},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:TO("sha256").update(J(u)).digest("hex").slice(0,24),...u}}function LO(e,t){let n=t.idempotency_key?e.observations.find(s=>s.idempotency_key===t.idempotency_key):e.observations.find(s=>s.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(s=>s.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function FO(e,t){let n=Sr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await RO("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Bd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function $O(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,s=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:s,sample_count:e.length}}async function Zg(e,t={}){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await NO(n,r,e),o=Jg.join(n,"improvement-ledger.json"),i=await Tu({pmRoot:n,filePath:o,op:"improvement_observe",author:s.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${s.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=od(a),m=LO(c,s);return m?{raw:a,result:m}:(c.observations.push(s),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${J(c)}
47
- `,result:s})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function ey(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=e.metric===void 0?void 0:Xg(e.metric),r=e.since===void 0?void 0:Qg(e.since,"since"),s=PO(e.limit),i=od(await q(Jg.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of i){let m=a.get(c.metric)??[];m.push(c),a.set(c.metric,m)}return{observations:[...i].reverse().slice(0,s),total:i.length,truncated:i.length>s,trends:[...a].map(([,c])=>$O(c)).sort((c,m)=>c.metric.localeCompare(m.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6162845d-f4b4-5d1f-a210-ddef1a5c38f6")}catch{}})();function ty(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function MO(e,t,n){let r=t,s=new Set([e.id]);for(;r!==void 0&&!s.has(r.id);)s.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function DO(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,s)=>r.entries[0].ts.localeCompare(s.entries[0].ts)||r.id.localeCompare(s.id)),t.push(...n.map(r=>r.children))}}function id(e=Yn,t=hn){return t.map(n=>{let r=e.filter(s=>((n==="model"?s.model_environment_keys:s.provenance_environment_keys?.[n])?.length??0)>0||s.provenance_resolvers?.[n]!==void 0).map(s=>s.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function UO(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let s=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?s.observed+=1:r.agent_provenance?.model===null?s.unavailable+=1:s.legacy_missing+=1,n.set(r.agent_harness,s)}return[...n.values()].map(r=>{let s=r.observed+r.unavailable;return{...r,coverage:s===0?null:r.observed/s,inert:s>=t&&r.observed===0}}).sort((r,s)=>r.harness.localeCompare(s.harness))}function ad(e,t=hn,n=1){let r=new Map;for(let s of e)if(s.agent_harness)for(let o of t){let i=`${s.agent_harness}\0${o}`,a=r.get(i)??{harness:s.agent_harness,dimension:o,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=s.agent_provenance?.[o];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(i,a)}return[...r.values()].map(s=>{let o=s.observed+s.unavailable;return{...s,coverage:o===0?null:s.observed/o,inert:o>=n&&s.observed===0}}).sort((s,o)=>s.harness.localeCompare(o.harness)||s.dimension.localeCompare(o.dimension))}function GO(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let s=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let u=`${c.agent_harness}\0${m}`,p=s.get(u)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),s.set(u,p)}let o=[...s.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[u])=>m.localeCompare(u)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),i=o.filter(c=>c.entries>=r),a=i.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:i.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:o,failures:a}}function jO(e){let t=[...e].sort((o,i)=>o.ts.localeCompare(i.ts)||o.author.localeCompare(i.author)||o.op.localeCompare(i.op)||o.before_hash.localeCompare(i.before_hash)||o.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let o of t){let i=o.agent_episode,a=ty(o),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(o);continue}let u={id:a.id,...i?.label===void 0?{}:{label:i.label},...i?.parent_id===void 0?{}:{parent_id:i.parent_id},source:a.source,entries:[o],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let s=[];for(let o of n.values()){let i=o.parent_id?r.get(o.parent_id):void 0;i&&MO(o,i,r)?i.children.push(o):s.push(o)}return DO(s),s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var qO=1e4,ny=1e5,KO=1e3,zO=30,BO=["append","comment","docs","file","learning","note","test_run"];function HO(e){let t=e??qO;if(!Number.isSafeInteger(t)||t<1||t>ny)throw new l(`History analytics event limit must be an integer from 1 to ${ny}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function ry(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",d.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function VO(e){let t=e?.trim();if(!t)return new Date(Date.now()-zO*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let s=Number(n[1]),o=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(s)||s<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-s*o).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function sy(e,t){let n=HO(t.eventLimit),r=VO(t.since),s=[],o=r,i=!1;for(;s.length<n;){let a=await Vo({pmRoot:e,since:o,limit:Math.min(KO,n-s.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(s.push(...c),i=a.has_more,o=a.next_cursor,!a.has_more)break}return{events:s,receipt:{since:r,events:s.length,truncated:i,...i?{next_cursor:o}:{},source:"history_event_index"}}}function WO(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function YO(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function JO(e){return BO.some(t=>e.startsWith(t))}function oy(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function XO(e,t,n){let r=new Map,s=new Map,o=new Map;for(let i of t){let a=WO(i.entry,e),c=YO(i.entry),m=s.get(i.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&s.set(i.item_id,u),!a)continue;let p=oy(r,a);p.events+=1,JO(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,o.set(i.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:o}}function QO(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let s=new Set((r.dependencies??[]).filter(o=>o.kind==="discovered_from").map(o=>o.id));for(let o of s){let i=t.get(o);i&&(oy(e,i).defectEscapes+=1)}}}function ZO(e,t,n,r){let s=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:s==="available"?t.closes/r:null,rework_rate:s==="available"?t.reopens/t.closes:null,defect_escape_rate:s==="available"?t.defectEscapes/t.closes:null,sample_status:s}}function eP(e,t,n,r,s,o){let{buckets:i,lastCloseValue:a}=XO(e,t,r);return QO(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>ZO(c,m,s,o)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function tP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,s=Date.parse(n),o=Date.parse(r);return!Number.isFinite(s)||!Number.isFinite(o)?1:Math.max(1,(o-s)/864e5)}function nP(e,t,n){let r=id(t),s=ad(e,hn,n),o=s.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),i=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:s,inert:o,undeclared:i,warnings:[...o.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...i.map(a=>`provenance_dimension_undeclared:${a}`)]}}function iy(e,t=Yn,n={}){let r=ry(n.minimumSample);return{...nP(e.events.map(s=>s.entry),t,r),window:e.receipt}}function ay(e,t,n,r={}){let s=ry(r.minimumSample),o=tP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>eP(i,e.events,t,n,s,o)),minimum_sample:s,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var rP=32;function sP(e){let t=[];for(let n of e??[]){let r=[];for(let s of n.split(",")){let o=s.slice(0,s.indexOf("=")).trim();r.length>0&&o!=="unit"&&o!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(s)}t.push(r.join(","))}return t}function Er(e,t){let n=sP(e).map(s=>{let[o,...i]=s.split(","),a=o.indexOf("="),c=o.slice(0,a).trim(),m=o.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${s}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,f;for(let _ of i){let h=_.indexOf("="),y=_.slice(0,h).trim(),g=_.slice(h+1).trim();if(y==="unit"&&g.length>0)p=g;else if(y==="threshold"&&g.length>0&&Number.isFinite(Number(g)))f=Number(g);else throw new l(`Invalid --measure attribute "${_}"`,d.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(s=>[s.name,s])).values()].sort((s,o)=>s.name.localeCompare(o.name)).slice(0,rP)}function cy(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(s=>s.name===t&&s.value<n).map(s=>({...s,run_id:r.run_id})))}function dy(e,t){let n=e.flatMap(o=>o.measurements??[]).filter(o=>o.name===t).sort((o,i)=>i.recorded_at.localeCompare(o.recorded_at)),r=n[0],s=n[1];return{name:t,latest:r?.value??null,previous:s?.value??null,delta:r!==void 0&&s!==void 0?r.value-s.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d28c7ac7-9801-5b0c-84c9-51deede398be")}catch{}})();function iP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function aP(e,t,n,r,s){let o=rr(e,"type",r),i=new Set(o.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),m=(s?[...o.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:o.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=iP([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>s||f>0));return{byType:m,byStatus:p,omitted:s?0:a.length+Object.values(u).filter(f=>f===0).length}}function cP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function dP(e){let t=ly.join(e,"history");if(!await k(t))return[];await _n({path:t,scope:"project"});let n=(await oP.readdir(t)).filter(s=>s.endsWith(".jsonl")).sort((s,o)=>s.localeCompare(o)),r=[];for(let s of n){let o=ly.join(t,s),i=await q(o);i!==null&&(await _n({path:o,scope:"project"}),r.push({id:s.slice(0,-6),raw:i}))}return r}async function lP(e,t){let n=[],r=S();for(let s of Er(t.observe,r))n.push(await Zg({metric:s.name,value:s.value,direction:t.direction,unit:s.unit,threshold:s.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function mP(e,t,n){let r={};return t.byAssignee&&(r.assignee=rr(e,"assignee",n)),t.byTag&&(r.tag=rr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=rr(e,"priority",n)),r}async function uP(e,t,n,r,s){let o={since:s.since,eventLimit:s.eventLimit,minimumSample:s.minimumSample},i=s.provenanceCoverage||s.fleetAttribution?await sy(e,o):void 0;return{provenanceCoverage:s.provenanceCoverage&&i?iy(i,n.agent_identity?.harness_signals,o):void 0,fleetAttribution:s.fleetAttribution&&i?ay(i,t,r,o):void 0}}function pP(e,t,n,r,s){let o=Object.keys(s.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...s.metadataCoverage?{metadata_coverage:s.metadataCoverage}:{},...o?{breakdowns:s.breakdowns}:{},...s.storage?{storage:s.storage}:{},...s.fieldUtilization?{field_utilization:s.fieldUtilization}:{},...s.improvementLedger?{improvement_ledger:s.improvementLedger}:{},...s.recordedObservations.length>0?{recorded_observations:s.recordedObservations}:{},...s.provenanceCoverage?{provenance_coverage:s.provenanceCoverage}:{},...s.fleetAttribution?{fleet_attribution:s.fleetAttribution}:{},generated_at:S()}}async function cd(e,t={}){let n=T(process.cwd(),e.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await lP(e,t),o=x(r,I()),i=M(r.schema),a=t.fieldUtilization?await Rs(n,r.item_format,o.type_to_folder,void 0,r.schema):await oe(n,r.item_format,o.type_to_folder,void 0,r.schema);await Iu({pmRoot:n,settings:r,itemIds:a.map(E=>E.id),commandLabel:"stats"});let c=Zs(i),m=aP(a,o.types,i.definitions.map(E=>E.id),c,t.includeEmpty===!0),u=await dP(n),p=0;for(let E of u)p+=cP(E.raw);let f=t.storage?Vg(u):void 0,_=t.metadataCoverage?Zp(a,c):void 0,h=mP(a,t,c),y=t.fieldUtilization?ef(a):void 0,g=t.measurements===!0||s.length>0?await ey({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:b,fleetAttribution:v}=await uP(n,a,r,i.terminal_statuses,t);return pP({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:y,improvementLedger:g,recordedObservations:s,provenanceCoverage:b,fleetAttribution:v})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0e63298a-d2d7-5217-af50-a206348b4cd4")}catch{}})();function my(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:w(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ye(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:w(e,"measurementSource"),measurementItem:w(e,"measurementItem"),measurementRevision:w(e,"measurementRevision"),author:w(e,"author"),message:w(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:w(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import fP from"node:fs/promises";import Ft from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad3110ca-e85b-5a7e-b0a1-591796c298eb")}catch{}})();var hy=Ft.join("runtime","telemetry","events.jsonl"),gy=Ft.join("runtime","telemetry","state.json"),_P=Ft.join("runtime","telemetry"),hP=20,uy=["status","flush","stats","clear"],py=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},dd=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,fy=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},gP=e=>({command:dd(e.event.command,"<unknown>"),eventType:dd(e.event.event_type,"unknown"),eventSchemaVersion:fy(e.event.schema_version),clientSchemaVersion:fy(e.client_schema_version)}),yP=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),bP=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},wP=e=>{let t=e?.command_resolution;return dd(t,"")||void 0},yy=(e,t)=>{e[t]=(e[t]??0)+1},vP=(e,t)=>{let n=bP(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=wP(t);r!==void 0&&yy(e.resolution_counts,r)},kP=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,_y=(e,t)=>{t!==void 0&&e.add(t)},SP=(e,t)=>{let n=gP(t),r=e.get(n.command)??yP();r.count+=1,r.max_attempts=Math.max(r.max_attempts,kP(t.attempts)),yy(r.event_type_counts,n.eventType),_y(r.event_schema_versions,n.eventSchemaVersion),_y(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&vP(r,t.event.payload),e.set(n.command,r)},EP=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((o,i)=>o-i),s=Object.entries(t.resolution_counts).sort((o,i)=>o[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((o,i)=>o[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((o,i)=>o-i),client_schema_versions:[...t.client_schema_versions].sort((o,i)=>o-i),...r.length>0?{duration_p50_ms:py(r,.5),duration_p95_ms:py(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...s.length>0?{command_resolution_counts:Object.fromEntries(s)}:{}}},TP=e=>{let t=(e??"status").trim().toLowerCase();if(uy.includes(t))return t;throw Te({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:uy,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},ld=()=>{throw new l("--limit must be a positive integer",d.USAGE)},by=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?ld():e,AP=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?ld():by(Number.parseInt(t,10))},CP=e=>e===void 0?hP:typeof e=="number"?by(e):typeof e=="string"?AP(e):ld(),RP=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},IP=e=>{try{let t=JSON.parse(e);return RP(t)?t:void 0}catch{return}},xP=e=>e===null?[]:e.split(`
48
- `).map(t=>t.trim()).filter(t=>t.length>0),wy=e=>{let t=xP(e),n=[],r=0;for(let s of t){let o=IP(s);o===void 0?r+=1:n.push(o)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},OP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),PP=e=>{try{let t=JSON.parse(e);return OP(t)?t:{}}catch{return{}}},NP=async e=>{let t=await q(e);return t===null||t.trim().length===0?{}:PP(t)},ni=e=>e??null,ri=async e=>{let t=await A(e),n=Ft.join(e,hy),r=Ft.join(e,gy),s=await q(n),o=wy(s),i=await NP(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:o.rows_total,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_size_bytes:Buffer.byteLength(s??"","utf8"),last_attempted_flush_at:ni(i.last_attempted_flush_at),last_successful_flush_at:ni(i.last_successful_flush_at),last_failed_flush_at:ni(i.last_failed_flush_at),last_failed_flush_error:ni(i.last_failed_flush_error)}},LP=e=>{let t=new Map;for(let n of e)SP(t,n);return[...t.entries()].map(([n,r])=>EP(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},FP=async(e,t)=>({action:"telemetry",subcommand:"status",status:await ri(t.globalPmRoot),generated_at:S()}),$P=async(e,t)=>{let n=await ri(t.globalPmRoot);await Bu(t.globalPmRoot);let r=await ri(t.globalPmRoot),s=Math.max(0,n.queue_entries-r.queue_entries),o=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:s,queue_progressed:s>0,queue_empty:o,queue_drained:o,status:r,generated_at:S()}},MP=async(e,t)=>{let n=CP(e.limit),r=await q(t.queuePath),s=wy(r),o=LP(s.entries),i=o.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:o.length,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_rows_total:s.rows_total,truncated:o.length>i.length,stats:i,generated_at:S()}},DP=async(e,t)=>{let n=await A(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await Ee(t.globalPmRoot,n,"telemetry:clear");let s=Ft.join(t.globalPmRoot,_P),o=await k(s);return await fP.rm(s,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:o&&!await k(s),queue_exists_after:await k(t.queuePath),state_exists_after:await k(t.statePath),status:await ri(t.globalPmRoot),generated_at:S()}},UP={status:FP,flush:$P,stats:MP,clear:DP};async function vy(e,t){let n=TP(e.subcommand),r=et(process.cwd());return UP[n](e,{globalPmRoot:r,queuePath:Ft.join(r,hy),statePath:Ft.join(r,gy)})}import{spawn as Gy}from"node:child_process";import{cp as Ay,mkdir as zP,mkdtemp as jy,open as fd,readdir as _d,rm as qy}from"node:fs/promises";import{tmpdir as Ky}from"node:os";import me from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62af7c1e-c1c7-529e-ab30-117103ac4607")}catch{}})();var ky=20;function GP(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return ky;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?ky:t}function md(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,s)=>{let o=yn(r.recorded_at,s.recorded_at);if(o!==0)return o;let i=r.run_id.localeCompare(s.run_id);return i!==0?i:r.kind.localeCompare(s.kind)}),n=GP();return t.length>n?t.slice(t.length-n):t}async function si(e){await Z({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=md([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a6a3402-dae3-56f8-b9ba-a4f6f8a47cda")}catch{}})();var Sy=100;function ud(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,d.USAGE);return n}function jP(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Sy?n:`${n.slice(0,Sy-3)}...`}function Ey(e){return e.map((t,n)=>`${n+1}. ${jP(t)}`).join("; ")}function qP(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function KP(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Ty(e,t){let n=qP(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((s,o)=>o+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(s=>`--${s}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,d.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,d.USAGE);if(r==="match"){let s=t.match.trim().toLowerCase();if(s.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let o=[],i=[];for(let a=0;a<e.length;a+=1)KP(e[a],s)&&(i.push(e[a]),o.push(a+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Ey(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:o,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let s=ud(t.onlyIndex);if(s>e.length)throw new l(`--only-index ${s} is out of range: this item has ${e.length} linked test(s). Available entries: ${Ey(e)}`,d.USAGE);return{selector:"only-index",requested:String(s),selected:[e[s-1]],selected_indexes:[s],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4322c352-6b95-5796-94eb-5a68745d53bc")}catch{}})();var ii=20*1024*1024,BP=3e3,HP=1e4,VP=5e3,Cy=120,WP=new Set(["locks","extensions","runtime"]),YP=new Set(["history","index","search","extensions","locks","runtime"]),JP=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],XP=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,QP=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,ZP=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function yd(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function eN(){return yd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",BP)}function tN(){return yd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",HP)}function nN(){return yd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",VP)}function rN(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function sN(e){let t=0,n=0,r=0;for(let s of e){if(s.status==="passed"){t+=1;continue}if(s.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function bd(e){let t=0,n=0,r=0,s=0;for(let o of e){let i=o.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(r+=1),i.auto_pm_context_applied===!0&&(s+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:s}}function oN(e){let t=e??"project";if(!Ze.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function ai(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Xt.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${Xt.join(", ")}`,d.USAGE)}function zy(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:ai(e.pm_context_mode)}function By(e,t){return e==="auto"?t?"tracker":"schema":e}function iN(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function aN(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function cN(e,t){let n={};if(!e)return n;for(let r of e){let s=dr(r,t);if(s)for(let[o,i]of Object.entries(s))n[o]=i}return n}function dN(e,t){if(!e)return[];let n=[];for(let r of e){let s=lr(r,t);s&&n.push(...s)}return[...new Set(n)]}function lN(e){let t=ci(e);return tr(t).some(n=>ga(n)!==null)}function Hy(e){let t=ci(e);return tr(t).some(n=>{let r=ga(n);if(!r)return!1;let s=Jp(r);return s?ZP.has(s.subcommand):!1})}function oi(e){if(e)return Vp.has(e.subcommand)?Rn(e.args,Wp)?.subcommand:e.subcommand}function Ry(e,t){if(e==="npx"||e==="bunx")return Xs(t)?.command;if(e==="pnpm")return oi(Rn(t,Kp));if(e==="npm")return oi(Rn(t,zp));if(e==="yarn")return oi(Rn(t,Bp));if(e==="bun")return oi(Rn(t,Hp))}function Iy(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function pd(e){return!e||!ba(e.command)&&!Yp(e.command)?!1:Js(e.args)==="test-all"}var mN=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),uN=new Set(["npx","bunx"]);function Vy(e){let t=e.split(" ").filter(i=>i.length>0),n=ya(t);if(n.length===0)return!1;let[r,...s]=n,o=mN.get(r);if(o){let i=s.findIndex(a=>o.test(a));return i>=0?Vy(s.slice(i+1).join(" ")):!1}return ba(r)||wa(r)?Js(s)==="test-all":r==="node"&&s.length>0&&wa(s[0])?Js(s.slice(1))==="test-all":uN.has(r)?pd(Xs(s)):r==="pnpm"?pd(va(s)):r==="npm"?pd(ka(s)):!1}function Wy(e){let t=ci(e);return tr(t).some(n=>Vy(n))}function Yy(e){if(Wy(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function ci(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function pN(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function fN(e){let t=/\bpm_path\s*=/.test(e)||/\$env:pm_path\s*=/.test(e),n=/\bpm_global_path\s*=/.test(e)||/\$env:pm_global_path\s*=/.test(e);return t&&n}function _N(e){let t=e.split(" ").filter(o=>o.length>0),n=ya(t);if(n.length===0)return!1;let[r,...s]=n;return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?hN(s):gN(r,s)}function hN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function gN(e,t){return e==="npx"||e==="bunx"?Iy(Xs(t)?.command):e==="pnpm"||e==="npm"?Iy((e==="pnpm"?va(t):ka(t))?.command)||Ry(e,t)==="vitest":(e==="yarn"||e==="bun")&&Ry(e,t)==="vitest"}function Jy(e){let t=ci(e);if(tr(t).some(s=>!pN(s)&&_N(s)&&!fN(s)))throw new l('Linked test runner commands must be sandbox-safe: use "node scripts/run-tests.mjs <test|coverage>", use a package-manager script such as "pnpm test", or include PM_PATH=... PM_GLOBAL_PATH=... INLINE in the command string (exporting them in your shell environment is not checked). Example: "PM_PATH=/tmp/pm-x PM_GLOBAL_PATH=/tmp/pm-x-g vitest run".',d.USAGE)}function yN(e){if(Wy(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function bN(e){return e?e.map(wN):[]}function wN(e){let t=e.trim(),n=ko(t)?So(ne(e,"--add"),"--add"):{command:t},r=le(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return Yy(r),Jy(r),{command:r,path:le(n.path),scope:oN(n.scope),timeout_seconds:vN(le(n.timeout_seconds),le(n.timeout)),pm_context_mode:Ro(le(n.pm_context_mode),"--add"),env_set:dr(le(n.env_set),"--add"),env_clear:lr(le(n.env_clear),"--add"),shared_host_safe:Co(le(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Zt(le(n.assert_stdout_contains)),assert_stdout_regex:Nn(le(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Zt(le(n.assert_stderr_contains)),assert_stderr_regex:Nn(le(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Io(le(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:xo(le(n.assert_json_field_equals),"--add"),assert_json_field_gte:Oo(le(n.assert_json_field_gte),"--add"),note:le(n.note)}}function le(e){let t=e?.trim();return t&&t.length>0?t:void 0}function vN(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",d.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(ie(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function kN(e){return e?e.flatMap(t=>{let n=jf(t,"--add-json");for(let r of n){let s=r.command;if(!s)throw new l("--add-json requires a non-empty command string",d.USAGE);Yy(s),Jy(s)}return n}):[]}function SN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",d.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let s=n.slice(r[0].length).trim();if(!s)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:s}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let s=ne(n,"--remove"),o=s.path!==void 0?"path":"command",i=s.path??s.command;if(!i?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:o,value:i.trim()}}return{kind:"either",value:n}}):[]}function EN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function TN(e){try{e.stdin?.end()}catch{}}function Xy(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=Cy?t:`${t.slice(0,Cy-3)}...`}function Qy(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function hd(e){try{process.stderr.write(`${e}
49
- `)}catch{}}function AN(e,t){if(!Qy(t))return null;let n=Xy(e.command),r=Date.now();hd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let s=setInterval(()=>{let o=Date.now()-r;hd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${o} command="${n}"`)},tN());return s.unref?.(),s}function CN(e,t,n,r){if(!Qy(r))return;let s=Xy(e.command),o=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let m=t.exitCode===null?"null":String(t.exitCode),u=c.length>0?` ${c.join(" ")}`:"";hd(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${o}${u} command="${s}"`)}async function xy(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Gy("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function RN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function IN(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await xy(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{xy(r)},eN()),t.forceKillTimer.unref?.()}}function xN(e){return new Promise(t=>{let n=!1,r=null,s=(o,i=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(o))};e.on("exit",(o,i)=>{n||(r=setTimeout(()=>{s({code:o,signal:i},!0)},nN()),r.unref?.())}),e.on("close",(o,i)=>{s({code:o,signal:i})})})}function ON(e,t,n,r){return Gy(e,{cwd:process.cwd(),env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function Oy(e){let t=await fd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,ii),s=Buffer.alloc(r);return r>0&&await t.read(s,0,r,0),{text:s.toString("utf8"),truncated:n>ii}}finally{await t.close()}}async function PN(e,t,n,r,s){let o=Date.now(),i=await jy(me.join(Ky(),"pm-linked-test-output-"));try{let a=me.join(i,"stdout.log"),c=me.join(i,"stderr.log"),[m,u]=await Promise.all([fd(a,"w"),fd(c,"w")]),p;try{p=ON(e,n,m.fd,u.fd)}finally{await Promise.all([m.close(),u.close()])}TN(p);let f={heartbeat:AN(r,s),forceKillTimer:null,timedOutTimer:null},_=IN(p,f),h=!1,y;p.on("error",$=>{y=$.message}),f.timedOutTimer=setTimeout(()=>{h=!0,_()},t),f.timedOutTimer.unref?.();let{code:g,signal:b}=await xN(p);RN(f);let[v,E]=await Promise.all([Oy(a),Oy(c)]),N=v.truncated||E.truncated,O=N?`
50
- [pm linked-test output truncated at ${ii} bytes per stream; the child process continued to completion]
51
- `:"",j={stdout:`${v.text}${O}`,stderr:E.text,exitCode:g,signal:b,timedOut:h,maxBufferExceeded:!1,outputTruncated:N,spawnError:y};return CN(r,j,o,s),j}finally{await qy(i,{recursive:!0,force:!0})}}function NN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${ii} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,s=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?s:`${s} ${n.join(" ")}`}function LN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
52
- `);return JP.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>XP.test(n)&&QP.test(n))}function FN(e){return LN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function $N(){return{infra_collision:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function di(e){let t=$N();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function Py(e,t){for(let[n,r]of Object.entries(t.env_set))Qt.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)Qt.has(n.toUpperCase())||delete e[n]}function MN(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function DN(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],s=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:s}}function UN(e,t,n){return{env_set:cN(e,"--env-set"),env_clear:dN(t,"--env-clear"),shared_host_safe:n===!0}}async function Gn(e,t,n=!1,r=zP){if(await k(e))try{await Wo("seed_linked_test",async()=>{if(await r(me.dirname(t),{recursive:!0}),n){await Ay(e,t,{recursive:!0,force:!0});return}await Ay(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&wt(s))return;throw s}}async function Ny(e,t,n){await Gn(C(n.projectPmRoot),C(e)),await Gn(me.join(n.projectPmRoot,"extensions"),me.join(e,"extensions"),!0),await Gn(C(n.globalPmRoot),C(t)),await Gn(me.join(n.globalPmRoot,"extensions"),me.join(t,"extensions"),!0)}async function Ly(e,t){if(!await k(e))return;let n=await _d(e,{withFileTypes:!0});for(let r of n){if(WP.has(r.name))continue;let s=me.join(e,r.name),o=me.join(t,r.name);if(r.isDirectory()){await Gn(s,o,!0);continue}r.isFile()&&await Gn(s,o)}}async function Un(e){if(!await k(e))return 0;let t=0,n=await _d(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||YP.has(r.name))continue;let s=me.join(e,r.name),o;try{o=await _d(s,{withFileTypes:!0})}catch{continue}for(let i of o)i.isFile()&&zd.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function GN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function jN(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let r of n){if(r.startsWith("[")&&r.endsWith("]")){let s=Number.parseInt(r.slice(1,-1),10);if(!Number.isInteger(s)||s<0)return[];t.push(s);continue}t.push(r)}return t}function Fy(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=jN(n);if(r.length===0)return{found:!1,value:void 0};let s=e;for(let o of r){if(typeof o=="number"){if(!Array.isArray(s)||o>=s.length)return{found:!1,value:void 0};s=s[o];continue}if(typeof s!="object"||s===null||!Object.prototype.hasOwnProperty.call(s,o))return{found:!1,value:void 0};s=s[o]}return{found:!0,value:s}}function qN(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function KN(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?tt(e,t):Object.is(e,t)}function zN(e,t,n){let r=[];r.push(...$y("stdout",t,e.assert_stdout_contains)),r.push(...My("stdout",t,e.assert_stdout_regex)),r.push(...$y("stderr",n,e.assert_stderr_contains)),r.push(...My("stderr",n,e.assert_stderr_regex)),r.push(...BN(t,e.assert_stdout_min_lines));let s=e.assert_json_field_equals??{},o=e.assert_json_field_gte??{};if(!(Object.keys(s).length>0||Object.keys(o).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,m]of Object.entries(s)){let u=Fy(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=qN(m);KN(u.value,p)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(u.value)})`)}for(let[c,m]of Object.entries(o)){let u=Fy(a,c);if(!u.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof u.value!="number"||!Number.isFinite(u.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}u.value<m&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${m}, actual ${u.value})`)}return r}function $y(e,t,n){let r=[];for(let s of n??[])t.includes(s)||r.push(`${e} missing required text: "${s}"`);return r}function My(e,t,n){let r=[];for(let s of n??[])try{new RegExp(s,"m").test(t)||r.push(`${e} failed regex assertion: /${s}/m`)}catch(o){r.push(`${e} regex assertion is invalid: /${s}/ (${o instanceof Error?o.message:String(o)})`)}return r}function BN(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var HN=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i}];function VN(e,t){let n=`${e}
53
- ${t}`;for(let r of HN)if(r.regex.test(n))return r.code;return null}function WN(e){return{root:e,schemaProjectPmPath:me.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:me.join(e,"schema","global"),trackerProjectPmPath:me.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:me.join(e,"tracker","global")}}async function YN(e,t=_r,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function JN(e,t,n){t&&(await Ny(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await Ny(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Ly(t.projectPmRoot,e.trackerProjectPmPath),await Ly(t.globalPmRoot,e.trackerGlobalPmPath)))}function XN(e,t,n){return e.some(r=>{let s=r.command??"",o=s.length>0&&Hy(s),i=n?.autoPmContext===!0&&o?"auto":zy(r,t,n?.overrideLinkedPmContext===!0);return By(i,o)==="tracker"})}async function QN(e,t){return{sourceProjectItemCount:t?await Un(t.projectPmRoot):0,sourceGlobalItemCount:t?await Un(t.globalPmRoot):0,schemaProjectItemCount:await Un(e.schemaProjectPmPath),schemaGlobalItemCount:await Un(e.schemaGlobalPmPath),trackerProjectItemCount:await Un(e.trackerProjectPmPath),trackerGlobalItemCount:await Un(e.trackerGlobalPmPath)}}function ZN(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,s=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,o=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:s,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:o,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==s||e.counts.sourceGlobalItemCount!==o),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots}}function eL(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?ai(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?lN(n):!1,s=r&&n?Hy(n):!1,o=e.options?.autoPmContext===!0&&s,i=o?"auto":zy(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=By(i,s);return{linkedOverridePmContextMode:t,executionContext:ZN({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:s,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:o})}}function Dy(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function gd(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function tL(e){if(!e.linkedTest.command)return Dy(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=yN(e.linkedTest.command);if(t)return Dy(e.linkedTest,e.executionContext,t);let n=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,r=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(n||r){let s=aN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return gd(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${s}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!iN(e.linkedTest)?gd(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function nL(e){let t=DN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return Py(n,e.runtimeDirectives),Py(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&MN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,n.PM_SOURCE_WORKSPACE_ROOT=process.env.PM_SOURCE_WORKSPACE_ROOT??process.cwd(),n.PM_SOURCE_PM_PATH=e.executionContext.source_project_pm_path,n[Ws]="read_only",n}function rL(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function sL(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal}) while --fail-on-empty-test-run is enabled. Update test selection or disable --fail-on-empty-test-run for this run.`}}function oL(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:GN(e.execution),failure_category:FN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:NN(e.execution,e.timeoutMs)}}function iL(e){if(e.options?.failOnEmptyTestRun===!0){let n=VN(e.execution.stdout,e.execution.stderr);if(n)return sL({...e,emptyRunSignal:n})}let t=zN(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?gd(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):rL(e.linkedTest,e.executionContext,e.execution)}async function aL(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await PN(t,n,nL(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?iL({...e,execution:r}):oL({...e,execution:r,timeoutMs:n})}async function wd(e,t,n){let r=[],s=await jy(me.join(Ky(),"pm-linked-test-")),o=WN(s),i=ai(n?.pmContext),a=n?.progress===!0?"always":"auto",c=UN(n?.envSet,n?.envClear,n?.sharedHostSafe),m=n?.sourceRoots,u=XN(e,i,n);try{await YN(o,_r,u),await JN(o,m,u);let p=await QN(o,m);for(let f=0;f<e.length;f+=1){let _=e[f],h=eL({linkedTest:_,layout:o,counts:p,sourceRoots:m,runLevelPmContextMode:i,options:n}),y=tL({linkedTest:_,executionContext:h.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:h.linkedOverridePmContextMode,options:n});if(y){r.push(y);continue}r.push(await aL({linkedTest:_,index:f,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:c,progressMode:a,executionContext:h.executionContext,options:n}))}}finally{await qy(o.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function cL(e){let{id:t,pmRoot:n,settings:r,typeToFolder:s}=e,o=await D(n,t,r.id_prefix,r.item_format,s);if(!o)throw new l(`Item ${t} not found`,d.NOT_FOUND);let i=await K(o,{schema:r.schema});return{itemId:o.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function dL(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode}function lL(e,t){let n=[...e];for(let r of t)n.some(s=>dL(s,r))||n.push(r);return n}function mL(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),s=e.filter((o,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?o.command===a.value:a.kind==="path"?o.path===a.value:o.command===a.value||o.path===a.value));return{tests:s,removed:e.length-s.length}}function uL(e,t,n,r){return mL(lL(e,t),n,r)}function pL(e){return(e.envSet?.length??0)>0||(e.envClear?.length??0)>0||e.sharedHostSafe===!0||e.pmContext!==void 0||e.overrideLinkedPmContext===!0||e.failOnContextMismatch===!0||e.failOnSkipped===!0||e.failOnEmptyTestRun===!0||e.requireAssertionsForPm===!0||e.checkContext===!0||e.autoPmContext===!0}function fL(e){if(pL(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",d.USAGE)}async function _L(e){let{id:t,options:n,pmRoot:r,settings:s,typeToFolder:o,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return cL({id:t,pmRoot:r,settings:s,typeToFolder:o});let m=0,u=await Z({pmRoot:r,settings:s,id:t,op:i.length>0?"tests_add":"tests_remove",author:R(n.author,s.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=uL(f,i,a,c);if(m=_.removed,(a.length>0||c.length>0)&&m===0)throw new l("No linked tests matched the requested removal selector",d.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return p.metadata.tests=_.tests,{changedFields:tt(f,_.tests)?[]:["tests"]}}});return{itemId:u.item.id,tests:u.item.tests??[],testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:m}}function hL(e,t){fL(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:ud(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?Ty(t,n):void 0,s=e.timeout===void 0?void 0:ie(e.timeout,"timeout");if(s!==void 0&&s<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:s,pmContextMode:ai(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function gL(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await wd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,sourceRoots:{projectPmRoot:r,globalPmRoot:et(process.cwd())}})}function yL(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let s=bd(n);r.push(`context_preflight:checked_pm_commands=${s.checked_pm_commands};tracker_read_commands=${s.tracker_read_commands};mismatches=${s.mismatches};auto_remediated=${s.auto_remediated}`)}return r}function bL(e){let t=sN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),s=S(),o=Er(e.options.measure,s);return{run_id:rN("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:s,recorded_at:s,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:o.length>0?o:void 0}}async function wL(e){let{options:t,pmRoot:n,settings:r,itemId:s,runStartedAt:o,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!o)return;let m=bL({options:t,runStartedAt:o,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return m;try{return await si({pmRoot:n,settings:r,itemId:s,author:R(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),m}catch(u){return c.push(`test_result_tracking_failed:${s}:${u instanceof Error?u.message:String(u)}`),m}}function Uy(e,t,n){let r;if(e.metricBelow!==void 0){let s=e.metricBelow.indexOf("="),o=e.metricBelow.slice(0,s).trim(),i=e.metricBelow.slice(s+1).trim(),a=Number(i);if(s<=0||o.length===0||i.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",d.USAGE);r=cy(t,o,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:dy(t,e.metricDiff)}}async function li(e,t,n){let r=Le(),s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);Er(t.measure,"validation"),Uy(t,[],void 0);let i=x(o,I()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...bN(a),...kN(c)],p=SN(m),f=EN(t.removeIndex),_=await _L({id:e,options:t,pmRoot:s,settings:o,typeToFolder:i.type_to_folder,adds:u,removes:p,removeIndexes:f}),h=hL(t,_.tests),y=t.run===!0?S():void 0,g=await gL({options:t,runOptions:h,pmRoot:s}),b=di(g),v=t.run===!0&&t.failOnSkipped===!0&&g.some($=>$.status==="skipped"),E=yL(t,h.runSelection,g),N=await wL({options:t,pmRoot:s,settings:o,itemId:_.itemId,runStartedAt:y,runResults:g,failOnSkippedTriggered:v,warnings:E}),O=N?md([..._.testRuns,N]):_.testRuns,j=Uy(t,O,N);return{ok:g.every($=>$.status!=="failed")&&v!==!0,id:_.itemId,tests:_.tests,run_results:g,failure_categories:b,selection:h.runSelection?{selector:h.runSelection.selector,requested:h.runSelection.requested,selected_indexes:h.runSelection.selected_indexes,selected_count:h.runSelection.selected_count,skipped_count:h.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:v?!0:void 0,warnings:E.length>0?E:void 0,changed:_.changed,count:_.tests.length,..._.removed>0?{removed:_.removed}:{},...j}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7fea0ecb-35e2-5d40-931f-ffdd1a465fdc")}catch{}})();var vL=(e,t)=>{if(e===void 0)return;let n=W(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},kL=e=>{if(e===void 0)return;let t=ie(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},Zy=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,d.USAGE);return n},SL=e=>e instanceof Error?e.message:String(e),EL=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},TL=e=>e.trim().replaceAll(/\s+/g," "),AL=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),CL=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),RL=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},mi=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),eb=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),IL=e=>typeof e=="number"?e:void 0,xL=e=>{let t={assert_stdout_contains:mi(e.assert_stdout_contains),assert_stdout_regex:mi(e.assert_stdout_regex),assert_stderr_contains:mi(e.assert_stderr_contains),assert_stderr_regex:mi(e.assert_stderr_regex),assert_stdout_min_lines:IL(e.assert_stdout_min_lines),assert_json_field_equals:eb(e.assert_json_field_equals),assert_json_field_gte:eb(e.assert_json_field_gte)};return JSON.stringify(t)},OL=e=>{let t=vd(e.command);return t!==void 0?`command:${e.scope}:${TL(t)}`:`path:${e.scope}:${vd(e.path)??""}`},tb=e=>{let t=AL(e.env_set),n=CL(e.env_clear),r=RL(e.pm_context_mode),s=e.shared_host_safe===!0?"true":"false",o=xL(e);return`${OL(e)}:${t}:${n}:${r}:${s}:${o}`},PL=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,NL=e=>{let t=0,n=0,r=0;for(let s of e){if(s.status==="passed"){t+=1;continue}if(s.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},LL=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},ui=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
54
- `)}catch{}},FL=async(e,t,n)=>{let r=[],s=0;for(let o of e){let i=await li(o.id,{run:!1},{...t,path:n});s+=i.tests.length,r.push({item:o,tests:i.tests})}return{itemTests:r,linkedTests:s}},$L=async e=>{let t=M(e.settings.schema),n=x(e.settings,I()),r=vL(e.options.status,t),s=Zy(e.options.limit,"--limit"),o=Zy(e.options.offset,"--offset")??0,a=(await oe(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(m=>r?m.status===r:!0).sort((m,u)=>m.id.localeCompare(u.id));return{filteredItems:s===void 0?a.slice(o):a.slice(o,o+s),statusFilter:r,limitFilter:s,offsetFilter:o}},ML=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let s=tb(r);if(!t.has(s)){t.set(s,r.timeout_seconds);continue}t.set(s,PL(t.get(s),r.timeout_seconds))}return t},DL=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=tb(u),f=t.seenTestKeys.has(p);if(!f){t.seenTestKeys.add(p);let _=t.effectiveTimeoutByKey.get(p);n.push(_===void 0?u:{...u,timeout_seconds:_})}return{test:u,key:p,duplicate:f}}),s=n.length>0?await wd(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext}):[],o=0,i=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=s[o];return o+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=NL(i),c=di(i),m=await jL(e,a,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:m,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:i,failure_categories:c}}},UL=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),GL=e=>e?!0:void 0,jL=async(e,t,n)=>{if(!n.trackingEnabled)return[];try{let r=UL(t,n.options);await si({pmRoot:n.pmRoot,settings:n.settings,itemId:e.item.id,author:n.trackingAuthor,message:`Track test-all run summary (${n.trackingRunId})`,entry:{run_id:n.trackingRunId,kind:"test-all",status:r?"failed":"passed",started_at:n.runStartedAt,finished_at:S(),recorded_at:S(),attempt:n.trackingAttempt,resumed_from:n.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:GL(n.options.failOnSkipped===!0&&t.skipped>0)}})}catch(r){return[`test_result_tracking_failed:${e.item.id}:${SL(r)}`]}return[]},qL=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},vd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},KL=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:et(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:ML(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:R(e.options.author,e.settings.author_default),trackingRunId:EL(),trackingAttempt:qL(),trackingResumedFrom:vd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),zL=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:di([]),trackingWarnings:[]},s=e.failOnEmptyTestRun===!0&&t===0;return s&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:s}},BL=async(e,t,n)=>{for(let[r,s]of e.entries()){ui(t.options,`item ${r+1}/${e.length} start id=${s.item.id} linked_tests=${s.tests.length}`);let o=await DL(s,t);LL(n.failureCategories,o.failureCategories),n.passed+=o.passed,n.failed+=o.failed,n.skipped+=o.skipped,n.trackingWarnings.push(...o.trackingWarnings),n.results.push(o.result),ui(t.options,`item ${r+1}/${e.length} end id=${s.item.id} status=${o.failed===0?"passed":"failed"} passed=${o.passed} failed=${o.failed} skipped=${o.skipped}`)}},HL=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(s=>s.run_results),r=bd(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},VL=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),WL=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),YL=async(e,t)=>{let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await $L({pmRoot:n,settings:r,options:e}),o=kL(e.timeout),i=S(),a=await FL(s.filteredItems,t,n);return ui(e,WL({...s,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:s.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:o,runStartedAt:i}},JL=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},nb=async(e,t)=>{let n=await YL(e,t),{accumulation:r,failOnEmptyTestRunTriggered:s}=zL(e,n.linkedTests,n.filteredItems),o=KL({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await BL(n.itemTests,o,r),HL(e,r);let i=JL({options:e,accumulation:r,failOnEmptyTestRunTriggered:s});return ui(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),VL({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered:s})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2643d11d-befc-5a87-8bec-760951eec4d0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2567f6a-cd1c-56b5-a93d-41e92ed574bf")}catch{}})();function rb(){return{metadata:{},body:""}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7be35c3f-df6f-5ed6-b887-a7d8d53910a7")}catch{}})();var ob=[{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm init","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm install <target> --project","pm upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]}],sb=new Map;for(let e of ob){sb.set(e.id,e);for(let t of e.aliases)sb.set(t,e)}function kd(){return ob.map(e=>e.id)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27be0fa5-1c6a-53de-a0e8-179aab7c795a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48da3e98-ab96-54de-8993-7de0c4edf19b")}catch{}})();var eB=[...Rr],tB=[...Ir],XL=new Set(Wn.filter(e=>e.hidden).map(e=>e.alias)),nB=eu("full").filter(e=>!XL.has(e)),rB=F(Gr),sB=F(jr),oB=F(Wr),iB=F(Zr),aB=F(es),cB=F(Xl),dB=F(Ql),lB=F(Qr),mB=F(ss),uB=F(ts),pB=F(ns),fB=F(Vr),_B=F(rs),hB=F(qr),gB=F(Kr,!1),yB=F(dm),bB=F(Hn),wB=F(Vn),vB=F(cs),kB=F(is),SB=F(Jr),EB=F(as),TB=F(os),AB=F(ds),CB=F(Yr),RB=F(Xr),IB=F(Br),xB=F(ls),OB=F(zr);var QL=F(ms),PB=`${QL} bash zsh fish`,NB=ZL(kd());var LB=F(Hr),FB=F(Bn);var $B=Ur.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function ZL(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0224a672-e326-5555-a4b4-1fa3550d9e61")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8f02f498-5cee-59fa-9f4e-fd882c58d401")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c770afea-3eb6-5476-ba07-8ec1c5d9c699")}catch{}})();var db=Symbol("pm.active-extension-host-context");function Ie(e){return{fullChangedFields:!0,options:e}}var G=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[db]=!0,n}run(t,n={}){return lb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return of(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return sa(await this.list(ra(t)))}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}append(t,n,r={}){return this.runTyped("append",{id:t,...Ie({...r,body:n})})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,s,o={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...s===void 0?{}:{value:s},options:o})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,s){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...s?{fieldTypeScope:s}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},s,o){return this.runTyped("plan",{...n===void 0?{}:{id:n},...s===void 0?{}:{stepRef:s},...o===void 0?{}:{reorderTo:o},options:{...r,subcommand:t}})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,s={}){return this.plan("reorder-step",t,s,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Ie(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ie(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Ie(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ie(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ie(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ie(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ie(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ie(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...Ie(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ie(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ie(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ie(r)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function tF(e={},t={}){return new G(t).context(e)}function nF(e={},t={}){return new G(t).list(e)}function rF(e={},t={}){return new G(t).listAllComplete(e)}function sF(e,t={},n={}){return new G(n).search(e,t)}function oF(e,t={},n={}){return new G(n).get(e,t)}function iF(e={},t={}){return new G(t).next(e)}function aF(e={},t={}){return new G(t).aggregate(e)}function cF(e,t={},n={}){return new G(n).comments(e,t)}function dF(e,t={},n={}){return new G(n).notes(e,t)}function lF(e,t={},n={}){return new G(n).learnings(e,t)}function mF(e,t={},n={}){return new G(n).files(e,t)}function uF(e,t={},n={}){return new G(n).filesDiscover(e,t)}function pF(e,t={},n={}){return new G(n).docs(e,t)}function fF(e,t={},n={}){return new G(n).deps(e,t)}function _F(e,t={},n={},r={}){return new G(r).graph(e,t,n)}function hF(e,t,n={},r={}){return new G(r).append(e,t,n)}function gF(e={},t={}){return new G(t).create(e)}function yF(e,t={},n={}){return new G(n).update(e,t)}function bF(e,t,n={},r={}){return new G(r).reopen(e,t,n)}function wF(e,t,n={},r={}){return new G(r).close(e,t,n)}function vF(e,t={},n={}){return new G(n).claim(e,t)}function kF(e={},t={}){return new G(t).claimNext(e)}function SF(e,t={},n={}){return new G(n).release(e,t)}function EF(e,t={},n={}){return new G(n).copy(e,t)}function TF(e,t={},n={}){return new G(n).delete(e,t)}function AF(e,t,n={},r={}){return new G(r).restore(e,t,n)}function CF(e,t={},n={}){return new G(n).focus(e,t)}function Xe(e,t){let n=w(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}var ib=ou(),RF=new eF;function pi(){Vi(Xd()),Wi(Qd()),Yi(Zd()),Ji(el()),Xi(tl()),Qi(nl()),Zi(rl())}async function IF(e,t,n,r){return iu(()=>t===void 0?ib.read(()=>ab(e,n,r)):ib.write(()=>OF(t,()=>ab(e,n,r))))}async function ab(e,t,n){let r=T(t,e.path);if(e.noExtensions)return pi(),La({pmRoot:r},()=>n(null));if(!await k(C(r)))return pi(),n(null);let s=null,o;try{let i=await A(r),a=await Mr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Dr({...a,loaded:a.loaded});o={loadResult:a,activationResult:c},Vi(c.hooks),Wi(c.commands),Yi(c.parsers),Ji(c.preflight),Xi(c.services),Qi(c.renderers),Zi(c.registrations),s={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){pi(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await La({pmRoot:r,packages:s?.packages},()=>n(s))}finally{pi(),o&&await sl(o.loadResult,o.activationResult).catch(()=>{})}}async function xF(e,t,n,r,s){if(!s)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let o=Ht(e),a=s.registrations.commands.find(m=>Ht(m.action)===o)?.command??s.commands.handlers.find(m=>Ht(m.command)===o)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=await vs({command:ua(a),args:ye(n.args??t.args),options:pa(t,n),global:r,pm_root:s.pmRoot,sdk:lf(s.pmRoot,G.forActiveExtensionHost({pmRoot:s.pmRoot,author:typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension"}))});if(!c.handled){let m=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${m}`,d.USAGE)}return c.result}async function OF(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var PF=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function NF(e){let t=Xe(e,"action"),n=Ht(t),r=_i(cf,n),s=r?.action??n,o={...e,action:s};return r?.options!==void 0&&(o.options={...r.options,...Ni(e.options)}),s==="package"&&(o.options={...Ni(o.options),vocabulary:"package"}),{action:s,args:o}}function LF(e){return!PF.has(Ht(e))}async function lb(e){let t=NF(e),n=da(t.args),r=LF(t.action),s=w(t.args,"cwd"),o=s??process.cwd();try{return e[db]===!0||RF.getStore()===!0?await cb(t.action,t.args,n,null):await IF(n,s,o,i=>cb(t.action,t.args,n,i))}finally{r&&xa()}}function _i(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function fi(e){return w(e.args,"target")??w(e.options,"target")}function Y(e,t=e.options){return e.id??Xe(t,"id")}async function FF(e){let t=pn("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),Ia(await It(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function $F(e){let t=Xe(e.args,"query"),n=pn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Ia(await or(t,n,e.global),n)}async function MF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await xt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function DF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options),s={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Ge(await vc(Y(e,s),s,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function UF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await at(Y(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function GF(e){let t=io(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),Af(Y(e),t,e.global)}function mb(e,t){return qp(Sg(e.options,t,Fe),e.global)}function jF(e){let t=ye(e.options.lookupPath);if(t&&t.length>0)return mb(e,t);let n=Y(e);return e.options.discover===!0?ha(n,ma(e.options),e.global):jp(n,Vs(e.options),e.global)}function qF(e){return vy({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:ip(e.args,e.options)},e.global)}function KF(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Up(e.global,t)}function zF(e){let t=w(e.args,"configAction")??w(e.options,"configAction")??w(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);return Y_(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),e.options,e.global,w(e.args,"value")??w(e.options,"value"))}function BF(e){let t=e.options;return Xu(Ju(t),e.global)}function HF(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}function VF(e){let t=w(e.args,"subcommand")??Xe(e.options,"subcommand"),n=e.options;return C_({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:WF(e),reorderTo:HF(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function WF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function YF(e){let t=w(e.args,"subcommand")??Xe(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:w(e.args,"name")??w(e.options,"name"),author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ye(n)}}function JF(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,a=_i({list:()=>Sp(t.global),show:()=>Ep(r,t.global),"show-status":()=>Tp(r,t.global),"list-fields":()=>Rp(t.global),"show-field":()=>Ip(r,t.global),"remove-type":()=>bp(r,{author:s,force:o},t.global),"remove-field":()=>Cp(r,{author:s,force:o},t.global),"remove-status":()=>kp(r,{author:s,force:o},t.global),"apply-preset":()=>xp(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:s,force:o},t.global)},n);return a?a():null}function XF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return Ap(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:ye(i),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:o,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:ye(a),author:r,force:s},t.global)}function QF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e,i=t.args.role??t.options.role;return vp(n,{role:i===void 0?void 0:ye(i),alias:o,description:w(t.args,"description")??w(t.options,"description"),order:Fe(t.args.order??t.options.order,"schema add-status order"),author:r,force:s},t.global)}function ZF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e;return yp(n,{description:w(t.args,"description")??w(t.options,"description"),defaultStatus:w(t.args,"defaultStatus")??w(t.args,"default_status")??w(t.options,"defaultStatus")??w(t.options,"default_status"),folder:w(t.args,"folder")??w(t.options,"folder"),alias:o,author:r,force:s},t.global)}function e$(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,i=w(t.args,"to")??Xe(t.options,"to"),a=w(t.args,"migrationId")??w(t.args,"migration_id")??w(t.options,"migrationId")??w(t.options,"migration_id"),c=w(t.args,"fieldTypeScope")??w(t.options,"fieldTypeScope")??w(t.args,"type")??w(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:i}:n==="rename-field"?{kind:"rename-field",from:r??"",to:i,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:i};return hp(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:s,force:o},t.global)}function t$(e){let t=YF(e),n=JF(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return e$(t);if(t.subcommand==="add-field")return XF(t);if(t.subcommand==="add-status")return QF(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Op({minCount:Fe(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):ZF(t);throw Te({command_path:"schema",token:t.subcommand,allowed:gp,exit_code:64})}function n$(e){let t=w(e.args,"subcommand")??Xe(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),o=_i({list:()=>cg(),show:()=>dg(r),lint:()=>lg(r),apply:()=>mg(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!o)throw Te({command_path:"profile",token:t,allowed:ag,exit_code:64});return o()}async function r$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await uf(Y(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function s$(e){let{changedFields:t,runnerOptions:n}=$e(e.args,e.options);return Ge(await __(_a(n),e.global),{changedFields:t})}async function o$(e){let{changedFields:t,runnerOptions:n}=$e(e.args,e.options),r=w(e.args,"reason"),s=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&s.force===void 0&&(s.force=!0),Ge(await Tf(fa(s),e.global),{changedFields:t})}async function i$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options),s=w(r,"target")??Xe(e.args,"target");return Ge(await Wt(Y(e,r),s,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function ub(e){let t={...e};return delete t.assignee,t}async function a$(e){let t=T(process.cwd(),e.global.path),n=await A(t),r=Qo(M(n.schema)),s=Y(e),o=await co(s,e.force,e.global,e.options),i=await at(s,{...ub(e.options),status:r,force:e.force},e.global);return{id:s,action:"start_task",claim:o,update:i}}async function c$(e){let t=T(process.cwd(),e.global.path),n=await A(t),r=Y(e),s=M(n.schema).open_status,o=await at(r,{...ub(e.options),status:s,force:e.force},e.global),i=await lo(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:o,release:i}}async function d$(e){let t=Y(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await it(t,n,{...e.options,force:e.force},e.global),s=await lo(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:s}}function l$(e){let t={...e.args,...e.options};return np(Xe(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),dp(t),e.global)}function m$(e){return mp(T(process.cwd(),e.global.path),{...e.args,...e.options})}var u$={init:e=>_r(w(e.args,"prefix"),e.global,e.options),context:e=>Aa(pn("context",e.options),e.global),next:e=>sr(pn("next",e.options),e.global),eval:Jh,events:Xh,merge:Qh,workspace:Zh,meet:Jo,event:Jo,remind:Jo,list:FF,get:e=>{let t=Y(e);return Ca(t,e.global,pn("get",e.options,[t]))},search:$F,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ye(e.options.status);return Ra(e.global,{...t.length===0?{}:{status:t},since:w(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Fe(e.options.limit,"limit")})},create:MF,copy:DF,focus:e=>Sc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:UF,"item-reopen":kg,restore:i$,claim:e=>e.options.next===!0||e.args.next===!0?bf(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):co(Y(e),e.force,e.global,e.options),release:e=>lo(Y(e),e.force,e.global,e.options),"start-task":a$,"pause-task":c$,"close-task":d$,close:vg,comments:GF,notes:e=>Rf(Y(e),io(e.options),e.global),learnings:e=>Cf(Y(e),io(e.options),e.global),files:jF,docs:e=>Gp(Y(e),Vs(e.options),e.global),test:e=>li(Y(e),e.options,e.global),"test-all":e=>nb(e.options,e.global),telemetry:qF,validate:e=>Qs(e.options,e.global,{runUpdate:(t,n,r)=>at(t,n,r)}),health:KF,assurance:e=>Xp(e.args,e.options,e.global),contracts:e=>Hg(e.options,e.global),config:zF,activity:BF,aggregate:e=>Sa(e.options,e.global),extension:e=>Cn(fi(e),e.options,e.global),package:e=>Cn(fi(e),e.options,e.global),install:e=>Cn(fi(e),{...e.options,install:!0},e.global),upgrade:e=>nf(fi(e),e.options,e.global),delete:e=>kc(Y(e),e.options,e.global),deps:e=>tp(Y(e),e.options,e.global),graph:l$,"files-discover":e=>ha(Y(e),e.options,e.global),"files-lookup":e=>mb(e,ye(e.options.paths)),history:e=>tf(Y(e),e.options,e.global),"history-redact":e=>Lu(Y(e),e.options,e.global),"history-repair":gg,"history-compact":yg,"history-author-acknowledge":m$,plan:VF,schema:t$,profile:n$,stats:e=>cd(e.global,my(e.options)),append:r$,"update-many":s$,"close-many":o$,gc:e=>rf(e.global,e.options)};async function cb(e,t,n,r){let s=la(t,e);zi(e,s),Um(e,s);let o={action:e,args:t,options:s,id:w(t,"id"),force:t.force===!0||s.force===!0,global:n,activeExtensions:r},i=_i(u$,e),a=i?await i(o):await xF(e,t,s,n,r);return s.resolvedOutputFormat="json",Jm(e,s,a)}var p$={closeManyOptionsFromFlat:fa,extensionOptionsFromArgs:pa,globalOptions:da,mutationListOptions:cp,normalizeActionName:Ht,normalizeCommandPath:ua,normalizeMcpUpdateOptions:lp,normalizeMcpOptionsArrays:ap,optionsWithAuthor:la,readRequiredString:Xe,readScalarString:sp,readScalarStringAllowBlank:op,readStringArray:ye,updateManyOptionsFromFlat:_a,withAddNoteOption:Vs,withFilesDiscoveryOptions:ma,withMutationCompaction:$e};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=p$);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d19cfa31-a02f-53a7-8685-5d169d6e051d")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cc0d4dd1-20e8-59d4-acb5-9f8ed639d35f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f44898af-0809-51e1-a6fb-74716c0971f5")}catch{}})();export{hn as AGENT_PROVENANCE_DIMENSIONS,lu as BASELINE_ITEM_FORMAT_VERSION,Yn as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,Rr as BUILTIN_ITEM_TYPE_VALUES,xr as CONFIDENCE_TEXT_VALUES,mu as CURRENT_ITEM_FORMAT_VERSION,Dt as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,dn as ISSUE_SEVERITY_VALUES,$d as ITEM_TYPE_VALUES,Oa as PM_CLI_EXPECTED_ERROR_NAME,iw as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,sw as PM_READ_OUTPUT_DIMENSIONS,ow as PM_READ_OUTPUT_OPTION_FLAGS,Ki as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,G as PmClient,cn as RISK_VALUES,Cw as SEMANTIC_ATTRIBUTION_LIMITS,Ir as STATUS_VALUES,hw as agentSessionEnvironment,aF as aggregate,id as analyzeAgentProvenanceDescriptorCoverage,uw as analyzeSdkCliParameterCompleteness,hF as append,dw as applyReadOutputDimensions,Zb as applyReadOutputSessionReferences,ew as attachReadOutputSessionReceipt,pw as boundAgentEpisodeIdentity,We as canonicalDocument,vF as claim,kF as claimNext,fu as classifyItemFormatVersion,wF as close,cF as comments,tF as context,EF as copy,gF as create,df as createPmCliExpectedError,rw as decodeReadOutputContinuationCursor,TF as deleteItem,fF as deps,ww as detectAgentIdentity,Sw as detectHarnessIdentity,vw as diagnoseAgentIdentity,pF as docs,uu as effectiveItemFormatVersion,rb as emptyImportedDocument,nw as encodeReadOutputContinuationCursor,GO as evaluateSemanticAttributionCoverage,Tw as explainSourceTraceability,mF as files,uF as filesDiscover,CF as focus,oF as get,_F as graph,jO as groupHistoryByEpisode,yf as isAlreadyClaimedError,ro as isPmCliExpectedError,lw as isReadOutputBudgetExceeded,lF as learnings,nF as list,rF as listAllComplete,iF as next,pu as normalizeItemFormatVersion,ge as normalizeItemId,W as normalizeStatusInput,dF as notes,S as nowIso,Qb as parseReadOutputSession,Ys as parseSourceLineRange,Ss as readAuthorEnvironment,tw as readOutputSessionRemainingTokens,Ea as recordClaimSemanticAttribution,eo as recordFocusSemanticAttribution,Ta as recordReleaseSemanticAttribution,gw as registerHarnessSignalDescriptors,SF as release,bF as reopen,fw as resolveAgentSessionContextFromSignals,Ew as resolveAuthorIdentity,ty as resolveHistoryEpisodeGroupIdentity,cw as resolveReadOutputDimensions,mw as resolveReadOutputEncoding,aw as resolveReadOutputSurface,Aw as resolveSemanticLineageIds,AF as restore,lb as runAction,_w as runWithAgentSessionContext,yw as runWithHarnessDetectionSignals,bw as runWithWorkspaceHarnessSignalDescriptors,sF as search,Rw as semanticAttributionAffinity,je as serializeItemDocument,UO as summarizeAgentModelProvenance,ad as summarizeAgentProvenance,yF as update,zi as validateReadOutputOptions,kw as writeAuthorEnvironment};
40
+ `}function YR(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Ah(e,t,n){Bc(e,"base");let r=Bc(t,"ours"),s=Bc(n,"theirs"),o=Math.min(r.length,s.length),i=0;for(;i<o&&r[i].eventId===s[i].eventId;)i+=1;if(i===r.length&&i===s.length)return{merged:Xo(r),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===s.length)return{merged:Xo(r),strategy:"fast_forward_ours",common_entries:i,entries_from_ours:r.length-i,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===r.length)return{merged:Xo(s),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:s.length-i,entries_total:s.length,reanchored:!1};let a=r.slice(i),c=new Set(a.map(f=>f.eventId)),d=s.slice(i).filter(f=>!c.has(f.eventId)),u=[...a,...d].sort((f,_)=>{if(f.timestamp!==void 0&&_.timestamp!==void 0){let g=vn(f.timestamp,_.timestamp);if(g!==0)return g}else{if(f.timestamp===void 0&&_.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let h=c.has(f.eventId),y=c.has(_.eventId);return h!==y?Number(y)-Number(h):0}),p=YR([...r.slice(0,i),...u]);return{merged:Xo(p),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:d.length,entries_total:p.length,reanchored:!0}}var JR=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],XR=["updated_at"];function cn(e,t){return Q(e??null)===Q(t??null)}function QR(e,t,n){let r=u=>Array.isArray(u)?u:[],s=new Set(r(e).map(u=>Q(u))),o=r(t),i=new Set(o.map(u=>Q(u))),a=r(n),c=new Set(a.map(u=>Q(u))),d=o.filter(u=>{let p=Q(u);return!s.has(p)||c.has(p)});for(let u of a){let p=Q(u);!i.has(p)&&!s.has(p)&&d.push(u)}return d}function ZR(e,t){return vn(String(e),String(t))>=0?e:t}function Th(e,t,n,r){return cn(t,n)?{value:t,from_theirs:!1,conflict:!1}:cn(e,t)?{value:n,from_theirs:!0,conflict:!1}:cn(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function Ch(e,t,n,r,s){let o=Th(e,t,n,r);if(!o.conflict||s==="preferred_side")return o;let i=Q(n).localeCompare(Q(t))<0;return{value:i?n:t,from_theirs:i,conflict:!0}}function Hc(e){return{...e.metadata}}function Vc(e,t,n){try{return Je(Eu(e,n),n)}catch(r){throw new m(`Item merge input (${t}) is not a readable item document: ${String(r)}`,l.GENERIC_FAILURE)}}function eI(e,t,n,r,s){let o=new Set(JR),i=new Set(XR),a=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((d,u)=>d.localeCompare(u)),c={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let d of a){let u=e[d],p=t[d],f=n[d];if(o.has(d)){let h=QR(u,p,f);c.merged[d]=h,cn(h,p)||c.unionFields.push(d);continue}if(i.has(d)){c.merged[d]=ZR(p,f);continue}let _=Ch(u,p,f,r,s);_.value!==void 0&&(c.merged[d]=_.value),_.conflict?(c.conflictFields.push(d),c.conflictDecisions.push({field:d,base:u,ours:p,theirs:f,retained:_.value,discarded:_.from_theirs?p:f})):_.from_theirs&&c.fieldsFromTheirs.push(d)}return c}function Rh(e,t,n,r={}){let s=r.preferred??"ours",o=r.conflictResolution??"preferred_side",i=e.trim().length>0,a=Vc(t,"ours",r),c=Vc(n,"theirs",r),d=i?Vc(e,"base",r):a,u=i?Hc(d):{},p=Hc(a),f=Hc(c),{merged:_,conflictFields:h,fieldsFromTheirs:y,unionFields:g,conflictDecisions:b}=eI(u,p,f,s,o),v=Ch(i?d.body:"",a.body,c.body,s,o);return v.conflict?(h.push("body"),b.push({field:"body",base:i?d.body:"",ours:a.body,theirs:c.body,retained:v.value,discarded:v.from_theirs?a.body:c.body})):v.from_theirs&&y.push("body"),{merged:qe({metadata:_,body:v.value},r),conflict_fields:h,fields_from_theirs:y,union_fields:g,conflict_decisions:b,requested_preference:s,conflict_resolution:o}}function Wc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yc(e,t){let n=xs(e);if(n)throw new m(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,l.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new m(`JSON merge input (${t}) is not valid JSON.`,l.GENERIC_FAILURE)}}function tI(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=d=>{let u=new Map;for(let p of d){let f=Q(p);u.set(f,(u.get(f)??0)+1)}return u},s=r(e),o=r(t),i=r(n);for(let[d,u]of s)if((o.get(d)??0)<u||(i.get(d)??0)<u)return null;let a=new Map(o),c=[];for(let d of n){let u=Q(d),p=a.get(u)??0;p>0?a.set(u,p-1):c.push(d)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function nI(e,t,n,r,s,o,i){if(!Wc(t)||!Wc(n))return null;let a=Wc(e)?e:{},c={},d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,p)=>u.localeCompare(p));for(let u of d){let p=s.length>0?`${s}.${u}`:u,f=rI(a,t,n,u,r,p,o,i);f!==void 0&&(c[u]=f)}return c}function Ih(e,t,n,r,s,o,i){if(cn(t,n))return t;let a=tI(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(s),a.merged;let c=nI(e,t,n,r,s,o,i);if(c!==null)return c;let d=Th(e,t,n,r);return d.conflict?o.push(s):d.from_theirs&&i.push(s),d.value}function rI(e,t,n,r,s,o,i,a){let c=Object.prototype.hasOwnProperty.call(t,r),d=Object.prototype.hasOwnProperty.call(n,r),u=Object.prototype.hasOwnProperty.call(e,r);if(c&&d)return Ih(e[r],t[r],n[r],s,o,i,a);if(c){if(u&&cn(e[r],t[r])){a.push(o);return}return u?(i.push(o),s==="theirs"?void 0:t[r]):t[r]}if(!(u&&cn(e[r],n[r])))return u?(i.push(o),s==="theirs"?n[r]:void 0):(a.push(o),n[r])}function xh(e,t,n,r={}){let s=r.preferred??"ours",o=Yc(e,"base"),i=Yc(t,"ours"),a=Yc(n,"theirs"),c=[],d=[],u=Ih(o,i,a,s,"",c,d);return{merged:`${JSON.stringify(u??null,null,2)}
41
+ `,conflict_paths:c,paths_from_theirs:d,preferred:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d79e3a4-6104-5855-837f-69a041b87b27")}catch{}})();var Oh=["item","history","relationship","json"];function aI(e){let t=e.trim().toLowerCase();if(Oh.includes(t))return t;throw new m(`Unknown merge artifact "${e}". Supported values: ${Oh.join(", ")}.`,l.USAGE)}function cI(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new m(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,l.USAGE)}async function Jc(e,t){try{return await sI(e,"utf8")}catch{throw new m(`Cannot read merge ${t} file at ${e}.`,l.NOT_FOUND)}}async function dI(e){let t=E(process.cwd(),e.path);return await P(ge(t))?A(t):null}function lI(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Ph(e,t){let n=aI(e.artifact),r=cI(e.prefer),s=iI.resolve(e.outputPath??e.oursPath),[o,i,a]=await Promise.all([Jc(e.basePath,"base"),Jc(e.oursPath,"ours"),Jc(e.theirsPath,"theirs")]),c,d,u=[],p={};if(n==="history"){let _=Eh(o,i,a);c=_.merged,p.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=Ah(o,i,a);c=_.merged,p.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await dI(t),h=Rh(o,i,a,{format:lI(e.itemPath??s,_),schema:_?.schema,extensionFieldNames:vt(R()),preferred:r,conflictResolution:"stable_value_order"});c=h.merged,u.push(...h.conflict_fields),p.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0&&(d={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,decisions:h.conflict_decisions})}else{let _=xh(o,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await oI(s,c,"utf8"),d!==void 0){let _=await zp(d);_!==null&&(p.receipt=rr(_))}let f=[];if(u.length>0){let _=p.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${p.receipt.receipt_id} with item ${p.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${u.join(", ")}; the item driver kept the direction-independent stable value. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&p.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:u.length===0,artifact:n,output_path:s,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:k()}}import Fh from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d201aa9f-1ed3-5655-8c06-e5729557b86a")}catch{}})();function Nh(e,t){return t==="body"?e.body:e.metadata[t]}function Xc(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(s=>{let o=t.findIndex((i,a)=>!r.has(a)&&Xc(s,i));return o<0?!1:(r.add(o),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,s])=>Object.hasOwn(n,r)&&Xc(s,n[r]))}function Lh(e,t){let n=new Set(t),r=[];for(let s=e.length-1;s>=0&&n.size>0;s-=1){let o=e[s],i=new Set;for(let c of xu(o.patch))i.add(Ks(c.path)),c.from&&i.add(Ks(c.from));let a=[...n].filter(c=>i.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:s+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function mI(e,t,n){let r=Fh.compare(t,n);if(r.length===0)return;let s=new Set;for(let h of r)s.add(Ks(h.path));let o=new Set([...s].filter(h=>Xc(Nh(t,h),Nh(n,h)))),i=new Set([...s].filter(h=>!o.has(h))),a=Lh(e,i),c=Lh(e,o),d=[...s].sort((h,y)=>h.localeCompare(y)),u=[...i].sort((h,y)=>h.localeCompare(y)),p=[...o].sort((h,y)=>h.localeCompare(y)),f=[...new Set(a.map(h=>h.author))].sort((h,y)=>h.localeCompare(y)),_=[...new Set(c.map(h=>h.author))].sort((h,y)=>h.localeCompare(y));return{reconciled_field_count:s.size,reconciled_fields:d,reverted_field_count:i.size,reverted_fields:u,discarded_events:a,discarded_authors:f,preserved_field_count:o.size,preserved_fields:p,preserved_events:c,preserved_authors:_,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function uI(e,t,n,r){let s=e.located?.itemPath??null,o=e.located?await K(e.located,{schema:t.schema}):null;if(!o)return{currentItemReplay:null,currentItemPath:s,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let i=Wt(o.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:i,currentItemPath:s,matchedChainBefore:Le(i,r)===a,currentItemRawBeforeLock:o.raw,loadedItem:o}}function pI(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function fI(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:k(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Fh.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Le(e.finalReplay,e.itemHashVersion),after_hash:Le(n,e.itemHashVersion),message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function _I(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function hI(e){return $s({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Ms({historyPath:e.historyPath,nextHistoryRaw:it(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function wr(e,t,n){let r=E(process.cwd(),n.path);await C(r);let s=await A(r),o=I(s,R()),i=await Ds(r,e,s,o.type_to_folder);if(!await P(i.historyPath))throw new m(`No history stream exists for ${i.id}.`,l.NOT_FOUND);let a=await q(i.historyPath),c=await Tt(i.historyPath,i.id);if(c.length===0)throw new m(`No history entries exist for ${i.id}; nothing to repair.`,l.USAGE);let d=kn(c),u=Ou(c),p=t.normalizeProvenance?qp(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=Pu(p.entries),_=new Set(p.entries.map(V=>V.item_hash_version).filter(V=>V!==void 0)),h=Ps(p.entries,f),y=await uI(i,s,c,f),g=h.finalDocument,b=y.currentItemReplay!==null&&Le(g,f)!==Le(y.currentItemReplay,f),v=b&&y.currentItemReplay?mI(h.entries,g,y.currentItemReplay):void 0,S=[h.entriesRehashed>0,h.entriesPatchRepaired>0,b,t.forceAuditEntry===!0,p.receipt.changed].some(Boolean),x=T(t.author,s.author_default),O=!!t.dryRun,j=pI({message:t.message,entriesRehashed:h.entriesRehashed,entriesPatchRepaired:h.entriesPatchRepaired,reconcileNeeded:b}),{rewrittenEntries:L,auditEntryAdded:Ee}=fI({reanchorEntries:h.entries,changed:S,reconcileNeeded:b,currentItemReplay:y.currentItemReplay,finalReplay:g,author:x,message:j,auditOperation:t.auditOperation??"history_repair",auditContext:p.receipt.changed?{...t.auditContext,provenance_normalization:p.receipt}:t.auditContext,itemHashVersion:f,explicitItemHashVersion:h.explicitItemHashVersion}),X=kn(L);if(!X.ok)throw new m(`history-repair produced an invalid rewritten chain (${X.errors.join(", ")}).`,l.GENERIC_FAILURE);let ie=_I(S,h.skippedOps,v);return S&&!O&&ie.push(...await hI({pmRoot:r,subject:i,settings:s,typeRegistry:o,historyRawBeforeLock:a,currentItemRawBeforeLock:y.currentItemRawBeforeLock,author:x,force:t.force,loadedItem:y.loadedItem,historyPath:i.historyPath,rewrittenEntries:L})),{id:i.id,dry_run:O,changed:S,history:{path:i.historyPath,entries_scanned:c.length,chain_drift_before:!d.ok,entries_rehashed:h.entriesRehashed,entries_patch_repaired:h.entriesPatchRepaired,converted_replace_to_add:h.convertedReplaceToAdd,skipped_ops:h.skippedOps,reconciled_with_item:b,audit_entry_added:Ee,verify_ok:X.ok,verify_errors:X.errors,item_hash_version_before:u.item_hash_version??null,item_hash_version_after:f,version_disposition:_.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:y.currentItemPath!==null,path:y.currentItemPath,matched_chain_before:y.matchedChainBefore},provenance_normalization:{requested:t.normalizeProvenance===!0,...p.receipt},...v?{reconciliation:v}:{},warnings:[...new Set(ie)].sort((V,Ge)=>V.localeCompare(Ge)),generated_at:k()}}function Mh(e,t){if(t&&e!==void 0)throw new m("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",l.USAGE);if(!t&&e===void 0)throw new m("history-repair: provide an item <id> or pass --all to repair every drifted stream.",l.USAGE)}async function Qo(e,t){let n=E(process.cwd(),t.path);await C(n);let r=await A(n),s=I(r,R()),o=[],i=await Ns(n,r.item_format,s.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await pp(n,i),c=e.normalizeProvenance?await Kp(n):[],d=[...new Set([...a.driftedItems,...c])].sort((_,h)=>_.localeCompare(h)),u=[],p=[],f={repaired:0,skipped_clean:0,failed:0};for(let _ of d)try{let h=await wr(_,{...e,auditContext:e.auditContextById?.[_],auditContextById:void 0},t),y=h.changed?"repaired":"skipped_clean";f[y]+=1,p.push(...h.warnings.map(g=>`${_}:${g}`)),u.push({id:_,outcome:y,entries_rehashed:h.history.entries_rehashed,entries_patch_repaired:h.history.entries_patch_repaired,reconciled_with_item:h.history.reconciled_with_item,...h.reconciliation?{reconciliation:h.reconciliation}:{},warnings:h.warnings})}catch(h){f.failed+=1,u.push({id:_,outcome:"failed",error:h instanceof Error?h.message:String(h)})}return e.dryRun||await Ru(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:i.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:u,totals:f,warnings:[...new Set([...o,...p])].sort((_,h)=>_.localeCompare(h)),generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c5620467-6c8c-5702-b742-57fba9e302c5")}catch{}})();async function $h(e,t){let n=e.dryRun===!0,r=await Bp(process.cwd(),{includeLossless:!0}),{pendingDecisions:s}=Hp(r);if(!n&&e.force!==!0&&s.length>0)throw new m(`Merge reconciliation would accept ${s.length} receipt(s) containing discarded scalar values. Review pm merge report and rerun with --force only after deciding which values to retain or re-apply.`,l.CONFLICT,{code:"merge_reconcile_discards_require_acceptance",required:"Explicitly review every discarded field before accepting reconciliation.",nextSteps:s.map(g=>`Review receipt ${g.id} for ${g.item_id}: ${g.decisions.map(b=>b.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let o=r.reduce((g,b)=>((g[b.item_id]??=[]).push(b),g),{}),i=Object.fromEntries(Object.entries(o).map(([g,b])=>[g,{merge:{receipts:b.map(rr)}}])),a=await Qo({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:i},t),c=new Set(a.streams.map(g=>g.id)),d=Object.keys(o).filter(g=>!c.has(g));(await Promise.allSettled(d.map(g=>wr(g,{dryRun:n,author:e.author??t.author,message:e.message??"record field-aware branch merge provenance",force:e.force,auditOperation:"merge_reconcile",auditContext:i[g],forceAuditEntry:!0},t)))).forEach((g,b)=>{let v=d[b];if(g.status==="fulfilled"){let S=g.value.changed?"repaired":"skipped_clean";a.streams.push({id:v,outcome:S,entries_rehashed:g.value.history.entries_rehashed,entries_patch_repaired:g.value.history.entries_patch_repaired,reconciled_with_item:g.value.history.reconciled_with_item,warnings:g.value.warnings}),a.totals[S]+=1}else a.streams.push({id:v,outcome:"failed",error:g.reason instanceof Error?g.reason.message:String(g.reason)}),a.totals.failed+=1});let p=0;!n&&a.totals.failed===0&&(await Promise.all(r.map(g=>Vp(process.cwd(),g))),p=r.length);let f=await so({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),_=f.checks.every(g=>g.status==="ok"),h=a.totals.failed===0&&_,y=n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.","No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:h?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:h,dry_run:n,repair:a,receipts:{pending_before:r.length,reconciled:p,summaries:r.map(rr)},validation:f,guidance:y,generated_at:f.generated_at}}import{createHash as gI}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01043e67-99d4-5b68-a1b2-33f35f5cef5f")}catch{}})();var Gh=1,jh=/^[A-Za-z0-9_-]+$/,yI=100,Dh=1e3;var Aj=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function Ve(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,s)=>r.localeCompare(s));return n.length===0?void 0:n}function bI(e){return gI("sha256").update(Q({type:Ve(e.type),author:Ve(e.author),item:Ve(e.item),harness:Ve(e.harness),agent_instance:Ve(e.agentInstance),provenance:Ve(e.provenanceFilter)})).digest("hex").slice(0,24)}function Uh(e,t){let n={version:Gh,fingerprint:t,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function wI(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Gh,n.fingerprint===t,typeof n.ts=="string",typeof n.stream_id=="string",typeof n.stream_offset=="number",Number.isSafeInteger(n.stream_offset),Number(n.stream_offset)>=0].every(Boolean)}function vI(e,t){let n=e.trim();if(n.length===0||n.length>4096||!jh.test(n))throw new m("Invalid mutation event cursor.",l.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new m("Invalid mutation event cursor.",l.USAGE,{code:"invalid_event_cursor"})}if(!wI(r,t))throw new m("Mutation event cursor does not match this query.",l.USAGE,{code:"event_cursor_query_mismatch"});return r}function kI(e){let t=e??yI;if(!Number.isSafeInteger(t)||t<0||t>Dh)throw new m(`Mutation event limit must be an integer from 0 to ${Dh}.`,l.USAGE,{code:"invalid_event_limit"});return t}function SI(e,t){let n=e?.trim();if(!n)return{};if(jh.test(n))return{cursor:vI(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new m("Mutation event --since must be an event cursor or ISO timestamp.",l.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function EI(e,t){let n=await la(e,t);if(n===null){if(!await Au(e))return{...await Tu(e,t),source:"authoritative_history"};n=await la(e,t)}if(n===null)throw new m("Mutation event index could not be opened after rebuild.",l.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function AI(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new m("Mutation event cursor mode must be batch or row.",l.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Zo(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await C(t);let n=kI(e.limit),r=AI(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new m("Mutation event projections are mutually exclusive. Use --provenance or --full.",l.USAGE);let s=await A(t),o=s.agent_identity.identity_vocabulary,i=np(s.agent_identity.harness_signals),a=rp({provenance:e.provenanceFilter},i),c=Ve(e.harness),d=bI(e),{cursor:u,sinceTimestamp:p}=SI(e.since,d),f={...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:Ve(e.type),authors:Ve(e.author),harnesses:c,harness_alias_authors:c?Object.entries(o.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:Ve(e.agentInstance),provenance:[...a].map(([y,g])=>({dimension:y,values:[...g]})),stream_ids:Ve(e.item),limit:n},_=await EI(t,f),h=_.events.map(y=>({...r==="row"?{cursor:Uh(y,d)}:{},item_id:y.stream_id,version:y.stream_offset+1,ts:y.entry.ts,author:y.entry.author,type:y.entry.op,...y.entry.message===void 0?{}:{message:y.entry.message},patch_count:y.entry.patch.length,...e.full===!0?{entry:y.entry}:{},...e.provenance===!0?{provenance:sp(y.entry,o,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:Uh(_.events[_.events.length-1],d)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:op(_.events.map(y=>y.entry),o,i)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32223457-5f57-5049-99cf-c5d766413fb6")}catch{}})();var TI="1h",CI="now",RI="+1d";function Mt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function qh(e,t,n){return{type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message}}async function Kh(e,t,n,r){let s=qh(e,t,n),o=[];return Mt(o,"start",n.start??CI),n.end!==void 0?Mt(o,"end",n.end):Mt(o,"duration",n.duration??TI),Mt(o,"location",n.location),Mt(o,"timezone",n.timezone),n.allDay===!0&&Mt(o,"all_day","true"),s.event=[o.join(",")],Nt(s,r)}function zh(e,t,n){return Kh("Meeting",e,t,n)}function Bh(e,t,n){return Kh("Event",e,t,n)}function Hh(e,t,n){let r=qh("Reminder",e,t),s=[];return Mt(s,"at",t.at??RI),Mt(s,"text",t.text??e),r.reminder=[s.join(",")],Nt(r,n)}import kr from"node:crypto";import{cp as Wh,lstat as LI,mkdir as dn,readFile as Gn,readdir as Zc,rename as Xh,rm as td,writeFile as ti}from"node:fs/promises";import F from"node:path";import{constants as $t}from"node:os";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1c74b5a9-67b8-597c-98de-a4487691081f")}catch{}})();var Vh=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),II=/^[a-z][a-z0-9_]{0,63}$/u,xI=new Map([[$t.errno.EACCES,"EACCES"],[$t.errno.EDQUOT,"EDQUOT"],[$t.errno.EMFILE,"EMFILE"],[$t.errno.ENFILE,"ENFILE"],[$t.errno.ENOMEM,"ENOMEM"],[$t.errno.ENOSPC,"ENOSPC"],[$t.errno.EPERM,"EPERM"],[$t.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),OI={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function PI(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&Vh.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:xI.get(Math.abs(t.errno))??null}function NI(e,t,n={}){let r=PI(e);if(r===null)return null;if(!II.test(t))throw new m("Host environment operation labels must be bounded identifiers.",l.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let s=Vh.get(r);return new m(`Host filesystem operation ${t} ${s.summary}.`,l.GENERIC_FAILURE,{code:n.codes?.[s.category]??OI[s.category].code,reason:r,required:s.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[s.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function ei(e,t,n={}){try{return await t()}catch(r){throw NI(r,e,n)??r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2580e043-8675-5070-b57e-30cae333228c")}catch{}})();var Qh="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var Zh=F.join("runtime","workspace-snapshots"),FI=new Set(["checkpoints","locks","runtime","search","transactions"]),MI=/^[a-z0-9][a-z0-9._-]*$/,vr="sdk-workspace-transaction",Qc={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},eg={renameEntry:Xh,removeEntry:async e=>{await td(e,{recursive:!0,force:!0})}},ed=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await Gn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==vr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await pe(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
42
+ `)}};async function tg(e,t=""){let n=await Zc(F.join(e,t),{withFileTypes:!0}),r=[];for(let s of n.sort((o,i)=>o.name.localeCompare(i.name))){if(t.length===0&&FI.has(s.name))continue;let o=F.posix.join(t.replaceAll(F.sep,"/"),s.name);if(s.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${o}`);if(s.isDirectory())r.push(...await tg(e,o));else if(s.isFile())r.push(o);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${o}`)}return r}async function ng(e){let t=await tg(e),n=kr.createHash("sha256"),r=[],s=0;for(let i of t){let a=await Gn(F.join(e,i));r.push(a),s+=a.byteLength,n.update(i),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let o=n.digest("hex");return{manifest:{schema:Qh,fingerprint:o,files:t,bytes:s},contents:r}}function Yh(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
43
+ `).filter(t=>t.trim().length>0).length}async function $I(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let s=t.slice(r,r+32),o=await Promise.all(s.map(async i=>[i,await Gn(F.join(e,i))]));for(let[i,a]of o)n.set(i,a)}return n}function nd(e){if(!MI.test(e))throw new m("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",l.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function rg(e,t){return ei(`workspace_snapshot_${e}`,t,{codes:{capacity:Qc.capacity.code,permission:Qc.permission.code,resource:Qc.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function ln(e){return F.join(e,Zh)}function sg(e){return new m(`Unknown workspace snapshot: ${e}`,l.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function og(e,t){try{return JSON.parse(await Gn(e,"utf8"))}catch(n){throw kt(n)?sg(t):n}}async function Jh(e,t,n){try{await td(e,{recursive:n})}catch(r){throw kt(r)?sg(t):r}}async function DI(e,t,n=eg){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function UI(e,t,n,r,s){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await s?.()}catch(o){throw await r.renameEntry(n,t),await r.removeEntry(e),o}await r.removeEntry(n)}async function GI(e,t){return nd(t),/^[a-f0-9]{64}$/.test(t)?t:(await og(F.join(ln(e),"refs",`${t}.json`),t)).fingerprint}async function rd(e,t={}){if(t.name!==void 0&&(nd(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new m("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",l.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await ng(e),s=ln(e),o=F.join(s,"objects",n.fingerprint),i=!1;try{i=(await LI(o)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&kt(a)))throw a}if(!i){let a=F.join(s,"objects",`.create-${process.pid}-${kr.randomUUID()}`);await rg("create_object",async()=>{await dn(F.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let u=F.join(a,"files",d);await dn(F.dirname(u),{recursive:!0}),await ti(u,r[c])}await ti(F.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
44
+ `,"utf8"),await dn(F.dirname(o),{recursive:!0})}),i=await DI(a,o)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=F.join(s,"refs");await dn(c,{recursive:!0});let d=F.join(c,`.ref-${process.pid}-${kr.randomUUID()}`);await ti(d,`${JSON.stringify(a,null,2)}
45
+ `,"utf8"),await Xh(d,F.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function Sr(e,t){let n=await GI(e,t),r=await og(F.join(ln(e),"objects",n,"manifest.json"),t);if(r.schema!==Qh||r.fingerprint!==n)throw new m(`Snapshot manifest identity mismatch: ${t}`,l.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function sd(e){let t=ln(e),n=await Zc(F.join(t,"objects")).catch(s=>{if(s instanceof Error&&"code"in s&&kt(s))return[];throw s}),r=await Zc(F.join(t,"refs")).catch(s=>{if(s instanceof Error&&"code"in s&&kt(s))return[];throw s});return{objects:await Promise.all(n.filter(s=>/^[a-f0-9]{64}$/.test(s)).sort().map(s=>Sr(e,s))),references:await Promise.all(r.filter(s=>s.endsWith(".json")).sort().map(async s=>JSON.parse(await Gn(F.join(t,"refs",s),"utf8"))))}}async function od(e,t){let n=await Sr(e,t),{manifest:r,contents:s}=await ng(e),o=new Map(r.files.map((p,f)=>[p,s[f]])),i=await $I(F.join(ln(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),d=new Set([...a,...c]);for(let p of d){let f=o.get(p),_=i.get(p);f!==void 0&&_!==void 0&&f.equals(_)&&d.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=Yh(o.get(p)),_=Yh(i.get(p));return{path:p,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(p=>p.removed_entries>0).sort((p,f)=>p.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(p=>!c.has(p)).length,added_file_count:[...c].filter(p=>!a.has(p)).length,removed_item_count:[...a].filter(p=>p.endsWith(".toon")&&!c.has(p)).length,affected_history_stream_count:u.length,removed_history_entry_count:u.reduce((p,f)=>p+f.removed_entries,0),affected_history_streams:u,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function ig(e,t,n={}){if(n.force!==!0)throw new m("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",l.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",s=n.lockTtlSeconds??60,o=n.lockWaitMs??5e3,i=await ye(e,vr,s,r,!1,!1,o),a=new ed(Gr(e,vr),r,s);a.start(),await a.refreshNow();let c,d=!1,u=!1;try{let p=await od(e,t),f=await Sr(e,t),_=await rd(e),h=f.fingerprint,y=ln(e),g=F.join(y,"objects",h,"files"),b=F.dirname(e),v=F.basename(e);c=F.join(b,`.${v}.restore-${kr.randomUUID()}`);let S=F.join(b,`.${v}.backup-${kr.randomUUID()}`);await rg("restore_stage",async()=>{await dn(c,{recursive:!0}),await Wh(g,c,{recursive:!0,force:!1}),await dn(F.join(c,"runtime"),{recursive:!0}),await Wh(y,F.join(c,Zh),{recursive:!0,force:!1})});let x=await Nu({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:p.changed_file_count,removed_file_count:p.removed_file_count,removed_item_count:p.removed_item_count,affected_history_stream_count:p.affected_history_stream_count,removed_history_entry_count:p.removed_history_entry_count},lockTtlSeconds:s,lockWaitMs:o}),O=F.relative(c,x.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let j=Gr(c,vr);return await dn(F.dirname(j),{recursive:!0}),await ti(j,await Gn(Gr(e,vr)),{flag:"wx"}),d=!0,await UI(c,e,S,eg,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:O,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!d&&await Promise.allSettled([td(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function ag(e,t){nd(t);let n=ln(e);if(!/^[a-f0-9]{64}$/.test(t))return await Jh(F.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await sd(e);if(r.some(s=>s.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Jh(F.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0492d773-2af2-5072-8164-9f8aab536191")}catch{}})();function Er(e){return{...e.args,...e.options}}function ut(e,t){let n=w(e,t);if(n!==void 0)return n;throw new m(`Missing required parameter: ${t}`,l.USAGE)}function jn(e){return typeof e=="string"?[e]:we(e)}function cg(e){return Sh(Er(e),e.global)}function dg(e){let t=Er(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new m("Mutation event cursor mode must be batch or row.",l.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Zo({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:jn(t.type),author:jn(t.author),item:jn(t.item),limit:t.limit===void 0?void 0:Me(t.limit,"limit"),full:t.full===!0,cursorMode:r,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:jn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:jn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:jn(t.provenanceFilter)}})}function lg(e){let t=Er(e),n=ut(t,"subcommand");if(n==="install")return Ep({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return $h({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return Wp({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return Ph({artifact:ut(t,"artifact"),basePath:ut(t,"basePath"),oursPath:ut(t,"oursPath"),theirsPath:ut(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw Re({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function mg(e){let t=Er(e),n=ut(t,"subcommand");if(n!=="snapshot")throw Re({command_path:"workspace",token:n,allowed:["snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??ut(t,"snapshot_action"),s=E(process.cwd(),e.global.path);if(r==="create")return rd(s,{name:w(t,"name")});if(r==="list")return sd(s);let o=ut(t,"target");if(r==="inspect")return Sr(s,o);if(r==="delete")return ag(s,o);if(r==="restore")return t.dryRun===!0?od(s,o):ig(s,o,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Me(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Me(t.lockWaitMs,"lockWaitMs")});throw Re({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function ni(e){let t=Er(e),n=ut(t,"title");return e.action==="meet"?zh(n,t,e.global):e.action==="event"?Bh(n,t,e.global):Hh(n,t,e.global)}import ZI from"node:path";import jI from"node:fs/promises";import ug from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5c70da27-21f6-5d31-b506-96e1818996d6")}catch{}})();var qI="templates",KI=".json",zI=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,BI=Ss.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),HI=new Set(BI);function VI(e){let t=e.trim();if(!zI.test(t))throw new m(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,l.USAGE);return t}function pg(e){return ug.join(e,qI)}function fg(e,t){return ug.join(pg(e),`${t}${KI}`)}async function WI(e){await C(e)}function _g(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function YI(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(HI.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let s=r.filter(o=>typeof o=="string");s.length>0&&(t[n]=s);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(s=>typeof s=="string")&&(t[n]=[...r])}return _g(t)}function JI(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new m(`Template "${t}" has invalid options payload.`,l.GENERIC_FAILURE);let n=e,r={};for(let[s,o]of Object.entries(n)){let i=s.trim();if(i.length===0)throw new m(`Template "${t}" contains an empty option key.`,l.GENERIC_FAILURE);if(typeof o=="string"){r[i]=o;continue}if(Array.isArray(o)&&o.every(a=>typeof a=="string")){r[i]=[...o];continue}throw new m(`Template "${t}" contains invalid value for option "${i}".`,l.GENERIC_FAILURE)}return _g(r)}function XI(e,t){let n;try{n=JSON.parse(e)}catch{throw new m(`Template "${t}" contains invalid JSON.`,l.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new m(`Template "${t}" has invalid document shape.`,l.GENERIC_FAILURE);let r=n,s=JI(r.options,t),o=k();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:o,updated_at:typeof r.updated_at=="string"?r.updated_at:o,options:s}}async function QI(e,t){let n=await q(fg(e,t));if(n===null)throw new m(`Template "${t}" not found`,l.NOT_FOUND);return XI(n,t)}async function id(e,t,n){let r=E(process.cwd(),n.path);await WI(r);let s=VI(e),o=YI(t);if(Object.keys(o).length===0)throw new m("templates save requires at least one create option flag",l.USAGE);let i=k(),a=fg(r,s),c=i;await P(a)&&(c=(await QI(r,s)).created_at);let d={name:s,created_at:c,updated_at:i,options:o},u=await A(r);return await jI.mkdir(pg(r),{recursive:!0}),await Rt({pmRoot:r,filePath:a,raw:`${JSON.stringify(d,null,2)}
46
+ `,op:"templates:save",author:T(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:d.name,created_at:d.created_at,updated_at:d.updated_at,path:a,options:d.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f65b4f1f-5501-5829-a04b-d4fbcfb59f5c")}catch{}})();var bg=["list","show","apply","lint"],ex="schema-types",tx="schema-statuses",nx="schema-fields";function ri(){let e=R();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function wg(){let{profiles:e,warnings:t}=Tm(ri());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:Om(n.definition)})),warnings:t,generated_at:k()}}function vg(e){let t;try{t=ys(e,ri())}catch(r){throw new m(r instanceof Error?r.message:String(r),l.USAGE)}let{resolved:n}=t;return{action:"show",...Pm(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function kg(e){let t;try{t=ys(e,ri())}catch(s){throw new m(s instanceof Error?s.message:String(s),l.USAGE)}let{resolved:n}=t,r=Jm(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:k()}}function rx(e,t){return ZI.join(e,"templates",`${t}.json`)}async function sx(e,t){let n=await q(rx(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let s=r.options;if(s!==null&&typeof s=="object"&&!Array.isArray(s))return s}}catch{}}async function hg(e,t,n,r){let s=new Map;for(let o of r.templates){let i=await sx(e,o.name);i!==void 0&&s.set(o.name,i)}return{typesRaw:await q(ot(e,t.files.types,st.types)),statusesRaw:await q(ot(e,t.files.statuses,st.statuses)),fieldsRaw:await q(ot(e,t.files.fields,st.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:s,installedPackages:new Set}}function qn(e){let t=[],n=[],r=[];for(let s of e)(s.status==="add"?t:s.status==="update"?n:r).push(s.key);return{added:t,updated:n,unchanged:r}}function gg(e,t,n,r,s){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:qn(t.types.changes),statuses:qn(t.statuses.changes),fields:qn(t.fields.changes),workflows:qn(t.workflows.changes.map(o=>({key:o.type,status:o.status}))),config:qn(t.config.changes),templates:qn(t.templates.changes.map(o=>({key:o.name,status:o.status}))),packages:t.packages,warnings:[...new Set(s)].sort((o,i)=>o.localeCompare(i)),generated_at:k()}}async function ox(e){await C(e)}function ix(e){try{let t=ys(e,ri());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new m(t instanceof Error?t.message:String(t),l.USAGE)}}async function Sg(e,t,n){let r=E(process.cwd(),n.path);await ox(r);let s=ix(e),o=s.profile,i=s.warnings,a=t.dryRun===!0,c=await A(r),d=bs(c.schema);if(a){let b=await hg(r,d,c,o),v=yg(o,b);return gg(o,v,!1,!0,[...i])}let u=T(t.author,c.author_default),p=Fu(c),f=!!t.force,_=[...i],h=[],y=async b=>{h.push(await ye(r,b,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(ex),await y(tx),await y(nx);let b=await hg(r,d,c,o);if(g=yg(o,b),g.types.changed){let v=ot(r,d.files.types,st.types);await Rt({pmRoot:r,filePath:v,raw:gs(g.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(o.types.map(O=>wm(O).name)),x=g.types.file.definitions.filter(O=>S.has(O.name));await xp(r,x,_,"profile:apply-type-folder"),_.push(...await z({path:v,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let v=ot(r,d.files.statuses,st.statuses);await Rt({pmRoot:r,filePath:v,raw:xm(g.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let v=ot(r,d.files.fields,st.fields);await Rt({pmRoot:r,filePath:v,raw:Cm(g.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let v of g.config.changes){if(v.status==="unchanged")continue;let S=vs(v.key);S!==void 0&&ks(c,S,v.value)}c.schema.type_workflows=g.workflows.result,await Ce(r,c,"profile:apply-config")}for(let v of g.templates.changes)v.status!=="unchanged"&&await id(v.name,{...v.options},n)}finally{for(let b of h.reverse())try{await b()}catch{}}return gg(o,g,g.changed,!1,_)}function yg(e,t){try{return Xm(e,t)}catch(n){throw new m(n instanceof Error?n.message:String(n),l.USAGE)}}import Ag from"node:fs/promises";import Tg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7e0f84f6-9528-55c5-8976-6f85cd920486")}catch{}})();function ax(e,t,n){let r=new Set,s=[];for(let o of e){let i=o.trim();if(i.length===0||r.has(i))continue;r.add(i);let a=t.get(i);if(a===void 0){s.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){s.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}s.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return s}function cx(e,t){let n=[...e].sort((s,o)=>o.entries-s.entries||s.id.localeCompare(o.id)),r=[];for(let s of n){if(t.scope==="closed"&&s.bucket!=="closed"){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(s.entries<=t.minEntries){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&s.entries<=t.allOver){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:s.id,entries:s.entries,selected:!0,skip_reason:null})}return r}function Eg(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return ax(t.ids,n,t.minEntries)}return cx(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="adcf4d1b-689d-52cb-903b-5fba857707f3")}catch{}})();function dx(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new m("history-compact --before requires a non-empty value.",l.USAGE);if(/^\d+$/.test(n)){let o=Number.parseInt(n,10);if(!Number.isSafeInteger(o)||o<1||o>t.length+1)throw new m(`history-compact --before version must be between 1 and ${t.length+1}.`,l.USAGE);let i=Math.max(0,Math.min(t.length,o-1));return{kind:"version",raw:n,compactCount:i,retainedCount:t.length-i}}let r=Date.parse(n);if(!Number.isFinite(r))throw new m(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,l.USAGE);let s=0;for(let[o,i]of t.entries()){let a=Date.parse(i.ts);if(!Number.isFinite(a))throw new m(`History for this item contains invalid timestamp at entry ${o+1}.`,l.GENERIC_FAILURE);if(a>=r)break;s+=1}return{kind:"timestamp",raw:n,compactCount:s,retainedCount:t.length-s}}function lx(e,t){let n=Os(),r=Os();for(let s=0;s<e.length;s+=1){let o=e[s];if(Le(n)!==o.before_hash)throw new m(`history-compact detected before-hash drift at entry ${s+1}; run pm history-repair first.`,l.CONFLICT);if(n=Fs(n,o.patch,s+1,o.op),Le(n)!==o.after_hash)throw new m(`history-compact detected after-hash drift at entry ${s+1}; run pm history-repair first.`,l.CONFLICT);s+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function mx(e,t,n){let r=structuredClone(t),s=[];for(let[o,i]of e.entries()){let a=Le(r);r=Fs(r,i.patch,n+o+1,i.op),s.push({...i,before_hash:a,after_hash:Le(r)})}return{entries:s,finalReplay:r}}async function ux(e,t,n){let r=e.located?await K(e.located,{schema:t.schema}):null;return r?{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:Le(Wt(r.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function px(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function fx(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function _x(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=lx(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),s=mx(r,t,e.boundary.compactCount),i=[Ke({nowIso:k(),author:e.author,op:"history_compact_baseline",before:Vt(Os()),after:Vt(t),message:fx(e.boundary)}),...s.entries];return e.dryRun||i.push(Ke({nowIso:k(),author:e.author,op:"history_compact",before:Vt(n),after:Vt(n),message:px(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function hx(e){return $s({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-compact",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Ms({historyPath:e.historyPath,nextHistoryRaw:it(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function ad(e,t,n){let r=E(process.cwd(),n.path);await C(r);let s=await A(r),o=I(s,R()),i=await Ds(r,e,s,o.type_to_folder),a=i.historyPath,c=await q(a);if(c===null)throw new m(`No history stream exists for ${i.id}.`,l.NOT_FOUND);let d=await Tt(a,i.id);if(d.length===0)throw new m(`No history entries exist for ${i.id}; nothing to compact.`,l.USAGE);let u=kn(d);if(!u.ok)throw new m(`history-compact requires a valid history chain (${u.errors.join(", ")}). Run pm history-repair ${i.id} first.`,l.CONFLICT);let p=dx(t.before,d),f=p.compactCount>0,_=!!t.dryRun,h=T(t.author,s.author_default),y=[];f||y.push("history_compact_noop_before_boundary");let g=await ux(i,s,d);g.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:S}=_x({historyEntries:d,boundary:p,changed:f,dryRun:_,author:h,options:t}),x=kn(b);if(!x.ok)throw new m(`history-compact produced an invalid rewritten chain (${x.errors.join(", ")}).`,l.GENERIC_FAILURE);f&&!_&&y.push(...await hx({pmRoot:r,subject:i,settings:s,typeRegistry:o,historyRawBeforeLock:c,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:h,force:t.force,loadedItem:g.loadedItem,historyPath:a,rewrittenEntries:b}));let O=p.retainedCount>0?p.compactCount+1:null;return{id:i.id,dry_run:_,changed:f,compact_boundary:{kind:p.kind,before:p.raw,entries_compacted:p.compactCount,entries_retained:p.retainedCount,first_retained_entry:O},history:{path:a,entries_scanned:d.length,entries_after:b.length,baseline_entry_added:v,audit_entry_added:S,verify_ok:x.ok,verify_errors:x.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:g.matchedChainBefore},warnings:[...new Set(y)].sort((j,L)=>j.localeCompare(L)),generated_at:k()}}var gx=3;function Cg(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new m("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",l.USAGE);if(e!==void 0&&(n||r))throw new m("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",l.USAGE);if(n&&r)throw new m("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",l.USAGE)}function yx(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function bx(e){let t=$(e.settings.schema),n=oo(t),r=await ae(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),s=new Map(r.map(d=>[d.id,n.classify(d.status)])),o=Tg.join(e.pmRoot,"history"),i=[],a=[];if(!await P(o))return{candidates:i,preselectionErrors:a};let c=(await Ag.readdir(o)).filter(d=>d.endsWith(".jsonl")).sort((d,u)=>d.localeCompare(u));for(let d of c){let u=Tg.join(o,d),p=d.slice(0,-6);try{let f=await Ag.readFile(u,"utf8");await yn({path:u,scope:"project"}),i.push({id:p,entries:yx(f),bucket:s.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:i,preselectionErrors:a}}async function wx(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await ad(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function Rg(e,t){let n=E(process.cwd(),t.path);await C(n);let r=await A(n),s=I(r,R()),{candidates:o,preselectionErrors:i}=await bx({pmRoot:n,settings:r,typeToFolder:s.type_to_folder}),a=e.ids!==void 0&&e.ids.length>0?"ids":"scan",c=e.minEntries??gx,d=r.history.compact_policy,u=a==="scan"&&e.allOver===void 0&&d.enabled,p=e.allOver??(u?d.max_entries:void 0),f=Eg(o,{ids:e.ids,scope:e.scope,minEntries:c,allOver:p}),_=!!e.dryRun,h=[...i],y={streams_considered:o.length+i.length,selected:0,items_compacted:0,items_skipped:0,items_errored:i.length};for(let g of f){let b=await wx({row:g,options:e,dryRun:_,global:t});if(h.push(b.result),!b.selected){y.items_skipped+=1;continue}y.selected+=1,b.compacted&&(y.items_compacted+=1),b.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:_,mode:a,scope:e.scope??null,criteria:{min_entries:c,all_over:p??null,policy_threshold_applied:u},totals:y,results:h,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f762b5e6-8224-531f-9dd1-f71dc18c3ddf")}catch{}})();function Ig(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return Mh(n,t),t?Qo(e.options,e.global):wr(n,e.options,e.global)}function xg(e){let t=e.options.ids,n=Array.isArray(t)?t.map(String).filter(d=>d.trim().length>0):typeof t=="string"?t.split(",").map(d=>d.trim()).filter(Boolean):void 0,r=Me(e.options.allOver??e.options.all_over,"history-compact allOver"),s=Me(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),o=w(e.options,"scope"),i=[];e.options.closed===!0&&i.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&i.push("all-streams"),(o==="closed"||o==="all-streams")&&i.push(o);let a=[...new Set(i)];if(a.length>1)throw new m("history-compact: closed and all-streams scopes are mutually exclusive.",l.USAGE);let c=a[0];return Cg(e.id,{ids:n,allOver:r,scope:c}),e.id!==void 0?ad(e.id,{before:w(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global):Rg({ids:n,scope:c,allOver:r,minEntries:s,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function si(e){return ws("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08dcee99-5572-5133-b76a-6a50e4e292e7")}catch{}})();async function cd(e,t,n,r){let s=t.trim();if(s.length===0)throw new m("pm item reopen requires a non-empty recurrence reason.",l.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let o=E(process.cwd(),r.path),i=$((await A(o)).schema),a=i.open_status,c=si(i),d=n.status??a,u=Y(d,i)??d;if(u!==a&&u!==c)throw new m(`Reopen target status must be ${a} or ${c}; received ${d}.`,l.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([a,c])],suggested_retry:`pm item reopen ${e} "${s}" --status ${a}`,suggested_retry_args:["item","reopen",e,s,"--status",a]}});let p=await k_(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,s);return{item:p.item,changed_fields:p.changed_fields,warnings:p.warnings,recurrence:p.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="55869854-565d-52d2-8dca-b66aade074bb")}catch{}})();function Og(e,t){let n=e.id??w(t,"id");if(!n)throw new m("Missing required argument: id",64);return n}function Pg(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function Ng(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return je(await ct(Og(e,r),Pg(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Lg(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return je(await cd(Og(e,r),Pg(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2ef0de1-bc44-5550-862c-f3929334fbef")}catch{}})();function Fg(e,t,n){let r;if(typeof e.lines=="string")r=to(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");r=to(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="90896fb6-ee3e-575d-b103-bbc1a83c6672")}catch{}})();var vx=ea("list").properties.outputSession,kx={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...vx},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Mg={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},re={type:"string",description:"pm item id, for example pm-abc1."},Sx=`Operation name (one of): ${Ji.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,Ex={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},Ax={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function U(e,t=[]){return{...Mg,properties:{...Mg.properties,...e},required:t}}var Tx=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:U({action:{type:"string",enum:[...Ji],description:Sx},id:re,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...kx},["action"])},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:U({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:U({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid, options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:U({query:{type:"string"},options:{type:"object"},...Ax},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:U({options:{type:"object"},...Ex})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:U({id:re,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:U({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:U({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:re,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:re,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:U({id:re,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:U({id:re,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:re,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:U({id:re,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:U({id:re,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:re,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:U({id:re,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:U({id:re,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:U({id:re,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List or add structured notes on a pm item. Use options.add to append a note; omit it to list existing notes.",inputSchema:U({id:re,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List or add learnings on a pm item. Use options.add to capture a learning/insight; omit it to list existing learnings.",inputSchema:U({id:re,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:U({id:re,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:U({subcommand:{type:"string",enum:[...Km]},id:re,target:re,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:U({id:re,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:U({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:U({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:U({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Schema mutations write workspace config files, not item history.",inputSchema:U({subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset"],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or custom field key (show-field/add-field/remove-field). Required for those subcommands."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...Ni]},description:`Lifecycle roles for add-status: ${Ni.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys."}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:U({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:U({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:U({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],Cx={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},Rx=Tx.map(e=>{let t=Cx[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:ea(t,{properties:n,required:r})}});function $g(){return Rx.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,s)=>r.localeCompare(s)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e8f1efca-4e83-570f-8c33-96f0405035b0")}catch{}})();var Dg=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),Ix=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Wg=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ii=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),Ar=new Set(["cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),Yg=new Map([["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),Jg=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),Xg=new Map([...Jg.entries()].flatMap(([e,t])=>pt(t).map(n=>[n,e]))),Qg=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],Zg=new Map(Qg.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),xx=10,Ox=20,Ug=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate work through typed operations."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage portable workspace primitives."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),ey=[["init",Nl],["install",Fl],["uninstall",Ml],["explore",$l],["manage",Kl],["describe",Dl],["reload",zl],["doctor",Bl],["catalog",Hl],["adopt",Vl],["adopt-all",Ul],["activate",Gl],["deactivate",jl],["migrate",ql]],Px=ey.map(([e,t])=>e==="init"?[e,Ll]:[e,t]),Nx=[...ey.map(([e,t])=>[`extension ${e}`,t]),...Px.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Jr],["config",Pl],["extension",Xr],["package",Wn],["packages",Wn],["install",Wl],["create",rs],["item mutate",fm],["item complete",_m],["item reopen",hm],["copy",ss],["focus",os],["update",is],["update-many",as],["upgrade",Yl],["calendar",Yn],["cal",Yn],["context",Jn],["ctx",Jn],["get",ds],["search",fs],["eval",ym],["workspace",St],["workspace snapshot",St],["workspace snapshot create",St],["workspace snapshot list",St],["workspace snapshot inspect",St],["workspace snapshot restore",St],["workspace snapshot delete",St],["next",ps],["aggregate",Hr],["deps",ms],["graph",us],["guide",ls],["reindex",Jl],["history",Vr],["history-compact",Il],["history-redact",Cl],["history-repair",Rl],["history-author-acknowledge",Wr],["merge",Tl],["schema",xl],["profile",Ol],["plan",Yr],["restore",Zl],["delete",em],["close",Xl],["close-many",Qr],["append",Zr],["claim",Ql],["release",tm],["start-task",nm],["pause-task",rm],["close-task",sm],["comments",vl],["notes",kl],["learnings",Sl],["files",El],["docs",Al],["test",am],["test-all",cm],["telemetry",dm],["test-runs",lm],["gc",mm],["stats",es],["duplicates",ts],["validate",um],["health",ns],["assurance",pm],...bm,["contracts",_s],["completion",hs],["activity",cs],...[...Wg].map(e=>[e,Br])],ud=new Map(Nx);function Lx(e){let t=Xg.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Gg(e){return Wi.includes(e)?_e(e):e.startsWith("extension-")?_e(`extension ${e.slice(10)}`):e.startsWith("package-")?_e(`package ${e.slice(8)}`):e.startsWith("item-")?_e(`item ${e.slice(5)}`):e.startsWith("test-runs-")?_e(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?_e(`templates ${e.slice(10)}`):ii.has(e)?Jg.get(e)??_e(e):null}function Fx(e,t){return e.command_path===null?!1:pt(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `)||t.startsWith(`${n} `))}function pt(e){return e.split("|").map(t=>_e(t)).filter(t=>t.length>0)}function Mx(e,t){let n=new Set(t),r=new Set;for(let s of e)if(s.command_path)for(let o of pt(s.command_path)){let i=o.split(" ").filter(a=>a.length>0);if(i.length!==0)for(let a=i.length;a>0;a-=1){let c=i.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((s,o)=>s.localeCompare(o))}function oi(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Tr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function $x(e,t){if(!t)return{...e};let r=Tr(e).filter(s=>{let o=s.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:r}}function dd(e,t){let r=Tr(e).filter(s=>{let o=s.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function _e(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function ty(e){return e.replace(/\s+/g,"-")}function Qe(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function jg(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=Qe(r);!s||n.has(s)||(n.add(s),t.push(s))}return t}function ld(e,t,n){n&&(e[t]=!0)}function qg(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function Dx(e){let t=qg(e.long,"long"),n=qg(e.short,"short"),r=t??n;if(!r)return null;let s={flag:r};n&&t&&(s.short=n),ld(s,"required",e.required===!0),ld(s,"repeatable",e.repeatable===!0),ld(s,"list",e.list===!0);let o=Qe(e.description);o&&(s.description=o);let i=Qe(e.value_name);i&&(s.value_name=i);let a=[Qe(e.value_type),Qe(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(s.value_type=a),s}function ny(e){let t=new Map;for(let r of e){let s=_e(r.target_command);if(s.length===0)continue;let o=t.get(s)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;o.sourceDedupe.has(i)||(o.sourceDedupe.add(i),o.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=Dx(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;o.dedupe.has(d)||(o.dedupe.add(d),o.flags.push(c))}t.set(s,o)}let n=new Map;for(let[r,s]of t.entries())n.set(r,{flags:s.flags,sources:s.sources.sort((o,i)=>{let a=o.layer.localeCompare(i.layer);return a!==0?a:(o.name??"").localeCompare(i.name??"")})});return n}function Ux(e){let t=ny(e.flagRegistrations),n=new Map;for(let o of e.commandDefinitions){let i=_e(o.command);if(i.length===0)continue;let a=Qe(o.action)??ty(i),c=Array.isArray(o.arguments)?o.arguments.map(d=>{let u=Qe(d.name);return u?{name:u,required:d.required===!0,variadic:d.variadic===!0,description:Qe(d.description)}:null}).filter(d=>d!==null):[];n.set(i,{command:i,action:a,source:{layer:o.layer,name:o.name},description:Qe(o.description),intent:Qe(o.intent),arguments:c,flags:t.get(i)?.flags??[],examples:jg(o.examples),failure_hints:jg(o.failure_hints)})}let r=new Set;for(let o of e.handlers)r.add(_e(o));for(let o of n.keys())r.add(o);for(let o of t.keys())r.add(o);let s=[];for(let o of[...r].sort((i,a)=>i.localeCompare(a))){let i=n.get(o);s.push(Gx(o,i,t.get(o)?.flags??[]))}return s}function Gx(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:ty(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function jx(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(s,o)=>o.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function qx(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function Kx(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",s=e.repeatable===!0||e.list===!0;return{type:s?"array":r,...s?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function zx(e){let t=e.command.split("|").map(s=>s.trim()).filter(s=>s.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let s of e.arguments)n[s.name]=qx(s,e.action),s.required&&r.push(s.name);for(let s of e.flags){let o=jx(s);!o||n[o]!==void 0||(n[o]=Kx(s,e.action),s.required===!0&&r.push(o))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function Bx(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function Hx(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((o,i)=>o.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let s=new Set(r.flags.map(o=>`${o.flag}|${o.short??""}`));for(let o of n.flags){let i=`${o.flag}|${o.short??""}`;if(!s.has(i))s.add(i),r.flags.push(o);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);a&&Bx(a,o)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function Vx(e,t=A){let n={mode:wt.extensions.policy.mode,trust_mode:wt.extensions.policy.trust_mode,default_sandbox_profile:wt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await P(ge(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let s=await t(r),o=await qr({pmRoot:r,settings:s,cwd:process.cwd(),noExtensions:!1}),i=await Kr({...o,loaded:o.loaded});return{handlers:new Set(i.commands.handlers.map(c=>_e(c.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:o.policy.mode,trust_mode:o.policy.trust_mode,default_sandbox_profile:o.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function Wx(e,t={}){let n=new Map;for(let r of Yi){let s=ii.has(r);if(s&&!t.includePackageOwnedActions)continue;let o=Gg(r);n.set(r,{action:r,provider:s?"extension":"core",requires_extension:s,command_path:o})}if(t.includePackageOwnedActions)for(let r of ii)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Gg(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:_e(r.command)});return[...n.values()].sort((r,s)=>(r.action??"").localeCompare(s.action??""))}function Yx(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null};let n=e.command_path?pt(e.command_path):[],r=n.some(i=>t.handlers.has(i)),s=n.map(i=>Yg.get(i)).find(i=>typeof i=="string"),o=t.disabledReason===null&&r;return{action:e.action,invocable:o,available:o,requires_extension:!0,provider:"extension",disabled_reason:o?null:t.disabledReason??(s?`optional_package_not_installed:${s}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function ry(e){return ud.get(e)??zr}function Jx(e){return Ar.has(e)?!1:ud.has(e)}function Xx(e){return Wg.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Kg(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function Qx(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function Zx(e){let t=new Map;for(let r of e.definitions){let s=Kg(r.cli_flag);if(!s)continue;let o=r.cli_aliases.map(a=>Qx(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>Kg(a)).filter(a=>a!==null&&a!==s);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},d=o?{flag:s,short:o}:{flag:s},u=`${d.flag}|${d.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(d));for(let p of i){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,s]of t.entries())n.set(r,Bi(s.flags));return n}function zg(e,t){let n=[],r=new Set;for(let s of[...e,...t]){let o=`${s.flag}|${s.short??""}`;r.has(o)||(r.add(o),n.push(s))}return Bi(n)}function eO(e,t,n,r){return e.map(s=>{let o=Jx(s),i=o?ry(s):[],a=n.get(Xx(s))??[],c=t.get(s),d=zg(i,a),u=zg(d,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":o?"core":"extension";return{command:s,flags:u,...r?{canonical_command:md(s),visibility:cu(md(s)),positionals:yl(s)?.slots??[],flag_invocations:au(s,u)}:{},provider:p,extension_sources:c?.sources}}).sort((s,o)=>s.command.localeCompare(o.command))}function tO(e,t=Xn){let n=new Set(e),r=new Map;for(let s of Qg){let o=s.aliases.filter(i=>n.has(i));r.set(s.canonical,{canonical:s.canonical,aliases:o,contracts:[]})}for(let s of t){if(!n.has(s.canonical)||s.registration==="commander"&&!n.has(s.alias))continue;let o=r.get(s.canonical)??{canonical:s.canonical,aliases:[],contracts:[]};o.aliases.includes(s.alias)||o.aliases.push(s.alias),o.contracts.push(s),r.set(s.canonical,o)}return[...r.values()].map(({contracts:s,...o})=>s.length===0?o:{...o,contracts:s}).sort((s,o)=>s.canonical.localeCompare(o.canonical))}function nO(){return{create_string_options:Qm,create_repeatable_options:Ss,update_string_options:Zm,update_repeatable_options:eu,list_string_options:pl,search_string_options:fl,calendar_string_options:_l,context_string_options:hl,activity_string_options:gl}}function Bg(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=fn(e,"create",n),s=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),o=[...new Set(s.map(a=>he("create",a)))].sort((a,c)=>a.localeCompare(c)),i=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:s,required_flags:o,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function rO(e){let t={},n={};for(let r of[...e.types].sort((s,o)=>s.localeCompare(o))){let s=e.by_type[r];t[r]=Bg(s,"strict"),n[r]=Bg(s,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function sO(e,t){let n=Tr(e);if(n.length===0)return e;let r=!1,s=n.map(o=>{let i=o.properties;if(typeof i!="object"||i===null)return o;let a=i.action;return typeof a!="object"||a===null||a.const!=="create"?o:(r=!0,{...o,"x-create-required-options":t})});return r?{...e,oneOf:s}:e}function oO(e){let t=oi(e.action)!==void 0||oi(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,s=e.schemaOnly===!0,o=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=oi(e.action),u=oi(e.command),p=!r&&!c&&!s&&!o&&!i&&!d&&!u;return{selectedAction:d,selectedCommand:u,summary:r,schemaOnly:s,flagsOnly:o,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function iO(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new m("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",l.USAGE)}async function aO(e,t=A){try{return await t(e)}catch{return structuredClone(wt)}}async function cO(e,t){let n=await aO(t),r=await Vx(e),s=I(n,r.registrations??R()),o=Ye(n.schema),i=Ux(r);return{settings:n,runtimeProbe:r,typeRegistry:s,statusRegistry:$(n.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:Zx(o),createRequiredOptionContracts:rO(s),extensionContracts:i,mergedExtensionContracts:Hx(i),extensionFlagMap:ny(r.flagRegistrations)}}function Hg(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ii.has(e.selectedAction)||e.selectedCommand!==void 0&&Ar.has(e.selectedCommand))}function dO(e,t){let n=Wx(t,{includePackageOwnedActions:Hg(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Bm);return n.filter(s=>!r.has(s.action))}return Hg(e)&&e.selectedCommand!==void 0&&Ar.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:Lx(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function lO(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new m(`Unknown action: "${e.selectedAction}".`,l.USAGE)}function mO(e,t){return[...new Set([...Wi.filter(n=>!Ar.has(n)),...[...ud.keys()].filter(n=>!Ar.has(n)),...e.flatMap(n=>n.command_path?pt(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>_e(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function uO(e,t){let n=t.slice(0,xx),r=t.length-n.length,s=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),o=t.slice(0,Ox),i=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new m(`Command "${e}" is a command namespace. Choose a concrete child command: ${s}.`,l.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:i,nextSteps:[`Retry with a child command, for example: ${i[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:o.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function pO(e,t){return new m(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,l.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function fO(e){return new m(`Unknown command: "${e}".`,l.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function _O(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(o=>o.startsWith(`${e.selectedCommand} `));if(r.length>0)throw uO(e.selectedCommand,r);let s=Yg.get(e.selectedCommand);throw s?pO(e.selectedCommand,s):fO(e.selectedCommand)}function hO(e,t){let n=dO(e,t.mergedExtensionContracts);lO(e,n);let r=mO(n,t.mergedExtensionContracts);_O(e,r);let s=e.selectedCommand?Xg.get(e.selectedCommand):void 0,o=e.selectedCommand?n.filter(d=>s?d.action===s:Fx(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!o.some(d=>d.action===e.selectedAction))throw new m(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,l.USAGE);let i=e.selectedAction?o.filter(d=>d.action===e.selectedAction):o,a=[...new Map(i.map(d=>Yx(d,t.runtimeProbe)).map(d=>[s?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:o,scopedActionDescriptors:i,selectedPackageOwnedAction:s,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function gO(e){return new Set(Tr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let s=r.const;return typeof s=="string"?s:null}).filter(t=>t!==null))}function yO(e){let t=Ym,n=Tr(t),r=gO(t),s=e.filter(o=>!r.has(o.action)).map(o=>zx(o));return s.length>0?{...t,oneOf:[...n,...s]}:t}function Vg(e,t,n){let r=new Set(t.actionDescriptors.map(o=>o.action)),s=e.selectedAction?$x(n,e.selectedAction):e.selectedCommand?dd(n,new Set(t.scopedActionDescriptors.map(o=>o.action))):dd(n,r);return e.runtimeOnly&&!e.selectedAction?dd(s,new Set(t.actions)):s}function bO(e,t,n){let r=yO(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?sO(Vg(e,n,r),t.createRequiredOptionContracts):Vg(e,n,r);return{mergedSchema:r,filteredSchema:o}}function wO(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?Mx(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function vO(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Xn.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function md(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":Zg.get(t)??t}var kO=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"]]),SO=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function EO(e,t){let n=Ug.get(e)??(e.includes(" ")?void 0:Ug.get(md(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>pt(d.command).includes(e));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let s=e.split(" "),o=s.at(-1),i=s.slice(0,-1).join(" "),a=kO.get(o),c=SO.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function AO(e,t=[],n={}){let r=n.includeFormatBudgets??!0,s=n.includeIntentProvenance??!0;return[...new Set(e.map(_e))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i)).map(o=>{let i=Xi(o,{generateFallback:!0}),a=o.split(" ")[0],c=Zg.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...ry(o).map(f=>f.flag),...t.filter(f=>pt(f.command).includes(o)).flatMap(f=>f.flags.map(_=>_.flag))]),u=(Dg.get(o)??Dg.get(c)??Ix).filter(f=>d.has(f)),p=EO(o,t);return{command:o,intent:p.intent,...s||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:i.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...i.default_max_estimated_tokens_by_format}}:{}}})}function TO(e){return e.map(t=>({budget:Xi(t,{generateFallback:!0}),envelope:lu(t)}))}function CO(e){let t=new Map;for(let n of e){let r=nu(n),s=r===void 0?[l.SUCCESS,l.GENERIC_FAILURE,l.USAGE,l.NOT_FOUND,l.CONFLICT,l.DEPENDENCY_FAILED]:r.exit_codes,o=s.join(","),i=t.get(o)??{commands:[],exit_codes:s};i.commands.push(n),t.set(o,i)}return[...t.values()]}function RO(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>pt(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(s=>pt(s.command).some(o=>r.has(o)))}return t.extensionContracts}function IO(e,t,n,r){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function xO(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(s=>s.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([s])=>r===void 0||s===r).map(([s,o])=>[s,[...new Set(o.map(i=>`--${i.cli_flag}`))].sort((i,a)=>i.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...$m],services:[...Dm],policy_modes:[...Um],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...qm],trust_modes:[...Gm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...jm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Bd],create_modes:[...Hd],close_validation_modes:[...Vd],workflow_enforcement_modes:[...Wd]},e.relationship_kind_contracts=[...tl,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(s=>s.definitions)].sort((s,o)=>s.kind.localeCompare(o.kind)).map(s=>({canonical:s.kind,aliases:[...s.aliases??[]],...s.inverse===void 0?{}:{inverse:s.inverse},ordering:s.ordering,hierarchy:s.hierarchy})))}function OO(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function PO(e,t,n,r,s){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=eO(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let o=new Set(r);e.list_projections=Object.entries(pu).filter(([i])=>o.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...uu],compact_fields:[...mu]}))}e.command_aliases=s}}function NO(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=nO();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function LO(e,t,n,r){e.command_summaries=AO(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Hm],allows_unbounded_opt_out:!0},e.grammar_contracts={nouns:zt.nouns,shared_verbs:zt.shared_verbs,scope_before_verb:zt.scope_before_verb,visible_top_level_ceiling:zt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:zt.ceiling_raise_requires_pm_item,positional_shape_budget:zt.positional_shape_budget,positional_shape_count:new Set(zi.map(({slots:s})=>wl(s))).size,positional_action_count:Ki.length,positional_action_parents:[...new Set(Ki.map(({parent:s})=>s))].sort((s,o)=>s.localeCompare(o)),...r.includePositionalSignatures?{positional_signatures:zi}:{}}}async function sy(e,t){let n=oO(e);iO(n);let r=E(process.cwd(),t.path),s=await cO(t,r),o=hO(n,s),i=bO(n,s,o),a=wO(n,o),c=vO(n,a),d=IO(n,i,o,c),u=RO(n,s,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&LO(d,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p}),n.summary)return d;let f=tO(o.commandCatalog);return n.flagsOnly&&!n.fullOutput||xO(d,s,n),OO(d,n,i,u),PO(d,n,s,c,f),NO(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...dp],gate_triggers:[...cp]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=bl),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=$g(),d.context_intents=ru(),d.read_output_dimensions=Qi,d.error_codes=iu,d.command_output_contracts=TO(c),d.diagnostic_output_contracts=Vm,d.command_exit_contracts={vocabulary:tu,command_sets:CO(c)}),d}import gP from"node:fs/promises";import ky from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed44fc89-8b6e-5c83-a4f4-ced4e9031dac")}catch{}})();function ai(e,t,n,r,s,o="min"){let i=s==="min"?e-t:t-e,a=o==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&a<0}function FO(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,s=null,o=null,i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;r+=1;let u;try{u=JSON.parse(d)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(ai(f,i,p,s,"min")&&(i=f,s=p),ai(f,a,p,o,"max","max")&&(a=f,o=p))}return{id:e,bytes:n,lines:r,oldest_ts:s,newest_ts:o}}function oy(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),s=e.map(({id:_,raw:h})=>FO(_,h)),o=0,i=0,a=null,c=null,d=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of s){if(o+=_.lines,i+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);ai(h,d,_.id,a?.id??null,"min")&&(d=h,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);ai(h,u,_.id,c?.id??null,"max")&&(u=h,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...s].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...s].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:o,total_bytes:i,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as $O}from"node:crypto";import{execFile as DO}from"node:child_process";import cy from"node:path";import{promisify as UO}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="939d5f93-d287-5c1c-bc78-d013f76735f2")}catch{}})();var iy=1;function MO(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function pd(e){if(e===null)return{format_version:iy,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new m("Improvement ledger contains invalid JSON.",l.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==iy||!Array.isArray(t.observations))throw new m("Improvement ledger has an unsupported shape or format version.",l.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!MO(r))throw new m("Improvement ledger contains an invalid observation.",l.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2e1edc9-c454-5cfa-85c8-e9fb0a76a296")}catch{}})();var GO=UO(DO),jO=50,ay=1e3,qO=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function dy(e){let t=e.trim().toLowerCase();if(!qO.test(t))throw new m(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,l.USAGE,{code:"invalid_improvement_metric"});return t}function KO(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new m("Improvement direction must be higher, lower, or target.",l.USAGE,{code:"invalid_improvement_observation"});return t}function Cr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new m(`${t} must not exceed 256 characters.`,l.USAGE,{code:"invalid_improvement_observation"});return n}}function zO(e){let t=e??jO;if(!Number.isSafeInteger(t)||t<0||t>ay)throw new m(`Improvement observation limit must be an integer from 0 to ${ay}.`,l.USAGE,{code:"invalid_improvement_observation_limit"});return t}function ly(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new m(`${t} must be an ISO timestamp.`,l.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function BO(e,t,n){if(!Number.isFinite(n.value))throw new m("Improvement observation value must be finite.",l.USAGE,{code:"invalid_improvement_observation"});let r=dy(n.metric),s=KO(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||s==="target"&&n.threshold===void 0)throw new m("Target-directed observations require a finite threshold.",l.USAGE,{code:"invalid_improvement_observation"});let o=await VO(e,n.revision),i=Cr(n.source,"source"),a=Cr(n.itemId,"itemId"),c=Cr(n.unit,"unit"),d=Cr(n.idempotencyKey,"idempotencyKey")??(o.revision_source==="unversioned"?void 0:[o.revision,r,i??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:s,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:ly(n.observedAt??k(),"observedAt"),...o,author:T(n.author,t.author_default),...a===void 0?{}:{item_id:a},...i===void 0?{}:{source:i},...d===void 0?{}:{idempotency_key:d}};return{id:$O("sha256").update(Q(u)).digest("hex").slice(0,24),...u}}function HO(e,t){let n=t.idempotency_key?e.observations.find(s=>s.idempotency_key===t.idempotency_key):e.observations.find(s=>s.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new m(`Improvement observation retry key already records a different value for ${t.metric}.`,l.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(s=>s.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new m(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,l.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function VO(e,t){let n=Cr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await GO("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Zd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function WO(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,s=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:s,sample_count:e.length}}async function my(e,t={}){let n=E(process.cwd(),t.path);await C(n);let r=await A(n),s=await BO(n,r,e),o=cy.join(n,"improvement-ledger.json"),i=await Lu({pmRoot:n,filePath:o,op:"improvement_observe",author:s.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${s.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=pd(a),d=HO(c,s);return d?{raw:a,result:d}:(c.observations.push(s),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${Q(c)}
47
+ `,result:s})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function uy(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await C(t);let n=e.metric===void 0?void 0:dy(e.metric),r=e.since===void 0?void 0:ly(e.since,"since"),s=zO(e.limit),i=pd(await q(cy.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of i){let d=a.get(c.metric)??[];d.push(c),a.set(c.metric,d)}return{observations:[...i].reverse().slice(0,s),total:i.length,truncated:i.length>s,trends:[...a].map(([,c])=>WO(c)).sort((c,d)=>c.metric.localeCompare(d.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6162845d-f4b4-5d1f-a210-ddef1a5c38f6")}catch{}})();function py(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function YO(e,t,n){let r=t,s=new Set([e.id]);for(;r!==void 0&&!s.has(r.id);)s.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function JO(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,s)=>r.entries[0].ts.localeCompare(s.entries[0].ts)||r.id.localeCompare(s.id)),t.push(...n.map(r=>r.children))}}function fd(e=Qn,t=bn){return t.map(n=>{let r=e.filter(s=>((n==="model"?s.model_environment_keys:s.provenance_environment_keys?.[n])?.length??0)>0||s.provenance_resolvers?.[n]!==void 0).map(s=>s.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function XO(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let s=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?s.observed+=1:r.agent_provenance?.model===null?s.unavailable+=1:s.legacy_missing+=1,n.set(r.agent_harness,s)}return[...n.values()].map(r=>{let s=r.observed+r.unavailable;return{...r,coverage:s===0?null:r.observed/s,inert:s>=t&&r.observed===0}}).sort((r,s)=>r.harness.localeCompare(s.harness))}function _d(e,t=bn,n=1){let r=new Map;for(let s of e)if(s.agent_harness)for(let o of t){let i=`${s.agent_harness}\0${o}`,a=r.get(i)??{harness:s.agent_harness,dimension:o,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=s.agent_provenance?.[o];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(i,a)}return[...r.values()].map(s=>{let o=s.observed+s.unavailable;return{...s,coverage:o===0?null:s.observed/o,inert:o>=n&&s.observed===0}}).sort((s,o)=>s.harness.localeCompare(o.harness)||s.dimension.localeCompare(o.dimension))}function QO(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let s=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let u=`${c.agent_harness}\0${d}`,p=s.get(u)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[d];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),s.set(u,p)}let o=[...s.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[u])=>d.localeCompare(u)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),i=o.filter(c=>c.entries>=r),a=i.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:i.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:o,failures:a}}function ZO(e){let t=[...e].sort((o,i)=>o.ts.localeCompare(i.ts)||o.author.localeCompare(i.author)||o.op.localeCompare(i.op)||o.before_hash.localeCompare(i.before_hash)||o.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let o of t){let i=o.agent_episode,a=py(o),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(o);continue}let u={id:a.id,...i?.label===void 0?{}:{label:i.label},...i?.parent_id===void 0?{}:{parent_id:i.parent_id},source:a.source,entries:[o],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let s=[];for(let o of n.values()){let i=o.parent_id?r.get(o.parent_id):void 0;i&&YO(o,i,r)?i.children.push(o):s.push(o)}return JO(s),s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var eP=1e4,fy=1e5,tP=1e3,nP=30,rP=["append","comment","docs","file","learning","note","test_run"];function sP(e){let t=e??eP;if(!Number.isSafeInteger(t)||t<1||t>fy)throw new m(`History analytics event limit must be an integer from 1 to ${fy}.`,l.USAGE,{code:"invalid_history_analytics_limit"});return t}function _y(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new m("History analytics minimum sample must be an integer from 1 to 10000.",l.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function oP(e){let t=e?.trim();if(!t)return new Date(Date.now()-nP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let s=Number(n[1]),o=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(s)||s<1)throw new m("History analytics --since duration must be positive.",l.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-s*o).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new m("History analytics --since must be an ISO timestamp or negative duration such as -30d.",l.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function hy(e,t){let n=sP(t.eventLimit),r=oP(t.since),s=[],o=r,i=!1;for(;s.length<n;){let a=await Zo({pmRoot:e,since:o,limit:Math.min(tP,n-s.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(s.push(...c),i=a.has_more,o=a.next_cursor,!a.has_more)break}return{events:s,receipt:{since:r,events:s.length,truncated:i,...i?{next_cursor:o}:{},source:"history_event_index"}}}function iP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function aP(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function cP(e){return rP.some(t=>e.startsWith(t))}function gy(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function dP(e,t,n){let r=new Map,s=new Map,o=new Map;for(let i of t){let a=iP(i.entry,e),c=aP(i.entry),d=s.get(i.item_id)===!0,u=c===void 0?d:n.has(c);if(c!==void 0&&s.set(i.item_id,u),!a)continue;let p=gy(r,a);p.events+=1,cP(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!d&&u?(p.closes+=1,o.set(i.item_id,a)):c!==void 0&&d&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:o}}function lP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let s=new Set((r.dependencies??[]).filter(o=>o.kind==="discovered_from").map(o=>o.id));for(let o of s){let i=t.get(o);i&&(gy(e,i).defectEscapes+=1)}}}function mP(e,t,n,r){let s=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:s==="available"?t.closes/r:null,rework_rate:s==="available"?t.reopens/t.closes:null,defect_escape_rate:s==="available"?t.defectEscapes/t.closes:null,sample_status:s}}function uP(e,t,n,r,s,o){let{buckets:i,lastCloseValue:a}=dP(e,t,r);return lP(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,d])=>mP(c,d,s,o)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function pP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,s=Date.parse(n),o=Date.parse(r);return!Number.isFinite(s)||!Number.isFinite(o)?1:Math.max(1,(o-s)/864e5)}function fP(e,t,n){let r=fd(t),s=_d(e,bn,n),o=s.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),i=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:s,inert:o,undeclared:i,warnings:[...o.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...i.map(a=>`provenance_dimension_undeclared:${a}`)]}}function yy(e,t=Qn,n={}){let r=_y(n.minimumSample);return{...fP(e.events.map(s=>s.entry),t,r),window:e.receipt}}function by(e,t,n,r={}){let s=_y(r.minimumSample),o=pP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>uP(i,e.events,t,n,s,o)),minimum_sample:s,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var _P=32;function hP(e){let t=[];for(let n of e??[]){let r=[];for(let s of n.split(",")){let o=s.slice(0,s.indexOf("=")).trim();r.length>0&&o!=="unit"&&o!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(s)}t.push(r.join(","))}return t}function Rr(e,t){let n=hP(e).map(s=>{let[o,...i]=s.split(","),a=o.indexOf("="),c=o.slice(0,a).trim(),d=o.slice(a+1).trim(),u=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(u))throw new m(`Invalid --measure "${s}"; expected name=value[,unit=...][,threshold=...]`,l.USAGE);let p,f;for(let _ of i){let h=_.indexOf("="),y=_.slice(0,h).trim(),g=_.slice(h+1).trim();if(y==="unit"&&g.length>0)p=g;else if(y==="threshold"&&g.length>0&&Number.isFinite(Number(g)))f=Number(g);else throw new m(`Invalid --measure attribute "${_}"`,l.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(s=>[s.name,s])).values()].sort((s,o)=>s.name.localeCompare(o.name)).slice(0,_P)}function wy(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(s=>s.name===t&&s.value<n).map(s=>({...s,run_id:r.run_id})))}function vy(e,t){let n=e.flatMap(o=>o.measurements??[]).filter(o=>o.name===t).sort((o,i)=>i.recorded_at.localeCompare(o.recorded_at)),r=n[0],s=n[1];return{name:t,latest:r?.value??null,previous:s?.value??null,delta:r!==void 0&&s!==void 0?r.value-s.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b56db1fc-d989-5d18-8b29-336a03f1e525")}catch{}})();function yP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function bP(e,t,n,r,s){let o=ir(e,"type",r),i=new Set(o.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),d=(s?[...o.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:o.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=yP([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>s||f>0));return{byType:d,byStatus:p,omitted:s?0:a.length+Object.values(u).filter(f=>f===0).length}}function wP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function vP(e){let t=ky.join(e,"history");if(!await P(t))return[];await yn({path:t,scope:"project"});let n=(await gP.readdir(t)).filter(s=>s.endsWith(".jsonl")).sort((s,o)=>s.localeCompare(o)),r=[];for(let s of n){let o=ky.join(t,s),i=await q(o);i!==null&&(await yn({path:o,scope:"project"}),r.push({id:s.slice(0,-6),raw:i}))}return r}async function kP(e,t){let n=[],r=k();for(let s of Rr(t.observe,r))n.push(await my({metric:s.name,value:s.value,direction:t.direction,unit:s.unit,threshold:s.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function SP(e,t,n){let r={};return t.byAssignee&&(r.assignee=ir(e,"assignee",n)),t.byTag&&(r.tag=ir(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=ir(e,"priority",n)),r}async function EP(e,t,n,r,s){let o={since:s.since,eventLimit:s.eventLimit,minimumSample:s.minimumSample},i=s.provenanceCoverage||s.fleetAttribution?await hy(e,o):void 0;return{provenanceCoverage:s.provenanceCoverage&&i?yy(i,n.agent_identity?.harness_signals,o):void 0,fleetAttribution:s.fleetAttribution&&i?by(i,t,r,o):void 0}}function AP(e,t,n,r,s){let o=Object.keys(s.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...s.metadataCoverage?{metadata_coverage:s.metadataCoverage}:{},...o?{breakdowns:s.breakdowns}:{},...s.storage?{storage:s.storage}:{},...s.fieldUtilization?{field_utilization:s.fieldUtilization}:{},...s.improvementLedger?{improvement_ledger:s.improvementLedger}:{},...s.recordedObservations.length>0?{recorded_observations:s.recordedObservations}:{},...s.provenanceCoverage?{provenance_coverage:s.provenanceCoverage}:{},...s.fleetAttribution?{fleet_attribution:s.fleetAttribution}:{},generated_at:k()}}async function hd(e,t={}){let n=E(process.cwd(),e.path);await C(n);let r=await A(n),s=await kP(e,t),o=I(r,R()),i=$(r.schema),a=t.fieldUtilization?await Ns(n,r.item_format,o.type_to_folder,void 0,r.schema):await ae(n,r.item_format,o.type_to_folder,void 0,r.schema);await Du({pmRoot:n,settings:r,itemIds:a.map(S=>S.id),commandLabel:"stats"});let c=oo(i),d=bP(a,o.types,i.definitions.map(S=>S.id),c,t.includeEmpty===!0),u=await vP(n),p=0;for(let S of u)p+=wP(S.raw);let f=t.storage?oy(u):void 0,_=t.metadataCoverage?lf(a,c):void 0,h=SP(a,t,c),y=t.fieldUtilization?mf(a):void 0,g=t.measurements===!0||s.length>0?await uy({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:b,fleetAttribution:v}=await EP(n,a,r,i.terminal_statuses,t);return AP({items:a.length,history_streams:u.length,history_entries:p},d.byType,d.byStatus,d.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:y,improvementLedger:g,recordedObservations:s,provenanceCoverage:b,fleetAttribution:v})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0e63298a-d2d7-5217-af50-a206348b4cd4")}catch{}})();function Sy(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:w(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:we(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:w(e,"measurementSource"),measurementItem:w(e,"measurementItem"),measurementRevision:w(e,"measurementRevision"),author:w(e,"author"),message:w(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:w(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import TP from"node:fs/promises";import Dt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad3110ca-e85b-5a7e-b0a1-591796c298eb")}catch{}})();var Ry=Dt.join("runtime","telemetry","events.jsonl"),Iy=Dt.join("runtime","telemetry","state.json"),CP=Dt.join("runtime","telemetry"),RP=20,Ey=["status","flush","stats","clear"],Ay=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},gd=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Ty=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},IP=e=>({command:gd(e.event.command,"<unknown>"),eventType:gd(e.event.event_type,"unknown"),eventSchemaVersion:Ty(e.event.schema_version),clientSchemaVersion:Ty(e.client_schema_version)}),xP=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),OP=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},PP=e=>{let t=e?.command_resolution;return gd(t,"")||void 0},xy=(e,t)=>{e[t]=(e[t]??0)+1},NP=(e,t)=>{let n=OP(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=PP(t);r!==void 0&&xy(e.resolution_counts,r)},LP=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Cy=(e,t)=>{t!==void 0&&e.add(t)},FP=(e,t)=>{let n=IP(t),r=e.get(n.command)??xP();r.count+=1,r.max_attempts=Math.max(r.max_attempts,LP(t.attempts)),xy(r.event_type_counts,n.eventType),Cy(r.event_schema_versions,n.eventSchemaVersion),Cy(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&NP(r,t.event.payload),e.set(n.command,r)},MP=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((o,i)=>o-i),s=Object.entries(t.resolution_counts).sort((o,i)=>o[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((o,i)=>o[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((o,i)=>o-i),client_schema_versions:[...t.client_schema_versions].sort((o,i)=>o-i),...r.length>0?{duration_p50_ms:Ay(r,.5),duration_p95_ms:Ay(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...s.length>0?{command_resolution_counts:Object.fromEntries(s)}:{}}},$P=e=>{let t=(e??"status").trim().toLowerCase();if(Ey.includes(t))return t;throw Re({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Ey,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},yd=()=>{throw new m("--limit must be a positive integer",l.USAGE)},Oy=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?yd():e,DP=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?yd():Oy(Number.parseInt(t,10))},UP=e=>e===void 0?RP:typeof e=="number"?Oy(e):typeof e=="string"?DP(e):yd(),GP=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},jP=e=>{try{let t=JSON.parse(e);return GP(t)?t:void 0}catch{return}},qP=e=>e===null?[]:e.split(`
48
+ `).map(t=>t.trim()).filter(t=>t.length>0),Py=e=>{let t=qP(e),n=[],r=0;for(let s of t){let o=jP(s);o===void 0?r+=1:n.push(o)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},KP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zP=e=>{try{let t=JSON.parse(e);return KP(t)?t:{}}catch{return{}}},BP=async e=>{let t=await q(e);return t===null||t.trim().length===0?{}:zP(t)},ci=e=>e??null,di=async e=>{let t=await A(e),n=Dt.join(e,Ry),r=Dt.join(e,Iy),s=await q(n),o=Py(s),i=await BP(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:o.rows_total,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_size_bytes:Buffer.byteLength(s??"","utf8"),last_attempted_flush_at:ci(i.last_attempted_flush_at),last_successful_flush_at:ci(i.last_successful_flush_at),last_failed_flush_at:ci(i.last_failed_flush_at),last_failed_flush_error:ci(i.last_failed_flush_error)}},HP=e=>{let t=new Map;for(let n of e)FP(t,n);return[...t.entries()].map(([n,r])=>MP(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},VP=async(e,t)=>({action:"telemetry",subcommand:"status",status:await di(t.globalPmRoot),generated_at:k()}),WP=async(e,t)=>{let n=await di(t.globalPmRoot);await tp(t.globalPmRoot);let r=await di(t.globalPmRoot),s=Math.max(0,n.queue_entries-r.queue_entries),o=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:s,queue_progressed:s>0,queue_empty:o,queue_drained:o,status:r,generated_at:k()}},YP=async(e,t)=>{let n=UP(e.limit),r=await q(t.queuePath),s=Py(r),o=HP(s.entries),i=o.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:o.length,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_rows_total:s.rows_total,truncated:o.length>i.length,stats:i,generated_at:k()}},JP=async(e,t)=>{let n=await A(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await Ce(t.globalPmRoot,n,"telemetry:clear");let s=Dt.join(t.globalPmRoot,CP),o=await P(s);return await TP.rm(s,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:o&&!await P(s),queue_exists_after:await P(t.queuePath),state_exists_after:await P(t.statePath),status:await di(t.globalPmRoot),generated_at:k()}},XP={status:VP,flush:WP,stats:YP,clear:JP};async function Ny(e,t){let n=$P(e.subcommand),r=nt(process.cwd());return XP[n](e,{globalPmRoot:r,queuePath:Dt.join(r,Ry),statePath:Dt.join(r,Iy)})}import{spawn as Qy}from"node:child_process";import{cp as Dy,mkdir as nN,mkdtemp as Zy,open as kd,readdir as Sd,rm as eb}from"node:fs/promises";import{tmpdir as tb}from"node:os";import ue from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62af7c1e-c1c7-529e-ab30-117103ac4607")}catch{}})();var Ly=20;function QP(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return Ly;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?Ly:t}function bd(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,s)=>{let o=vn(r.recorded_at,s.recorded_at);if(o!==0)return o;let i=r.run_id.localeCompare(s.run_id);return i!==0?i:r.kind.localeCompare(s.kind)}),n=QP();return t.length>n?t.slice(t.length-n):t}async function li(e){await ne({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=bd([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a6a3402-dae3-56f8-b9ba-a4f6f8a47cda")}catch{}})();var Fy=100;function wd(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new m(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,l.USAGE);return n}function ZP(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Fy?n:`${n.slice(0,Fy-3)}...`}function My(e){return e.map((t,n)=>`${n+1}. ${ZP(t)}`).join("; ")}function eN(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function tN(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function $y(e,t){let n=eN(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((s,o)=>o+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new m(`Combine at most one linked-test selector per run: ${n.map(s=>`--${s}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,l.USAGE);let r=n[0];if(e.length===0)throw new m(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,l.USAGE);if(r==="match"){let s=t.match.trim().toLowerCase();if(s.length===0)throw new m("--match requires a non-empty substring to match against linked-test command/path values",l.USAGE);let o=[],i=[];for(let a=0;a<e.length;a+=1)tN(e[a],s)&&(i.push(e[a]),o.push(a+1));if(i.length===0)throw new m(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${My(e)}`,l.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:o,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let s=wd(t.onlyIndex);if(s>e.length)throw new m(`--only-index ${s} is out of range: this item has ${e.length} linked test(s). Available entries: ${My(e)}`,l.USAGE);return{selector:"only-index",requested:String(s),selected:[e[s-1]],selected_indexes:[s],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5fe0ee3e-9590-56fc-b238-e56ff1970e52")}catch{}})();var ui=20*1024*1024,rN=3e3,sN=1e4,oN=5e3,Uy=120,iN=new Set(["locks","extensions","runtime"]),aN=new Set(["history","index","search","extensions","locks","runtime"]),cN=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],dN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,lN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,mN=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Td(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function uN(){return Td("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",rN)}function pN(){return Td("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",sN)}function fN(){return Td("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",oN)}function _N(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function hN(e){let t=0,n=0,r=0;for(let s of e){if(s.status==="passed"){t+=1;continue}if(s.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function Cd(e){let t=0,n=0,r=0,s=0;for(let o of e){let i=o.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(r+=1),i.auto_pm_context_applied===!0&&(s+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:s}}function gN(e){let t=e??"project";if(!tt.includes(t))throw new m(`Invalid scope "${e}"`,l.USAGE);return t}function pi(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(en.includes(t))return t;throw new m(`Invalid --pm-context value "${e}". Expected one of: ${en.join(", ")}`,l.USAGE)}function nb(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:pi(e.pm_context_mode)}function rb(e,t){return e==="auto"?t?"tracker":"schema":e}function yN(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function bN(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function wN(e,t){let n={};if(!e)return n;for(let r of e){let s=pr(r,t);if(s)for(let[o,i]of Object.entries(s))n[o]=i}return n}function vN(e,t){if(!e)return[];let n=[];for(let r of e){let s=fr(r,t);s&&n.push(...s)}return[...new Set(n)]}function kN(e){let t=fi(e);return sr(t).some(n=>Aa(n)!==null)}function sb(e){let t=fi(e);return sr(t).some(n=>{let r=Aa(n);if(!r)return!1;let s=af(r);return s?mN.has(s.subcommand):!1})}function mi(e){if(e)return rf.has(e.subcommand)?On(e.args,sf)?.subcommand:e.subcommand}function Gy(e,t){if(e==="npx"||e==="bunx")return ro(t)?.command;if(e==="pnpm")return mi(On(t,Zp));if(e==="npm")return mi(On(t,ef));if(e==="yarn")return mi(On(t,tf));if(e==="bun")return mi(On(t,nf))}function jy(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function vd(e){return!e||!Ca(e.command)&&!of(e.command)?!1:no(e.args)==="test-all"}var SN=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),EN=new Set(["npx","bunx"]);function ob(e){let t=e.split(" ").filter(i=>i.length>0),n=Ta(t);if(n.length===0)return!1;let[r,...s]=n,o=SN.get(r);if(o){let i=s.findIndex(a=>o.test(a));return i>=0?ob(s.slice(i+1).join(" ")):!1}return Ca(r)||Ra(r)?no(s)==="test-all":r==="node"&&s.length>0&&Ra(s[0])?no(s.slice(1))==="test-all":EN.has(r)?vd(ro(s)):r==="pnpm"?vd(Ia(s)):r==="npm"?vd(xa(s)):!1}function ib(e){let t=fi(e);return sr(t).some(n=>ob(n))}function ab(e){if(ib(e))throw new m('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',l.USAGE)}function fi(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function AN(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function TN(e){let t=/\bpm_path\s*=/.test(e)||/\$env:pm_path\s*=/.test(e),n=/\bpm_global_path\s*=/.test(e)||/\$env:pm_global_path\s*=/.test(e);return t&&n}function CN(e){let t=e.split(" ").filter(o=>o.length>0),n=Ta(t);if(n.length===0)return!1;let[r,...s]=n;return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?RN(s):IN(r,s)}function RN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function IN(e,t){return e==="npx"||e==="bunx"?jy(ro(t)?.command):e==="pnpm"||e==="npm"?jy((e==="pnpm"?Ia(t):xa(t))?.command)||Gy(e,t)==="vitest":(e==="yarn"||e==="bun")&&Gy(e,t)==="vitest"}function cb(e){let t=fi(e);if(sr(t).some(s=>!AN(s)&&CN(s)&&!TN(s)))throw new m('Linked test runner commands must be sandbox-safe: use "node scripts/run-tests.mjs <test|coverage>", use a package-manager script such as "pnpm test", or include PM_PATH=... PM_GLOBAL_PATH=... INLINE in the command string (exporting them in your shell environment is not checked). Example: "PM_PATH=/tmp/pm-x PM_GLOBAL_PATH=/tmp/pm-x-g vitest run".',l.USAGE)}function xN(e){if(ib(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function ON(e){return e?e.map(PN):[]}function PN(e){let t=e.trim(),n=Ro(t)?Io(se(e,"--add"),"--add"):{command:t},r=me(n.command);if(!r)throw new m("--add requires command=<value> or a bare command (path=<value> is optional metadata)",l.USAGE);return ab(r),cb(r),{command:r,path:me(n.path),scope:gN(n.scope),timeout_seconds:NN(me(n.timeout_seconds),me(n.timeout)),pm_context_mode:Lo(me(n.pm_context_mode),"--add"),env_set:pr(me(n.env_set),"--add"),env_clear:fr(me(n.env_clear),"--add"),shared_host_safe:No(me(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:nn(me(n.assert_stdout_contains)),assert_stdout_regex:Mn(me(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:nn(me(n.assert_stderr_contains)),assert_stderr_regex:Mn(me(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Fo(me(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Mo(me(n.assert_json_field_equals),"--add"),assert_json_field_gte:$o(me(n.assert_json_field_gte),"--add"),note:me(n.note)}}function me(e){let t=e?.trim();return t&&t.length>0?t:void 0}function NN(e,t){if(e&&t&&e!==t)throw new m("--add timeout and timeout_seconds must match when both are provided",l.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(ce(n,"timeout_seconds"));if(r<=0)throw new m("--add timeout_seconds must be a positive integer",l.USAGE);return r}function LN(e){return e?e.flatMap(t=>{let n=Xf(t,"--add-json");for(let r of n){let s=r.command;if(!s)throw new m("--add-json requires a non-empty command string",l.USAGE);ab(s),cb(s)}return n}):[]}function FN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new m("--remove requires command or path value",l.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let s=n.slice(r[0].length).trim();if(!s)throw new m("--remove requires a non-empty command=<value> or path=<value>",l.USAGE);return{kind:r[1].toLowerCase(),value:s}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new m("--remove structured selectors require command=<value> or path=<value>",l.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let s=se(n,"--remove"),o=s.path!==void 0?"path":"command",i=s.path??s.command;if(!i?.trim())throw new m("--remove requires command=<value> and/or path=<value>",l.USAGE);return{kind:o,value:i.trim()}}return{kind:"either",value:n}}):[]}function MN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new m("--remove-index must be a positive integer",l.USAGE);return n}))]:[]}function $N(e){try{e.stdin?.end()}catch{}}function db(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=Uy?t:`${t.slice(0,Uy-3)}...`}function lb(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Ed(e){try{process.stderr.write(`${e}
49
+ `)}catch{}}function DN(e,t){if(!lb(t))return null;let n=db(e.command),r=Date.now();Ed(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let s=setInterval(()=>{let o=Date.now()-r;Ed(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${o} command="${n}"`)},pN());return s.unref?.(),s}function UN(e,t,n,r){if(!lb(r))return;let s=db(e.command),o=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let d=t.exitCode===null?"null":String(t.exitCode),u=c.length>0?` ${c.join(" ")}`:"";Ed(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${d} elapsed_ms=${o}${u} command="${s}"`)}async function qy(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Qy("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function GN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function jN(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await qy(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{qy(r)},uN()),t.forceKillTimer.unref?.()}}function qN(e){return new Promise(t=>{let n=!1,r=null,s=(o,i=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(o))};e.on("exit",(o,i)=>{n||(r=setTimeout(()=>{s({code:o,signal:i},!0)},fN()),r.unref?.())}),e.on("close",(o,i)=>{s({code:o,signal:i})})})}function KN(e,t,n,r){return Qy(e,{cwd:process.cwd(),env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function Ky(e){let t=await kd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,ui),s=Buffer.alloc(r);return r>0&&await t.read(s,0,r,0),{text:s.toString("utf8"),truncated:n>ui}}finally{await t.close()}}async function zN(e,t,n,r,s){let o=Date.now(),i=await Zy(ue.join(tb(),"pm-linked-test-output-"));try{let a=ue.join(i,"stdout.log"),c=ue.join(i,"stderr.log"),[d,u]=await Promise.all([kd(a,"w"),kd(c,"w")]),p;try{p=KN(e,n,d.fd,u.fd)}finally{await Promise.all([d.close(),u.close()])}$N(p);let f={heartbeat:DN(r,s),forceKillTimer:null,timedOutTimer:null},_=jN(p,f),h=!1,y;p.on("error",L=>{y=L.message}),f.timedOutTimer=setTimeout(()=>{h=!0,_()},t),f.timedOutTimer.unref?.();let{code:g,signal:b}=await qN(p);GN(f);let[v,S]=await Promise.all([Ky(a),Ky(c)]),x=v.truncated||S.truncated,O=x?`
50
+ [pm linked-test output truncated at ${ui} bytes per stream; the child process continued to completion]
51
+ `:"",j={stdout:`${v.text}${O}`,stderr:S.text,exitCode:g,signal:b,timedOut:h,maxBufferExceeded:!1,outputTruncated:x,spawnError:y};return UN(r,j,o,s),j}finally{await eb(i,{recursive:!0,force:!0})}}function BN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${ui} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,s=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?s:`${s} ${n.join(" ")}`}function HN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
52
+ `);return cN.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>dN.test(n)&&lN.test(n))}function VN(e){return HN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function WN(){return{infra_collision:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function _i(e){let t=WN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function zy(e,t){for(let[n,r]of Object.entries(t.env_set))tn.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)tn.has(n.toUpperCase())||delete e[n]}function YN(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function JN(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],s=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:s}}function XN(e,t,n){return{env_set:wN(e,"--env-set"),env_clear:vN(t,"--env-clear"),shared_host_safe:n===!0}}async function zn(e,t,n=!1,r=nN){if(await P(e))try{await ei("seed_linked_test",async()=>{if(await r(ue.dirname(t),{recursive:!0}),n){await Dy(e,t,{recursive:!0,force:!0});return}await Dy(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&kt(s))return;throw s}}async function By(e,t,n){await zn(ge(n.projectPmRoot),ge(e)),await zn(ue.join(n.projectPmRoot,"extensions"),ue.join(e,"extensions"),!0),await zn(ge(n.globalPmRoot),ge(t)),await zn(ue.join(n.globalPmRoot,"extensions"),ue.join(t,"extensions"),!0)}async function Hy(e,t){if(!await P(e))return;let n=await Sd(e,{withFileTypes:!0});for(let r of n){if(iN.has(r.name))continue;let s=ue.join(e,r.name),o=ue.join(t,r.name);if(r.isDirectory()){await zn(s,o,!0);continue}r.isFile()&&await zn(s,o)}}async function Kn(e){if(!await P(e))return 0;let t=0,n=await Sd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||aN.has(r.name))continue;let s=ue.join(e,r.name),o;try{o=await Sd(s,{withFileTypes:!0})}catch{continue}for(let i of o)i.isFile()&&Qd.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function QN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function ZN(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let r of n){if(r.startsWith("[")&&r.endsWith("]")){let s=Number.parseInt(r.slice(1,-1),10);if(!Number.isInteger(s)||s<0)return[];t.push(s);continue}t.push(r)}return t}function Vy(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=ZN(n);if(r.length===0)return{found:!1,value:void 0};let s=e;for(let o of r){if(typeof o=="number"){if(!Array.isArray(s)||o>=s.length)return{found:!1,value:void 0};s=s[o];continue}if(typeof s!="object"||s===null||!Object.prototype.hasOwnProperty.call(s,o))return{found:!1,value:void 0};s=s[o]}return{found:!0,value:s}}function eL(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function tL(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?rt(e,t):Object.is(e,t)}function nL(e,t,n){let r=[];r.push(...Wy("stdout",t,e.assert_stdout_contains)),r.push(...Yy("stdout",t,e.assert_stdout_regex)),r.push(...Wy("stderr",n,e.assert_stderr_contains)),r.push(...Yy("stderr",n,e.assert_stderr_regex)),r.push(...rL(t,e.assert_stdout_min_lines));let s=e.assert_json_field_equals??{},o=e.assert_json_field_gte??{};if(!(Object.keys(s).length>0||Object.keys(o).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,d]of Object.entries(s)){let u=Vy(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=eL(d);tL(u.value,p)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(u.value)})`)}for(let[c,d]of Object.entries(o)){let u=Vy(a,c);if(!u.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof u.value!="number"||!Number.isFinite(u.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}u.value<d&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${d}, actual ${u.value})`)}return r}function Wy(e,t,n){let r=[];for(let s of n??[])t.includes(s)||r.push(`${e} missing required text: "${s}"`);return r}function Yy(e,t,n){let r=[];for(let s of n??[])try{new RegExp(s,"m").test(t)||r.push(`${e} failed regex assertion: /${s}/m`)}catch(o){r.push(`${e} regex assertion is invalid: /${s}/ (${o instanceof Error?o.message:String(o)})`)}return r}function rL(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var sL=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i}];function oL(e,t){let n=`${e}
53
+ ${t}`;for(let r of sL)if(r.regex.test(n))return r.code;return null}function iL(e){return{root:e,schemaProjectPmPath:ue.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:ue.join(e,"schema","global"),trackerProjectPmPath:ue.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:ue.join(e,"tracker","global")}}async function aL(e,t=br,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function cL(e,t,n){t&&(await By(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await By(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Hy(t.projectPmRoot,e.trackerProjectPmPath),await Hy(t.globalPmRoot,e.trackerGlobalPmPath)))}function dL(e,t,n){return e.some(r=>{let s=r.command??"",o=s.length>0&&sb(s),i=n?.autoPmContext===!0&&o?"auto":nb(r,t,n?.overrideLinkedPmContext===!0);return rb(i,o)==="tracker"})}async function lL(e,t){return{sourceProjectItemCount:t?await Kn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Kn(t.globalPmRoot):0,schemaProjectItemCount:await Kn(e.schemaProjectPmPath),schemaGlobalItemCount:await Kn(e.schemaGlobalPmPath),trackerProjectItemCount:await Kn(e.trackerProjectPmPath),trackerGlobalItemCount:await Kn(e.trackerGlobalPmPath)}}function mL(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,s=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,o=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:s,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:o,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==s||e.counts.sourceGlobalItemCount!==o),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots}}function uL(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?pi(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?kN(n):!1,s=r&&n?sb(n):!1,o=e.options?.autoPmContext===!0&&s,i=o?"auto":nb(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=rb(i,s);return{linkedOverridePmContextMode:t,executionContext:mL({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:s,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:o})}}function Jy(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Ad(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function pL(e){if(!e.linkedTest.command)return Jy(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=xN(e.linkedTest.command);if(t)return Jy(e.linkedTest,e.executionContext,t);let n=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,r=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(n||r){let s=bN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Ad(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${s}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!yN(e.linkedTest)?Ad(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function fL(e){let t=JN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return zy(n,e.runtimeDirectives),zy(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&YN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,n.PM_SOURCE_WORKSPACE_ROOT=process.env.PM_SOURCE_WORKSPACE_ROOT??process.cwd(),n.PM_SOURCE_PM_PATH=e.executionContext.source_project_pm_path,n[eo]="read_only",n}function _L(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function hL(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal}) while --fail-on-empty-test-run is enabled. Update test selection or disable --fail-on-empty-test-run for this run.`}}function gL(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:QN(e.execution),failure_category:VN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:BN(e.execution,e.timeoutMs)}}function yL(e){if(e.options?.failOnEmptyTestRun===!0){let n=oL(e.execution.stdout,e.execution.stderr);if(n)return hL({...e,emptyRunSignal:n})}let t=nL(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Ad(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):_L(e.linkedTest,e.executionContext,e.execution)}async function bL(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await zN(t,n,fL(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?yL({...e,execution:r}):gL({...e,execution:r,timeoutMs:n})}async function Rd(e,t,n){let r=[],s=await Zy(ue.join(tb(),"pm-linked-test-")),o=iL(s),i=pi(n?.pmContext),a=n?.progress===!0?"always":"auto",c=XN(n?.envSet,n?.envClear,n?.sharedHostSafe),d=n?.sourceRoots,u=dL(e,i,n);try{await aL(o,br,u),await cL(o,d,u);let p=await lL(o,d);for(let f=0;f<e.length;f+=1){let _=e[f],h=uL({linkedTest:_,layout:o,counts:p,sourceRoots:d,runLevelPmContextMode:i,options:n}),y=pL({linkedTest:_,executionContext:h.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:h.linkedOverridePmContextMode,options:n});if(y){r.push(y);continue}r.push(await bL({linkedTest:_,index:f,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:c,progressMode:a,executionContext:h.executionContext,options:n}))}}finally{await eb(o.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function wL(e){let{id:t,pmRoot:n,settings:r,typeToFolder:s}=e,o=await D(n,t,r.id_prefix,r.item_format,s);if(!o)throw new m(`Item ${t} not found`,l.NOT_FOUND);let i=await K(o,{schema:r.schema});return{itemId:o.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function vL(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode}function kL(e,t){let n=[...e];for(let r of t)n.some(s=>vL(s,r))||n.push(r);return n}function SL(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),s=e.filter((o,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?o.command===a.value:a.kind==="path"?o.path===a.value:o.command===a.value||o.path===a.value));return{tests:s,removed:e.length-s.length}}function EL(e,t,n,r){return SL(kL(e,t),n,r)}function AL(e){return(e.envSet?.length??0)>0||(e.envClear?.length??0)>0||e.sharedHostSafe===!0||e.pmContext!==void 0||e.overrideLinkedPmContext===!0||e.failOnContextMismatch===!0||e.failOnSkipped===!0||e.failOnEmptyTestRun===!0||e.requireAssertionsForPm===!0||e.checkContext===!0||e.autoPmContext===!0}function TL(e){if(AL(e)&&e.run!==!0)throw new m("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",l.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new m("--match, --only-index, and --only-last require --run",l.USAGE)}async function CL(e){let{id:t,options:n,pmRoot:r,settings:s,typeToFolder:o,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return wL({id:t,pmRoot:r,settings:s,typeToFolder:o});let d=0,u=await ne({pmRoot:r,settings:s,id:t,op:i.length>0?"tests_add":"tests_remove",author:T(n.author,s.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=EL(f,i,a,c);if(d=_.removed,(a.length>0||c.length>0)&&d===0)throw new m("No linked tests matched the requested removal selector",l.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return p.metadata.tests=_.tests,{changedFields:rt(f,_.tests)?[]:["tests"]}}});return{itemId:u.item.id,tests:u.item.tests??[],testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:d}}function RL(e,t){TL(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:wd(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?$y(t,n):void 0,s=e.timeout===void 0?void 0:ce(e.timeout,"timeout");if(s!==void 0&&s<=0)throw new m("Test timeout must be a positive number",l.USAGE);return{defaultTimeoutSeconds:s,pmContextMode:pi(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function IL(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Rd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,sourceRoots:{projectPmRoot:r,globalPmRoot:nt(process.cwd())}})}function xL(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let s=Cd(n);r.push(`context_preflight:checked_pm_commands=${s.checked_pm_commands};tracker_read_commands=${s.tracker_read_commands};mismatches=${s.mismatches};auto_remediated=${s.auto_remediated}`)}return r}function OL(e){let t=hN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),s=k(),o=Rr(e.options.measure,s);return{run_id:_N("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:s,recorded_at:s,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:o.length>0?o:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode}))}}async function PL(e){let{options:t,pmRoot:n,settings:r,itemId:s,runStartedAt:o,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!o)return;let d=OL({options:t,runStartedAt:o,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return d;try{return await li({pmRoot:n,settings:r,itemId:s,author:T(t.author,r.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),d}catch(u){return c.push(`test_result_tracking_failed:${s}:${u instanceof Error?u.message:String(u)}`),d}}function Xy(e,t,n){let r;if(e.metricBelow!==void 0){let s=e.metricBelow.indexOf("="),o=e.metricBelow.slice(0,s).trim(),i=e.metricBelow.slice(s+1).trim(),a=Number(i);if(s<=0||o.length===0||i.length===0||!Number.isFinite(a))throw new m("--metric-below must use name=value",l.USAGE);r=wy(t,o,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:vy(t,e.metricDiff)}}async function hi(e,t,n){let r=Fe(),s=E(process.cwd(),n.path);await C(s);let o=await A(s);if((t.measure?.length??0)>0&&t.run!==!0)throw new m("--measure requires --run",l.USAGE);Rr(t.measure,"validation"),Xy(t,[],void 0);let i=I(o,R()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),d=await r.resolveList(t.remove,"--remove"),u=[...ON(a),...LN(c)],p=FN(d),f=MN(t.removeIndex),_=await CL({id:e,options:t,pmRoot:s,settings:o,typeToFolder:i.type_to_folder,adds:u,removes:p,removeIndexes:f}),h=RL(t,_.tests),y=t.run===!0?k():void 0,g=await IL({options:t,runOptions:h,pmRoot:s}),b=_i(g),v=t.run===!0&&t.failOnSkipped===!0&&g.some(L=>L.status==="skipped"),S=xL(t,h.runSelection,g),x=await PL({options:t,pmRoot:s,settings:o,itemId:_.itemId,runStartedAt:y,runResults:g,failOnSkippedTriggered:v,warnings:S}),O=x?bd([..._.testRuns,x]):_.testRuns,j=Xy(t,O,x);return{ok:g.every(L=>L.status!=="failed")&&v!==!0,id:_.itemId,tests:_.tests,run_results:g,failure_categories:b,selection:h.runSelection?{selector:h.runSelection.selector,requested:h.runSelection.requested,selected_indexes:h.runSelection.selected_indexes,selected_count:h.runSelection.selected_count,skipped_count:h.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:v?!0:void 0,warnings:S.length>0?S:void 0,changed:_.changed,count:_.tests.length,..._.removed>0?{removed:_.removed}:{},...j}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bb2758a5-a5c1-5f6e-be42-0e173fe16fe3")}catch{}})();var NL=(e,t)=>{if(e===void 0)return;let n=Y(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new m(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n},LL=e=>{if(e===void 0)return;let t=ce(e,"timeout");if(t<=0)throw new m("timeout must be a positive number",l.USAGE);return t},mb=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new m(`${t} must be a non-negative integer`,l.USAGE);return n},FL=e=>e instanceof Error?e.message:String(e),ML=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},$L=e=>e.trim().replaceAll(/\s+/g," "),DL=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),UL=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),GL=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},gi=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),ub=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),jL=e=>typeof e=="number"?e:void 0,qL=e=>{let t={assert_stdout_contains:gi(e.assert_stdout_contains),assert_stdout_regex:gi(e.assert_stdout_regex),assert_stderr_contains:gi(e.assert_stderr_contains),assert_stderr_regex:gi(e.assert_stderr_regex),assert_stdout_min_lines:jL(e.assert_stdout_min_lines),assert_json_field_equals:ub(e.assert_json_field_equals),assert_json_field_gte:ub(e.assert_json_field_gte)};return JSON.stringify(t)},KL=e=>{let t=Id(e.command);return t!==void 0?`command:${e.scope}:${$L(t)}`:`path:${e.scope}:${Id(e.path)??""}`},pb=e=>{let t=DL(e.env_set),n=UL(e.env_clear),r=GL(e.pm_context_mode),s=e.shared_host_safe===!0?"true":"false",o=qL(e);return`${KL(e)}:${t}:${n}:${r}:${s}:${o}`},zL=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,BL=e=>{let t=0,n=0,r=0;for(let s of e){if(s.status==="passed"){t+=1;continue}if(s.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},HL=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},yi=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
54
+ `)}catch{}},VL=async(e,t,n)=>{let r=[],s=0;for(let o of e){let i=await hi(o.id,{run:!1},{...t,path:n});s+=i.tests.length,r.push({item:o,tests:i.tests})}return{itemTests:r,linkedTests:s}},WL=async e=>{let t=$(e.settings.schema),n=I(e.settings,R()),r=NL(e.options.status,t),s=mb(e.options.limit,"--limit"),o=mb(e.options.offset,"--offset")??0,a=(await ae(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>r?d.status===r:!0).sort((d,u)=>d.id.localeCompare(u.id));return{filteredItems:s===void 0?a.slice(o):a.slice(o,o+s),statusFilter:r,limitFilter:s,offsetFilter:o}},YL=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let s=pb(r);if(!t.has(s)){t.set(s,r.timeout_seconds);continue}t.set(s,zL(t.get(s),r.timeout_seconds))}return t},JL=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=pb(u),f=t.seenTestKeys.has(p);if(!f){t.seenTestKeys.add(p);let _=t.effectiveTimeoutByKey.get(p);n.push(_===void 0?u:{...u,timeout_seconds:_})}return{test:u,key:p,duplicate:f}}),s=n.length>0?await Rd(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext}):[],o=0,i=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=s[o];return o+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=BL(i),c=_i(i),d=await ZL(e,a,i,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:d,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:i,failure_categories:c}}},XL=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),QL=e=>e?!0:void 0,ZL=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let s=XL(t,r.options);await li({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:s?"failed":"passed",started_at:r.runStartedAt,finished_at:k(),recorded_at:k(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:QL(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(o=>o.command?.trim()).slice(0,32).map(o=>({command:o.command.trim(),requested_pm_context_mode:o.execution_context?.requested_pm_context_mode,pm_context_mode:o.execution_context?.pm_context_mode}))}})}catch(s){return[`test_result_tracking_failed:${e.item.id}:${FL(s)}`]}return[]},eF=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},Id=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},tF=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:nt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:YL(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:T(e.options.author,e.settings.author_default),trackingRunId:ML(),trackingAttempt:eF(),trackingResumedFrom:Id(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),nF=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:_i([]),trackingWarnings:[]},s=e.failOnEmptyTestRun===!0&&t===0;return s&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:s}},rF=async(e,t,n)=>{for(let[r,s]of e.entries()){yi(t.options,`item ${r+1}/${e.length} start id=${s.item.id} linked_tests=${s.tests.length}`);let o=await JL(s,t);HL(n.failureCategories,o.failureCategories),n.passed+=o.passed,n.failed+=o.failed,n.skipped+=o.skipped,n.trackingWarnings.push(...o.trackingWarnings),n.results.push(o.result),yi(t.options,`item ${r+1}/${e.length} end id=${s.item.id} status=${o.failed===0?"passed":"failed"} passed=${o.passed} failed=${o.failed} skipped=${o.skipped}`)}},sF=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(s=>s.run_results),r=Cd(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},oF=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),iF=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),aF=async(e,t)=>{let n=E(process.cwd(),t.path);await C(n);let r=await A(n),s=await WL({pmRoot:n,settings:r,options:e}),o=LL(e.timeout),i=k(),a=await VL(s.filteredItems,t,n);return yi(e,iF({...s,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:s.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:o,runStartedAt:i}},cF=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},fb=async(e,t)=>{let n=await aF(e,t),{accumulation:r,failOnEmptyTestRunTriggered:s}=nF(e,n.linkedTests,n.filteredItems),o=tF({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await rF(n.itemTests,o,r),sF(e,r);let i=cF({options:e,accumulation:r,failOnEmptyTestRunTriggered:s});return yi(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),oF({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered:s})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2643d11d-befc-5a87-8bec-760951eec4d0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="863df651-49e0-552f-a7f0-92c3cc9a12a2")}catch{}})();function _b(){return{metadata:{},body:""}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7be35c3f-df6f-5ed6-b887-a7d8d53910a7")}catch{}})();var gb=[{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm init","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm install <target> --project","pm upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]}],hb=new Map;for(let e of gb){hb.set(e.id,e);for(let t of e.aliases)hb.set(t,e)}function xd(){return gb.map(e=>e.id)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27be0fa5-1c6a-53de-a0e8-179aab7c795a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48da3e98-ab96-54de-8993-7de0c4edf19b")}catch{}})();var GB=[...Nr],jB=[...Lr],dF=new Set(Xn.filter(e=>e.hidden).map(e=>e.alias)),qB=du("full").filter(e=>!dF.has(e)),KB=M(Br),zB=M(Hr),BB=M(Zr),HB=M(ss),VB=M(os),WB=M(om),YB=M(im),JB=M(rs),XB=M(ds),QB=M(is),ZB=M(as),eH=M(Qr),tH=M(cs),nH=M(Vr),rH=M(Wr,!1),sH=M(gm),oH=M(Yn),iH=M(Jn),aH=M(ps),cH=M(ms),dH=M(ts),lH=M(us),mH=M(ls),uH=M(fs),pH=M(es),fH=M(ns),_H=M(Jr),hH=M(_s),gH=M(Yr);var lF=M(hs),yH=`${lF} bash zsh fish`,bH=mF(xd());var wH=M(Xr),vH=M(Wn);var kH=zr.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function mF(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0224a672-e326-5555-a4b4-1fa3550d9e61")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1cbb3565-26d8-5657-b724-602658bec852")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a27b9b88-a8de-5e38-ab7f-dfcc61d1fad6")}catch{}})();var vb=Symbol("pm.active-extension-host-context");function Pe(e){return{fullChangedFields:!0,options:e}}var G=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[vb]=!0,n}run(t,n={}){return kb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return hf(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return pa(await this.list(ua(t)))}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}append(t,n,r={}){return this.runTyped("append",{id:t,...Pe({...r,body:n})})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,s,o={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...s===void 0?{}:{value:s},options:o})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,s){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...s?{fieldTypeScope:s}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},s,o){return this.runTyped("plan",{...n===void 0?{}:{id:n},...s===void 0?{}:{stepRef:s},...o===void 0?{}:{reorderTo:o},options:{...r,subcommand:t}})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,s={}){return this.plan("reorder-step",t,s,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Pe(t))}update(t,n={}){return this.runTyped("update",{id:t,...Pe(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Pe(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Pe(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Pe(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Pe(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Pe(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Pe(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...Pe(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Pe(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Pe(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Pe(r)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function pF(e={},t={}){return new G(t).context(e)}function fF(e={},t={}){return new G(t).list(e)}function _F(e={},t={}){return new G(t).listAllComplete(e)}function hF(e,t={},n={}){return new G(n).search(e,t)}function gF(e,t={},n={}){return new G(n).get(e,t)}function yF(e={},t={}){return new G(t).next(e)}function bF(e={},t={}){return new G(t).aggregate(e)}function wF(e,t={},n={}){return new G(n).comments(e,t)}function vF(e,t={},n={}){return new G(n).notes(e,t)}function kF(e,t={},n={}){return new G(n).learnings(e,t)}function SF(e,t={},n={}){return new G(n).files(e,t)}function EF(e,t={},n={}){return new G(n).filesDiscover(e,t)}function AF(e,t={},n={}){return new G(n).docs(e,t)}function TF(e,t={},n={}){return new G(n).deps(e,t)}function CF(e,t={},n={},r={}){return new G(r).graph(e,t,n)}function RF(e,t,n={},r={}){return new G(r).append(e,t,n)}function IF(e={},t={}){return new G(t).create(e)}function xF(e,t={},n={}){return new G(n).update(e,t)}function OF(e,t,n={},r={}){return new G(r).reopen(e,t,n)}function PF(e,t,n={},r={}){return new G(r).close(e,t,n)}function NF(e,t={},n={}){return new G(n).claim(e,t)}function LF(e={},t={}){return new G(t).claimNext(e)}function FF(e,t={},n={}){return new G(n).release(e,t)}function MF(e,t={},n={}){return new G(n).copy(e,t)}function $F(e,t={},n={}){return new G(n).delete(e,t)}function DF(e,t,n={},r={}){return new G(r).restore(e,t,n)}function UF(e,t={},n={}){return new G(n).focus(e,t)}function Ze(e,t){let n=w(e,t);if(!n)throw new m(`Missing required argument: ${t}`,64);return n}var yb=fu(),GF=new uF;function bi(){na(ol()),ra(il()),sa(al()),oa(cl()),ia(dl()),aa(ll()),ca(ml())}async function jF(e,t,n,r){return _u(()=>t===void 0?yb.read(()=>bb(e,n,r)):yb.write(()=>KF(t,()=>bb(e,n,r))))}async function bb(e,t,n){let r=E(t,e.path);if(e.noExtensions)return bi(),qa({pmRoot:r},()=>n(null));if(!await P(ge(r)))return bi(),n(null);let s=null,o;try{let i=await A(r),a=await qr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Kr({...a,loaded:a.loaded});o={loadResult:a,activationResult:c},na(c.hooks),ra(c.commands),sa(c.parsers),oa(c.preflight),ia(c.services),aa(c.renderers),ca(c.registrations),s={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){bi(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await qa({pmRoot:r,packages:s?.packages},()=>n(s))}finally{bi(),o&&await ul(o.loadResult,o.activationResult).catch(()=>{})}}async function qF(e,t,n,r,s){if(!s)throw new m(`Unsupported native pm action: ${e}`,l.USAGE);let o=Yt(e),a=s.registrations.commands.find(d=>Yt(d.action)===o)?.command??s.commands.handlers.find(d=>Yt(d.command)===o)?.command;if(!a)throw new m(`Unsupported native pm action: ${e}`,l.USAGE);let c=await Ts({command:wa(a),args:we(n.args??t.args),options:va(t,n),global:r,pm_root:s.pmRoot,sdk:wf(s.pmRoot,G.forActiveExtensionHost({pmRoot:s.pmRoot,author:typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension"}))});if(!c.handled){let d=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new m(`Unsupported native pm action: ${e}${d}`,l.USAGE)}return c.result}async function KF(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var zF=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function BF(e){let t=Ze(e,"action"),n=Yt(t),r=vi(yf,n),s=r?.action??n,o={...e,action:s};return r?.options!==void 0&&(o.options={...r.options,...qi(e.options)}),s==="package"&&(o.options={...qi(o.options),vocabulary:"package"}),{action:s,args:o}}function HF(e){return!zF.has(Yt(e))}async function kb(e){let t=BF(e),n=ga(t.args),r=HF(t.action),s=w(t.args,"cwd"),o=s??process.cwd();try{return e[vb]===!0||GF.getStore()===!0?await wb(t.action,t.args,n,null):await jF(n,s,o,i=>wb(t.action,t.args,n,i))}finally{r&&Da()}}function vi(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function wi(e){return w(e.args,"target")??w(e.options,"target")}function J(e,t=e.options){return e.id??Ze(t,"id")}async function VF(e){let t=hn("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),$a(await Pt(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function WF(e){let t=Ze(e.args,"query"),n=hn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),$a(await cr(t,n,e.global),n)}async function YF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return je(await Nt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function JF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options),s={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return je(await Ic(J(e,s),s,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function XF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return je(await dt(J(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function QF(e){let t=po(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),Mf(J(e),t,e.global)}function Sb(e,t){return Qp(Fg(e.options,t,Me),e.global)}function ZF(e){let t=we(e.options.lookupPath);if(t&&t.length>0)return Sb(e,t);let n=J(e);return e.options.discover===!0?Ea(n,ba(e.options),e.global):Xp(n,Zs(e.options),e.global)}function eM(e){return Ny({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:hp(e.args,e.options)},e.global)}function tM(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Yp(e.global,t)}function nM(e){let t=w(e.args,"configAction")??w(e.options,"configAction")??w(e.options,"action");if(t===void 0)throw new m("Missing required argument: configAction",64);return ah(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),e.options,e.global,w(e.args,"value")??w(e.options,"value"))}function rM(e){let t=e.options;return ap(ip(t),e.global)}function sM(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new m(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new m(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new m(`${t} must be a finite integer.`,64);return r}}function oM(e){let t=w(e.args,"subcommand")??Ze(e.options,"subcommand"),n=e.options;return U_({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:iM(e),reorderTo:sM(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function iM(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function aM(e){let t=w(e.args,"subcommand")??Ze(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:w(e.args,"name")??w(e.options,"name"),author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:we(n)}}function cM(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,a=vi({list:()=>Np(t.global),show:()=>Lp(r,t.global),"show-status":()=>Fp(r,t.global),"list-fields":()=>Dp(t.global),"show-field":()=>Up(r,t.global),"remove-type":()=>Ip(r,{author:s,force:o},t.global),"remove-field":()=>$p(r,{author:s,force:o},t.global),"remove-status":()=>Pp(r,{author:s,force:o},t.global),"apply-preset":()=>Gp(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:s,force:o},t.global)},n);return a?a():null}function dM(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return Mp(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:we(i),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:o,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:we(a),author:r,force:s},t.global)}function lM(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e,i=t.args.role??t.options.role;return Op(n,{role:i===void 0?void 0:we(i),alias:o,description:w(t.args,"description")??w(t.options,"description"),order:Me(t.args.order??t.options.order,"schema add-status order"),author:r,force:s},t.global)}function mM(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e;return Rp(n,{description:w(t.args,"description")??w(t.options,"description"),defaultStatus:w(t.args,"defaultStatus")??w(t.args,"default_status")??w(t.options,"defaultStatus")??w(t.options,"default_status"),folder:w(t.args,"folder")??w(t.options,"folder"),alias:o,author:r,force:s},t.global)}function uM(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,i=w(t.args,"to")??Ze(t.options,"to"),a=w(t.args,"migrationId")??w(t.args,"migration_id")??w(t.options,"migrationId")??w(t.options,"migration_id"),c=w(t.args,"fieldTypeScope")??w(t.options,"fieldTypeScope")??w(t.args,"type")??w(t.options,"type"),d=n==="rename-type"?{kind:"rename-type",from:r??"",to:i}:n==="rename-field"?{kind:"rename-field",from:r??"",to:i,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:i};return Tp(d,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:s,force:o},t.global)}function pM(e){let t=aM(e),n=cM(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return uM(t);if(t.subcommand==="add-field")return dM(t);if(t.subcommand==="add-status")return lM(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?jp({minCount:Me(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):mM(t);throw Re({command_path:"schema",token:t.subcommand,allowed:Cp,exit_code:64})}function fM(e){let t=w(e.args,"subcommand")??Ze(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),o=vi({list:()=>wg(),show:()=>vg(r),lint:()=>kg(r),apply:()=>Sg(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!o)throw Re({command_path:"profile",token:t,allowed:bg,exit_code:64});return o()}async function _M(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return je(await kf(J(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function hM(e){let{changedFields:t,runnerOptions:n}=$e(e.args,e.options);return je(await C_(Sa(n),e.global),{changedFields:t})}async function gM(e){let{changedFields:t,runnerOptions:n}=$e(e.args,e.options),r=w(e.args,"reason"),s=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&s.force===void 0&&(s.force=!0),je(await Ff(ka(s),e.global),{changedFields:t})}async function yM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options),s=w(r,"target")??Ze(e.args,"target");return je(await Xt(J(e,r),s,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Eb(e){let t={...e};return delete t.assignee,t}async function bM(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=si($(n.schema)),s=J(e),o=await _o(s,e.force,e.global,e.options),i=await dt(s,{...Eb(e.options),status:r,force:e.force},e.global);return{id:s,action:"start_task",claim:o,update:i}}async function wM(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=J(e),s=$(n.schema).open_status,o=await dt(r,{...Eb(e.options),status:s,force:e.force},e.global),i=await ho(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:o,release:i}}async function vM(e){let t=J(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await ct(t,n,{...e.options,force:e.force},e.global),s=await ho(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:s}}function kM(e){let t={...e.args,...e.options};return up(Ze(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),bp(t),e.global)}function SM(e){return vp(E(process.cwd(),e.global.path),{...e.args,...e.options})}var EM={init:e=>br(w(e.args,"prefix"),e.global,e.options),context:e=>La(hn("context",e.options),e.global),next:e=>ar(hn("next",e.options),e.global),eval:cg,events:dg,merge:lg,workspace:mg,meet:ni,event:ni,remind:ni,list:VF,get:e=>{let t=J(e);return Fa(t,e.global,hn("get",e.options,[t]))},search:WF,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:we(e.options.status);return Ma(e.global,{...t.length===0?{}:{status:t},since:w(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Me(e.options.limit,"limit")})},create:YF,copy:JF,focus:e=>Oc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:XF,"item-reopen":Lg,restore:yM,claim:e=>e.options.next===!0||e.args.next===!0?If(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):_o(J(e),e.force,e.global,e.options),release:e=>ho(J(e),e.force,e.global,e.options),"start-task":bM,"pause-task":wM,"close-task":vM,close:Ng,comments:QF,notes:e=>Df(J(e),po(e.options),e.global),learnings:e=>$f(J(e),po(e.options),e.global),files:ZF,docs:e=>Jp(J(e),Zs(e.options),e.global),test:e=>hi(J(e),e.options,e.global),"test-all":e=>fb(e.options,e.global),telemetry:eM,validate:e=>so(e.options,e.global,{runUpdate:(t,n,r)=>dt(t,n,r)}),health:tM,assurance:e=>cf(e.args,e.options,e.global),contracts:e=>sy(e.options,e.global),config:nM,activity:rM,aggregate:e=>Oa(e.options,e.global),extension:e=>xn(wi(e),e.options,e.global),package:e=>xn(wi(e),e.options,e.global),install:e=>xn(wi(e),{...e.options,install:!0},e.global),upgrade:e=>pf(wi(e),e.options,e.global),delete:e=>xc(J(e),e.options,e.global),deps:e=>mp(J(e),e.options,e.global),graph:kM,"files-discover":e=>Ea(J(e),e.options,e.global),"files-lookup":e=>Sb(e,we(e.options.paths)),history:e=>uf(J(e),e.options,e.global),"history-redact":e=>zu(J(e),e.options,e.global),"history-repair":Ig,"history-compact":xg,"history-author-acknowledge":SM,plan:oM,schema:pM,profile:fM,stats:e=>hd(e.global,Sy(e.options)),append:_M,"update-many":hM,"close-many":gM,gc:e=>ff(e.global,e.options)};async function wb(e,t,n,r){let s=ya(t,e);Zi(e,s),Wm(e,s);let o={action:e,args:t,options:s,id:w(t,"id"),force:t.force===!0||s.force===!0,global:n,activeExtensions:r},i=vi(EM,e),a=i?await i(o):await qF(e,t,s,n,r);return s.resolvedOutputFormat="json",ou(e,s,a)}var AM={closeManyOptionsFromFlat:ka,extensionOptionsFromArgs:va,globalOptions:ga,mutationListOptions:yp,normalizeActionName:Yt,normalizeCommandPath:wa,normalizeMcpUpdateOptions:wp,normalizeMcpOptionsArrays:gp,optionsWithAuthor:ya,readRequiredString:Ze,readScalarString:fp,readScalarStringAllowBlank:_p,readStringArray:we,updateManyOptionsFromFlat:Sa,withAddNoteOption:Zs,withFilesDiscoveryOptions:ba,withMutationCompaction:$e};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=AM);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d19cfa31-a02f-53a7-8685-5d169d6e051d")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cc0d4dd1-20e8-59d4-acb5-9f8ed639d35f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f44898af-0809-51e1-a6fb-74716c0971f5")}catch{}})();export{bn as AGENT_PROVENANCE_DIMENSIONS,bu as BASELINE_ITEM_FORMAT_VERSION,Qn as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,Nr as BUILTIN_ITEM_TYPE_VALUES,Fr as CONFIDENCE_TEXT_VALUES,wu as CURRENT_ITEM_FORMAT_VERSION,jt as DEPENDENCY_KIND_VALUES,l as EXIT_CODE,un as ISSUE_SEVERITY_VALUES,zd as ITEM_TYPE_VALUES,Ua as PM_CLI_EXPECTED_ERROR_NAME,fw as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,uw as PM_READ_OUTPUT_DIMENSIONS,pw as PM_READ_OUTPUT_OPTION_FLAGS,Qi as PM_READ_OUTPUT_SURFACE_CONTRACTS,m as PmCliError,G as PmClient,mn as RISK_VALUES,Fw as SEMANTIC_ATTRIBUTION_LIMITS,Lr as STATUS_VALUES,Ew as agentSessionEnvironment,bF as aggregate,fd as analyzeAgentProvenanceDescriptorCoverage,ww as analyzeSdkCliParameterCompleteness,RF as append,gw as applyReadOutputDimensions,aw as applyReadOutputSessionReferences,cw as attachReadOutputSessionReceipt,vw as boundAgentEpisodeIdentity,Je as canonicalDocument,NF as claim,LF as claimNext,Su as classifyItemFormatVersion,PF as close,wF as comments,pF as context,MF as copy,IF as create,bf as createPmCliExpectedError,mw as decodeReadOutputContinuationCursor,$F as deleteItem,TF as deps,Rw as detectAgentIdentity,Ow as detectHarnessIdentity,Iw as diagnoseAgentIdentity,AF as docs,vu as effectiveItemFormatVersion,_b as emptyImportedDocument,lw as encodeReadOutputContinuationCursor,QO as evaluateSemanticAttributionCoverage,Nw as explainSourceTraceability,SF as files,EF as filesDiscover,UF as focus,gF as get,CF as graph,ZO as groupHistoryByEpisode,Rf as isAlreadyClaimedError,lo as isPmCliExpectedError,yw as isReadOutputBudgetExceeded,kF as learnings,fF as list,_F as listAllComplete,yF as next,ku as normalizeItemFormatVersion,be as normalizeItemId,Y as normalizeStatusInput,vF as notes,k as nowIso,iw as parseReadOutputSession,to as parseSourceLineRange,Rs as readAuthorEnvironment,dw as readOutputSessionRemainingTokens,Pa as recordClaimSemanticAttribution,io as recordFocusSemanticAttribution,Na as recordReleaseSemanticAttribution,Aw as registerHarnessSignalDescriptors,FF as release,OF as reopen,kw as resolveAgentSessionContextFromSignals,Pw as resolveAuthorIdentity,py as resolveHistoryEpisodeGroupIdentity,hw as resolveReadOutputDimensions,bw as resolveReadOutputEncoding,_w as resolveReadOutputSurface,Lw as resolveSemanticLineageIds,DF as restore,kb as runAction,Sw as runWithAgentSessionContext,Tw as runWithHarnessDetectionSignals,Cw as runWithWorkspaceHarnessSignalDescriptors,hF as search,Mw as semanticAttributionAffinity,qe as serializeItemDocument,XO as summarizeAgentModelProvenance,_d as summarizeAgentProvenance,xF as update,Zi as validateReadOutputOptions,xw as writeAuthorEnvironment};
55
55
  //# sourceMappingURL=sdk-core.js.map