@unbrained/pm-cli 2026.8.21 → 2026.8.23

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 +44 -0
  3. package/dist/cli/error-guidance.d.ts +22 -4
  4. package/dist/cli/error-guidance.js +73 -16
  5. package/dist/cli/main.d.ts +3 -0
  6. package/dist/cli/main.js +51 -9
  7. package/dist/cli/register-mutation.js +6 -6
  8. package/dist/cli/register-operations.d.ts +73 -0
  9. package/dist/cli/register-operations.js +39 -14
  10. package/dist/cli/register-setup.js +3 -3
  11. package/dist/cli/schema-registration-helpers.d.ts +8 -1
  12. package/dist/cli/schema-registration-helpers.js +14 -5
  13. package/dist/cli-bundle/bundle-manifest.json +149 -149
  14. package/dist/cli-bundle/chunks/chunk-3ENVHX6C.js +36 -0
  15. package/dist/cli-bundle/chunks/{chunk-LOVTQ52Z.js → chunk-DW2CGEMU.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-EG6CLDZT.js +5 -0
  17. package/dist/cli-bundle/chunks/{chunk-LARJJ3RK.js → chunk-F3AI2JFL.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-N3DSV4CH.js → chunk-HWZ6CELB.js} +8 -8
  19. package/dist/cli-bundle/chunks/chunk-HZBMLSZI.js +201 -0
  20. package/dist/cli-bundle/chunks/chunk-JB4KZWBF.js +3 -0
  21. package/dist/cli-bundle/chunks/chunk-KPH73XXJ.js +2 -0
  22. package/dist/cli-bundle/chunks/{chunk-BKYB45NQ.js → chunk-KXPMB2YL.js} +50 -50
  23. package/dist/cli-bundle/chunks/{chunk-BUNIEJNE.js → chunk-QDVHNHAQ.js} +2 -2
  24. package/dist/cli-bundle/chunks/chunk-TFI5V5N2.js +13 -0
  25. package/dist/cli-bundle/chunks/{register-list-query-F57EWDEF.js → register-list-query-UJB5FMV2.js} +2 -2
  26. package/dist/cli-bundle/chunks/register-mutation-NX5XE4VX.js +20 -0
  27. package/dist/cli-bundle/chunks/register-operations-RXIJIYXC.js +2 -0
  28. package/dist/cli-bundle/chunks/{register-setup-HXU7IZZD.js → register-setup-GFUZEKRE.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-F4YEW5I2.js → chunk-37Z4OEAP.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/chunk-3UPTYG44.js +8 -0
  31. package/dist/cli-bundle/focused-chunks/chunk-5S7E72FY.js +16 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-4ERLO7QD.js → chunk-AUFH5H35.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-E7X25GC3.js +2 -0
  34. package/dist/cli-bundle/focused-chunks/chunk-FQCSTBWE.js +4 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-FH6DYED3.js → chunk-FZS4H32O.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/chunk-IFLWKY2R.js +156 -0
  37. package/dist/cli-bundle/focused-chunks/{chunk-YKBKIEAJ.js → chunk-JOWDB2MH.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/chunk-LYVSW5VM.js +2 -0
  39. package/dist/cli-bundle/focused-chunks/chunk-MRCNF3U6.js +2 -0
  40. package/dist/cli-bundle/focused-chunks/{chunk-UZE7XUZK.js → chunk-OFVUGTLJ.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-FJ22HNRP.js → chunk-OGLQBL46.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/chunk-OY7QAV4Y.js +51 -0
  43. package/dist/cli-bundle/focused-chunks/chunk-QGFNI65N.js +26 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-KDNG7TKQ.js → chunk-R27IDGHD.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/chunk-UYRFYCDQ.js +5 -0
  46. package/dist/cli-bundle/focused-chunks/{chunk-2NIY5NKG.js → chunk-ZHVA42R5.js} +9 -9
  47. package/dist/cli-bundle/main.js +13 -13
  48. package/dist/cli-bundle/sdk-authoring.js +1 -1
  49. package/dist/cli-bundle/sdk-contracts.js +2 -2
  50. package/dist/cli-bundle/sdk-core.js +40 -40
  51. package/dist/cli-bundle/sdk-governance.js +1 -1
  52. package/dist/cli-bundle/sdk-graph.js +1 -1
  53. package/dist/cli-bundle/sdk-merge.js +33 -32
  54. package/dist/cli-bundle/sdk-query.js +1 -1
  55. package/dist/cli-bundle/sdk-runtime.js +1 -1
  56. package/dist/cli-bundle/sdk-testing.js +1 -1
  57. package/dist/cli-bundle/sdk.js +5 -5
  58. package/dist/core/config/nested-settings.js +8 -2
  59. package/dist/core/config/positional-value.d.ts +1 -1
  60. package/dist/core/config/positional-value.js +5 -2
  61. package/dist/core/extensions/extension-hook-runtime.js +22 -20
  62. package/dist/core/extensions/extension-types.d.ts +8 -1
  63. package/dist/core/extensions/extension-types.js +2 -2
  64. package/dist/core/extensions/loader.js +7 -3
  65. package/dist/core/extensions/service-ownership.d.ts +8 -0
  66. package/dist/core/extensions/service-ownership.js +20 -0
  67. package/dist/core/history/history.js +3 -3
  68. package/dist/core/item/id.js +20 -5
  69. package/dist/core/item/item-format.js +81 -2
  70. package/dist/core/reproducibility/context.d.ts +4 -0
  71. package/dist/core/reproducibility/context.js +14 -8
  72. package/dist/core/shared/author.d.ts +55 -1
  73. package/dist/core/shared/author.js +333 -16
  74. package/dist/core/shared/constants.js +3 -2
  75. package/dist/core/shared/errors.d.ts +4 -0
  76. package/dist/core/shared/errors.js +2 -2
  77. package/dist/core/store/settings-validator.d.ts +1 -0
  78. package/dist/core/store/settings-validator.js +6 -3
  79. package/dist/core/store/settings.js +5 -2
  80. package/dist/mcp/server.d.ts +1 -1
  81. package/dist/mcp/server.js +30 -9
  82. package/dist/sdk/agent/identity-config.d.ts +63 -0
  83. package/dist/sdk/agent/identity-config.js +107 -0
  84. package/dist/sdk/agent/refusal-corpus-contracts.d.ts +76 -0
  85. package/dist/sdk/agent/refusal-corpus-contracts.js +194 -0
  86. package/dist/sdk/agent/refusal-reachability.d.ts +1 -1
  87. package/dist/sdk/authoring.d.ts +1 -1
  88. package/dist/sdk/authoring.js +2 -2
  89. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +77 -0
  90. package/dist/sdk/cli-contracts/agent-output-contracts.js +326 -2
  91. package/dist/sdk/cli-contracts/commander-mutation-options.js +3 -3
  92. package/dist/sdk/cli-contracts/enum-contracts.d.ts +4 -0
  93. package/dist/sdk/cli-contracts/enum-contracts.js +9 -2
  94. package/dist/sdk/cli-contracts/flag-contracts.js +9 -2
  95. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +4 -4
  96. package/dist/sdk/cli-contracts/registration-helpers.js +5 -2
  97. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +3 -1
  98. package/dist/sdk/cli-contracts/runtime-contracts.js +4 -3
  99. package/dist/sdk/cli-contracts/tool-parameter-tables.js +22 -2
  100. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  101. package/dist/sdk/cli-contracts/tool-schema.js +14 -3
  102. package/dist/sdk/cli-contracts.d.ts +4 -4
  103. package/dist/sdk/cli-contracts.js +5 -5
  104. package/dist/sdk/config.d.ts +6 -1
  105. package/dist/sdk/config.js +119 -14
  106. package/dist/sdk/context-intent-contracts.js +4 -2
  107. package/dist/sdk/core-governance.d.ts +1 -1
  108. package/dist/sdk/core-governance.js +3 -3
  109. package/dist/sdk/extension/install-sources.d.ts +1 -1
  110. package/dist/sdk/extension/install-sources.js +6 -3
  111. package/dist/sdk/extension/output-ownership.d.ts +1 -0
  112. package/dist/sdk/extension/output-ownership.js +3 -2
  113. package/dist/sdk/extension/scaffold.js +11 -5
  114. package/dist/sdk/flag-invocation-contracts.js +4 -2
  115. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +74 -2
  116. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +87 -26
  117. package/dist/sdk/governance/assurance-action.js +30 -10
  118. package/dist/sdk/governance/health.d.ts +3 -0
  119. package/dist/sdk/governance/health.js +39 -7
  120. package/dist/sdk/governance/hierarchy-validation.d.ts +29 -0
  121. package/dist/sdk/governance/hierarchy-validation.js +109 -0
  122. package/dist/sdk/governance/validate.d.ts +3 -9
  123. package/dist/sdk/governance/validate.js +84 -111
  124. package/dist/sdk/graph/assembly.d.ts +6 -1
  125. package/dist/sdk/graph/assembly.js +16 -22
  126. package/dist/sdk/graph/governance-contracts.d.ts +1 -1
  127. package/dist/sdk/graph/governance-contracts.js +8 -2
  128. package/dist/sdk/graph/governance.js +46 -2
  129. package/dist/sdk/graph/hierarchy-integrity.d.ts +94 -0
  130. package/dist/sdk/graph/hierarchy-integrity.js +311 -0
  131. package/dist/sdk/graph/index.d.ts +2 -1
  132. package/dist/sdk/graph/index.js +3 -2
  133. package/dist/sdk/graph/remediation.js +32 -2
  134. package/dist/sdk/graph/run.d.ts +31 -2
  135. package/dist/sdk/graph/run.js +80 -31
  136. package/dist/sdk/graph/workspace-relationship-kind-registry.d.ts +8 -0
  137. package/dist/sdk/graph/workspace-relationship-kind-registry.js +28 -0
  138. package/dist/sdk/index.d.ts +8 -3
  139. package/dist/sdk/index.js +9 -4
  140. package/dist/sdk/item-children.js +21 -8
  141. package/dist/sdk/lifecycle/create.js +129 -97
  142. package/dist/sdk/lifecycle/hierarchy-mutation-lock.d.ts +15 -0
  143. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +25 -0
  144. package/dist/sdk/lifecycle/update.d.ts +2 -0
  145. package/dist/sdk/lifecycle/update.js +174 -84
  146. package/dist/sdk/merge/three-way.js +105 -26
  147. package/dist/sdk/query/complete-list.d.ts +3 -3
  148. package/dist/sdk/query/complete-list.js +46 -3
  149. package/dist/sdk/query/list.d.ts +4 -3
  150. package/dist/sdk/query/list.js +89 -49
  151. package/dist/sdk/read-output-budget.d.ts +21 -0
  152. package/dist/sdk/read-output-budget.js +39 -2
  153. package/dist/sdk/read-output-contracts.d.ts +10 -4
  154. package/dist/sdk/read-output-contracts.js +105 -32
  155. package/dist/sdk/relationship-context.js +3 -4
  156. package/dist/sdk/relationships.js +17 -10
  157. package/dist/sdk/reproducibility/process.d.ts +19 -0
  158. package/dist/sdk/reproducibility/process.js +88 -0
  159. package/dist/sdk/runtime-primitives.d.ts +1 -1
  160. package/dist/sdk/runtime-primitives.js +3 -3
  161. package/dist/sdk/runtime.d.ts +3 -2
  162. package/dist/sdk/runtime.js +7 -5
  163. package/dist/sdk/test/batch.d.ts +6 -0
  164. package/dist/sdk/test/batch.js +26 -6
  165. package/dist/sdk/test/entry.d.ts +1 -1
  166. package/dist/sdk/test/entry.js +3 -2
  167. package/dist/sdk/test/execution.d.ts +28 -3
  168. package/dist/sdk/test/execution.js +201 -34
  169. package/dist/sdk/test/parsers.d.ts +6 -0
  170. package/dist/sdk/test/parsers.js +21 -2
  171. package/dist/sdk/test/trust.d.ts +33 -0
  172. package/dist/sdk/test/trust.js +207 -0
  173. package/dist/types.d.ts +34 -0
  174. package/dist/types.js +2 -2
  175. package/docs/AGENT_PROVENANCE_ADR.md +41 -5
  176. package/docs/AGENT_UX_CONTRACTS.md +20 -4
  177. package/docs/COMMANDS.md +29 -14
  178. package/docs/CONFIGURATION.md +4 -0
  179. package/docs/DEPENDENCY_KIND_CONTRACT.md +31 -3
  180. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +115 -0
  181. package/docs/EXTENSIONS.md +2 -1
  182. package/docs/MERGE_SAFETY.md +15 -1
  183. package/docs/README.md +1 -0
  184. package/docs/READ_OUTPUT_CONTRACTS.md +19 -2
  185. package/docs/RELATIONSHIP_GRAPH.md +6 -3
  186. package/docs/REPRODUCIBLE_WORKSPACES.md +42 -8
  187. package/docs/SDK.md +9 -0
  188. package/docs/SDK_AGENT_SESSION_CONTEXT.md +6 -4
  189. package/docs/SDK_EVIDENCE_TRACEABILITY.md +1 -1
  190. package/docs/TESTING.md +83 -1
  191. package/docs/agent-task-token-baseline.json +2 -2
  192. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  193. package/marketplace.json +2 -2
  194. package/package.json +2 -2
  195. package/packages/pm-beads/package.json +1 -1
  196. package/packages/pm-calendar/package.json +1 -1
  197. package/packages/pm-command-kit/package.json +1 -1
  198. package/packages/pm-digital-twin/package.json +1 -1
  199. package/packages/pm-governance-audit/package.json +1 -1
  200. package/packages/pm-guide-shell/package.json +1 -1
  201. package/packages/pm-kanban/package.json +1 -1
  202. package/packages/pm-lifecycle-hooks/package.json +1 -1
  203. package/packages/pm-linked-test-adapters/package.json +1 -1
  204. package/packages/pm-search-advanced/package.json +1 -1
  205. package/packages/pm-templates/package.json +1 -1
  206. package/packages/pm-todos/package.json +1 -1
  207. package/packages/pm-vcs/package.json +1 -1
  208. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  209. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  210. package/sdk/public-surface.json +1021 -53
  211. package/dist/cli-bundle/chunks/chunk-2MA6ZQVZ.js +0 -197
  212. package/dist/cli-bundle/chunks/chunk-3AFAUHUE.js +0 -2
  213. package/dist/cli-bundle/chunks/chunk-7VHZS727.js +0 -5
  214. package/dist/cli-bundle/chunks/chunk-JSLOFXGA.js +0 -3
  215. package/dist/cli-bundle/chunks/chunk-OCLPLFAY.js +0 -35
  216. package/dist/cli-bundle/chunks/chunk-S4IRYKBU.js +0 -13
  217. package/dist/cli-bundle/chunks/register-mutation-7IY2D5KO.js +0 -20
  218. package/dist/cli-bundle/chunks/register-operations-FALL3YTU.js +0 -2
  219. package/dist/cli-bundle/focused-chunks/chunk-7WZRLCYF.js +0 -50
  220. package/dist/cli-bundle/focused-chunks/chunk-CKKQSJNN.js +0 -2
  221. package/dist/cli-bundle/focused-chunks/chunk-EEFKYMDR.js +0 -16
  222. package/dist/cli-bundle/focused-chunks/chunk-F2A56DHV.js +0 -8
  223. package/dist/cli-bundle/focused-chunks/chunk-FV5ACOK7.js +0 -2
  224. package/dist/cli-bundle/focused-chunks/chunk-JEAVFOWM.js +0 -2
  225. package/dist/cli-bundle/focused-chunks/chunk-NJ63LOP6.js +0 -155
  226. package/dist/cli-bundle/focused-chunks/chunk-NXRTQ7HI.js +0 -2
  227. package/dist/cli-bundle/focused-chunks/chunk-TJ7EMJ46.js +0 -4
  228. package/dist/cli-bundle/focused-chunks/chunk-ZOSEELYJ.js +0 -26
@@ -1,55 +1,55 @@
1
- import{n as wm,o as _s,p as Am,q as Tm,r as Ui,s as ys,t as Cm,u as Gi,v as bs,y as Km,z as zm}from"./focused-chunks/chunk-ZOSEELYJ.js";import{a as Wm,f as Ym,h as Kt,m as Zm,o as eu,r as tu,s as nu,w as ru}from"./focused-chunks/chunk-NXRTQ7HI.js";import{$ as ga,$a as Jp,Aa as Op,Ba as Pp,Bb as ef,Ca as Np,Cb as of,Da as Lp,Db as af,Ea as Rn,Fa as Fp,G as ip,Ga as Mp,I as w,Ia as tr,J as ap,Ja as $p,K as cp,Ka as Dp,L as Me,La as Up,M as dp,Ma as Gp,N as ma,Na as jp,O as lp,Oa as qp,P as ua,Q as Ys,R as pa,Ra as Kp,S as Vt,Sa as Xs,T as fa,Ta as Iw,U as be,Ua as zp,V as _a,Va as Bp,W as $e,Wa as ya,X as mp,Xa as Hp,Y as up,Ya as Vp,Z as ha,Za as Wp,_ as pp,_a as Yp,a as Wi,ab as Xp,b as qu,bb as nr,cb as ba,db as wa,eb as Qs,fb as va,gb as Qp,ha as fp,hb as ka,i as tp,ib as Zs,j as np,ja as Js,jb as In,ka as _p,kb as Sa,la as hp,lb as Ea,ma as gp,mb as Zp,na as yp,oa as bp,pa as wp,pb as eo,qa as vp,ra as kp,sa as Sp,ta as Ep,ua as Ap,va as Tp,wa as Cp,xa as Rp,ya as Ip,za as xp}from"./focused-chunks/chunk-7WZRLCYF.js";import{e as gm,g as ym,h as bm,k as vm,q as Em}from"./focused-chunks/chunk-KDNG7TKQ.js";import{b as Bm,c as ws,e as Hm,f as Vm,g as hw}from"./focused-chunks/chunk-YKBKIEAJ.js";import{H as Vi,L as qm,a as al,b as cl,c as dl,d as ll,f as ml}from"./focused-chunks/chunk-CKKQSJNN.js";import{a as Uu,b as Gu,c as ro}from"./focused-chunks/chunk-F2A56DHV.js";import{Z as op,b as ju,e as rp,f as Zn,g as er,i as la,t as sp}from"./focused-chunks/chunk-FV5ACOK7.js";import{Ba as xw,Ca as Ta,D as to,Da as Ca,E as nf,Ea as no,F as sr,Fa as Ow,G as rf,Ga as Pw,O as xt,Q as Aa,Ya as Ra,bb as or,c as oa,db as sf,e as ia,g as Fu,h as Ps,hb as Ia,i as aa,j as Mu,k as Ns,l as Ls,m as Fs,n as $u,o as Du,s as Yu,t as Ju,u as Xu,v as Qu,w as Zu,wb as ir,x as ep,xb as xa,y as rr}from"./focused-chunks/chunk-EEFKYMDR.js";import{a as su,b as ou,c as iu}from"./focused-chunks/chunk-UZE7XUZK.js";import{A as ca,B as Ws,Ca as Wu,D as zu,E as Bu,Ea as so,F as Qn,Ia as xn,a as Ms,b as $s,c as Ds,d as Us,h as Gs,j as js,k as qs,l as Ku,m as Ks,n as zs,o as It,p as Sn,q as Bs,r as En,s as Hs,t as ne,u as Vs,v as ze,va as Cn,w as Fe,wa as Hu,x as ie,xa as da,y as An,ya as Vu,z as Tn}from"./focused-chunks/chunk-2NIY5NKG.js";import{c as fm,f as _m,g as hm,i as fs,j as St,k as Rm,l as Im,m as xm}from"./focused-chunks/chunk-F4YEW5I2.js";import{$ as Gl,A as zr,Aa as am,B as wl,Ba as es,C as vl,Ca as cm,D as kl,Da as dm,E as Br,Ea as lm,F as Sl,Fa as ts,G as El,Ga as ns,H as Al,Ha as rs,I as Hr,Ia as ss,J as Vr,Ja as Vn,K as Tl,Ka as os,L as Wr,La as mm,Ma as Wn,N as Cl,Na as is,O as Hn,Oa as as,P as Rl,Pa as cs,Q as Il,Qa as ds,R as xl,Ra as um,S as Ol,Sa as kt,T as Pl,Ta as ls,U as Nl,Ua as ms,V as Ll,Va as us,W as Fl,Wa as ps,X as Ml,Y as $l,Z as Dl,Za as pm,_ as Ul,aa as jl,ab as F,ba as ql,ca as Kl,d as Mi,da as zl,e as ul,ea as Bl,fa as Yr,ga as Jr,h as pl,ha as Hl,i as $i,ia as Vl,j as qt,ja as Wl,ka as Yl,l as fl,la as Jl,ma as Xl,na as Ql,oa as Zl,q as Di,qa as em,ra as tm,s as jr,sa as nm,t as qr,ta as rm,u as Kr,ua as sm,v as _l,va as om,w as hl,wa as Xr,x as gl,xa as Qr,y as yl,ya as Zr,z as bl,za as im}from"./focused-chunks/chunk-FJ22HNRP.js";import{c as tf}from"./focused-chunks/chunk-4ERLO7QD.js";import{$a as Iu,Ab as Nu,Bb as Z,Cb as Lu,Da as Ke,Db as Te,Ea as Tt,F as Es,G as du,Ga as Rs,H as lu,Ha as Le,I as gn,Ia as Bt,J as Jn,Ja as ku,K as vw,Ka as Ht,L as kw,La as Su,M as Sw,N as Ew,Na as Eu,O as Aw,Oa as wn,P as As,Pa as Au,Q as Tw,Qa as Is,R as Cw,Ra as ot,S as Rw,T as yn,U as T,V as k,Wa as Tu,X as bn,Xa as Cu,Ya as Ct,Z as Q,_ as Ne,_a as Ru,a as au,ab as A,ba as mu,bb as Ae,c as cu,ca as Ts,cb as xu,da as uu,db as Ou,e as Yi,ea as pu,eb as Rt,f as Ji,fa as fu,fb as sa,g as Xi,ga as _u,gb as ye,h as Qi,ha as hu,hb as Xn,i as Zi,j as ea,ja as W,k as ta,l as R,la as se,m as _n,ma as Cs,n as zt,na,nb as vn,o as z,oa as gu,p as ks,pa as qe,pb as kn,q as hn,qa as Ye,ra as At,rb as Pu,sa as yu,sb as C,t as Ss,ta as bu,tb as D,ua as ra,ub as K,v as je,w as gw,wa as wu,wb as oe,x as yw,xa as vu,xb as xs,y as bw,yb as Os,z as ww,zb as it}from"./focused-chunks/chunk-NJ63LOP6.js";import{$ as Wd,B as Li,C as zn,D as he,G as I,Ga as Ur,H as pe,Ha as il,I as Mr,Ia as Gr,J as un,K as Bn,L as Hd,La as rt,M as E,N as Vd,Na as hs,O as tt,Oa as st,P as ge,Pa as Et,Q as jt,Qa as km,S as Ee,Sa as $,T as $r,Ta as gs,Ua as We,Wa as Sm,Z as pn,ba as Fi,ca as Yd,ea as Jd,ga as Dr,h as wt,i as Lr,ia as Xd,j as Fr,ja as Qd,la as Zd,ma as el,na as tl,oa as nl,pa as rl,q as x,qa as sl,r as Gt,ra as ol,s as vt,t as q,u as ue,w as mn}from"./focused-chunks/chunk-TJ7EMJ46.js";import{b as vs,h as Jm,i as Xm,l as fn,p as Qm}from"./focused-chunks/chunk-FH6DYED3.js";import{A as jd,B as qd,C as Kd,D as zd,Da as nw,E as Ci,Ea as rw,F as Ri,Fa as sw,G as Ii,Ga as ow,H as xi,Ha as Gm,I as Oi,J as Pi,L as Nr,Na as zi,Pa as iw,Qa as aw,R as Ni,T as Bd,W as bt,Y as l,Z as m,_a as cw,aa as J,ab as dw,ba as nt,bb as lw,cb as Bi,db as mw,ea as Yn,eb as Hi,hb as jm,ia as Om,ib as uw,ja as Pm,ka as Nm,kb as pw,l as xr,la as Lm,lb as fw,m as Dd,ma as Fm,mb as _w,n as Or,na as Mm,o as Ti,oa as ji,pa as $m,qa as Dm,s as Ut,t as et,ta as qi,u as dn,ua as Um,v as ln,va as Ki,w as Pr,y as Ud,z as Gd}from"./focused-chunks/chunk-JEAVFOWM.js";import{AsyncLocalStorage as sF}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 cf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Nw(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 Oa(e,t){let n=Nw(t),r=n==="brief"?n:cf(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:cf(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 df(e,t){let n=E(t??process.cwd(),e),r=await A(n);return oe(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 Lw=new Map;function Pa(){Lw.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 Fw={"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 lf(e){return Object.fromEntries(Dm.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var mf={ctx:{action:"context"},...Fw,...lf("extension"),...lf("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 Na="PmCliError";function Mw(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 uf(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,Mw(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 oo(e){if(!(e instanceof Error)||e.name!==Na)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 La(e){let t=Jd();for(let n of e)t.register(n);return t}function pf(e,t){return{client:t,isItemNotFoundError:n=>oo(n)&&n.exitCode===l.NOT_FOUND,getItemAt:(n,r)=>Du(n,r,{pmRoot:e}),openRelationshipEventStore:n=>Gu.open({pmRoot:e,nodes:n.nodes,registry:La(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new Qd(n.nodes,n.edges,La(n.definitions)),analyzeRelationshipImpact:(n,r,s)=>ju(n,r,s),validateRelationshipEvents:n=>{let r=new Uu(n.nodes,{registry:La(n.definitions)});return n.events.map(s=>r.append({...s,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>qu({...n,pmRoot:e})}}import{readFile as $w}from"node:fs/promises";import Dw 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 Fa="context-intents.json";function io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Uw(e,t,n){if(!io(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 ff(e,t){let n=Array.isArray(e)?e:io(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)=>Uw(r,t,s))}async function Gw(e){let t=Dw.join(e,Fa),n;try{n=await $w(t,"utf8")}catch(s){if(Gt(s))return[];throw await Pu(e),s}let r;try{r=JSON.parse(n)}catch(s){let o=s instanceof Error?s.message:String(s);throw new TypeError(`Invalid ${Fa}: ${o}`,{cause:s})}return ff(r,Fa)}function jw(e){if(!io(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return io(n)?n.contextIntents??n.context_intents:void 0}function qw(e){return e.flatMap(t=>{let n=jw(t.module);return n===void 0?[]:ff(n,`package ${t.name}`)})}async function Kw(e){let t=await Gw(e.pmRoot),n=qw(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Ma(e,t){let n=await Kw(e);return await Xm(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 _f(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 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 Mm,o as So,p as jm,q as qm,r as Ji,s as To,t as Km,u as Xi,v as Co,y as iu,z as au}from"./focused-chunks/chunk-QGFNI65N.js";import{a as mu,f as uu,h as Bt,m as hu,o as gu,r as yu,s as wu,w as bu}from"./focused-chunks/chunk-MRCNF3U6.js";import{$ as Ca,$a as ff,Aa as Wp,Ba as Yp,Ca as Jp,Da as Xp,Ea as Pn,Fa as Qp,G as Sp,Ga as Zp,Gb as vf,Hb as Tf,I as b,Ia as ir,Ib as Cf,J as Ep,Ja as ef,K as Ap,Ka as tf,L as De,La as nf,M as Tp,Ma as rf,N as va,Na as of,O as Cp,Oa as sf,P as ka,Q as os,R as Sa,Ra as af,S as Yt,Sa as ss,T as Ea,Ta as Qb,U as ve,Ua as cf,V as Aa,Va as df,W as Ue,Wa as Ra,X as Rp,Xa as lf,Y as Ip,Ya as mf,Z as Ta,Za as uf,_ as xp,_a as pf,a as sa,ab as _f,b as sp,bb as ar,cb as Ia,db as xa,eb as is,fb as Oa,gb as hf,ha as Op,hb as Pa,i as yp,ib as as,j as wp,ja as sr,jb as Ln,ka as Pp,kb as La,la as Lp,lb as Na,ma as Np,mb as gf,na as Fp,nb as yf,oa as Mp,ob as wf,pa as $p,pb as Nn,qa as Dp,qb as Fa,ra as Up,rb as bf,sa as Gp,ta as jp,ua as qp,ub as cs,va as Kp,wa as zp,xa as Bp,ya as Hp,za as Vp}from"./focused-chunks/chunk-OY7QAV4Y.js";import{e as Lm,g as Nm,h as Fm,k as $m,q as Gm}from"./focused-chunks/chunk-R27IDGHD.js";import{b as cu,c as Ro,e as du,f as lu,g as Fb}from"./focused-chunks/chunk-JOWDB2MH.js";import{H as oa,L as su,a as Sl,b as El,c as Al,d as Tl,f as Cl}from"./focused-chunks/chunk-E7X25GC3.js";import{a as np,b as rp,c as ms}from"./focused-chunks/chunk-3UPTYG44.js";import{P as kp,b as op,j as vp}from"./focused-chunks/chunk-LYVSW5VM.js";import{Ba as Zb,Ca as $a,D as ds,Da,E as Sf,Ea as ls,F as dr,Fa as ev,G as Ef,Ga as tv,O as Pt,Q as Ma,Ya as Ua,bb as lr,c as ha,db as Af,e as ga,g as Qu,h as Go,hb as Ga,i as ya,j as Zu,k as jo,l as qo,m as Ko,n as ep,o as tp,s as up,t as pp,u as fp,v as _p,w as hp,wb as mr,x as gp,xb as ja,y as cr}from"./focused-chunks/chunk-5S7E72FY.js";import{a as vu,b as ku,c as Su}from"./focused-chunks/chunk-OFVUGTLJ.js";import{A as wa,B as ns,Ca as mp,D as ap,E as cp,Ea as us,F as nr,Ia as Fn,a as zo,b as Bo,c as Ho,d as Vo,h as Wo,j as Yo,k as Jo,l as ip,m as Xo,n as Qo,o as xt,p as Cn,q as Zo,r as Rn,s as es,t as se,u as ts,v as ze,va as On,w as $e,wa as dp,x as me,xa as ba,y as In,ya as lp,z as xn}from"./focused-chunks/chunk-ZHVA42R5.js";import{c as xm,f as Om,g as Pm,i as ko,j as Et,k as zm,l as Bm,m as Hm}from"./focused-chunks/chunk-37Z4OEAP.js";import{$ as nm,A as Xr,Aa as Sm,B as Ml,Ba as ao,C as $l,Ca as Em,D as Dl,Da as Am,E as Qr,Ea as Tm,F as Ul,Fa as co,G as Gl,Ga as lo,H as jl,Ha as mo,I as Zr,Ia as uo,J as eo,Ja as Xn,K as ql,Ka as po,L as to,La as Cm,Ma as Qn,N as Kl,Na as fo,O as Jn,Oa as _o,P as zl,Pa as ho,Q as Bl,Qa as go,R as Hl,Ra as Rm,S as Vl,Sa as St,T as Wl,Ta as yo,U as Yl,Ua as wo,V as Jl,Va as bo,W as Xl,Wa as vo,X as Ql,Y as Zl,Z as em,Za as Im,_ as tm,aa as rm,ab as M,ba as om,ca as sm,d as Vi,da as im,e as Rl,ea as am,fa as no,ga as ro,h as Il,ha as cm,i as Wi,ia as dm,j as zt,ja as lm,ka as mm,l as xl,la as um,ma as pm,na as fm,oa as _m,q as Yi,qa as hm,ra as gm,s as Wr,sa as ym,t as Yr,ta as wm,u as Jr,ua as bm,v as Ol,va as vm,w as Pl,wa as oo,x as Ll,xa as so,y as Nl,ya as io,z as Fl,za as km}from"./focused-chunks/chunk-OGLQBL46.js";import{c as kf}from"./focused-chunks/chunk-AUFH5H35.js";import{$a as Ku,Ba as $u,Bb as le,Ca as Du,Cb as Do,Db as Uo,Eb as at,F as Po,Fb as Ju,G as Tu,Gb as re,H as Cu,Hb as Xu,I as vn,Ia as Ke,Ib as xe,J as er,Ja as Ct,Jb as bp,K as Gb,Kb as rr,L as jb,La as Mo,Lb as or,M as qb,Ma as Me,Mb as Ot,N as Kb,Na as Vt,O as zb,Oa as Uu,P as Bb,Pa as Wt,Q as Hb,Qa as Gu,R as Vb,Rb as rs,S as Wb,Sa as ju,T as Lo,Ta as En,U as Yb,Ua as qu,V as Jb,Va as $o,W as Xb,Wa as it,X as kn,Y as T,Z as k,a as Eu,aa as Sn,ab as zu,bb as Rt,c as Au,ca as ne,da as we,db as Bu,e as ia,eb as Hu,f as aa,fb as A,g as ca,ga as Ru,gb as Ie,h as da,ha as No,hb as Vu,i as la,ia as Iu,ib as Wu,j as ma,ja as xu,jb as It,k as ua,ka as Ou,kb as _a,l as R,la as Pu,lb as be,m as wn,ma as Lu,mb as tr,n as Ht,o as z,oa as Z,p as xo,q as bn,qa as te,ra as Fo,sa as pa,sb as An,t as Oo,ta as Nu,ua as qe,ub as Tn,v as je,va as Je,w as Mb,wa as Tt,wb as Yu,x as $b,xa as Fu,xb as C,y as Db,ya as Mu,yb as U,z as Ub,za as fa,zb as K}from"./focused-chunks/chunk-IFLWKY2R.js";import{$ as ll,B as Bi,C as Wn,D as ge,G as I,Ga as Hr,H as _e,Ha as kl,I as Kr,Ia as Vr,J as hn,K as Yn,L as cl,La as ot,M as E,N as dl,Na as Eo,O as nt,Oa as st,P as ye,Pa as At,Q as Kt,Qa as Dm,S as Re,Sa as $,T as zr,Ta as Ao,Ua as Ye,Wa as Um,Z as gn,ba as Hi,ca as ml,ea as ul,ga as Br,h as vt,i as jr,ia as pl,j as qr,ja as fl,la as _l,ma as hl,na as gl,oa as yl,pa as wl,q as P,qa as bl,r as qt,ra as vl,s as kt,t as q,u as fe,w as _n}from"./focused-chunks/chunk-FQCSTBWE.js";import{b as Io,h as pu,i as fu,l as yn,p as _u}from"./focused-chunks/chunk-FZS4H32O.js";import{A as rl,B as ol,C as sl,D as il,E as Di,Ea as vb,F as Ui,Fa as kb,G as Gi,Ga as Sb,H as ji,Ha as Eb,I as qi,J as Ki,Ja as nu,L as Gr,Na as ru,R as zi,Sa as ta,T as al,W as bt,Xa as Ab,Y as l,Ya as Tb,Z as m,aa as J,ba as rt,ea as Zn,gb as Cb,ia as Vm,ib as Rb,ja as Wm,jb as Ib,ka as Ym,kb as na,l as $r,la as Jm,lb as xb,m as el,ma as Xm,mb as ra,n as Dr,na as Qm,o as $i,oa as Qi,pa as Zm,pb as ou,qb as Ob,ra as eu,s as jt,sb as Pb,t as tt,tb as Lb,u as pn,ua as Zi,ub as Nb,v as fn,va as tu,w as Ur,wa as ea,y as tl,z as nl}from"./focused-chunks/chunk-UYRFYCDQ.js";import{AsyncLocalStorage as tM}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 Rf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nv(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 qa(e,t){let n=nv(t),r=n==="brief"?n:Rf(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:Rf(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 If(e,t){let n=E(t??process.cwd(),e),r=await A(n);return le(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 rv=new Map;function Ka(){rv.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 ov={"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 xf(e){return Object.fromEntries(eu.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Of={ctx:{action:"context"},...ov,...xf("extension"),...xf("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 za="PmCliError";function sv(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 Pf(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,sv(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 ps(e){if(!(e instanceof Error)||e.name!==za)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 Ba(e){let t=ul();for(let n of e)t.register(n);return t}function Lf(e,t){return{client:t,isItemNotFoundError:n=>ps(n)&&n.exitCode===l.NOT_FOUND,getItemAt:(n,r)=>tp(n,r,{pmRoot:e}),openRelationshipEventStore:n=>rp.open({pmRoot:e,nodes:n.nodes,registry:Ba(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new fl(n.nodes,n.edges,Ba(n.definitions)),analyzeRelationshipImpact:(n,r,o)=>op(n,r,o),validateRelationshipEvents:n=>{let r=new np(n.nodes,{registry:Ba(n.definitions)});return n.events.map(o=>r.append({...o,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>sp({...n,pmRoot:e})}}import{readFile as iv}from"node:fs/promises";import av 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 Ha="context-intents.json";function fs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cv(e,t,n){if(!fs(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function Nf(e,t){let n=Array.isArray(e)?e:fs(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,o)=>cv(r,t,o))}async function dv(e){let t=av.join(e,Ha),n;try{n=await iv(t,"utf8")}catch(o){if(qt(o))return[];throw await Yu(e),o}let r;try{r=JSON.parse(n)}catch(o){let s=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Ha}: ${s}`,{cause:o})}return Nf(r,Ha)}function lv(e){if(!fs(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return fs(n)?n.contextIntents??n.context_intents:void 0}function mv(e){return e.flatMap(t=>{let n=lv(t.module);return n===void 0?[]:Nf(n,`package ${t.name}`)})}async function uv(e){let t=await dv(e.pmRoot),n=mv(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Va(e,t){let n=await uv(e);return await fu(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 Ff(e,t,n){if(t.body===void 0)throw new m("Missing required --body text",l.USAGE);let r=$e(),o=E(process.cwd(),n.path);await C(o);let s=await A(o),i=T(t.author,s.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 re({pmRoot:o,settings:s,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:d.item,appended:c,changed_fields:d.changedFields}}import{readFile as zw}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 co(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,t}function hf(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 $a(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Wt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function On(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 Da(e){return typeof e=="object"&&e!==null&&"code"in e}async function Bw(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 zw(s,"utf8"),emptyFlag:"--file"}}catch(o){if(Da(o)&&Gt(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 lo(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 Bw(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 cr(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 yf(e){return e==="comments"?"--stdin":"--add -"}function Hw(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=yf(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 Vw(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> ${yf(e.collectionKey)}`]})}async function Pn(e,t,n,r){Vw(r,t);let s=E(process.cwd(),n.path);await C(s);let o=await A(s),i=I(o,R()),a=Qn(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=Wt(h.document.metadata,r.collectionKey);return ao(_.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 Z({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Wt(g.metadata,r.collectionKey),v=gf(r.input.index,b.length,r.collectionKey);return hf(b[v],"deleted"),b.splice(v,1),g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){cr(g,r.conflictGuidance)}let y=Wt(h.item,r.collectionKey);return ao(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??"";Hw(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 Z({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Wt(g.metadata,r.collectionKey),v=gf(r.input.index,b.length,r.collectionKey),S=b[v];return hf(S,"edited"),b[v]={...S,text:u,edited_at:k()},g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){cr(g,r.conflictGuidance)}let y=Wt(h.item,r.collectionKey);return ao(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=Wt(_.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(_){cr(_,r.conflictGuidance)}let f=Wt(p.item,r.collectionKey);return ao(p.item.id,r.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:f.length,entry:f.at(-1)},t.fullHistory===!0)}function gf(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 ao(e,t,n,r,s,o,i=!1){let a=o===void 0||i?$a(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 bf(e,t,n){return[...await At(Ee(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 wf="no_available_next_item";function vf(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 mo(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=yn(a),d=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(d=y.trim().length>0?y:null,Sm(_.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 bf(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 Ta({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 kf(e,t,n={},r={}){let s=Ww(n.maxAttempts),o=await A(E(process.cwd(),t.path)),i={...n,author:T(n.author,o.author_default)},a=await or({...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 Yw(c.slice(0,s),e,t,i)}function Ww(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 Yw(e,t,n,r={},s=mo){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(!vf(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:[wf]};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:wf,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 uo(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=yn(i),c=r.ownershipReleaseBypass===!0,d=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 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){cr(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 Ca({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 Jw=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function Sf(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 Ua(e,t){return Ga(e,t,{operation:"close"})}function Ga(e,t,n){let r=Sf(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 ja(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 Xw=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function Qw(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 Zw(e){let t=[];for(let n of Xw){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function ev(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 tv(e){return typeof e!="string"||e.trim().length===0}async function nv(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 ev(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 rv(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 sv(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),s=tf(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&&se(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function ov(e,t,n,r,s,o){let i=sv(n,r,o),a=[];for(let c of i)try{let d=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:${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 iv(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 av(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)tv(e[s])&&(e[s]=o,n.push(s));return n}function cv(e,t,n,r){let s=[];if(t!=="off"){let o=Zw(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:vs(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 dv(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function lv(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function mv(e,t){if(se(e.status,t.statusRegistry)&&!t.force)throw new m(`Item ${e.id} is already terminal; use --force to close again.`,l.CONFLICT);let n=iv(e,t.options),r=av(e,t.duplicateOf),s=cv(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"]:[],...dv(e,t.closeReason),...n];if(Vu(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(...lv(e));let a=ja(e,t.lifecyclePolicy);return i.push(...a.changedFields),s.push(...a.warnings),{changedFields:i,...s.length>0?{warnings:s}:{}}}async function Ef(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 it(s,e,o.id_prefix,c);let u=await nv(s,o,n.duplicateOf,d.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Ua({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=Qw(n.validateClose)??o.governance.close_validation_default,h=await oe(s,o.item_format,c,void 0,o.schema),y=rv(h,d.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:d.id,op:"close",author:a,message:n.message,force:n.force,mutate(S){return mv(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 ov(s,o,h,d.id,a,i)]}}function at(e,t,n,r){return Ef(e,t,n,r)}import uv from"fast-json-patch";import qa 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 pv(e,t){return Fu(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function fv(e){let t=aa(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Ye(Bt(t))}async function _v(e,t,n,r){let s=await D(e,t,n.id_prefix,n.item_format,r);if(s){let c=Ee(e,s.id),d=await xu({pmRoot:e,settings:n,itemId:s.id,commandLabel:"restore"});return{id:s.id,historyPath:c,located:s,historyPolicyWarnings:d.warnings}}let o=ye(t,n.id_prefix),i=sa(t),a=o===i?[o]:[o,i];for(let c of a){let d=Ee(e,c);if(await x(d))return{id:c,historyPath:d,located:null,historyPolicyWarnings:[]}}throw new m(`Item ${t} not found`,l.NOT_FOUND)}function hv(e,t){let n=Ht(e),r=Ht(t),s=uv.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 gv(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 yv(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:fv(t),originalRaw:null}}function bv(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 wv(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await ue(e.existingItemPath,e.resolvedOriginalRaw),await qa.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await ue(e.existingItemPath,e.resolvedOriginalRaw);return}await qa.rm(e.restoredItemPath,{force:!0})}async function vv(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 Yt(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 _v(s,e,o,i.type_to_folder),c=a.id,d=await q(a.historyPath),u=await At(a.historyPath,c);if(u.length===0)throw new m(`No history exists for ${c}; restore is unavailable.`,l.NOT_FOUND);let p=pv(t,u),f=Mu(aa(u,p.historyIndex),p),_=ku(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 Ne(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 gv({pmRoot:s,resolvedId:c,subject:a,settings:o,typeToFolder:i.type_to_folder,historyRawBeforeLock:d,currentItemRawBeforeLock:y}),N="toon",O=yv(v,u),j=bv({document:O.document,author:g,force:n.force,enforcement:o.governance.ownership_enforcement,resolvedId:c}),M=hv(O.document,_);await ks({pm_root:s,operation:"restore",before:O.document,after:_,changed_fields:M,sdk:Os({pmRoot:s,settings:o,typeToFolder:i.type_to_folder})});let Oe=qe(_,{format:N,schema:o.schema}),te=jt(s,_.metadata.type,c,N,i.type_to_folder),_e=await vn(s,g),ce=[];try{await ue(te,Oe),S&&te!==S&&await qa.rm(S);let ft=Ke({nowIso:k(),author:g,op:"restore",before:O.document,after:_,message:n.message});try{await Tt(a.historyPath,ft)}catch(_t){throw await wv({existingItemPath:S,resolvedOriginalRaw:O.originalRaw,restoredItemPath:te}),_t}ce=await kn({pmRoot:s,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:te,previousItemPath:S??void 0,document:_})}finally{await _e()}let Ze=await vv({restoredItemPath:te,historyPath:a.historyPath,before:O.document,after:_});_n({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:O.document.metadata.status,status:_.metadata.status,previous:zt(O.document.metadata,M),current:zt(_.metadata,M),changed_fields:M});let pt=u[p.historyIndex];return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,entry_ts:pt.ts,entry_op:pt.op},changed_fields:M,warnings:[...a.historyPolicyWarnings,...j,...ce,...Ze]}}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 Tf=1,Ka="close-many",kv=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function Sv(e,t){return rr(e,t,{includePagination:!1})}function Ev(e,t){return rr(e,t)}function Av(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 Tv(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 Cv(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 Rv(e,t){let n=$(t.schema),r=I(t,R()),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,d)=>c.localeCompare(d));return{childrenByParent:o,parentByChild:i}}function Af(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 Iv(e){let t=await Ds(e.pmRoot,Ka,e.rollbackId,Tf),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Us(t.items,(s,o)=>Yt(s,o,{author:e.options.author,message:n,force:!0},e.global));return{...Kt({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 xv(e,t,n,r,s){return e.map(o=>{let i=(t.get(o.id)??[]).filter(c=>!n.has(c)),a=!Cf(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 Ov(e){let t=await $s(e.pmRoot,Ka,e.checkpointId,{schema_version:Tf,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 Pv(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 at(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:pn(s)})}}return{rows:t,closedIds:n}}function Nv(e){return typeof e.rollback=="string"?e.rollback:void 0}function Lv(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(Ev(e.list,e.status))throw new m("Rollback mode does not accept filter options",l.USAGE)}function Fv(e){if(!Sv(e.list,e.status))throw new m(`close-many requires at least one filter to scope the close (for example: ${kv}). Refusing to match every item.`,l.USAGE)}function Mv(e,t){let n=new Map;return[...e].sort((r,s)=>{let o=Af(s.id,t,n)-Af(r.id,t,n);return o!==0?o:r.id.localeCompare(s.id)})}function Cf(e,t,n){return n||!se(e.status,t)}function $v(e,t,n){return new Set(e.filter(r=>Cf(r,t,n)).map(r=>r.id))}async function Dv(e){Fv(e.options);let t=$(e.settings.schema),n=Cv(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,s=await xt(e.options.status,Tv(e.options.list),e.global),{childrenByParent:o,parentByChild:i}=await Rv(e.pmRoot,e.settings),a=Mv(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=$v(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:xv(a,o,u,t,r)}}function Uv(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 Gv(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 Ov({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 Rf(e,t){let n=E(process.cwd(),t.path);await C(n);let r=await A(n),s=e.dryRun===!0,o=Nv(e);if(Av(e.list),o!==void 0)return Lv(e,o),Iv({pmRoot:n,rollbackId:o,options:e,global:t});let i=await Dv({pmRoot:n,settings:r,options:e,global:t});if(s)return Uv(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=k(),d=Ms(Ka,c),u=await Gv({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 Pv({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{...Kt({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 jv}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 za(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 jv(i,"utf8"),emptyFlag:"--file"}}catch(a){if(Da(a)&&Gt(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 qv(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 za(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 za(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 za(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 If(e,t,n){let r=Fe(),s=await qv(t,r),o=s.mode==="add"||s.mode==="edit",i=s.value??"";return Pn(e,t,n,{input:{...s,rawValue:t.add??i,value:o?On(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 xf(e,t,n){return Pn(e,t,n,{input:await lo(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>On(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 Kv(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 zv(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 Bv(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 Of(e,t,n){let r=Kv(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:J(r),i=[t.since,t.eventType].some(h=>h!==void 0),a=Bv(t.since),c=Qn(t.limit),d=await Pn(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await lo(o===void 0?t:{add:o},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>On(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:zv(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?$a(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 dr(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 lr(e,t,n=la()){for(let r of t??[])try{Xd(e,r.id,r.kind,n)}catch(s){throw new m(pn(s),l.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Pf(e,t){return(await K(e,{schema:t})).document.metadata.created_at}async function Hv(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:Pf(n,t.schema)}function Vv(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 Wv(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 Pf(n.get(s),e.context.schema)])));for(let s of e.holders){let o=await Hv(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 Vv({holder:s,dependency:i,sourceCreatedAt:o,targetCreatedAt:a,registry:e.registry})}}}async function Jt(e){let t=e.registry??la(),n=(e.dependencies??[]).filter(i=>!rp(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 Wv({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 po(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function fo(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function _o(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Pr.includes(t))return t;let n=ie(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 ho(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 Yv=new Set(["none","null"]);function go(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:Yv.has(e.trim().toLowerCase())}function yo(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 we(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 bo(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 Lf(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 Ba(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function ve(e,t,n){if(!t.includes(e))throw new m(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,l.USAGE);return e}var Ff=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Jv(e,t){return t==="defined"?e!==void 0:!!e}function Nf(e,t,n){if(!Jv(e,n))return;let r=ie(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new m(`--event ${t} must be an integer >= 1`,l.USAGE);return r}function Xv(e,t,n){let r=e?Q(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 Qv(e){return Array.from(new Set(Ba(e).map(t=>ve(t.toLowerCase(),zd,"event weekday")))).sort((t,n)=>Ci(t)-Ci(n))}function Zv(e){return Array.from(new Set(Ba(e).map(t=>{let n=ie(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 ek(e,t){return Array.from(new Set(Ba(e).map(n=>Q(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Mf(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=ve(s.toLowerCase(),Kd,"event recurrence frequency"),_=Nf(o,"recur_interval",r),h=Nf(i,"recur_count",r),y=Xv(a,t,n),g=Qv(c),b=Zv(d),v=ek(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 $f="--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.",tk="--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).",nk=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,rk=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Uf=1e3,Ha=60*Uf,sk=60*Ha;function Df(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 ok(e,t){let n=new Date(e),r=t.trim(),s=nk.exec(r);if(s){let a=s[1]==="-"?-1:1,c=Number.parseInt(s[2],10)*a;return Df(n.getTime()+c*Ha,r)}let o=rk.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=_*sk+h*Ha+y*Uf;return Df(n.getTime()+f*g,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return Q(i,n,"event.duration")}function Gf(e,t,n,r){if(t&&n)throw new m(tk,l.USAGE);if(n){let o=ok(e,n);if(o<e)throw new m($f,l.USAGE);return o===e?void 0:o}if(!t)return;let s=Q(t,r,"event.end");if(s<e)throw new m($f,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 ik=["at","date","text","title"],ak=["start","date","end","duration","title","description","location","timezone","all_day",...Ff],ck=["key","value"];function jf(e,t){return t==="trimmed"?e?.trim():e}function dk(e,t){return t==="defined"?e!==void 0:!!e}function wo(e,t,n){return e.map(r=>{let s=ne(r,"--reminder");ze(s,"--reminder",ik);let o=jf(s.at??s.date,n.valueMode),i=jf(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:Q(o,t,"reminder.at"),text:a}})}function vo(e,t,n){return e.map(r=>{let s=ne(r,"--event");ze(s,"--event",ak);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=Q(o,t,"event.start"),a=s.end?.trim(),c=s.duration?.trim(),d=Gf(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,M,Oe]of v)if(M!==void 0&&!Oe)throw new m(`--event ${j} must not be empty`,l.USAGE);let S=s.all_day?.trim(),N=Mf(s,i,t,n.recurrenceEmptyNumericGuard),O=dk(S,n.allDayEmptyGuard)?Lf(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:N}})}function ko(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=ne(r,"--type-option");ze(a,"--type-option",ck),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]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var lk=new Set(["event","meeting","reminder","milestone","decision","adr"]);function qf(e,t,n,r){if(lk.has(t.trim().toLowerCase())||n!==r.open_status)return;let s=gs("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 Xt=["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"],mk=new Set(Xt),uk=Xt.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),pk=new RegExp(`^(?:[-*+]\\s+)?(?:${uk})\\s*[:=]`,"i");function So(e){return e.startsWith("```")||e.includes(`
6
- `)?!0:pk.test(e)}function Eo(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!mk.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: ${Xt.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 Zt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Js,_p,"FORCE_COLOR"]),Co=/^[A-Za-z_][A-Za-z0-9_]*$/,Qt=["schema","tracker","auto"];function mr(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(!Co.test(i))throw new m(`${t} env_set key "${i}" is invalid`,l.USAGE);if(Zt.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 ur(e,t){if(!e)return;let n=Cn(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(!Co.test(r))throw new m(`${t} env_clear key "${r}" is invalid`,l.USAGE);if(Zt.has(r.toUpperCase()))throw new m(`${t} env_clear key "${r}" is reserved for sandbox safety`,l.USAGE)}return n}function Ro(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 Io(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Qt.includes(n))return n;throw new m(`${t} pm_context_mode must be one of: ${Qt.join(", ")}`,l.USAGE)}function en(e){if(!e)return;let t=Cn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Ln(e,t,n){let r=en(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 xo(e,t){if(!e)return;let n=ie(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 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 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 Po(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 fk=new Set(Xt);function No(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _k(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!fk.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: ${Xt.join(", ")}.`);return n}function Nn(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 Ao(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 Kf(e,t,n){let r=Ao(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 hk(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 gk(e,t){let n=Nn(e,"scope",t);if(n===void 0)return"project";if(!et.includes(n))throw t(`field "scope" must be one of: ${et.join(", ")}`);return n}function yk(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!No(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(!Co.test(s))throw t(`field "env_set" key "${s}" is invalid`);if(Zt.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 bk(e,t){let n=Ao(e,"env_clear",t);if(n){for(let r of n){if(!Co.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(Zt.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function wk(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 vk(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 kk(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!No(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 Sk(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!No(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 Ek(e,t,n){let r=p=>new m(`${n} ${t} ${p}`,l.USAGE);if(!No(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Xt.join(", ")}.`);let s=_k(e,r),o=Nn(s,"command",r),i=Nn(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=Nn(s,"path",r),d=Nn(s,"pm_context_mode",r);if(d!==void 0&&!Qt.includes(d))throw r(`field "pm_context_mode" must be one of: ${Qt.join(", ")}`);let u=Nn(s,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:gk(s,r),timeout_seconds:hk(s,r),pm_context_mode:d,env_set:yk(s,r),env_clear:bk(s,r),shared_host_safe:wk(s,"shared_host_safe",r),assert_stdout_contains:Ao(s,"assert_stdout_contains",r),assert_stdout_regex:Kf(s,"assert_stdout_regex",r),assert_stderr_contains:Ao(s,"assert_stderr_contains",r),assert_stderr_regex:Kf(s,"assert_stderr_regex",r),assert_stdout_min_lines:vk(s,r),assert_json_field_equals:kk(s,r),assert_json_field_gte:Sk(s,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function zf(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)=>Ek(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 Va=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Wa=[{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"}],Bf=[...Va,...Wa],Lo=[{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 Fo(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 Mo(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 Ak={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 Tk(e){return Ak[e]}function Ya(e){return Tk(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]="a10348fe-746d-5dc7-8cd4-30453c602a3f")}catch{}})();var Ck=["strict","progressive"],Rk=["lightweight"],Yf=new Set(["Reminder","Meeting","Event"]),Ik=new Set(["author","created_at","text"]),Xa=[...Bf,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...Lo],xk=(()=>{let e=new Map;for(let t of Xa)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),$o=new Map(Xa.map(e=>[e.optionKey,e.canonical])),Ok=Xa.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function Pk(e,t){let n=W(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 Nk(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 Ja(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 Lk=go();function Jf(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([...$o.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Be(o))continue;let i=s==="rank"?"order":$o.get(s)??s;n(i),t[s]=void 0}return bo(t,Lk)}function de(e){if(e!==void 0)return e}function Fk(e,t){return Fo({raw:e,supportedFields:Ok,resolveDefinition:n=>xk.get(n)??Mo(n,"create",t)})}var Hf=["id","kind","type","author","created_at","source_kind"],Do=["path","scope","note"];function Mk(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(we(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let i=o.trim(),a=Qa(i,Hf);dr(i,a);let c=a?ne(o,"--dep"):{id:i,kind:"related"};a&&ze(c,"--dep",Hf);let d=de(c.id),u=$k(de(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=Zn(de(c.source_kind)),f=de(c.author);return{id:er(d,n,p),kind:ve(u,Ut,"dependency kind"),created_at:Ja(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function $k(e){return typeof e=="string"?Dr(e)??e.trim():e}function Qa(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:Vs(e)}function nn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(we(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=ne(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(d).filter(f=>!Ik.has(f)).length>0)return{created_at:Ja(d.created_at,n),author:de(d.author)??r,text:a};let p=d.text??"";if(p==="")throw new m(`${e} requires text=<value>`,l.USAGE);return{created_at:Ja(d.created_at,n),author:de(d.author)??r,text:p}}),explicitEmpty:!1})}function Za(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(we(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),s=Qa(r,Do),o=s?ne(n,"--file"):{path:r};if(s&&ze(o,"--file",Do),!o.path)throw new m("--file requires path=<value> or a bare file path",l.USAGE);return{path:o.path,scope:ve(o.scope??"project",et,"file scope"),note:de(o.note)}}),explicitEmpty:!1})}function ec(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(we(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),s=So(r)?Eo(ne(n,"--test"),"--test"):{command:r},o=de(s.command),i=de(s.path);if(!o)throw new m("--test requires command=<value> or a bare command (path=<value> is optional metadata)",l.USAGE);let a=de(s.timeout_seconds),c=de(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:ve(s.scope??"project",et,"test scope"),timeout_seconds:d?ie(d,"timeout_seconds"):void 0,pm_context_mode:Io(s.pm_context_mode,"--test"),env_set:mr(s.env_set,"--test"),env_clear:ur(s.env_clear,"--test"),shared_host_safe:Ro(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:en(s.assert_stdout_contains),assert_stdout_regex:Ln(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:en(s.assert_stderr_contains),assert_stderr_regex:Ln(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:xo(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:Oo(s.assert_json_field_equals,"--test"),assert_json_field_gte:Po(s.assert_json_field_gte,"--test"),note:de(s.note)}}),explicitEmpty:!1})}function tc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(we(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),s=Qa(r,Do),o=s?ne(n,"--doc"):{path:r};if(s&&ze(o,"--doc",Do),!o.path)throw new m("--doc requires path=<value> or a bare doc path",l.USAGE);return{path:o.path,scope:ve(o.scope??"project",et,"doc scope"),note:de(o.note)}}),explicitEmpty:!1})}function Dk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(we(e,"--reminder","Use --clear-reminders to clear reminders."),{values:wo(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function Uk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(we(e,"--event","Use --clear-events to clear linked events."),{values:vo(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function Gk(e,t,n,r=[]){let s=[...Nr.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 jk(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Vf(e,t,n){let r=zn("create",e);if(!r)throw new m(`Unsupported ${n} entry "${e}" for type "${t}"`,l.CONFLICT);return r}function qk(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 Xf(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 Kk(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Vf(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Vf(r,e.name,"required_create_repeatables"));return n}function zk(e,t,n,r){for(let s of e)if(!(!Xf(t,s)&&!n.has(s)))throw new m(`Option ${he("create",s)} is disabled for type "${r}" by command_option_policies`,l.USAGE)}function Bk(e,t,n){if(t!=="strict")return;let r=e.filter(o=>n.has(o)&&!Ya(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 Hk(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(we(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:ko(e),explicitEmpty:!1})}async function Vk(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 Wk(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: ${Ck.join(", ")}`,l.USAGE)}function Yk(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: ${Rk.join(", ")}`,l.USAGE)}function Jk(e,t,n){let r=Wk(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 Xk(e,t,n,r){let s=e.name,o=qk(t),i=Kk(e,n),a=un(e,"create",i);if(a.errors.length>0)throw new m(a.errors.join("; "),l.CONFLICT);zk(a.disabled,o,r,s),Bk(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&Ya(u)?!0:Xf(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 Qf=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function Qk(e,t){let n=[];for(let r of e){let s=r.match(Qf);s&&s[2]===t&&n.push(s[1])}return[...new Set(n)].sort((r,s)=>r.localeCompare(s))}function Zk(e,t){return e.filter(n=>{let r=n.match(Qf);return!r||r[2]!==t})}function eS(e,t,n,r){let s=Zk(e,t);if(s.length===0)return;let o=Zf(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 tS(e,t){let r=e.options.find(s=>s.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function nS(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 Zf(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(...nS(c,e.name,r)),a.add(c));for(let c of n){let d=tS(e,c);s.push("--type-option",`${c}=${d}`)}return s.join(" ")}function nc(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 rS(e){return Tn(e)}function sS(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 oS(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function iS(){let e=R();return e?e.commands.some(t=>t.action==="templates-show"||oS(t.command)==="templates show"):!1}function aS(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 cS(e,t,n){if(!iS())throw new m("--template requires the templates package. Install it first (for example: pm install templates --project).",l.USAGE);let r=await Ss({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 aS(r.result,e)}function dS(e){return C(e)}function B(e,t,n){return e.has(t)||n===void 0?void 0:de(n)}function tn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var lS=new Set(["milestone","meeting","reminder","event"]);function e_(e,t,n,r){let s=t!==void 0,o=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return lS.has(e.toLowerCase())&&!s&&!o&&!i}function mS(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`),e_(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 uS(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let s=await Es(r);return s===void 0?{parent:e,parentSource:void 0}:{parent:s,parentSource:"focus"}}async function pS(e,t,n,r,s,o){let i=qs(s);if(zs(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=ye(i,t.id_prefix);return{parent:i,warnings:Ks(c,o).warnings}}async function fS(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await pS(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function _S(e){if(e.explicitId===void 0)return Xn(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||Ku(t))throw new m("--id must not be empty or use a placeholder token",l.USAGE);let n=ye(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 Wf(e,t,n,r,s){let o=B(e,t,n);if(o===void 0)return{value:void 0,warnings:[]};let i=Ws(r,o,s);return{value:i.value,warnings:i.warnings}}async function hS(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=ye(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 gS(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 yS(e,t){return e.options.filter(n=>zn("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 bS(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 cS(h,t,n);o=Jf(sS(y,o))}if(o.type===void 0&&gS(o,r,s),o.type===void 0)throw new m("Missing required option --type <value>",l.USAGE);let a=pe(o.type,s);if(!a){let h=Bu(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 m(St(o.type,s.types,Et(n,r.schema)),l.USAGE)}let c=Mr(a,s);if(!c)throw new m(`Invalid type value "${o.type}"`,l.USAGE);let d=c.name,u=yS(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=Yk(o.schedulePreset);if(f!==void 0&&!Yf.has(d))throw new m(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,l.USAGE);let _=Jk(o.createMode,f,r.governance.create_mode_default);return{resolvedOptions:o,typeDefinition:c,type:d,schedulePreset:f,createMode:_,warnings:i}}function wS(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 vS(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 m(`Cannot combine --unset ${o} with ${he("create",r)}`,l.USAGE)}}function kS(e){let t=(n,r)=>{let s=$o.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;yo(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 SS(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 ES(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=[Zf(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".'),Yf.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 AS(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?It(t.tags):[];return En(n,t.addTags)}function TS(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=tn(e,"order",n,s=>ie(s,"order"));if(r!==void 0&&!Number.isInteger(r))throw new m("Order must be an integer",l.USAGE);return r}function CS(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: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:Ga(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function RS(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=jt(t,n,r,s.item_format,o.type_to_folder),g=Ee(t,r),b=await Ne(t,r,s.locks.ttl_seconds,i,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),v=[];try{let S=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 m(`Item "${r}" already exists`,l.CONFLICT);await ks({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:Os({pmRoot:t,settings:s,typeToFolder:o.type_to_folder})});let O=await vn(t,i,{required:s.governance.duplicate_detection_mode==="strict"&&h!==!0}),j=[];try{s.governance.duplicate_detection_mode==="strict"&&h!==!0&&await xn(_,{pmRoot:t,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1}),await ue(y,qe(c,{format:s.item_format,schema:s.schema,extensionFieldNames:a}));try{let M=Ke({nowIso:f,author:i,op:"create",before:d,after:c,message:u});await Tt(g,M)}catch(M){throw await mn(y),M}j=await kn({pmRoot:t,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:y,document:c})}finally{await O()}v=[...S?ro(S,[...S,c.metadata],r):[],...j,...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})],_n({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:zt(c.metadata,p),changed_fields:p})}finally{await b()}return v}async function Ot(e,t){let n=Jf(await Vk(e)),r=E(process.cwd(),t.path);await dS(r);let s=await A(r),o=$(s.schema),i=We(s.schema),a=I(s,R()),c=await bS(n,t,r,s,a);n=c.resolvedOptions;let{typeDefinition:d,type:u,createMode:p}=c,f=Fk(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=wS(n,f);vS(n,f),kS(n);let y=Xk(d,n,p,h),g=k(),b=T(de(n.author),s.author_default),v=Mk(n.dep,g,s.id_prefix,b),S=nn("--comment",n.comment,g,b),N=nn("--note",n.note,g,b),O=nn("--learning",n.learning,g,b),j=Za(n.file),M=ec(n.test),Oe=tc(n.doc),te=Dk(n.reminder,g),_e=Uk(n.event,g),ce=Hk(n.typeOption),Ze=Bn(u,ce.values,a),pt=R(),ft=wt(pt),_t=Lr(n.field,pt),ht=mu(n,i,u),yi=new Set(ht.missing_required_flags),bi=i.definitions.filter(H=>yi.has(`--${H.cli_flag}`));SS(_t,ht,f);let qn=Qk(Ze.errors,u),gt=qn.map(H=>`--type-option ${H}=<value>`),Ad=[...new Set([...y,...gt,...ht.missing_required_flags])].sort((H,Ai)=>H.localeCompare(Ai));ES({combinedMissingFlags:Ad,typeDefinition:d,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:qn,openStatus:o.open_status,type:u,createMode:p,missingRequiredRuntimeFields:bi}),eS(Ze.errors,u,d,o);let Se=await _S({pmRoot:r,settings:s,typeRegistry:a,explicitId:n.id}),Pe=n.status!==void 0?Pk(n.status,o):Nk(d,o),$t=n.priority!==void 0?rS(n.priority):2,P=f.metadataKeys,yt=AS(P,n),Kn=tn(P,"deadline",n.deadline,H=>Q(H,new Date(g),"deadline")),Ge=tn(P,"estimated_minutes",n.estimatedMinutes,H=>An(H,"estimated-minutes")),Cr=B(P,"acceptance_criteria",n.acceptanceCriteria),gb=B(P,"definition_of_ready",n.definitionOfReady),yb=TS(P,n),bb=B(P,"goal",n.goal),wb=B(P,"objective",n.objective),vb=B(P,"value",n.value),kb=B(P,"impact",n.impact),Sb=B(P,"outcome",n.outcome),Eb=B(P,"why_now",n.whyNow),Ab=B(P,"assignee",n.assignee),Tb=P.has("author")?void 0:de(n.author)??b,Cb=B(P,"parent",n.parent),Td=await uS(Cb,n,P,r),wi=Td.parent,Rb=Td.parentSource,Ib=B(P,"reviewer",n.reviewer),xb=tn(P,"risk",n.risk,H=>ve(po(H),dn,"risk")),Ob=tn(P,"confidence",n.confidence,H=>_o(H)),Pb=n.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,Cd=s.validation.sprint_release_format,Dt=[...c.warnings,...mS(u,Se,Kn,te.values,_e.values)],Rd=await fS({itemId:Se,parent:wi,pmRoot:r,settings:s,typeRegistry:a,policy:Pb});wi=Rd.parent,Dt.push(...Rd.warnings);let Id=Wf(P,"sprint",n.sprint,"sprint",Cd),Nb=Id.value;Dt.push(...Id.warnings);let xd=Wf(P,"release",n.release,"release",Cd),Lb=xd.value;Dt.push(...xd.warnings);let Od=B(P,"blocked_by",n.blockedBy),Pd=await hS({pmRoot:r,settings:s,typeRegistry:a,statusRegistry:o,blockedBy:Od,dependencyValues:v.values,status:Pe,statusExplicit:n.status!==void 0,nowValue:g,author:b}),vi=Pd.dependencyValues;lr(Se,vi),Dt.push(...await Jt({pmRoot:r,dependencies:vi,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Se,createdAt:g}],schema:s.schema})),Pe=Pd.status;let Fb=B(P,"blocked_reason",n.blockedReason),Mb=B(P,"unblock_note",n.unblockNote),$b=B(P,"reporter",n.reporter),Db=tn(P,"severity",n.severity,H=>ve(fo(H),ln,"severity")),Ub=B(P,"environment",n.environment),Gb=B(P,"repro_steps",n.reproSteps),Nd=B(P,"resolution",n.resolution),jb=B(P,"expected_result",n.expectedResult),qb=B(P,"actual_result",n.actualResult),Kb=B(P,"affected_version",n.affectedVersion),zb=B(P,"fixed_version",n.fixedVersion),Bb=B(P,"component",n.component),Hb=tn(P,"regression",n.regression,H=>ho(H)),Vb=B(P,"customer_impact",n.customerImpact),ki=nc(n.title,"--title"),Si=n.description??"",Rr=n.body??"",Ld=await xn({title:ki,description:Si,body:Rr},{pmRoot:r,mode:s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Dt.push(...so(Ld));let Ei=CS(Pe,o,s,n,Nd,g),Wb=Ei.closeReason,Yb=Pe===o.close_status?g:void 0,Jb=Ei.completedAt;Dt.push(...Ei.warnings);let Ir=na({id:Se,title:ki,description:Si,type:u,type_options:Ze.normalized,status:Pe,closed_at:Yb,completed_at:Jb,close_reason:Wb,priority:$t,tags:yt,created_at:g,updated_at:g,deadline:Kn,assignee:Ab,author:Tb,estimated_minutes:Ge,acceptance_criteria:Cr,definition_of_ready:gb,order:yb,goal:bb,objective:wb,value:vb,impact:kb,outcome:Sb,why_now:Eb,parent:wi,reviewer:Ib,risk:xb,confidence:Ob,sprint:Nb,release:Lb,blocked_by:Od,blocked_reason:Fb,unblock_note:Mb,reporter:$b,severity:Db,environment:Ub,repro_steps:Gb,resolution:Nd,expected_result:jb,actual_result:qb,affected_version:Kb,fixed_version:zb,component:Bb,regression:Hb,customer_impact:Vb,dependencies:vi,comments:S.values,notes:N.values,learnings:O.values,files:j.values,tests:M.values,docs:Oe.values,reminders:te.values,events:_e.values,..._t,...ht.values});try{Fr(Ir,pt)}catch(H){throw new m(H instanceof Error?H.message:"Invalid extension item field values",l.USAGE)}let Xb=Ye({metadata:Ir,body:Rr},{schema:s.schema,extensionFieldNames:ft}),Qb={metadata:{},body:""},Fd=[..._].sort((H,Ai)=>H.localeCompare(Ai)),Zb=jk(n.message,Fd),Md=Gk(Ir,Rr,Fd,[...Object.keys(_t),...Object.keys(ht.values??{})]),ew=await RS({pmRoot:r,type:u,id:Se,settings:s,typeRegistry:a,author:b,extensionFieldNames:ft,afterDocument:Xb,beforeDocument:Qb,historyMessage:Zb,changedFields:Md,nowValue:g,similarityCandidate:{title:ki,description:Si,body:Rr},allowDuplicate:n.allowDuplicate}),$d=structuredClone(Ir);p==="strict"&&_.has("dependencies")&&($d.dependencies=[]);let tw=qf(Se,u,Pe,o);return e_(u,Kn,te.values,_e.values)&&wu(`[pm] warning: ${u} '${Se}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Se} --deadline <ISO>' or 'pm update ${Se} --event "start=<ISO>,end=<ISO>"'.`),{item:$d,changed_fields:Md,warnings:[...Dt,...ew],...Object.fromEntries([["parent_source",Rb],["next_transition",tw],["similarity_advisory",Ld]].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]="d024d9cf-81f8-5690-b8f4-03620e3e9bf8")}catch{}})();var ic=[...Va,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Wa,...Lo],IS=(()=>{let e=new Map;for(let t of ic)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Uo=new Map(ic.map(e=>[e.optionKey,e.canonical])),xS=ic.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),OS=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),PS=go({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function NS(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([...Uo.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Be(o))continue;let i=s==="rank"?"order":Uo.get(s)??s;n(i),t[s]=void 0}return bo(t,PS)}function c_(e,t,n=[]){return Fo({raw:e,supportedFields:xS,resolveDefinition:r=>{let s=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return IS.get(r)??Mo(r,"update",t)??(s?{optionKey:"field",metadataKey:s}:void 0)}})}var t_=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 n_(e){let t=e.disallowedFlags.flatMap(r=>{let s=t_.get(r);return s?[s(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let s=t_.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 LS(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 n_({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=>OS.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw n_({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 FS(e,t){let n=W(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 MS(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Im({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: ${xm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new m(s,l.USAGE);return`workflow_transition_not_allowed: ${s}`}function $S(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 dependency created_at timestamp "${e}"`,l.USAGE);return new Date(n).toISOString()}function Go(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var DS=["id","kind","type","author","created_at","source_kind"],US=["id","kind","type","source_kind"];function d_(e){return e.startsWith("```")||e.includes(`
8
- `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Vs(e)}function l_(e){return typeof e=="string"?Dr(e)??e.trim():e}function qo(e,t,n,r){return e?(we(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=d_(i);dr(i,a);let c=a?ne(o,"--dep"):{id:i,kind:"related"};a&&ze(c,"--dep",DS);let d=c.id?.trim(),u=l_((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=Zn(Go(c.source_kind)),f=Go(c.author);return{id:er(d,t,p),kind:ve(u,Ut,"dependency kind"),created_at:$S(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function GS(e,t){return e?(we(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=d_(r);if(dr(r,s,"--dep-remove"),s){let o=ne(r,"--dep-remove");ze(o,"--dep-remove",US);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=l_(Go(o.kind??o.type)),c=Zn(Go(o.source_kind));return{id:er(i,t,c),kind:a?ve(a,Ut,"dependency kind"):void 0,source_kind:c}}if(r.toLowerCase()==="undefined")throw new m(`--dep-remove id must not use placeholder token "${r}"`,l.USAGE);return{id:ye(r,t)}})):[]}function jo(e){let t=e.source_kind?.trim().toLowerCase()??"";return`${e.id.trim().toLowerCase()}::${e.kind}::${t}`}function jS(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 qS(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,ye(i,r),r,s,o);return a?{id:a.id}:{unresolved:i}}function KS(e,t,n,r,s){let o=jS(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 zS(e){return`${e.path}::${e.scope}`}function BS(e){return`${e.path}::${e.scope}`}function HS(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}`}function m_(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 VS(e){return Tn(e)}function r_(e,t){let n=zn("update",e);if(!n)throw new m(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,l.CONFLICT);return n}function WS(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=c_(e.unset,t,n);for(let i of o.optionKeys)s(i,!0)}return r}function YS(e,t,n,r,s){let o=Mr(e,n);if(!o)throw new m(`Invalid type value "${e}"`,l.USAGE);let i=un(o,"update",[]);if(i.errors.length>0)throw new m(i.errors.join("; "),l.CONFLICT);let a=WS(t,r,s);for(let c of i.disabled)if(a.has(r_(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(r_(c,e)))throw new m(`Missing required option ${he("update",c)} for type "${e}"`,l.USAGE)}var JS=new Set(["order","rank"]),XS=Li.filter(e=>!JS.has(e)),u_=["tags","closeReason",...XS],QS=["title","description","body","status","closeReason","completedAt","priority","type",...Li,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],ZS=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>Q(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>An(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"}],eE=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>ve(po(e),dn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>_o(e)}],tE=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>ve(fo(e),ln,"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=>ho(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function oc(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 nE(e){let t=Fe();return NS({...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 rE(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 rc(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 ac(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);rc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),rc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),rc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function sE(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 oE(e){let t={};for(let n of u_)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function iE(e,t){let n=oE(e);for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=Uo.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 aE(e){let t=(n,r)=>{let s=Uo.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;yo(n,he("update",r),o)};for(let n of u_)t(e[n],String(n));t(e.order??e.rank,"order"),we(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),we(e.event,"--event","Use --clear-events to clear linked events.")}function cE(e,t){let n={};for(let r of QS)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 dE(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 it(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 lE(e){await C(e)}function mE(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 uE(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=qs(e.options.parent);if(zs(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=ye(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:Ks(r,e.parentReferencePolicy).warnings}}function pE(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function fE(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 it(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=MS({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return s?[s]:[]}async function _E(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 ct(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 at(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 hE(e,t,n,r){return t.title!==void 0&&(e.metadata.title=nc(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 gE(e,t,n,r,s){let o=FS(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 yE(e,t,n,r){if(t.options.status!==void 0&&gE(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!se(e.metadata.status,t.statusRegistry))throw new m("--completed-at can only be set on a terminal item",l.USAGE);e.metadata.completed_at=Q(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function bE(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&&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 wE(e,t,n,r){yE(e,t,n,r),bE(e,t,n,r)}function vE(e,t,n){let r=pe(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=VS(t.options.priority),n.push("priority")),t.options.type!==void 0){let s=pe(t.options.type,t.typeRegistry);if(!s)throw new m(St(t.options.type,t.typeRegistry.types,Et(t.pmRoot,t.settings.schema)),l.USAGE);e.metadata.type=s,r=s,n.push("type")}return YS(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),kE(e,t,r,n),r}function kE(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=ko(t.options.typeOption??[]),i=Bn(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=Bn(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 SE(e,t){let n=new Set(t.map(s=>jo(s))),r=new Set;return e.filter(s=>{let o=jo(s);return n.has(o)?r.has(o)?!1:(r.add(o),!0):!0})}function EE(e,t,n){let r=t.filter(s=>!e.some(o=>m_(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})),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, kind, and optional source_kind shown in dependencies."]})}function AE(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=SE(r,t.dependencyUpdates.additions);let s=new Set(r.map(o=>jo(o)));for(let o of t.dependencyUpdates.additions){let i=jo(o);s.has(i)||(r.push(o),s.add(i))}}t.dependencyRemovals.length>0&&(EE(r,t.dependencyRemovals,e.metadata.id),r=r.filter(s=>!t.dependencyRemovals.some(o=>m_(s,o)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function TE(e,t,n){sc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),sc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),sc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function sc(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 CE(e,t,n){s_(e,"files",t.options.file,t.fileUpdates.values,zS,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),RE(e,t,n),s_(e,"docs",t.options.doc,t.docUpdates.values,BS,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function s_(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 RE(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=o_(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=o_([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function o_(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let s=HS(r);n.has(s)||(t.push(r),n.add(s))}return t}function IE(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?It(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Hs(En(i,r),s),n.changedFields.push("tags")}oc(ZS,t.options,n),OE(e,t,n.changedFields)}function xE(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=Bs(Sn(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 OE(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 m("Order must be an integer",l.USAGE);e.metadata.order=s}n.push("order")}}function PE(e,t,n,r){NE(e,t,n.changedFields),LE(e,t,n.changedFields),oc(eE,t.options,n),i_(e,t,"sprint",r,n.changedFields),i_(e,t,"release",r,n.changedFields),FE(e,t,n.changedFields),oc(tE,t.options,n)}function NE(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 LE(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 i_(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=Ws(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=o.value,r.push(...o.warnings)}s.push(n)}}function FE(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)&&KS(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function ME(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=wo(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=vo(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function $E(e,t,n){a_(e,t.runtimeFieldRegistry.definitions.map(s=>s.metadata_key),t.clearItemMetadataKeys,n),a_(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)}nt(e[s],o)||(e[s]=o,n.push(s))}let r=Lr(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))nt(e[s],o)||(e[s]=o,n.push(s))}function a_(e,t,n,r){for(let s of t)!n.has(s)||e[s]===void 0||(delete e[s],r.push(s))}function DE(e,t){let n=structuredClone(e.metadata),r=e.body,s=[],o=[],i=hE(e,t.options,t.statusRegistry,s),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:s,nowValue:t.nowValue};wE(e,t,i,s),vE(e,t,s),AE(e,t,s),TE(e,t,s),CE(e,t,s),IE(e,t,c),xE(e,t,c),PE(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"))&&lr(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")),ME(e,t,s),$E(a,t,s);try{Fr(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:!nt(n[p],d[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&o.push(`acceptance_criteria_replaced:${Sn(n.acceptance_criteria).length}:${Sn(d.acceptance_criteria).length}`),{changedFields:u,warnings:o}}async function p_(e,t,n,r={}){t=await nE(t);let s=E(process.cwd(),n.path);await lE(s);let o=await A(s),i=$(o.schema),a=We(o.schema),c=R(),d=wt(c),u=I(o,c),p=o.governance.workflow_enforcement??"off",f=p==="off"?[]:Rm(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=c_(t.unset,a,d),y=new Set(h.optionKeys),g=new Set(h.metadataKeys);ac(t),sE({definitions:rE(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:g}),LS(e,t,g),iE(t,h),aE(t);let b=T(t.author,o.author_default),v=new Date,S=v.toISOString(),N=qo(t.dep,o.id_prefix,S,b);lr(e,N.additions);let O=await Jt({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=GS(t.depRemove,o.id_prefix),M=nn("--comment",t.comment,S,b),Oe=t.ownershipMetadataBypass===!0&&M.values?{...M,values:M.values.map(Ge=>({...Ge,author:b}))}:M,te=nn("--note",t.note,S,b),_e=nn("--learning",t.learning,S,b),ce=Za(t.file),Ze=ec(t.test),pt=tc(t.doc),ft=[],_t=await uE({id:e,options:t,unsetTargets:h,pmRoot:s,settings:o,typeRegistry:u,parentReferencePolicy:_}),ht=await qS(t.blockedBy,g.has("blocked_by"),s,o.id_prefix,o.item_format,u.type_to_folder),yi=ht.id,bi=[..._t.warnings,...pE(ht)],qn=Ts(t,a,t.runtimeFieldCommands),gt=cE(t,qn);if(!Object.values(gt).some(Boolean))return dE({pmRoot:s,id:e,settings:o,typeRegistry:u});ft.push(...await fE({options:t,fieldFlags:gt,workflowEnforcement:p,typeWorkflows:f,statusRegistry:i,typeRegistry:u,pmRoot:s,id:e,settings:o}));let Se=await _E({options:t,fieldFlags:gt,statusRegistry:i,workflowTransitionWarnings:ft,global:n,id:e});if(Se)return Se;mE(t);let Pe=gt.dep||gt.depRemove||gt.blockedBy?await oe(s,o.item_format,u.type_to_folder,void 0,o.schema):void 0,$t,P,yt=await Nu({pmRoot:s,settings:o,typeToFolder:u.type_to_folder,id:e,op:UE(t,r),author:b,message:t.message,resolveHistoryContext:()=>P,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:d,skipNoop:!0,mutate(Ge){return $t=GE({document:Ge,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),P=$t?{recurrence:$t}:void 0,Pe=Pe?.map(Cr=>Cr.id===Ge.metadata.id?structuredClone(Ge.metadata):Cr),DE(Ge,{options:t,settings:o,typeRegistry:u,statusRegistry:i,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:d,clearItemMetadataKeys:g,dependencyUpdates:N,dependencyRemovals:j,commentUpdates:Oe,noteUpdates:te,learningUpdates:_e,fileUpdates:ce,testUpdates:Ze,docUpdates:pt,resolvedParentValue:_t.resolvedParentValue,resolvedBlockedByDependencyId:yi,runtimeFieldUpdates:qn,nowValue:v,nowIso:S,author:b,pmRoot:s})}}),Kn=Pe?ro(Pe,Pe.map(Ge=>Ge.id===yt.item.id?yt.item:Ge),yt.item.id):[];return{item:yt.item,changed_fields:yt.changedFields,warnings:[...ft,...bi,...O,...Kn,...yt.warnings],...$t===void 0?{}:{lifecycle_transition:$t}}}function UE(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function GE(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 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=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 ct(e,t,n){return p_(e,t,n)}async function f_(e,t,n,r){let s=await p_(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 h_=1,dc="update-many",jE=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),qE=["--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(", "),KE={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"},zE=[{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"}],BE={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"},g_=e=>{let t={};for(let[n,r]of Object.entries(e))jE.has(n)||r!==void 0&&(t[n]=r);return t},HE=e=>Object.keys(g_(e)).length>0,y_=e=>typeof e=="string"?e.trim():e,VE=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},cc=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},WE=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??y_(e)},YE={priority:VE,estimatedMinutes:cc,order:cc,rank:cc,regression:WE},JE=(e,t)=>{if(t!==void 0)return(YE[e]??y_)(t)},XE=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return BE[t]??t},Ko=(e,t)=>nt(e,t),QE=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],ZE=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,eA=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",__=(e,t)=>t===void 0?void 0:e[t],Fn=e=>Array.isArray(e)?e.length:0,tA=(e,t,n)=>{let r=n[e.addKey],s=__(n,e.removeKey),o=Fn(r),i=Fn(s),a=n[e.clearKey]===!0,c=__(n,e.replaceKey)===!0;if(![a,c,o>0,i>0].includes(!0))return;let d=QE(e.field,t[e.field]);return{field:e.field,before:d,after:{operation:eA({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:o,remove_count:i,before_count:ZE(e.field,d)}}},nA=(e,t)=>{let n=[];for(let r of zE){let s=tA(r,e,t);s!==void 0&&n.push(s)}return n},rA=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],sA=(e,t)=>{if(![t.tags!==void 0,Fn(t.addTags)>0,Fn(t.removeTags)>0].includes(!0))return;let n=rA(e.tags),r=t.tags===void 0?n:It(t.tags),s=En(r,t.addTags),o=Hs(s,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!Ko(i,o))return{field:"tags",before:n,after:o}},oA=(e,t)=>{let n=e.acceptance_criteria,r=Bs(Sn(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(!Ko(typeof n=="string"?n:"",s))return{field:"acceptance_criteria",before:n,after:s}},iA=(e,t,n)=>{for(let[r,s]of Object.entries(KE)){let o=n[r];if(o===void 0)continue;let i=t[s],a=JE(r,o);Ko(i,a)||e.push({field:s,before:i,after:a})}},aA=(e,t,n,r)=>{let s=Ts(n,r,["update_many"]);for(let[o,i]of Object.entries(s)){let a=t[o];Ko(a,i)||e.push({field:o,before:a,after:i})}},cA=(e,t,n)=>{for(let r of n??[]){let s=XE(r),o=t[s];o!==void 0&&e.push({field:s,before:o,after:null})}},dA=(e,t,n={})=>{let r=e,s=[],o=sA(r,n);if(o&&s.push(o),iA(s,r,n),Fn(n.addAc)>0||Fn(n.removeAc)>0){let i=oA(r,n);i!==void 0&&s.push(i)}return s.push(...nA(r,n)),aA(s,r,n,t),cA(s,r,n.unset),{id:e.id,changes:s}},lA=(e,t)=>zu(e,t,{strict:!0,flagLabel:"--filter-status"}),mA=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)},uA=[({update:e})=>{e.priority!==void 0&&Tn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=I(t,R());if(!pe(e.type,r))throw new m(St(e.type,r.types,Et(n,t.schema)),l.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!W(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&&Q(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&An(e.estimatedMinutes,"estimated-minutes")}],pA=(e,t,n,r)=>{let s={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let o of uA)o(s)},fA=async e=>{let t=await Ds(e.pmRoot,dc,e.rollbackId,h_),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Us(t.items,(s,o)=>Yt(s,o,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...Kt({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}},_A=async e=>{let t={schema_version:h_,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 $s(e.pmRoot,dc,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},hA=(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))},lc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},gA=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:We(n.schema)}},yA=e=>{if(e.options.dryRun===!0)throw new m("--dry-run cannot be combined with --rollback",l.USAGE);if(rr(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 fA({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},bA=async e=>{lA(e.options.status,e.runtime.statusRegistry);let t=await xt(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=dA(s,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?o:{...o,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await xt(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:hA(e.options.list?.ids,r)}},wA=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:[],...lc(e)}),vA=e=>({...Kt({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:[],...lc(e)}),kA=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 ct(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:pn(i)})}}return{rows:t,updatedIds:n}},SA=async e=>{if(e.plan.actionable.length===0)return vA(e.plan);let t=k(),n=Ms(dc,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 _A({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 kA({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{...Kt({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,...lc(e.plan)}},b_=async(e,t)=>{let n=await gA(t),r=typeof e.rollback=="string"?e.rollback:void 0,s=g_(e.update);if(mA(e.list),r!==void 0)return yA({runtime:n,rollbackId:r,options:e,global:t,updateSummary:s});if(!HE(e.update))throw new m(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${qE}).`,l.USAGE);pA(e.update,n.settings,n.statusRegistry,n.pmRoot),ac(e.update);let o=await Jt({pmRoot:n.pmRoot,dependencies:qo(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 bA({options:e,global:t,runtime:n,updateSummary:s,dependencyWarnings:o});return await Jt({pmRoot:n.pmRoot,dependencies:qo(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?wA(i):SA({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 EA=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],w_=["brief","standard","deep"],S_="plan-step-",hc="draft",_c=["bug-investigation","feature-implementation","refactoring-sprint"],v_={"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 AA(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(v_,t)?v_[t]:void 0;if(!n)throw new m(`Unknown plan template "${e}". Allowed: ${_c.join(", ")}`,l.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${_c[0]}`]});return n.map(r=>({...r}))}function TA(e,t){return t>0?Math.round(e/t*100):0}function E_(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=>Cn(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Cn(e,{unique:!1}):[]}function ke(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function A_(e,t=hc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ri.find(s=>s===n);if(!r)throw new m(`Invalid plan mode "${e}". Allowed: ${Ri.join(", ")}`,l.USAGE);return r}function gc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ii.find(s=>s===n);if(!r)throw new m(`Invalid step status "${e}". Allowed: ${Ii.join(", ")}`,l.USAGE);return r}function T_(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Oi.find(s=>s===n);if(!r)throw new m(`Invalid step link kind "${e}". Allowed: ${Oi.join(", ")}`,l.USAGE);return r}function CA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=xi.find(r=>r===t);if(!n)throw new m(`Invalid plan harness "${e}". Allowed: ${xi.join(", ")}`,l.USAGE);return n}function RA(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=w_.find(r=>r===t);if(!n)throw new m(`Invalid --depth "${e}". Allowed: ${w_.join(", ")}`,l.USAGE);return n}function IA(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 mc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function xA(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(!mc.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 ${[...mc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:s,suggested_retry:`pm plan show <id> --fields ${[...mc].join(",")}`}});return r}function yc(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 bc(e){let t=yc(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 wc(e){let t=yc(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 vc(e){let t=yc(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 OA(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=TA(t.completed,t.total),t}function PA(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${S_}${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 Mn(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 k_(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 NA(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=k_(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=Mn(e,i);if(o.has(a.id))continue;o.add(a.id);let c=k_(a);if(c){s.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:s}}function LA(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 FA(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function MA(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 Ce(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=OA(n),s=FA(n),o={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??hc,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:MA(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 Re(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&&!da(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function C_(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 $A(e){let t=E(process.cwd(),e.path);await C(t);let n=await A(t);return{pmRoot:t,settings:n}}async function R_(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 C_(s.document.metadata),{document:s.document,itemId:r.id}}function DA(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 UA(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 GA(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 jA(e){let t=e.stepTitle?.trim()||void 0,n=E_(e.step),r=e.template?.trim()?AA(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(s=>s.title)],templateSteps:r}}function qA(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 ${_c[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 KA(e,t){let n=gc(e.stepStatus,"pending"),r=kc(e,"depends_on"),s=ke(e.file).map(bc),o=ke(e.test).map(wc),i=ke(e.doc).map(vc),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 zA(e){let t=jA(e),n=GA(e);if(qA(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[KA(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((s,o)=>({id:`${S_}${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 BA(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=A_(e.mode,hc),o=CA(e.harness),i=e.fromSearch?.trim(),a=UA(e),{steps:c,hasPerStepDetailOptions:d}=zA(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:ke(e.file),test:ke(e.test),doc:ke(e.doc),field:ke(e.field),assignee:T(e.author,n.settings.author_default),blockedBy:void 0,dep:DA(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")},_=await Ot(f,t),h=await Z({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=Ce(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Re(_.item.id,y),warnings:[..._.warnings],generated_at:k()}}async function HA(e,t,n){let r=RA(t.depth),s=IA(t.fields),{document:o,itemId:i}=await R_(n,e),a=Ce(o.metadata,s===null?r:"deep");return{action:"show",plan:s===null?a:xA(a,s),next_actions:Re(i,a),warnings:[],generated_at:k()}}function VA(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 Je(e){let t=T(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){C_(s.metadata);let o=$(e.ctx.settings.schema);if(se(s.metadata.status,o)||da(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=VA(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 WA(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new m("pm plan add-step requires --step-title",l.USAGE);let s=gc(t.stepStatus,"pending"),o=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await Je({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;I_(u,void 0,s,o);let f=YA(u,t,{order:p,title:r,status:s});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),d=Ce(i.metadata,"standard");return{action:"add-step",plan:d,step:a,next_actions:Re(c,d),warnings:[],generated_at:k()}}function I_(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 YA(e,t,n){let r=kc(t,"depends_on"),s=ke(t.file).map(bc),o=ke(t.test).map(wc),i=ke(t.doc).map(vc),a=k();return{id:PA(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 kc(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=T_(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 uc(e,t,n,r){let{document:s,resultStep:o,itemId:i}=await Je({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,d){let u=Mn(c,r.stepRef),p=k(),f=r.finalStatus??gc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return I_(c,u.status==="in_progress"?u.id:void 0,f,_),JA(u,t,f,p),d.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Ce(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:Re(i,a),warnings:[],generated_at:k()}}function JA(e,t,n,r){XA(e,t,n),QA(e,t),e.status=n,e.updated_at=r,ZA(e,n,r)}function XA(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 QA(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=ke(t.file).map(bc),s=ke(t.test).map(wc),o=ke(t.doc).map(vc);r.length>0&&(e.files=pc(e.files,r)),s.length>0&&(e.tests=pc(e.tests,s)),o.length>0&&(e.docs=pc(e.docs,o))}function pc(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 ZA(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function eT(e,t,n,r,s){let{document:o,itemId:i}=await Je({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${s}`,mutator(c){let d=Mn(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=Ce(o.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Re(i,a),warnings:[],generated_at:k()}}async function tT(e,t,n,r){let{document:s,itemId:o}=await Je({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=Mn(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=Ce(s.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Re(o,i),warnings:[],generated_at:k()}}async function nT(e,t,n,r){let s=kc(t,T_(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 Je({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Mn(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 N=S.kind==="depends_on"?"blocked_by":S.kind,O={id:S.id,kind:N,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=Ce(i.metadata,"standard");return{action:"link",plan:d,step:c,next_actions:Re(a,d),warnings:[],generated_at:k()}}async function rT(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 Je({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(d){let u=Mn(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=Ce(o.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Re(i,c),warnings:[],generated_at:k()}}async function fc(e,t,n,r){let s=LA(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 Je({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=Ce(i.metadata,"deep");return{action:r,plan:c,next_actions:Re(a,c),warnings:[],generated_at:k()}}async function sT(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 Je({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=Ce(s.metadata,"brief");return{action:"resume",plan:i,next_actions:Re(o,i),warnings:[],generated_at:k()}}async function oT(e,t,n){let r=A_(t.mode??"approved","approved"),{document:s,itemId:o}=await Je({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=Ce(s.metadata,"brief");return{action:"approve",plan:i,next_actions:Re(o,i),warnings:[],generated_at:k()}}function x_(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function iT(e,t){let n=Ce(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Re(e.itemId,n),warnings:x_(t),generated_at:k()}}function aT(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 cT(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let s of ke(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 Ot({...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:aT(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 dT(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 lT(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=pe(s,o);if(!i)throw new m(`Invalid --materialize-type "${s}"`,l.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,d=await R_(n,e),u=(d.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=NA(u,r);if(p.length===0){if(f.length>0)return iT(d,f);throw new m("No matching plan steps found for --steps",l.NOT_FOUND)}let _=await cT({targets:p,parent:a,planItemId:d.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await Je({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(b){return dT(b,p,_),{changedSteps:p.map(v=>v.id)}}}),g=Ce(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Re(y,g),warnings:x_(f),generated_at:k()}}function mT(e){if(e.subcommand==="create")return e;let t=E_(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 dt(e,t){if(!e.id)throw new m(`pm plan ${t} requires a plan id`,l.USAGE);return e.id}function rn(e,t){let n=dt(e,t);if(!e.stepRef)throw new m(`pm plan ${t} requires <plan-id> <step>`,l.USAGE);return{id:n,stepRef:e.stepRef}}function uT(e){let t=rn(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 pT={create:(e,t)=>BA(e.options,e.global,t),show:(e,t)=>HA(dt(e,"show"),e.options,t),"add-step":(e,t)=>WA(dt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=rn(e,"update-step");return uc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=rn(e,"complete-step");return uc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=rn(e,"block-step");return uc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=uT(e);return eT(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=rn(e,"remove-step");return tT(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=rn(e,"link");return nT(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=rn(e,"unlink");return rT(n.id,e.options,t,n.stepRef)},decision:(e,t)=>fc(dt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>fc(dt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>fc(dt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>sT(dt(e,"resume"),e.options,t),approve:(e,t)=>oT(dt(e,"approve"),e.options,t),materialize:(e,t)=>lT(dt(e,"materialize"),e.options,t)};function fT(e){let t=pT[e];if(!t)throw Te({command_path:"plan",token:e,allowed:EA});return t}async function O_(e){let t=await $A(e.global),n=mT(e);return fT(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 _T(e,t){return[...new Set([...Nr.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 hT(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Sc(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 it(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 Xn(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=wt(R()),g=Ye({metadata:h,body:a.document.body},{schema:s.schema,extensionFieldNames:y}),b=await xn({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=_T(g.metadata,g.body),S=jt(r,g.metadata.type,p,s.item_format,o.type_to_folder),N=Ee(r,p),O=await Ne(r,p,s.locks.ttl_seconds,u,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),j={metadata:{},body:""},M,Oe;try{let te=await vn(r,u,{required:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await xn({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 m(`Cannot copy to ${p}: an item with that id already exists at ${_e.itemPath}. Retry the copy to allocate a new id.`,l.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${_e.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await ue(S,qe(g,{format:s.item_format,schema:s.schema,extensionFieldNames:y}));try{let ce=Ke({nowIso:d,author:u,op:"create",before:j,after:g,message:hT(i.id,t.message)});await Tt(N,ce)}catch(ce){throw await mn(S),ce}Oe=await kn({pmRoot:r,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:S,document:g})}finally{await te()}M=[...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:N,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:j,after:g,changed_fields:v})],_n({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:zt(g.metadata,v),changed_fields:v})}finally{await O()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:v,warnings:[...so(b),...Oe,...M],...b===void 0?{}:{similarity_advisory:b}}}import zo 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 Ec(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 Lu({pmRoot:r,settings:s,id:e,author:o,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?zo.relative(r,i.targetPath).split(zo.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:zo.relative(r,Ee(r,i.item.id)).split(zo.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 gT(e){await C(e)}async function Ac(e,t,n){let r=E(process.cwd(),n.path);if(await gT(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=yn(T(void 0,p.author_default));return await lu(r),await no({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 Es(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 yT(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 it(r,e,o.id_prefix,i.type_to_folder);let c=ye(a.id,o.id_prefix),d=await K(a,{schema:o.schema}),u=P_(d.document.metadata.title);return await du(r,c),await no({pmRoot:r,settings:o,principal:yn(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 yT(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 P_(o.document.metadata.title)}function P_(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 N_=new Set(["item_format"]),L_=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"]),bT=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"]),wT=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","telemetry_tracking"]),vT={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function kT(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(N_.has(t)||L_.has(t)||bT.has(t)||t==="context")return t}function ST(e){let t=e.trim().toLowerCase();return vT[t]??e}function F_(e,t){let n=kT(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."}:N_.has(n)?{routable:!0,flag:"format",value:t}:L_.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:wT.has(n)?ST(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 M_=["project","global"],lt={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"]},ET=Object.keys(lt).map(e=>lt[e][0]),AT=Object.fromEntries(Object.keys(lt).flatMap(e=>lt[e].map(t=>[t,e]))),TT={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)."},CT=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],RT=new Set(["metadata_required_fields",...CT]),IT=new Set(["test_result_tracking","telemetry_tracking"]),xT=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),OT=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),PT=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),NT=new Set(["governance_preset","governance_create_default_type"]),j_=e=>RT.has(e),LT=e=>OT.has(e),FT=e=>PT.has(e),MT=e=>NT.has(e);function Tc(e){return e==="definition_of_done"||j_(e)}function $T(e){if(M_.includes(e))return e;throw new m(`Invalid config scope "${e}". Allowed: ${M_.join(", ")}`,l.USAGE)}function DT(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 UT(e){let t=AT[e];if(t)return t;let n=Ui.map(r=>r.key).join(", ");throw new m(`Invalid config key "${e}". Supported: ${ET.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,l.USAGE)}function GT(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 jT(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 q_(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 K_(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 z_(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 Rc(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 B_(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 H_(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 V_(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 W_(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 Y_(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 J_(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 X_(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 $_(e,t){switch(e){case"history_missing_stream_policy":return q_(t);case"sprint_release_format_policy":return ca(t);case"parent_reference_policy":case"governance_parent_reference_policy":return js(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Rc(t);case"governance_preset":return B_(t);case"governance_ownership_enforcement":return H_(t);case"governance_create_mode_default":return V_(t);case"governance_close_validation_default":return W_(t);case"governance_require_close_reason":return X_(t);case"governance_workflow_enforcement":return Y_(t);case"governance_force_required_for_stale_lock":return J_(t);case"test_result_tracking":return K_(t);case"telemetry_tracking":return z_(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var D_={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"},qT=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function KT(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=>D_[o]===void 0);if(s.length>0)throw new m(`Config set metadata-required-fields received unsupported values: ${s.join(", ")}. Supported values: ${qT.join(", ")}`,l.USAGE);return[...new Set(r.map(o=>D_[o]))].sort((o,i)=>o.localeCompare(i))}function zT(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 ${lt[e][0]} cannot combine --clear-criteria with --criterion values`,l.USAGE);return[]}if(r.length===0)throw new m(`Config set ${lt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,l.USAGE);return r}function BT(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function HT(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 UT(t)}function Q_(e){if(!e)throw new m("Config action requires <key>",l.USAGE)}var VT={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 Ic(e,t){return VT[t](e)}function Ue(e,t){return t.length===0?e:{...e,warnings:t}}async function WT(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):tt(n),s=ge(r);return e==="project"&&await C(r),{pmRoot:r,settingsPath:s}}function YT(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 U_(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 JT(e,t,n,r,s){let o=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!Pi.includes(c))throw new m(`Context --default-depth must be one of ${Pi.join("|")}`,l.USAGE);i.default_depth!==c&&(i.default_depth=c,o=!0)}if(t.activityLimit!==void 0){let c=U_(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,o=!0)}if(t.staleThresholdDays!==void 0){let c=U_(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=YT(d);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,o=!0)}}return o&&await Ae(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 XT(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 QT(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 XT(t,s,o);Q_(n);let i=F_(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&&$_(n,o.policy)!==$_(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 ZT(e){let t=Object.keys(lt).map(r=>({key:r,aliases:lt[r],value_kind:r==="context"?"object":Tc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:Tc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:TT[r],value:Ic(e.settings,r)})),n=Ui.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Gi(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 eC(e){let t=Object.fromEntries(Object.keys(lt).map(n=>[n,Ic(e.settings,n)]));return Ue({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function tC(e,t){let n=Ic(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 nC(e,t,n,r){if(t==="get"){let a=Gi(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=Cm(n,s);if(!o.ok)throw new m(o.error.message,l.USAGE);let i=bs(e.settings,n,o.parsed.value);return i&&await Ae(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 X(e,t,n){t&&await Ae(e.target.pmRoot,e.settings,n)}function G_(e,t,n){return e!==n||t!==n}function ae(e,t,n,r){return Ue({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Cc(e,t,n,r){return Ue({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function rC(e,t){let n=jT(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 Hu(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 Ae(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 sC(e,t,n){if(t==="history_missing_stream_policy"){let o=q_(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=ca(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=js(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=Rc(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 oC(e,t,n){if(t==="metadata_required_fields"){let a=KT(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 X(e,c,"config:set:metadata_required_fields"),Cc(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=zT(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}`),Cc(e,t,[...s],i)}async function iC(e,t,n){if(t==="governance_preset"){let c=B_(n.policy),d=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await X(e,d,"config:set:governance_preset"),ae(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 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 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=pe(s,o);if(!i)throw new m(St(s,o.types,Et(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 X(e,a,"config:set:governance_create_default_type"),ae(e,t,e.settings.governance.create_default_type,a)}async function aC(e,t,n){if(t==="governance_ownership_enforcement"){let o=H_(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=V_(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=W_(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 cC(e,t,n){if(t==="governance_parent_reference_policy"){let o=js(n.policy),i=e.settings.governance.preset!=="custom"||G_(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=Rc(n.policy),i=e.settings.governance.preset!=="custom"||G_(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=Y_(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 dC(e,t,n){if(t==="governance_require_close_reason"){let a=X_(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=J_(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 lC(e,t,n){if(t==="test_result_tracking"){let a=K_(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=z_(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 mC(e,t,n){let r=GT(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"),Cc(e,t,[...e.settings.workflow.definition_of_done],s)}async function uC(e,t,n){if(n.clearCriteria===!0&&!Tc(t))throw new m("--clear-criteria is only supported with config set criteria-list keys",l.USAGE);return t==="item_format"?rC(e,n):t==="context"?JT(e.settings,n,e.target,e.scope,e.warnings):t==="definition_of_done"?mC(e,t,n):j_(t)?oC(e,t,n):IT.has(t)?lC(e,t,n):xT.has(t)?dC(e,t,n):LT(t)?aC(e,t,n):FT(t)?cC(e,t,n):MT(t)?iC(e,t,n):sC(e,t,n)}async function Z_(e,t,n,r,s,o){let i=$T(e),a=DT(t),c=a==="get"||a==="set"?ys(n):void 0,d=c?void 0:HT(a,n),u=QT(a,n,d,c,o,r),p=await WT(i,s),{settings:f,metadata:_,warnings:h}=await Iu(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:BT(h)};return c?nC(y,a,c,u):a==="list"?ZT(y):a==="export"?eC(y):(Q_(d),a==="get"?tC(y,d):uC(y,d,u))}import KC from"node:fs/promises";import V from"node:path";import zC from"node:readline/promises";import{stdin as BC,stdout as Ie}from"node:process";import Oc from"node:fs/promises";import re from"node:path";import pC from"node:readline/promises";import{stdin as fC,stdout as Bo}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 th=["ask","add","skip","status"],_C=["AGENTS.md","CLAUDE.md"],hC=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],gC=8,Pc=1,yC="<!-- pm-cli:agent-guidance:start:",bC=`<!-- pm-cli:agent-guidance:start:v${Pc} -->`,xc="<!-- pm-cli:agent-guidance:end -->",_r="Add workflow guidance later: pm init --agent-guidance add";var wC=()=>pC.createInterface({input:fC,output:Bo});function pr(e,t){let n=re.relative(e,t);return n.length===0?re.basename(t):n.split(re.sep).join("/")}function eh(e){return e.endsWith(`
4
+ `,{changedFields:["body"]}}});return{item:d.item,appended:c,changed_fields:d.changedFields}}import{readFile as pv}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 hs(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,t}function Mf(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 Wa(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 Mn(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 s=se(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function Ya(e){return typeof e=="object"&&e!==null&&"code"in e}async function fv(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=$e();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 o=e.file.trim();if(!o)throw new m("--file path cannot be empty",l.USAGE);try{return{value:await pv(o,"utf8"),emptyFlag:"--file"}}catch(s){if(Ya(s)&&qt(s))throw new m(`--file path not found: ${o}`,l.USAGE);let i=s instanceof Error?s.message:String(s);throw new m(`Failed to read --file path "${o}": ${i}`,l.USAGE)}}async function gs(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 fv(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 pr(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 Df(e){return e==="comments"?"--stdin":"--add -"}function _v(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let o=Df(t.collectionKey),s=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 ${o} to read stdin, or use text=${r} for literal dash-leading text.`,l.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${s} ${o}`,`${s} --add text=${r}`]})}function hv(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> ${Df(e.collectionKey)}`]})}async function $n(e,t,n,r){hv(r,t);let o=E(process.cwd(),n.path);await C(o);let s=await A(o),i=I(s,R()),a=nr(t.limit);if(r.input.mode==="list"){let _=await U(o,e,s.id_prefix,s.item_format,i.type_to_folder);if(!_)throw new m(`Item ${e} not found`,l.NOT_FOUND);let h=await K(_,{schema:s.schema}),y=Jt(h.document.metadata,r.collectionKey);return _s(_.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=T(t.author,s.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,h;try{h=await re({pmRoot:o,settings:s,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let w=Jt(g.metadata,r.collectionKey),v=$f(r.input.index,w.length,r.collectionKey);return Mf(w[v],"deleted"),w.splice(v,1),g.metadata[r.collectionKey]=w,{changedFields:[r.collectionKey]}}})}catch(g){pr(g,r.conflictGuidance)}let y=Jt(h.item,r.collectionKey);return _s(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??"";_v(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 re({pmRoot:o,settings:s,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let w=Jt(g.metadata,r.collectionKey),v=$f(r.input.index,w.length,r.collectionKey),S=w[v];return Mf(S,"edited"),w[v]={...S,text:u,edited_at:k()},g.metadata[r.collectionKey]=w,{changedFields:[r.collectionKey]}}})}catch(g){pr(g,r.conflictGuidance)}let y=Jt(h.item,r.collectionKey);return _s(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 re({pmRoot:o,settings:s,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(_){pr(_,r.conflictGuidance)}let f=Jt(p.item,r.collectionKey);return _s(p.item.id,r.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:f.length,entry:f.at(-1)},t.fullHistory===!0)}function $f(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,s=t===1?`1 ${r}`:`${t} ${n}`;throw new m(`${o} index ${e??"(missing)"} out of range (item has ${s})`,l.USAGE)}return e-1}function _s(e,t,n,r,o,s,i=!1){let a=s===void 0||i?Wa(n,s!==void 0&&i?void 0:r):s.entry===void 0?[]:[s.entry],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...[o,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...s===void 0?{}:{mutation_receipt:{action:s.action,entry_index:s.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 Uf(e,t,n){return[...await Tt(Re(e,t),t).catch(()=>[])].reverse().find(s=>s.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 Gf="no_available_next_item";function jf(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 ys(e,t,n,r={}){let o=E(process.cwd(),n.path);await C(o);let s=await A(o),i=$(s.schema),a=T(r.author,s.author_default),c=kn(a),d=null,u=!1,p=[],f=await re({pmRoot:o,settings:s,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,Um(_.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 Uf(o,_.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 $a({pmRoot:o,settings:s,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 qf(e,t,n={},r={}){let o=gv(n.maxAttempts),s=await A(E(process.cwd(),t.path)),i={...n,author:T(n.author,s.author_default)},a=await lr({...r,callerAuthor:i.author,limit:String(o)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return yv(c.slice(0,o),e,t,i)}function gv(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 yv(e,t,n,r={},o=ys){let s=0;for(let a of e){s+=1;try{let c=await o(a.id,t,n,r),d={...c,recommendation:a,attempts:s,available:!0};if(!c.skipped)return d}catch(c){if(!jf(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:s,warnings:[Gf]};let i=s===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: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 ws(e,t,n,r={}){let o=E(process.cwd(),n.path);await C(o);let s=await A(o),i=T(r.author,s.author_default),a=kn(i),c=r.ownershipReleaseBypass===!0,d=null,u;try{u=await re({pmRoot:o,settings:s,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){pr(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 Da({pmRoot:o,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 wv=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function Kf(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 Ja(e,t){return Xa(e,t,{operation:"close"})}function Xa(e,t,n){let r=Kf(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new 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:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function Qa(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],s=o.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"&&s.length>0){let d=o.filter(u=>u.kind!=="blocked_by");d.length>0?e.dependencies=d:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...s.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 bv=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function vv(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 kv(e){let t=[];for(let n of bv){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,o=t;for(;typeof o=="string"&&o.trim().length>0;){let s=o.trim();if(s===n)return!0;if(r.has(s))return!1;r.add(s),o=(await e(s))?.duplicate_of}return!1}function Ev(e){return typeof e!="string"||e.trim().length===0}async function Av(e,t,n,r){let o=n?.trim();if(!o)return;if(o===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 s=I(t,R()),i=new Map,a=async d=>{if(i.has(d))return i.get(d)??null;let u=await U(e,d,t.id_prefix,t.item_format,s.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(o);if(!c)throw new m(`Duplicate target "${o}" 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 ${o}" --duplicate-of ${o}`],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 "${o}" 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 "${o}" 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 Tv(e,t,n){return e.filter(r=>r.parent===t&&!te(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function Cv(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),o=kf(e),s=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:o.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let d=r.get(c);return d!==void 0&&te(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function Rv(e,t,n,r,o,s){let i=Cv(n,r,s),a=[];for(let c of i)try{let d=await re({pmRoot:e,settings:t,id:c.id,op:"update",author:o,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=s.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 Iv(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:s}of r){if(typeof o!="string")continue;let i=o.trim();i.length!==0&&(e[s]=i,n.push(s))}return n}function xv(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:s}of r)Ev(e[o])&&(e[o]=s,n.push(o));return n}function Ov(e,t,n,r){let o=[];if(t!=="off"){let s=kv(e);if(s.length>0){let i=s.map(a=>a.label);if(t==="strict"){let a=s.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:Io(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."]})}o.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);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function Pv(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function Lv(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function Nv(e,t){if(te(e.status,t.statusRegistry)&&!t.force)throw new m(`Item ${e.id} is already terminal; use --force to close again.`,l.CONFLICT);let n=Iv(e,t.options),r=xv(e,t.duplicateOf),o=Ov(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let i=["status","closed_at",...s?["completed_at"]:[],...Pv(e,t.closeReason),...n];if(lp(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(...Lv(e));let a=Qa(e,t.lifecyclePolicy);return i.push(...a.changedFields),o.push(...a.warnings),{changedFields:i,...o.length>0?{warnings:o}:{}}}async function zf(e,t,n,r){let o=E(process.cwd(),r.path);await C(o);let s=await A(o),i=$(s.schema),a=T(n.author,s.author_default),c=I(s,R()).type_to_folder,d=await U(o,e,s.id_prefix,s.item_format,c);if(!d)throw await at(o,e,s.id_prefix,c);let u=await Av(o,s,n.duplicateOf,d.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Ja({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=vv(n.validateClose)??s.governance.close_validation_default,h=await le(o,s.item_format,c,void 0,s.schema),y=Tv(h,d.id,i),g=new Date().toISOString(),w=n.completedAt===void 0?g:ne(n.completedAt,new Date(g),"completed-at"),v=await re({pmRoot:o,settings:s,id:d.id,op:"close",author:a,message:n.message,force:n.force,mutate(S){return Nv(S.metadata,{pmRoot:o,statusRegistry:i,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:g,completedAt:w,lifecyclePolicy:p})}});return{item:v.item,changed_fields:v.changedFields,warnings:[...v.warnings,...await Rv(o,s,h,d.id,a,i)]}}function ct(e,t,n,r){return zf(e,t,n,r)}import Fv from"fast-json-patch";import Za 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 Mv(e,t){return Qu(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function $v(e){let t=ya(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Je(Vt(t))}async function Dv(e,t,n,r){let o=await U(e,t,n.id_prefix,n.item_format,r);if(o){let c=Re(e,o.id),d=await Vu({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"});return{id:o.id,historyPath:c,located:o,historyPolicyWarnings:d.warnings}}let s=be(t,n.id_prefix),i=_a(t),a=s===i?[s]:[s,i];for(let c of a){let d=Re(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 Uv(e,t){let n=Wt(e),r=Wt(t),o=Fv.compare(n,r),s=new Set;for(let i of o){if(i.path==="/body"||i.path.startsWith("/body/")){s.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];s.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(s).sort((i,a)=>i.localeCompare(a))}async function Gv(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 U(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 jv(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:$v(t),originalRaw:null}}function qv(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 Kv(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await fe(e.existingItemPath,e.resolvedOriginalRaw),await Za.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await fe(e.existingItemPath,e.resolvedOriginalRaw);return}await Za.rm(e.restoredItemPath,{force:!0})}async function zv(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 o=E(process.cwd(),r.path);await C(o);let s=await A(o),i=I(s,R()),a=await Dv(o,e,s,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=Mv(t,u),f=Zu(ya(u,p.historyIndex),p),_=Uu(f,{schema:s.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:s.schema}):null)?.raw??null,g=T(n.author,s.author_default),w=await we(o,c,s.locks.ttl_seconds,g,!!n.force,s.governance.force_required_for_stale_lock,s.locks.wait_ms);try{let{loadedItemUnderLock:v,existingItemPath:S}=await Gv({pmRoot:o,resolvedId:c,subject:a,settings:s,typeToFolder:i.type_to_folder,historyRawBeforeLock:d,currentItemRawBeforeLock:y}),x="toon",O=jv(v,u),D=qv({document:O.document,author:g,force:n.force,enforcement:s.governance.ownership_enforcement,resolvedId:c}),N=Uv(O.document,_);await xo({pm_root:o,operation:"restore",before:O.document,after:_,changed_fields:N,sdk:Uo({pmRoot:o,settings:s,typeToFolder:i.type_to_folder})});let ce=qe(_,{format:x,schema:s.schema}),V=Kt(o,_.metadata.type,c,x,i.type_to_folder),de=await An(o,g),Y=[];try{await fe(V,ce),S&&V!==S&&await Za.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 Kv({existingItemPath:S,resolvedOriginalRaw:O.originalRaw,restoredItemPath:V}),ht}Y=await Tn({pmRoot:o,preferredFormat:s.item_format,typeToFolder:i.type_to_folder,schema:s.schema,itemPath:V,previousItemPath:S??void 0,document:_})}finally{await de()}let Te=await zv({restoredItemPath:V,historyPath:a.historyPath,before:O.document,after:_});wn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:O.document.metadata.status,status:_.metadata.status,previous:Ht(O.document.metadata,N),current:Ht(_.metadata,N),changed_fields:N});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:N,warnings:[...a.historyPolicyWarnings,...D,...Y,...Te]}}finally{await w()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7113374-b169-5f92-9c20-075a47520440")}catch{}})();var Hf=1,ec="close-many",Bv=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function Hv(e,t){return cr(e,t,{includePagination:!1})}function Vv(e,t){return cr(e,t)}function Wv(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 Yv(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function Jv(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 Xv(e,t){let n=$(t.schema),r=I(t,R()),o=await le(e,t.item_format,r.type_to_folder,void 0,t.schema),s=new Map,i=new Map;for(let a of o){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),te(a.status,n)))continue;let c=s.get(a.parent);c?c.push(a.id):s.set(a.parent,[a.id])}for(let a of s.values())a.sort((c,d)=>c.localeCompare(d));return{childrenByParent:s,parentByChild:i}}function Bf(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,s=t.get(e),i=[],a=new Set,c=!1;for(;s!==void 0&&!a.has(s);){let d=n?.get(s);if(d!==void 0){o+=d+1;break}a.add(s),i.push(s),o+=1,s=t.get(s)}if(s!==void 0&&a.has(s)&&(c=!0),!c){n?.set(e,o);for(let[d,u]of i.entries())n?.set(u,o-d-1)}return o}async function Qv(e){let t=await Ho(e.pmRoot,ec,e.rollbackId,Hf),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Vo(t.items,(o,s)=>Xt(o,s,{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 Zv(e,t,n,r,o){return e.map(s=>{let i=(t.get(s.id)??[]).filter(c=>!n.has(c)),a=!Vf(s,r,o);return{id:s.id,title:typeof s.title=="string"?s.title:"",status:s.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function ek(e){let t=await Bo(e.pmRoot,ec,e.checkpointId,{schema_version:Hf,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 tk(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await ct(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){t.push({id:r.id,status:"failed",error:gn(o)})}}return{rows:t,closedIds:n}}function nk(e){return typeof e.rollback=="string"?e.rollback:void 0}function rk(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(Vv(e.list,e.status))throw new m("Rollback mode does not accept filter options",l.USAGE)}function ok(e){if(!Hv(e.list,e.status))throw new m(`close-many requires at least one filter to scope the close (for example: ${Bv}). Refusing to match every item.`,l.USAGE)}function sk(e,t){let n=new Map;return[...e].sort((r,o)=>{let s=Bf(o.id,t,n)-Bf(r.id,t,n);return s!==0?s:r.id.localeCompare(o.id)})}function Vf(e,t,n){return n||!te(e.status,t)}function ik(e,t,n){return new Set(e.filter(r=>Vf(r,t,n)).map(r=>r.id))}async function ak(e){ok(e.options);let t=$(e.settings.schema),n=Jv(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await Pt(e.options.status,Yv(e.options.list),e.global),{childrenByParent:s,parentByChild:i}=await Xv(e.pmRoot,e.settings),a=sk(o.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=ik(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:a,unmatchedIds:c.filter(p=>!d.has(p)),planRows:Zv(a,s,u,t,r)}}function ck(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 dk(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 ek({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 Wf(e,t){let n=E(process.cwd(),t.path);await C(n);let r=await A(n),o=e.dryRun===!0,s=nk(e);if(Wv(e.list),s!==void 0)return rk(e,s),Qv({pmRoot:n,rollbackId:s,options:e,global:t});let i=await ak({pmRoot:n,settings:r,options:e,global:t});if(o)return ck(i);let a=new Set(i.planRows.filter(w=>w.action==="close").map(w=>w.id)),c=k(),d=zo(ec,c),u=await dk({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 tk({matched:i.matched,closableIds:a,reason:i.reason,closeOptions:p,global:t}),h=f.filter(w=>w.status==="closed").length,y=f.filter(w=>w.status==="skipped").length,g=f.filter(w=>w.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 lk}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 tc(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",s=Number(n)+Number(r)+Number(o);if(s===0)return;if(s>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 lk(i,"utf8"),emptyFlag:"--file"}}catch(a){if(Ya(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 mk(e,t){let n=e.edit,r=e.delete,o=n!==void 0,s=r!==void 0;if(o&&s)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(s){if(await tc(e,t)!==void 0)throw new m("--delete does not take comment text",l.USAGE);return{mode:"delete",index:r}}if(o){let c=await tc(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 tc(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 Yf(e,t,n){let r=$e(),o=await mk(t,r),s=o.mode==="add"||o.mode==="edit",i=o.value??"";return $n(e,t,n,{input:{...o,rawValue:t.add??i,value:s?Mn(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(o.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 Jf(e,t,n){return $n(e,t,n,{input:await gs(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Mn(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 uk(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 pk(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 fk(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 Xf(e,t,n){let r=uk(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new m("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",l.USAGE,{code:"structured_event_input_conflict"});let s=r===void 0?void 0:J(r),i=[t.since,t.eventType].some(h=>h!==void 0),a=fk(t.since),c=nr(t.limit),d=await $n(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await gs(s===void 0?t:{add:s},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>Mn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:pk(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),w=[!u,h.event_type===u].includes(!0);return[!i,[y,g,w].every(Boolean)].includes(!0)}),f=i?Wa(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 fr(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 _r(e,t,n=Ot()){for(let r of t??[])try{pl(e,r.id,r.kind,n)}catch(o){throw new m(gn(o),l.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Qf(e,t){return(await K(e,{schema:t})).document.metadata.created_at}async function _k(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await U(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Qf(n,t.schema)}function hk(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 gk(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:s})=>s===null?[]:[[o,s]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await Qf(n.get(o),e.context.schema)])));for(let o of e.holders){let s=await _k(o,e.context);if(s!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(s),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw hk({holder:o,dependency:i,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function Qt(e){let t=e.registry??Ot(),n=(e.dependencies??[]).filter(i=>!bp(i.source_kind)),r=[...new Set(n.map(i=>i.id))],o=await Promise.all(r.map(async i=>({target:i,located:await U(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=o.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new m(`Dependency target${s.length===1?"":"s"} not found: ${s.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:s,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 ${s.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:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await gk({dependencies:n,missingTargets:s,resolutions:o,holders:e.holders??[],registry:t,context:e}),s.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 bs(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function vs(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function ks(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Ur.includes(t))return t;let n=me(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 Ss(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 yk=new Set(["none","null"]);function Es(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:yk.has(e.trim().toLowerCase())}function As(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 ke(e,t,n){if(!e||e.length===0||!e.some(s=>Be(s)))return;let o=n?` ${n}`:"";throw new m(`${t} no longer accepts "none" or "null".${o}`.trim(),l.USAGE)}function Ts(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 o=r;if(!o.some(a=>Be(a)))continue;if(o.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 e_(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 nc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Se(e,t,n){if(!t.includes(e))throw new m(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,l.USAGE);return e}var t_=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function wk(e,t){return t==="defined"?e!==void 0:!!e}function Zf(e,t,n){if(!wk(e,n))return;let r=me(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new m(`--event ${t} must be an integer >= 1`,l.USAGE);return r}function bk(e,t,n){let r=e?ne(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 vk(e){return Array.from(new Set(nc(e).map(t=>Se(t.toLowerCase(),il,"event weekday")))).sort((t,n)=>Di(t)-Di(n))}function kk(e){return Array.from(new Set(nc(e).map(t=>{let n=me(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(nc(e).map(n=>ne(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function n_(e,t,n,r){let o=e.recur_freq?.trim(),s=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(![o,s,i,a,c,d,u].some(S=>S!==void 0))return;if(!o)throw new m("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",l.USAGE);let f=Se(o.toLowerCase(),sl,"event recurrence frequency"),_=Zf(s,"recur_interval",r),h=Zf(i,"recur_count",r),y=bk(a,t,n),g=vk(c),w=kk(d),v=Sk(u,n);return{freq:f,interval:_,count:h,until:y,by_weekday:g.length>0?g:void 0,by_month_day:w.length>0?w: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 r_="--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.",Ek="--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).",Ak=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,Tk=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,s_=1e3,rc=60*s_,Ck=60*rc;function o_(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 Rk(e,t){let n=new Date(e),r=t.trim(),o=Ak.exec(r);if(o){let a=o[1]==="-"?-1:1,c=Number.parseInt(o[2],10)*a;return o_(n.getTime()+c*rc,r)}let s=Tk.exec(r);if(s){let[,a,c,d,u]=s;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*rc+y*s_;return o_(n.getTime()+f*g,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return ne(i,n,"event.duration")}function i_(e,t,n,r){if(t&&n)throw new m(Ek,l.USAGE);if(n){let s=Rk(e,n);if(s<e)throw new m(r_,l.USAGE);return s===e?void 0:s}if(!t)return;let o=ne(t,r,"event.end");if(o<e)throw new m(r_,l.USAGE);if(o!==e)return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var Ik=["at","date","text","title"],xk=["start","date","end","duration","title","description","location","timezone","all_day",...t_],Ok=["key","value"];function a_(e,t){return t==="trimmed"?e?.trim():e}function Pk(e,t){return t==="defined"?e!==void 0:!!e}function Cs(e,t,n){return e.map(r=>{let o=se(r,"--reminder");ze(o,"--reminder",Ik);let s=a_(o.at??o.date,n.valueMode),i=a_(o.text??o.title,n.valueMode);if(!s||!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:ne(s,t,"reminder.at"),text:a}})}function Rs(e,t,n){return e.map(r=>{let o=se(r,"--event");ze(o,"--event",xk);let s=(o.start??o.date)?.trim();if(!s)throw new m("--event requires start=<iso|relative> or date=<iso|relative>",l.USAGE);let i=ne(s,t,"event.start"),a=o.end?.trim(),c=o.duration?.trim(),d=i_(i,a,c,t),u=o.title,p=o.description,f=o.location,_=o.timezone,h=u?.trim(),y=p?.trim(),g=f?.trim(),w=_?.trim(),v=[["title",u,h],["description",p,y],["location",f,g],["timezone",_,w]];for(let[D,N,ce]of v)if(N!==void 0&&!ce)throw new m(`--event ${D} must not be empty`,l.USAGE);let S=o.all_day?.trim(),x=n_(o,i,t,n.recurrenceEmptyNumericGuard),O=Pk(S,n.allDayEmptyGuard)?e_(S,"--event all_day"):void 0;return{start_at:i,end_at:d,title:h,description:y,location:g,all_day:O,timezone:w,recurrence:x}})}function Is(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 o,s;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",Ok),o=a.key?.trim(),s=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);o=r.slice(0,d).trim(),s=r.slice(d+1).trim()}if(!o||!s)throw new m("--type-option requires key and value",l.USAGE);t[o]=s}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 Lk="hierarchy-integrity";async function xs(e){let t=e.required?await we(e.pmRoot,Lk,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 Nk=new Set(["event","meeting","reminder","milestone","decision","adr"]);function c_(e,t,n,r){if(Nk.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=Ao("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm start-task ${e}`,to_status:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="44e6a87d-0ca5-53af-b199-b66bb2b98fb5")}catch{}})();var Zt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_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"],Fk=new Set(Zt),Mk=Zt.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),$k=new RegExp(`^(?:[-*+]\\s+)?(?:${Mk})\\s*[:=]`,"i");function Os(e){return e.startsWith("```")||e.includes(`
6
+ `)?!0:$k.test(e)}function Ps(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!Fk.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw new m(`${t} provides key "${o}" more than once after case normalization`,l.USAGE);n[i]=s}if(r.length>0)throw new m(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).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:o,...s}=n;return{...s,command:s.command??o}}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]="64adcc3c-3646-5990-9442-4c4374a2dc7d")}catch{}})();var nn=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",sr,Pp,"FORCE_COLOR"]),Fs=/^[A-Za-z_][A-Za-z0-9_]*$/,tn=["schema","tracker","auto"],d_=["source","isolated","snapshot"];function hr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new m(`${t} env_set must include at least one KEY=VALUE assignment`,l.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=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=o.slice(0,s).trim(),a=o.slice(s+1);if(!Fs.test(i))throw new m(`${t} env_set key "${i}" is invalid`,l.USAGE);if(nn.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 gr(e,t){if(!e)return;let n=On(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(!Fs.test(r))throw new m(`${t} env_clear key "${r}" is invalid`,l.USAGE);if(nn.has(r.toUpperCase()))throw new m(`${t} env_clear key "${r}" is reserved for sandbox safety`,l.USAGE)}return n}function Ms(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 $s(e,t){if(!e)return;let n=e.trim().toLowerCase();if(tn.includes(n))return n;throw new m(`${t} pm_context_mode must be one of: ${tn.join(", ")}`,l.USAGE)}function rn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(d_.includes(n))return n;throw new m(`${t} workspace_context_mode must be one of: ${d_.join(", ")}`,l.USAGE)}function on(e){if(!e)return;let t=On(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Dn(e,t,n){let r=on(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(s){throw new m(`${t} ${n} includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`,l.USAGE)}return r}}function Ds(e,t){if(!e)return;let n=me(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 Us(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new m(`${t} assert_json_field_equals must include at least one path=value assignment`,l.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new m(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,l.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+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 Gs(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new m(`${t} assert_json_field_gte must include at least one path=value assignment`,l.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new m(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,l.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+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 Dk=new Set(Zt);function js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Uk(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!Dk.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw t(`provides key "${o}" more than once after case normalization`);n[i]=s}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${Zt.join(", ")}.`);return n}function en(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 Ls(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=o.filter(i=>i.length>0);return s.length>0?s:void 0}function l_(e,t,n){let r=Ls(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`)}return r}}function Ns(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 Gk(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:Ns(n,"timeout_seconds",t),s=r===void 0?void 0:Ns(r,"timeout",t);if(o!==void 0&&s!==void 0&&o!==s)throw t("timeout and timeout_seconds must match when both are provided");let i=o??s;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function jk(e,t){let n=en(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 qk(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!js(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Fs.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(nn.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=s}return Object.keys(r).length>0?r:void 0}function Kk(e,t){let n=Ls(e,"env_clear",t);if(n){for(let r of n){if(!Fs.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(nn.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function zk(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 Bk(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=Ns(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 Hk(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!js(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(s)}return Object.keys(r).length>0?r:void 0}function Vk(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!js(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=Ns(s,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function Wk(e,t,n){let r=f=>new m(`${n} ${t} ${f}`,l.USAGE);if(!js(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Zt.join(", ")}.`);let o=Uk(e,r),s=en(o,"command",r),i=en(o,"cmd",r);if(s!==void 0&&i!==void 0&&s!==i)throw r("command and cmd must match when both are provided");let a=s??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=en(o,"path",r),d=en(o,"pm_context_mode",r);if(d!==void 0&&!tn.includes(d))throw r(`field "pm_context_mode" must be one of: ${tn.join(", ")}`);let u=rn(en(o,"workspace_context_mode",r),`${n} ${t}`),p=en(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:jk(o,r),timeout_seconds:Gk(o,r),pm_context_mode:d,workspace_context_mode:u,env_set:qk(o,r),env_clear:Kk(o,r),shared_host_safe:zk(o,"shared_host_safe",r),assert_stdout_contains:Ls(o,"assert_stdout_contains",r),assert_stdout_regex:l_(o,"assert_stdout_regex",r),assert_stderr_contains:Ls(o,"assert_stderr_contains",r),assert_stderr_regex:l_(o,"assert_stderr_regex",r),assert_stdout_min_lines:Bk(o,r),assert_json_field_equals:Hk(o,r),assert_json_field_gte:Vk(o,r),note:p!==void 0&&p.trim().length>0?p.trim():void 0}}function m_(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(s){throw new m(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. 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 o=Array.isArray(r)?r:[r];if(o.length===0)throw new m(`${t} array must include at least one linked-test entry object`,l.USAGE);return o.map((s,i)=>Wk(s,o.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 oc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],sc=[{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"}],u_=[...oc,...sc],qs=[{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 Ks(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 o=r.trim().toLowerCase();if(!o)throw new m("--unset values must not be empty",l.USAGE);if(Be(o))throw new m('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',l.USAGE);let s=e.resolveDefinition(o);if(!s)throw new m(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,l.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function zs(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let s of o){if(s.allow_unset===!1)continue;let i=new Set;if(typeof s.key=="string"&&s.key.length>0&&i.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&i.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(i.add(s.cli_flag.replaceAll("-","_").toLowerCase()),i.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let a of s.cli_aliases)typeof a!="string"||a.length===0||(i.add(a.replaceAll("-","_").toLowerCase()),i.add(a.toLowerCase()));if(i.has(r))return{optionKey:s.key,metadataKey:s.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 Yk={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 Jk(e){return Yk[e]}function ic(e){return Jk(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]="f8c8e154-737b-58db-9a8b-7f4399342e83")}catch{}})();var Xk=["strict","progressive"],Qk=["lightweight"],h_=new Set(["Reminder","Meeting","Event"]),Zk=new Set(["author","created_at","text"]),cc=[...u_,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...qs],eS=(()=>{let e=new Map;for(let t of cc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Bs=new Map(cc.map(e=>[e.optionKey,e.canonical])),tS=cc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function nS(e,t){let n=Z(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new m(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n}function rS(e,t){let n=e.default_status;if(n!==void 0){let r=Z(n,t);if(r)return r}return t.open_status}function ac(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 oS=Es();function g_(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s};Be(t.template)&&(t.template=void 0);let r=new Set([...Bs.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!Be(s))continue;let i=o==="rank"?"order":Bs.get(o)??o;n(i),t[o]=void 0}return Ts(t,oS)}function pe(e){if(e!==void 0)return e}function sS(e,t){return Ks({raw:e,supportedFields:tS,resolveDefinition:n=>eS.get(n)??zs(n,"create",t)})}var p_=["id","kind","type","author","created_at","source_kind"],Hs=["path","scope","note"];function iS(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let i=s.trim(),a=dc(i,p_);fr(i,a);let c=a?se(s,"--dep"):{id:i,kind:"related"};a&&ze(c,"--dep",p_);let d=pe(c.id),u=aS(pe(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=rr(pe(c.source_kind)),f=pe(c.author);return{id:or(d,n,p),kind:Se(u,jt,"dependency kind"),created_at:ac(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function aS(e){return typeof e=="string"?Br(e)??e.trim():e}function dc(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:ts(e)}function an(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(ke(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=>!Zk.has(f)).length>0)return{created_at:ac(d.created_at,n),author:pe(d.author)??r,text:a};let p=d.text??"";if(p==="")throw new m(`${e} requires text=<value>`,l.USAGE);return{created_at:ac(d.created_at,n),author:pe(d.author)??r,text:p}}),explicitEmpty:!1})}function lc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),o=dc(r,Hs),s=o?se(n,"--file"):{path:r};if(o&&ze(s,"--file",Hs),!s.path)throw new m("--file requires path=<value> or a bare file path",l.USAGE);return{path:s.path,scope:Se(s.scope??"project",tt,"file scope"),note:pe(s.note)}}),explicitEmpty:!1})}function mc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),o=Os(r)?Ps(se(n,"--test"),"--test"):{command:r},s=pe(o.command),i=pe(o.path);if(!s)throw new m("--test requires command=<value> or a bare command (path=<value> is optional metadata)",l.USAGE);let a=pe(o.timeout_seconds),c=pe(o.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:s,path:i,scope:Se(o.scope??"project",tt,"test scope"),timeout_seconds:d?me(d,"timeout_seconds"):void 0,pm_context_mode:$s(o.pm_context_mode,"--test"),workspace_context_mode:rn(o.workspace_context_mode,"--test"),env_set:hr(o.env_set,"--test"),env_clear:gr(o.env_clear,"--test"),shared_host_safe:Ms(o.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:on(o.assert_stdout_contains),assert_stdout_regex:Dn(o.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:on(o.assert_stderr_contains),assert_stderr_regex:Dn(o.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Ds(o.assert_stdout_min_lines,"--test"),assert_json_field_equals:Us(o.assert_json_field_equals,"--test"),assert_json_field_gte:Gs(o.assert_json_field_gte,"--test"),note:pe(o.note)}}),explicitEmpty:!1})}function uc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),o=dc(r,Hs),s=o?se(n,"--doc"):{path:r};if(o&&ze(s,"--doc",Hs),!s.path)throw new m("--doc requires path=<value> or a bare doc path",l.USAGE);return{path:s.path,scope:Se(s.scope??"project",tt,"doc scope"),note:pe(s.note)}}),explicitEmpty:!1})}function cS(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Cs(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function dS(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--event","Use --clear-events to clear linked events."),{values:Rs(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function lS(e,t,n,r=[]){let o=[...Gr.filter(s=>e[s]!==void 0),...r.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(o))}function mS(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function f_(e,t,n){let r=Wn("create",e);if(!r)throw new m(`Unsupported ${n} entry "${e}" for type "${t}"`,l.CONFLICT);return r}function uS(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 y_(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 pS(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(f_(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(f_(r,e.name,"required_create_repeatables"));return n}function fS(e,t,n,r){for(let o of e)if(!(!y_(t,o)&&!n.has(o)))throw new m(`Option ${ge("create",o)} is disabled for type "${r}" by command_option_policies`,l.USAGE)}function _S(e,t,n){if(t!=="strict")return;let r=e.filter(s=>n.has(s)&&!ic(s));if(r.length===0)return;let o=[...new Set(r.map(s=>ge("create",s)))].sort((s,i)=>s.localeCompare(i));throw new m(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,l.USAGE)}function hS(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Is(e),explicitEmpty:!1})}async function gS(e){let t=$e();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 yS(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: ${Xk.join(", ")}`,l.USAGE)}function wS(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: ${Qk.join(", ")}`,l.USAGE)}function bS(e,t,n){let r=yS(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 vS(e,t,n,r){let o=e.name,s=uS(t),i=pS(e,n),a=hn(e,"create",i);if(a.errors.length>0)throw new m(a.errors.join("; "),l.CONFLICT);fS(a.disabled,s,r,o),_S(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&ic(u)?!0:y_(s,u),d=a.required.filter(u=>!c(u));return[...new Set(d.map(u=>ge("create",u)))].sort((u,p)=>u.localeCompare(p))}var w_=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function kS(e,t){let n=[];for(let r of e){let o=r.match(w_);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function SS(e,t){return e.filter(n=>{let r=n.match(w_);return!r||r[2]!==t})}function ES(e,t,n,r){let o=SS(e,t);if(o.length===0)return;let s=b_(n,[],[],r.open_status);throw new m(o.join("; "),l.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function AS(e,t){let r=e.options.find(o=>o.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function TS(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 b_(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],i=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of i)a.has(c)||(o.push(...TS(c,e.name,r)),a.add(c));for(let c of n){let d=AS(e,c);o.push("--type-option",`${c}=${d}`)}return o.join(" ")}function pc(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 xn(e)}function RS(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=Array.isArray(o)?[...o]:o;for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=Array.isArray(o)?[...o]:o);return n}function IS(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function xS(){let e=R();return e?e.commands.some(t=>t.action==="templates-show"||IS(t.command)==="templates show"):!1}function OS(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[o,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[o]=s;continue}if(Array.isArray(s)&&s.every(i=>typeof i=="string")){r[o]=[...s];continue}throw new m(`Templates package returned unsupported option value for "${o}" in template "${t}".`,l.GENERIC_FAILURE)}return r}async function PS(e,t,n){if(!xS())throw new m("--template requires the templates package. Install it first (for example: pm install templates --project).",l.USAGE);let r=await Oo({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let o=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.${o}`,l.USAGE)}return OS(r.result,e)}function LS(e){return C(e)}function B(e,t,n){return e.has(t)||n===void 0?void 0:pe(n)}function sn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var NS=new Set(["milestone","meeting","reminder","event"]);function v_(e,t,n,r){let o=t!==void 0,s=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return NS.has(e.toLowerCase())&&!o&&!s&&!i}function FS(e,t,n,r,o){let s=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),v_(e,n,r,o)&&s.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)`),s}async function MS(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await Po(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function $S(e,t,n,r,o,s){let i=Jo(o);if(Qo(r,i,t.id_prefix),await U(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:Xo(c,s).warnings}}async function DS(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await $S(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function US(e){if(e.explicitId===void 0)return tr(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||ip(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 __(e,t,n,r,o){let s=B(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let i=ns(r,s,o);return{value:i.value,warnings:i.warnings}}async function GS(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:s,status:i,statusExplicit:a,nowValue:c,author:d}=e,u=e.dependencyValues;if(s===void 0)return{dependencyValues:u,status:i};let p=be(s,n.id_prefix),f=await U(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=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((y,g)=>y.localeCompare(g))[0]??o.open_status;return{dependencyValues:u,status:h}}function jS(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let o=t.governance.create_default_type?.trim();if(o&&o.length>0&&_e(o,n)){e.type=o;return}_e("Task",n)&&(e.type="Task")}function qS(e,t){return e.options.filter(n=>Wn("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 KS(e,t,n,r,o){let s=e,i=[];if(s.template!==void 0){let h=s.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);s=g_(RS(y,s))}if(s.type===void 0&&jS(s,r,o),s.type===void 0)throw new m("Missing required option --type <value>",l.USAGE);let a=_e(s.type,o);if(!a){let h=cp(s.type),y=h?_e(h,o):void 0;if(y)i.push(`type_coercion:${s.type.trim()}:${y}`),s.type=y,a=y;else throw new m(Et(s.type,o.types,At(n,r.schema)),l.USAGE)}let c=Kr(a,o);if(!c)throw new m(`Invalid type value "${s.type}"`,l.USAGE);let d=c.name,u=qS(c,s),p=u.map(h=>`${h.key}=${String(s[h.key])}`);if(p.length>0){s.typeOption=[...p,...s.typeOption??[]];for(let h of u)delete s[h.key]}let f=wS(s.schedulePreset);if(f!==void 0&&!h_.has(d))throw new m(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,l.USAGE);let _=bS(s.createMode,f,r.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:d,schedulePreset:f,createMode:_,warnings:i}}function zS(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of o)if(s.enabled){if(s.values&&s.values.length>0)throw new m(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,l.USAGE);n.add(s.metadataKey),r.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function BS(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=Bs.get(r)??r;throw new m(`Cannot combine --unset ${s} with ${ge("create",r)}`,l.USAGE)}}function HS(e){let t=(n,r)=>{let o=Bs.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;As(n,ge("create",r),s)};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 VS(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 WS(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:s,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=[b_(n,r,o,s),...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".'),h_.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 YS(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 Rn(n,t.addTags)}function JS(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=sn(e,"order",n,o=>me(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new m("Order must be an integer",l.USAGE);return r}function XS(e,t,n,r,o,s){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?s:ne(r.completedAt,new Date(s),"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:o}:{explicit:r.closeReason};return{closeReason:Xa(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function QS(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:s,author:i,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=Kt(t,n,r,o.item_format,s.type_to_folder),g=Re(t,r),w=Ot(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(D=>w.resolve(D.kind)?.hierarchy),S=await xs({pmRoot:t,author:i,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:v}),x=v,O=[];try{let D=await we(t,r,o.locks.ttl_seconds,i,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let N=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await le(t,o.item_format,s.type_to_folder,void 0,o.schema):void 0;if(await U(t,r,o.id_prefix,o.item_format,s.type_to_folder))throw new m(`Item "${r}" already exists`,l.CONFLICT);if(N){let Y=$(o.schema);rs(N,[...N,c.metadata],r,Te=>te(Te,Y),w)}await xo({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:Uo({pmRoot:t,settings:o,typeToFolder:s.type_to_folder})});let V=await An(t,i,{required:o.governance.duplicate_detection_mode==="strict"&&h!==!0}),de=[];try{o.governance.duplicate_detection_mode==="strict"&&h!==!0&&await Fn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await fe(y,qe(c,{format:o.item_format,schema:o.schema,extensionFieldNames:a}));try{let Y=Ke({nowIso:f,author:i,op:"create",before:d,after:c,message:u});await Ct(g,Y)}catch(Y){throw await _n(y),Y}x&&(await S(),x=!1),de=await Tn({pmRoot:t,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:y,document:c})}finally{await V()}O=[...N?ms(N,[...N,c.metadata],r):[],...de,...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})],wn({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 D()}}finally{x&&await S()}return O}async function Lt(e,t){let n=g_(await gS(e)),r=E(process.cwd(),t.path);await LS(r);let o=await A(r),s=$(o.schema),i=Ye(o.schema),a=I(o,R()),c=await KS(n,t,r,o,a);n=c.resolvedOptions;let{typeDefinition:d,type:u,createMode:p}=c,f=sS(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=zS(n,f);BS(n,f),HS(n);let y=vS(d,n,p,h),g=k(),w=T(pe(n.author),o.author_default),v=iS(n.dep,g,o.id_prefix,w),S=an("--comment",n.comment,g,w),x=an("--note",n.note,g,w),O=an("--learning",n.learning,g,w),D=lc(n.file),N=mc(n.test);N.values=await Nn(N.values,w,g);let ce=uc(n.doc),V=cS(n.reminder,g),de=dS(n.event,g),Y=hS(n.typeOption),Te=Yn(u,Y.values,a),ft=R(),_t=vt(ft),ht=jr(n.field,ft),gt=Ru(n,i,u),Ti=new Set(gt.missing_required_flags),Ci=i.definitions.filter(W=>Ti.has(`--${W.cli_flag}`));VS(ht,gt,f);let Vn=kS(Te.errors,u),Ut=Vn.map(W=>`--type-option ${W}=<value>`),jd=[...new Set([...y,...Ut,...gt.missing_required_flags])].sort((W,Mi)=>W.localeCompare(Mi));WS({combinedMissingFlags:jd,typeDefinition:d,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:Vn,openStatus:s.open_status,type:u,createMode:p,missingRequiredRuntimeFields:Ci}),ES(Te.errors,u,d,s);let Ce=await US({pmRoot:r,settings:o,typeRegistry:a,explicitId:n.id}),yt=n.status!==void 0?nS(n.status,s):rS(d,s),Ri=n.priority!==void 0?CS(n.priority):2,L=f.metadataKeys,Fe=YS(L,n),et=sn(L,"deadline",n.deadline,W=>ne(W,new Date(g),"deadline")),Lr=sn(L,"estimated_minutes",n.estimatedMinutes,W=>In(W,"estimated-minutes")),wt=B(L,"acceptance_criteria",n.acceptanceCriteria),Ii=B(L,"definition_of_ready",n.definitionOfReady),We=JS(L,n),xi=B(L,"goal",n.goal),Nr=B(L,"objective",n.objective),Gw=B(L,"value",n.value),jw=B(L,"impact",n.impact),qw=B(L,"outcome",n.outcome),Kw=B(L,"why_now",n.whyNow),zw=B(L,"assignee",n.assignee),Bw=L.has("author")?void 0:pe(n.author)??w,Hw=B(L,"parent",n.parent),qd=await MS(Hw,n,L,r),Oi=qd.parent,Vw=qd.parentSource,Ww=B(L,"reviewer",n.reviewer),Yw=sn(L,"risk",n.risk,W=>Se(bs(W),pn,"risk")),Jw=sn(L,"confidence",n.confidence,W=>ks(W)),Xw=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Kd=o.validation.sprint_release_format,Gt=[...c.warnings,...FS(u,Ce,et,V.values,de.values)],zd=await DS({itemId:Ce,parent:Oi,pmRoot:r,settings:o,typeRegistry:a,policy:Xw});Oi=zd.parent,Gt.push(...zd.warnings);let Bd=__(L,"sprint",n.sprint,"sprint",Kd),Qw=Bd.value;Gt.push(...Bd.warnings);let Hd=__(L,"release",n.release,"release",Kd),Zw=Hd.value;Gt.push(...Hd.warnings);let Vd=B(L,"blocked_by",n.blockedBy),Wd=await GS({pmRoot:r,settings:o,typeRegistry:a,statusRegistry:s,blockedBy:Vd,dependencyValues:v.values,status:yt,statusExplicit:n.status!==void 0,nowValue:g,author:w}),Pi=Wd.dependencyValues;_r(Ce,Pi),Gt.push(...await Qt({pmRoot:r,dependencies:Pi,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ce,createdAt:g}],schema:o.schema})),yt=Wd.status;let eb=B(L,"blocked_reason",n.blockedReason),tb=B(L,"unblock_note",n.unblockNote),nb=B(L,"reporter",n.reporter),rb=sn(L,"severity",n.severity,W=>Se(vs(W),fn,"severity")),ob=B(L,"environment",n.environment),sb=B(L,"repro_steps",n.reproSteps),Yd=B(L,"resolution",n.resolution),ib=B(L,"expected_result",n.expectedResult),ab=B(L,"actual_result",n.actualResult),cb=B(L,"affected_version",n.affectedVersion),db=B(L,"fixed_version",n.fixedVersion),lb=B(L,"component",n.component),mb=sn(L,"regression",n.regression,W=>Ss(W)),ub=B(L,"customer_impact",n.customerImpact),Li=pc(n.title,"--title"),Ni=n.description??"",Fr=n.body??"",Jd=await Fn({title:Li,description:Ni,body:Fr},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Gt.push(...us(Jd));let Fi=XS(yt,s,o,n,Yd,g),pb=Fi.closeReason,fb=yt===s.close_status?g:void 0,_b=Fi.completedAt;Gt.push(...Fi.warnings);let Mr=pa({id:Ce,title:Li,description:Ni,type:u,type_options:Te.normalized,status:yt,closed_at:fb,completed_at:_b,close_reason:pb,priority:Ri,tags:Fe,created_at:g,updated_at:g,deadline:et,assignee:zw,author:Bw,estimated_minutes:Lr,acceptance_criteria:wt,definition_of_ready:Ii,order:We,goal:xi,objective:Nr,value:Gw,impact:jw,outcome:qw,why_now:Kw,parent:Oi,reviewer:Ww,risk:Yw,confidence:Jw,sprint:Qw,release:Zw,blocked_by:Vd,blocked_reason:eb,unblock_note:tb,reporter:nb,severity:rb,environment:ob,repro_steps:sb,resolution:Yd,expected_result:ib,actual_result:ab,affected_version:cb,fixed_version:db,component:lb,regression:mb,customer_impact:ub,dependencies:Pi,comments:S.values,notes:x.values,learnings:O.values,files:D.values,tests:N.values,docs:ce.values,reminders:V.values,events:de.values,...ht,...gt.values});try{qr(Mr,ft)}catch(W){throw new m(W instanceof Error?W.message:"Invalid extension item field values",l.USAGE)}let hb=Je({metadata:Mr,body:Fr},{schema:o.schema,extensionFieldNames:_t}),gb={metadata:{},body:""},Xd=[..._].sort((W,Mi)=>W.localeCompare(Mi)),yb=mS(n.message,Xd),Qd=lS(Mr,Fr,Xd,[...Object.keys(ht),...Object.keys(gt.values??{})]),wb=await QS({pmRoot:r,type:u,id:Ce,settings:o,typeRegistry:a,author:w,extensionFieldNames:_t,afterDocument:hb,beforeDocument:gb,historyMessage:yb,changedFields:Qd,nowValue:g,similarityCandidate:{title:Li,description:Ni,body:Fr},allowDuplicate:n.allowDuplicate}),Zd=structuredClone(Mr);p==="strict"&&_.has("dependencies")&&(Zd.dependencies=[]);let bb=c_(Ce,u,yt,s);return v_(u,et,V.values,de.values)&&$u(`[pm] warning: ${u} '${Ce}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ce} --deadline <ISO>' or 'pm update ${Ce} --event "start=<ISO>,end=<ISO>"'.`),{item:Zd,changed_fields:Qd,warnings:[...Gt,...wb],...Object.fromEntries([["parent_source",Vw],["next_transition",bb],["similarity_advisory",Jd]].filter(W=>W[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]="c88f01be-6abe-5fa2-9792-3f54e61bb282")}catch{}})();var gc=[...oc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...sc,...qs],ZS=(()=>{let e=new Map;for(let t of gc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Vs=new Map(gc.map(e=>[e.optionKey,e.canonical])),eE=gc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),tE=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),nE=Es({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function rE(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s},r=new Set([...Vs.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!Be(s))continue;let i=o==="rank"?"order":Vs.get(o)??o;n(i),t[o]=void 0}return Ts(t,nE)}function I_(e,t,n=[]){return Ks({raw:e,supportedFields:eE,resolveDefinition:r=>{let o=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return ZS.get(r)??zs(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var k_=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 S_(e){let t=e.disallowedFlags.flatMap(r=>{let o=k_.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=k_.get(r);return o?[`Replace ${r} with: ${o(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 oE(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new m("Choose only one package-provided ownership bypass mode.",l.USAGE);let s=(c,d,u)=>{c&&u.push(d)};if(o){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(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 S_({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=[];s(t.status!==void 0,"--status",i),s(t.closeReason!==void 0,"--close-reason",i),s(t.assignee!==void 0,"--assignee",i),s(t.parent!==void 0,"--parent",i),s(t.blockedBy!==void 0,"--blocked-by",i),s(t.blockedReason!==void 0,"--blocked-reason",i),s(t.unblockNote!==void 0,"--unblock-note",i),s(t.dep!==void 0,"--dep",i),s(t.depRemove!==void 0,"--dep-remove",i),s(t.replaceDeps===!0,"--replace-deps",i),s(t.replaceTests===!0,"--replace-tests",i),s(t.replaceFiles===!0,"--replace-files",i),s(t.replaceDocs===!0,"--replace-docs",i),s(t.note!==void 0,"--note",i),s(t.learning!==void 0,"--learning",i),s(t.test!==void 0,"--test",i),s(t.reminder!==void 0,"--reminder",i),s(t.event!==void 0,"--event",i),s(t.clearDeps===!0,"--clear-deps",i),s(t.clearComments===!0,"--clear-comments",i),s(t.clearNotes===!0,"--clear-notes",i),s(t.clearLearnings===!0,"--clear-learnings",i),s(t.clearFiles===!0,"--clear-files",i),s(t.clearTests===!0,"--clear-tests",i),s(t.clearDocs===!0,"--clear-docs",i),s(t.clearReminders===!0,"--clear-reminders",i),s(t.clearEvents===!0,"--clear-events",i);let a=[...n].filter(c=>tE.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw S_({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 sE(e,t){let n=Z(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new m(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n}function iE(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Bm({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Z(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Z(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Hm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new m(o,l.USAGE);return`workflow_transition_not_allowed: ${o}`}function aE(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:x_(e)}function x_(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 Un(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var cE=["id","kind","type","author","created_at","source_kind"],dE=["id","kind","type","author","created_at","source_kind"];function O_(e){return e.startsWith("```")||e.includes(`
8
+ `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:ts(e)}function P_(e){return typeof e=="string"?Br(e)??e.trim():e}function Ys(e,t,n,r){return e?(ke(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let i=s.trim(),a=O_(i);fr(i,a);let c=a?se(s,"--dep"):{id:i,kind:"related"};a&&ze(c,"--dep",cE);let d=c.id?.trim(),u=P_((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=rr(Un(c.source_kind)),f=Un(c.author);return{id:or(d,t,p),kind:Se(u,jt,"dependency kind"),created_at:aE(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function lE(e,t){return e?(ke(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 o=O_(r);if(fr(r,o,"--dep-remove"),o){let s=se(r,"--dep-remove");ze(s,"--dep-remove",dE);let i=s.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=P_(Un(s.kind??s.type)),c=rr(Un(s.source_kind)),d=Un(s.author),u=Un(s.created_at);return{id:or(i,t,c),kind:a?Se(a,jt,"dependency kind"):void 0,source_kind:c,author:d,created_at:u?x_(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 Ws(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function mE(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),s=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function uE(e,t,n,r){let o=[...e??[]],s=!1;if(t===void 0){let i=o.filter(a=>a.kind!=="blocked_by");return i.length!==o.length&&(o=i,s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(i=>i.kind==="blocked_by"&&i.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function pE(e,t,n,r,o,s){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await U(n,be(i,r),r,o,s);return a?{id:a.id}:{unresolved:i}}function fE(e,t,n,r,o){let s=uE(e.dependencies,t,n,r);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,o.includes("dependencies")||o.push("dependencies"))}function _E(e){return`${e.path}::${e.scope}`}function hE(e){return`${e.path}::${e.scope}`}function gE(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function L_(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 yE(e){return xn(e)}function E_(e,t){let n=Wn("update",e);if(!n)throw new m(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,l.CONFLICT);return n}function wE(e,t,n){let r=new Set,o=(s,i)=>{i&&r.add(s)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=I_(e.unset,t,n);for(let i of s.optionKeys)o(i,!0)}return r}function bE(e,t,n,r,o){let s=Kr(e,n);if(!s)throw new m(`Invalid type value "${e}"`,l.USAGE);let i=hn(s,"update",[]);if(i.errors.length>0)throw new m(i.errors.join("; "),l.CONFLICT);let a=wE(t,r,o);for(let c of i.disabled)if(a.has(E_(c,e)))throw new m(`Option ${ge("update",c)} is disabled for type "${e}" by command_option_policies`,l.USAGE);for(let c of i.required)if(!a.has(E_(c,e)))throw new m(`Missing required option ${ge("update",c)} for type "${e}"`,l.USAGE)}var vE=new Set(["order","rank"]),kE=Bi.filter(e=>!vE.has(e)),N_=["tags","closeReason",...kE],SE=["title","description","body","status","closeReason","completedAt","priority","type",...Bi,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],EE=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>ne(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>In(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"}],AE=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Se(bs(e),pn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>ks(e)}],TE=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Se(vs(e),fn,"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=>Ss(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function hc(e,t,n){for(let r of e){let o=t[r.optionKey],s=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!s)){if(s){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new m(`${ge("update",String(r.optionKey))} must be a string value`,l.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function CE(e){let t=$e();return rE({...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 RE(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 fc(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 yc(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);fc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),fc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),fc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function IE(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 xE(e){let t={};for(let n of N_)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function OE(e,t){let n=xE(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=Vs.get(r)??r;throw new m(`Cannot combine --unset ${s} with ${ge("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 o=Vs.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;As(n,ge("update",r),s)};for(let n of N_)t(e[n],String(n));t(e.order??e.rank,"order"),ke(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),ke(e.event,"--event","Use --clear-events to clear linked events.")}function LE(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 NE(e){let t=await U(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 FE(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return le(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function ME(e){e.before&&rs(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>te(t,e.statusRegistry),Ot())}async function $E(e){await C(e)}function DE(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 UE(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Jo(e.options.parent);if(Qo(e.id,t,e.settings.id_prefix),await U(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:Xo(r,e.parentReferencePolicy).warnings}}function GE(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function jE(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await U(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?_e(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=iE({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function qE(e){if(!e.fieldFlags.status||Z(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=[],o=[];if(n.length>0){let a=await dt(e.id,{...e.options,status:void 0,closeReason:void 0,message:void 0},e.global);o=a.changed_fields,r.push(...a.warnings)}let s=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,...s.warnings,"auto_routed_from_update_to_close"];return{item:s.item,changed_fields:[...o,...s.changed_fields],warnings:i}}function KE(e,t,n,r){return t.title!==void 0&&(e.metadata.title=pc(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")),Z(e.metadata.status,n)??e.metadata.status}function zE(e,t,n,r,o){let s=sE(n,t.statusRegistry);if(e.metadata.status=s,o.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!te(s,t.statusRegistry)&&te(r,t.statusRegistry)&&e.metadata.closed_at!==void 0&&(delete e.metadata.closed_at,o.push("closed_at"),e.metadata.completed_at!==void 0&&(delete e.metadata.completed_at,o.push("completed_at")))}function BE(e,t,n,r){if(t.options.status!==void 0&&zE(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!te(e.metadata.status,t.statusRegistry))throw new m("--completed-at can only be set on a terminal item",l.USAGE);e.metadata.completed_at=ne(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function HE(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new m("--close-reason must not be empty",l.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&te(n,t.statusRegistry)&&!te(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function VE(e,t,n,r){BE(e,t,n,r),HE(e,t,n,r)}function WE(e,t,n){let r=_e(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=yE(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=_e(t.options.type,t.typeRegistry);if(!o)throw new m(Et(t.options.type,t.typeRegistry.types,At(t.pmRoot,t.settings.schema)),l.USAGE);e.metadata.type=o,r=o,n.push("type")}return bE(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),YE(e,t,r,n),r}function YE(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 s=Is(t.options.typeOption??[]),i=Yn(n,s,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 o=Yn(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new m(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,l.USAGE);e.metadata.type_options=o.normalized}function JE(e,t){let n=new Set(t.map(o=>Ws(o))),r=new Set;return e.filter(o=>{if(!n.has(Ws(o)))return!0;let s=mE(o);return r.has(s)?!1:(r.add(s),!0)})}function XE(e,t,n){let r=t.filter(o=>!e.some(s=>L_(s,o)));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(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function QE(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=JE(r,t.dependencyUpdates.additions);let o=new Set(r.map(s=>Ws(s)));for(let s of t.dependencyUpdates.additions){let i=Ws(s);o.has(i)||(r.push(s),o.add(i))}}t.dependencyRemovals.length>0&&(XE(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(s=>L_(o,s)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function ZE(e,t,n){_c(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),_c(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),_c(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function _c(e,t,n,r,o,s){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],s.push(t))}function eA(e,t,n){A_(e,"files",t.options.file,t.fileUpdates.values,_E,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),tA(e,t,n),A_(e,"docs",t.options.doc,t.docUpdates.values,hE,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function A_(e,t,n,r,o,s,i,a){if(!(n===void 0&&!i.has(t))){if(s)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=>o(u)));for(let u of r){let p=o(u);d.has(p)||(c.push(u),d.add(p))}e.metadata[t]=c}a.push(t)}}function tA(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=T_(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=T_([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function T_(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=gE(r);n.has(o)||(t.push(r),n.add(o))}return t}function nA(e,t,n){let r=t.options.addTags,o=t.options.removeTags,s=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){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=es(Rn(i,r),o),n.changedFields.push("tags")}hc(EE,t.options,n),oA(e,t,n.changedFields)}function rA(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let s=Zo(Cn(e.metadata.acceptance_criteria),r,o);if(s.unmatchedRemovals.length>0)throw new m(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,l.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.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=s.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 oA(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=me(r??"","order");if(!Number.isInteger(o))throw new m("Order must be an integer",l.USAGE);e.metadata.order=o}n.push("order")}}function sA(e,t,n,r){iA(e,t,n.changedFields),aA(e,t,n.changedFields),hc(AE,t.options,n),C_(e,t,"sprint",r,n.changedFields),C_(e,t,"release",r,n.changedFields),cA(e,t,n.changedFields),hc(TE,t.options,n)}function iA(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 aA(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 C_(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=ns(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,r.push(...s.warnings)}o.push(n)}}function cA(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)&&fE(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function dA(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Cs(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=Rs(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function lA(e,t,n){R_(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),R_(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let i=o.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(d=>d.metadata_key===o)?.cli_flag??i;throw new m(`Cannot combine --unset ${i} with --${c}`,l.USAGE)}rt(e[o],s)||(e[o]=s,n.push(o))}let r=jr(t.options.field,t.extensionRegistrations);for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new m(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,l.USAGE);for(let[o,s]of Object.entries(r))rt(e[o],s)||(e[o]=s,n.push(o))}function R_(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function mA(e,t){let n=structuredClone(e.metadata),r=e.body,o=[],s=[],i=KE(e,t.options,t.statusRegistry,o),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};VE(e,t,i,o),WE(e,t,o),QE(e,t,o),ZE(e,t,o),eA(e,t,o),nA(e,t,c),rA(e,t,c),sA(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&_r(e.metadata.id,e.metadata.dependencies),Z(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),dA(e,t,o),lA(a,t,o);try{qr(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(o)].filter(p=>p==="body"?e.body!==r:!rt(n[p],d[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${Cn(n.acceptance_criteria).length}:${Cn(d.acceptance_criteria).length}`),{changedFields:u,warnings:s}}async function F_(e,t,n,r={}){t=await CE(t);let o=E(process.cwd(),n.path);await $E(o);let s=await A(o),i=$(s.schema),a=Ye(s.schema),c=R(),d=vt(c),u=I(s,c),p=s.governance.workflow_enforcement??"off",f=p==="off"?[]:zm(s.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],h=I_(t.unset,a,d),y=new Set(h.optionKeys),g=new Set(h.metadataKeys);yc(t),IE({definitions:RE(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:g}),oE(e,t,g),OE(t,h),PE(t);let w=T(t.author,s.author_default),v=new Date,S=v.toISOString(),x=Ys(t.dep,s.id_prefix,S,w);_r(e,x.additions);let O=await Qt({pmRoot:o,dependencies:x.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),D=lE(t.depRemove,s.id_prefix),N=an("--comment",t.comment,S,w),ce=t.ownershipMetadataBypass===!0&&N.values?{...N,values:N.values.map(Fe=>({...Fe,author:w}))}:N,V=an("--note",t.note,S,w),de=an("--learning",t.learning,S,w),Y=lc(t.file),Te=mc(t.test);Te.values=await Nn(Te.values,w,S);let ft=uc(t.doc),_t=[],ht=await UE({id:e,options:t,unsetTargets:h,pmRoot:o,settings:s,typeRegistry:u,parentReferencePolicy:_}),gt=await pE(t.blockedBy,g.has("blocked_by"),o,s.id_prefix,s.item_format,u.type_to_folder),Ti=gt.id,Ci=[...ht.warnings,...GE(gt)],Vn=No(t,a,t.runtimeFieldCommands),Ut=LE(t,Vn);if(!Object.values(Ut).some(Boolean))return NE({pmRoot:o,id:e,settings:s,typeRegistry:u});_t.push(...await jE({options:t,fieldFlags:Ut,workflowEnforcement:p,typeWorkflows:f,statusRegistry:i,typeRegistry:u,pmRoot:o,id:e,settings:s}));let Ce=await qE({options:t,fieldFlags:Ut,statusRegistry:i,workflowTransitionWarnings:_t,global:n,id:e});if(Ce)return Ce;DE(t);let yt=Ot(),Ri=Ut.parent&&!g.has("parent")||x.additions.some(Fe=>yt.resolve(Fe.kind)?.hierarchy),L=await xs({pmRoot:o,author:w,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Ri});try{let Fe=await FE({fieldFlags:Ut,clearedMetadataKeys:g,pmRoot:o,settings:s,typeToFolder:u.type_to_folder}),et,Lr,wt=await Ju({pmRoot:o,settings:s,typeToFolder:u.type_to_folder,id:e,op:uA(t,r),author:w,message:t.message,resolveHistoryContext:()=>Lr,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:d,skipNoop:!0,mutate(We){et=pA({document:We,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),Lr=et?{recurrence:et}:void 0,Fe=Fe?.map(Nr=>Nr.id===We.metadata.id?structuredClone(We.metadata):Nr);let xi=mA(We,{options:t,settings:s,typeRegistry:u,statusRegistry:i,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:d,clearItemMetadataKeys:g,dependencyUpdates:x,dependencyRemovals:D,commentUpdates:ce,noteUpdates:V,learningUpdates:de,fileUpdates:Y,testUpdates:Te,docUpdates:ft,resolvedParentValue:ht.resolvedParentValue,resolvedBlockedByDependencyId:Ti,runtimeFieldUpdates:Vn,nowValue:v,nowIso:S,author:w,pmRoot:o});return ME({before:Fe,document:We,statusRegistry:i}),xi}});await L();let Ii=Fe?ms(Fe,Fe.map(We=>We.id===wt.item.id?wt.item:We),wt.item.id):[];return{item:wt.item,changed_fields:wt.changedFields,warnings:[..._t,...Ci,...O,...Ii,...wt.warnings],...et===void 0?{}:{lifecycle_transition:et}}}finally{await L()}}function uA(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function pA(e){if(e.recurrenceReason===void 0)return;let t=Z(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!te(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=Z(n,e.statusRegistry)??n,o=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(i=>{let a=o[i];return typeof a=="string"?[[i,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:s}}async function dt(e,t,n){return F_(e,t,n)}async function M_(e,t,n,r){let o=await F_(e,t,n,{recurrenceReason:r});if(o.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{...o,lifecycle_transition:o.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a157c2e-e9e6-5bce-b124-0a7d34e3c7dc")}catch{}})();var D_=1,bc="update-many",fA=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),_A=["--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(", "),hA={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"},gA=[{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"}],yA={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"},U_=e=>{let t={};for(let[n,r]of Object.entries(e))fA.has(n)||r!==void 0&&(t[n]=r);return t},wA=e=>Object.keys(U_(e)).length>0,G_=e=>typeof e=="string"?e.trim():e,bA=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},wc=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},vA=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??G_(e)},kA={priority:bA,estimatedMinutes:wc,order:wc,rank:wc,regression:vA},SA=(e,t)=>{if(t!==void 0)return(kA[e]??G_)(t)},EA=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return yA[t]??t},Js=(e,t)=>rt(e,t),AA=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],TA=(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",$_=(e,t)=>t===void 0?void 0:e[t],Gn=e=>Array.isArray(e)?e.length:0,RA=(e,t,n)=>{let r=n[e.addKey],o=$_(n,e.removeKey),s=Gn(r),i=Gn(o),a=n[e.clearKey]===!0,c=$_(n,e.replaceKey)===!0;if(![a,c,s>0,i>0].includes(!0))return;let d=AA(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:s,remove_count:i,before_count:TA(e.field,d)}}},IA=(e,t)=>{let n=[];for(let r of gA){let o=RA(r,e,t);o!==void 0&&n.push(o)}return n},xA=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],OA=(e,t)=>{if(![t.tags!==void 0,Gn(t.addTags)>0,Gn(t.removeTags)>0].includes(!0))return;let n=xA(e.tags),r=t.tags===void 0?n:xt(t.tags),o=Rn(r,t.addTags),s=es(o,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!Js(i,s))return{field:"tags",before:n,after:s}},PA=(e,t)=>{let n=e.acceptance_criteria,r=Zo(Cn(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 o=r.criteria.join("; ");if(!Js(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},LA=(e,t,n)=>{for(let[r,o]of Object.entries(hA)){let s=n[r];if(s===void 0)continue;let i=t[o],a=SA(r,s);Js(i,a)||e.push({field:o,before:i,after:a})}},NA=(e,t,n,r)=>{let o=No(n,r,["update_many"]);for(let[s,i]of Object.entries(o)){let a=t[s];Js(a,i)||e.push({field:s,before:a,after:i})}},FA=(e,t,n)=>{for(let r of n??[]){let o=EA(r),s=t[o];s!==void 0&&e.push({field:o,before:s,after:null})}},MA=(e,t,n={})=>{let r=e,o=[],s=OA(r,n);if(s&&o.push(s),LA(o,r,n),Gn(n.addAc)>0||Gn(n.removeAc)>0){let i=PA(r,n);i!==void 0&&o.push(i)}return o.push(...IA(r,n)),NA(o,r,n,t),FA(o,r,n.unset),{id:e.id,changes:o}},$A=(e,t)=>ap(e,t,{strict:!0,flagLabel:"--filter-status"}),DA=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)},UA=[({update:e})=>{e.priority!==void 0&&xn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=I(t,R());if(!_e(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&&!Z(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&&ne(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&In(e.estimatedMinutes,"estimated-minutes")}],GA=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let s of UA)s(o)},jA=async e=>{let t=await Ho(e.pmRoot,bc,e.rollbackId,D_),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Vo(t.items,(o,s)=>Xt(o,s,{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}},qA=async e=>{let t={schema_version:D_,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 Bo(e.pmRoot,bc,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},KA=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},vc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},zA=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)}},BA=e=>{if(e.options.dryRun===!0)throw new m("--dry-run cannot be combined with --rollback",l.USAGE);if(cr(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 jA({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},HA=async e=>{$A(e.options.status,e.runtime.statusRegistry);let t=await Pt(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let s=MA(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?s:{...s,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await Pt(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:KA(e.options.list?.ids,r)}},VA=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:[],...vc(e)}),WA=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:[],...vc(e)}),YA=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(s=>s.changes.length>0).map(s=>s.id));for(let s of e.items){if(!o.has(s.id)){t.push({id:s.id,status:"skipped"});continue}try{let i=await dt(s.id,{...e.options.update,message:r,runtimeFieldCommands:["update_many"]},e.global);t.push({id:s.id,status:"updated",changed_fields:i.changed_fields,warnings:i.warnings}),n.push(s.id)}catch(i){t.push({id:s.id,status:"failed",error:gn(i)})}}return{rows:t,updatedIds:n}},JA=async e=>{if(e.plan.actionable.length===0)return WA(e.plan);let t=k(),n=zo(bc,t),r=new Set(e.plan.actionable.map(p=>p.id)),o=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),s=e.options.checkpoint===!1?void 0:await qA({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),i=await YA({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,...s?{checkpoint:s}:{},updated_count:c,skipped_count:d,failed_count:u,rows:i.rows,ids:i.updatedIds,...vc(e.plan)}},j_=async(e,t)=>{let n=await zA(t),r=typeof e.rollback=="string"?e.rollback:void 0,o=U_(e.update);if(DA(e.list),r!==void 0)return BA({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!wA(e.update))throw new m(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${_A}).`,l.USAGE);GA(e.update,n.settings,n.statusRegistry,n.pmRoot),yc(e.update);let s=await Qt({pmRoot:n.pmRoot,dependencies:Ys(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 HA({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:s});return await Qt({pmRoot:n.pmRoot,dependencies:Ys(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?VA(i):JA({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 XA=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],q_=["brief","standard","deep"],B_="plan-step-",Cc="draft",Tc=["bug-investigation","feature-implementation","refactoring-sprint"],K_={"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 QA(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(K_,t)?K_[t]:void 0;if(!n)throw new m(`Unknown plan template "${e}". Allowed: ${Tc.join(", ")}`,l.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Tc[0]}`]});return n.map(r=>({...r}))}function ZA(e,t){return t>0?Math.round(e/t*100):0}function H_(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 Ge(e){return Array.isArray(e)?e.flatMap(t=>On(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?On(e,{unique:!1}):[]}function Ee(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=Cc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ui.find(o=>o===n);if(!r)throw new m(`Invalid plan mode "${e}". Allowed: ${Ui.join(", ")}`,l.USAGE);return r}function Rc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Gi.find(o=>o===n);if(!r)throw new m(`Invalid step status "${e}". Allowed: ${Gi.join(", ")}`,l.USAGE);return r}function W_(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=qi.find(o=>o===n);if(!r)throw new m(`Invalid step link kind "${e}". Allowed: ${qi.join(", ")}`,l.USAGE);return r}function eT(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=ji.find(r=>r===t);if(!n)throw new m(`Invalid plan harness "${e}". Allowed: ${ji.join(", ")}`,l.USAGE);return n}function tT(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=q_.find(r=>r===t);if(!n)throw new m(`Invalid --depth "${e}". Allowed: ${q_.join(", ")}`,l.USAGE);return n}function nT(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 kc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function rT(e,t){let n=e,r={},o=[];for(let s of t){let i=s.startsWith("plan.")?s.slice(5):s;if(i.length!==0){if(!kc.has(i)){o.push(s);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(o.length>0)throw new m(`Unknown Plan --fields value(s): ${o.join(", ")}`,l.USAGE,{nextSteps:[`Use --fields ${[...kc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...kc].join(",")}`}});return r}function Ic(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let s=o.indexOf("=");if(s<=0)throw new m(`Invalid ${t} entry "${o}"; 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[o.slice(0,s).trim().toLowerCase()]=o.slice(s+1).trim()}return n}function xc(e){let t=Ic(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 Oc(e){let t=Ic(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 Pc(e){let t=Ic(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 oT(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=ZA(t.completed,t.total),t}function sT(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 m("Could not allocate step id (limit reached)",l.GENERIC_FAILURE)}function jn(e,t){let n=t.trim();if(n.length===0)throw new m("Step reference cannot be empty",l.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),s=e.find(i=>i.order===o);if(s)return s}throw new m(`Step "${t}" not found in plan`,l.NOT_FOUND)}function z_(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=[],o=[];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=z_(i);if(a){o.push({from_step:i.id,...a});continue}r.push(i)}return{targets:r,skipped:o}}let s=new Set;for(let i of t){let a=jn(e,i);if(s.has(a.id))continue;s.add(a.id);let c=z_(a);if(c){o.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:o}}function aT(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 cT(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function dT(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 Oe(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=oT(n),o=cT(n),s={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Cc,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:dT(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(s.steps=n),t==="deep"&&(s.decisions=e.plan_decisions??[],s.discoveries=e.plan_discoveries??[],s.validation=e.plan_validation??[]),s}function Pe(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&&!ba(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function Y_(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 lT(e){let t=E(process.cwd(),e.path);await C(t);let n=await A(t);return{pmRoot:t,settings:n}}async function J_(e,t){let n=I(e.settings,R()),r=await U(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 o=await K(r,{schema:e.settings.schema});return Y_(o.document.metadata),{document:o.document,itemId:r.id}}function mT(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of Ge(e.related))t.push(`id=${n},kind=related`);for(let n of Ge(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of Ge(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function uT(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 pT(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||Ge(e.dependsOn).length>0||Ge(e.link).length>0}function fT(e){let t=e.stepTitle?.trim()||void 0,n=H_(e.step),r=e.template?.trim()?QA(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function _T(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 ${Tc[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 hT(e,t){let n=Rc(e.stepStatus,"pending"),r=Lc(e,"depends_on"),o=Ee(e.file).map(xc),s=Ee(e.test).map(Oc),i=Ee(e.doc).map(Pc),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:o.length>0?o:void 0,tests:s.length>0?s: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=fT(e),n=pT(e);if(_T(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[hT(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((o,s)=>({id:`${B_}${String(s+1).padStart(3,"0")}`,order:s+1,title:o,body:t.templateSteps[s]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}async function yT(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 o=V_(e.mode,Cc),s=eT(e.harness),i=e.fromSearch?.trim(),a=uT(e),{steps:c,hasPerStepDetailOptions:d}=gT(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:Ee(e.file),test:Ee(e.test),doc:Ee(e.doc),field:Ee(e.field),assignee:T(e.author,n.settings.author_default),blockedBy:void 0,dep:mT(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")},_=await Lt(f,t),h=await re({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 w=["plan_mode"];g.metadata.plan_mode=o,s&&(g.metadata.plan_harness=s,w.push("plan_harness"));let v=e.scope?.trim();v&&(g.metadata.plan_scope=v,w.push("plan_scope"));let S=e.resumeContext?.trim();return S&&(g.metadata.plan_resume_context=S,w.push("plan_resume_context")),g.metadata.plan_steps=c,w.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],w.push("plan_validation")),p&&(g.metadata.assignee=p,w.push("assignee")),{changedFields:w}}}),y=Oe(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Pe(_.item.id,y),warnings:[..._.warnings],generated_at:k()}}async function wT(e,t,n){let r=tT(t.depth),o=nT(t.fields),{document:s,itemId:i}=await J_(n,e),a=Oe(s.metadata,o===null?r:"deep");return{action:"show",plan:o===null?a:rT(a,o),next_actions:Pe(i,a),warnings:[],generated_at:k()}}function bT(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function Xe(e){let t=T(e.options.author,e.ctx.settings.author_default),n,r=await re({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){Y_(o.metadata);let s=$(e.ctx.settings.schema);if(te(o.metadata.status,s)||ba(o.metadata.plan_mode))throw new m(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.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=(o.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(o.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,o);n=c.resultStep;let d=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));o.metadata.plan_steps=d;let u=bT(a,o.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 vT(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new m("pm plan add-step requires --step-title",l.USAGE);let o=Rc(t.stepStatus,"pending"),s=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;X_(u,void 0,o,s);let f=kT(u,t,{order:p,title:r,status:o});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),d=Oe(i.metadata,"standard");return{action:"add-step",plan:d,step:a,next_actions:Pe(c,d),warnings:[],generated_at:k()}}function X_(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(s=>s.id!==t&&s.status==="in_progress");if(o)throw new m(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,l.CONFLICT)}function kT(e,t,n){let r=Lc(t,"depends_on"),o=Ee(t.file).map(xc),s=Ee(t.test).map(Oc),i=Ee(t.doc).map(Pc),a=k();return{id:sT(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:o.length>0?o:void 0,tests:s.length>0?s:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function Lc(e,t){let n=Ge(e.dependsOn).map(u=>({id:u,kind:t})),r=Ge(e.related).map(u=>({id:u,kind:"related"})),o=Ge(e.blocks).map(u=>({id:u,kind:"blocks"})),s=Ge(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=Ge(e.link),a=W_(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,...o,...s,...d]}async function Sc(e,t,n,r){let{document:o,resultStep:s,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=jn(c,r.stepRef),p=k(),f=r.finalStatus??Rc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return X_(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=Oe(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:s,next_actions:Pe(i,a),warnings:[],generated_at:k()}}function ST(e,t,n,r){ET(e,t,n),AT(e,t),e.status=n,e.updated_at=r,TT(e,n,r)}function ET(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 AT(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=Ee(t.file).map(xc),o=Ee(t.test).map(Oc),s=Ee(t.doc).map(Pc);r.length>0&&(e.files=Ec(e.files,r)),o.length>0&&(e.tests=Ec(e.tests,o)),s.length>0&&(e.docs=Ec(e.docs,s))}function Ec(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let s=JSON.stringify(o);r.has(s)||(r.add(s),n.push(o))}return n}function TT(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,o){let{document:s,itemId:i}=await Xe({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(c){let d=jn(c,r),u=c.filter(f=>f.id!==d.id),p=Math.max(1,Math.min(o,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=Oe(s.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Pe(i,a),warnings:[],generated_at:k()}}async function RT(e,t,n,r){let{document:o,itemId:s}=await Xe({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=jn(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=Oe(o.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:k()}}async function IT(e,t,n,r){let o=Lc(t,W_(t.linkKind,"related"));if(o.length===0)throw new m("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",l.USAGE);let s=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=jn(u,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of o){let w=h(g);y.has(w)||(_.push(g),y.add(w))}if(f.linked_items=_,f.updated_at=k(),s){let g=p.metadata.dependencies??[],w=S=>`${S.kind}:${S.id}`,v=new Set(g.map(w));for(let S of o){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(w(O))||(g.push(O),v.add(w(O)))}p.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),d=Oe(i.metadata,"standard");return{action:"link",plan:d,step:c,next_actions:Pe(a,d),warnings:[],generated_at:k()}}async function xT(e,t,n,r){let o=Ge(t.link);if(o.length===0)throw new m("pm plan unlink requires --link <id> to remove",l.USAGE);let{document:s,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=jn(d,r),p=(u.linked_items??[]).filter(f=>!o.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=k(),{changedSteps:[u.id],resultStep:u}}}),c=Oe(s.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Pe(i,c),warnings:[],generated_at:k()}}async function Ac(e,t,n,r){let o=aT(r,t);if(!o){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 s=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:s,decision:o,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:s,text:o}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Oe(i.metadata,"deep");return{action:r,plan:c,next_actions:Pe(a,c),warnings:[],generated_at:k()}}async function OT(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new m("pm plan resume requires --resume-context <text>",l.USAGE);let{document:o,itemId:s}=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=Oe(o.metadata,"brief");return{action:"resume",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:k()}}async function PT(e,t,n){let r=V_(t.mode??"approved","approved"),{document:o,itemId:s}=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=Oe(o.metadata,"brief");return{action:"approve",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:k()}}function Q_(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function LT(e,t){let n=Oe(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Pe(e.itemId,n),warnings:Q_(t),generated_at:k()}}function NT(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let s=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${s}`)}return r}async function FT(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Ee(e.options.field)){let s=o.indexOf("=");if(s<=0)throw new m(`Invalid --field entry "${o}"; expected name=value`,l.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0)throw new m(`Invalid --field entry "${o}"; 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 "${o}"; 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 "${o}"; "${p}" is reserved by materialize and cannot be overridden`,l.USAGE);n[p]=a}for(let o of e.targets){let s=await Lt({...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:NT(e.parent,e.planItemId,o)},{path:e.pmRoot});t.push({id:s.item.id,title:s.item.title,type:e.resolvedTypeName,parent:s.item.parent,tags:s.item.tags??[],from_step:o.id})}return t}function MT(e,t,n){for(let r of t){let o=n.find(a=>a.from_step===r.id);if(!o)continue;let s=e.find(a=>a.id===r.id);if(!s)continue;let i=s.linked_items??[];i.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),s.linked_items=i,s.updated_at=k()}}async function $T(e,t,n){let r=Ge(t.steps);if(r.length===0)throw new m("pm plan materialize requires --steps <ids|orders|all>",l.USAGE);let o=t.materializeType?.trim()||"Task",s=I(n.settings,R()),i=_e(o,s);if(!i)throw new m(`Invalid --materialize-type "${o}"`,l.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,d=await J_(n,e),u=(d.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=iT(u,r);if(p.length===0){if(f.length>0)return LT(d,f);throw new m("No matching plan steps found for --steps",l.NOT_FOUND)}let _=await FT({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(w){return MT(w,p,_),{changedSteps:p.map(v=>v.id)}}}),g=Oe(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Pe(y,g),warnings:Q_(f),generated_at:k()}}function DT(e){if(e.subcommand==="create")return e;let t=H_(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 cn(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 UT(e){let t=cn(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 GT={create:(e,t)=>yT(e.options,e.global,t),show:(e,t)=>wT(lt(e,"show"),e.options,t),"add-step":(e,t)=>vT(lt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=cn(e,"update-step");return Sc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=cn(e,"complete-step");return Sc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=cn(e,"block-step");return Sc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=UT(e);return CT(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=cn(e,"remove-step");return RT(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=cn(e,"link");return IT(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=cn(e,"unlink");return xT(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Ac(lt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Ac(lt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Ac(lt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>OT(lt(e,"resume"),e.options,t),approve:(e,t)=>PT(lt(e,"approve"),e.options,t),materialize:(e,t)=>$T(lt(e,"materialize"),e.options,t)};function jT(e){let t=GT[e];if(!t)throw xe({command_path:"plan",token:e,allowed:XA});return t}async function Z_(e){let t=await lT(e.global),n=DT(e);return jT(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 qT(e,t){return[...new Set([...Gr.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,o)=>r.localeCompare(o))}function KT(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Nc(e,t,n){let r=E(process.cwd(),n.path);await C(r);let o=await A(r),s=I(o,R()),i=await U(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!i)throw await at(r,e,o.id_prefix,s.type_to_folder);let a=await K(i,{schema:o.schema}),c=a.document.metadata,d=k(),u=T(t.author,o.author_default),p=await tr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:s.type_to_folder,probeExisting:!1}),f=$(o.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:o.schema,extensionFieldNames:y}),w=await Fn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=qT(g.metadata,g.body),S=Kt(r,g.metadata.type,p,o.item_format,s.type_to_folder),x=Re(r,p),O=await we(r,p,o.locks.ttl_seconds,u,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),D={metadata:{},body:""},N,ce;try{let V=await An(r,u,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await Fn({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let de=await U(r,p,o.id_prefix,o.item_format,s.type_to_folder);if(de)throw new m(`Cannot copy to ${p}: an item with that id already exists at ${de.itemPath}. Retry the copy to allocate a new id.`,l.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${de.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await fe(S,qe(g,{format:o.item_format,schema:o.schema,extensionFieldNames:y}));try{let Y=Ke({nowIso:d,author:u,op:"create",before:D,after:g,message:KT(i.id,t.message)});await Ct(x,Y)}catch(Y){throw await _n(S),Y}ce=await Tn({pmRoot:r,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:S,document:g})}finally{await V()}N=[...await z({path:S,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:D,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:D,after:g,changed_fields:v})],wn({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:[...us(w),...ce,...N],...w===void 0?{}:{similarity_advisory:w}}}import Xs 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 Fc(e,t,n){let r=E(process.cwd(),n.path);await C(r);let o=await A(r),s=T(t.author,o.author_default),i=await Xu({pmRoot:r,settings:o,id:e,author:s,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?Xs.relative(r,i.targetPath).split(Xs.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:Xs.relative(r,Re(r,i.item.id)).split(Xs.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 zT(e){await C(e)}async function Mc(e,t,n){let r=E(process.cwd(),n.path);if(await zT(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=kn(T(void 0,p.author_default));return await Cu(r),await ls({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 Po(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 BT(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let s=await A(r),i=I(s,R()),a=await U(r,e,s.id_prefix,s.item_format,i.type_to_folder);if(!a)throw await at(r,e,s.id_prefix,i.type_to_folder);let c=be(a.id,s.id_prefix),d=await K(a,{schema:s.schema}),u=eh(d.document.metadata.title);return await Tu(r,c),await ls({pmRoot:r,settings:s,principal:kn(T(void 0,s.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 BT(e,t){let n=await A(e),r=I(n,R()),o=await U(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let s=await K(o,{schema:n.schema});return eh(s.document.metadata.title)}function eh(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]="77fa2822-1681-59d5-8388-037cf13c45dd")}catch{}})();var th=new Set(["item_format"]),nh=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"]),HT=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","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),VT=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),WT={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function YT(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(th.has(t)||nh.has(t)||HT.has(t)||t==="context")return t}function JT(e){let t=e.trim().toLowerCase();return WT[t]??e}function rh(e,t){let n=YT(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."}:th.has(n)?{routable:!0,flag:"format",value:t}:nh.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:VT.has(n)?JT(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]="09703f32-9491-5d3a-9f90-f038d9982e17")}catch{}})();var XT=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,$c=128,QT=1e4;function oh(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>$c)throw new Error(`A legacy author must contain 1-${$c} characters.`);return t}function ZT(e){let t=e?.trim().toLowerCase();if(!t||!XT.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function eC(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function tC(e,t){let n=new Set;for(let r of(e??[]).slice(0,QT)){let o=r.trim().slice(0,$c);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function nC(e,t){let n=oh(t.legacy_author),r=ZT(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function rC(e,t){if(t.operation==="add")return nC(e,t);if(t.operation==="remove"){let r=oh(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function Dc(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function sh(e,t){let n=e?.version??1,r={...e?.aliases},o=rC(r,t),s={version:o?n+1:n,aliases:eC(r)};return{vocabulary:s,preview:{operation:t.operation,changed:o,version_before:n,version_after:s.version,alias_count:Object.keys(s.aliases).length,residual_author_count:tC(t.observed_authors,s.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2f750f85-6c55-5f0f-b5c0-396764839d2a")}catch{}})();var ih=["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"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},oC=Object.keys(mt).map(e=>mt[e][0]),sC=Object.fromEntries(Object.keys(mt).flatMap(e=>mt[e].map(t=>[t,e]))),iC={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.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},aC=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],cC=new Set(["metadata_required_fields",...aC]),dC=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),lC=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),mC=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),uC=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),pC=new Set(["governance_preset","governance_create_default_type"]),mh=e=>cC.has(e),fC=e=>mC.has(e),_C=e=>uC.has(e),hC=e=>pC.has(e);function Uc(e){return e==="definition_of_done"||mh(e)}function gC(e){if(ih.includes(e))return e;throw new m(`Invalid config scope "${e}". Allowed: ${ih.join(", ")}`,l.USAGE)}function yC(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw xe({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function wC(e){let t=sC[e];if(t)return t;let n=Ji.map(r=>r.key).join(", ");throw new m(`Invalid config key "${e}". Supported: ${oC.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,l.USAGE)}function bC(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new 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 vC(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 uh(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 kC(e){return jc(e,"test-result-tracking")}function jc(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new m(`Config set ${t} requires --policy with one of: enabled, disabled`,l.USAGE)}function ph(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 qc(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 fh(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 _h(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 hh(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 gh(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 yh(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 wh(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 bh(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)}var SC={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function ah(e,t){let n=SC[e];if(n)return jc(t,n);switch(e){case"history_missing_stream_policy":return uh(t);case"sprint_release_format_policy":return wa(t);case"parent_reference_policy":case"governance_parent_reference_policy":return Yo(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return qc(t);case"governance_preset":return fh(t);case"governance_ownership_enforcement":return _h(t);case"governance_create_mode_default":return hh(t);case"governance_close_validation_default":return gh(t);case"governance_require_close_reason":return bh(t);case"governance_workflow_enforcement":return yh(t);case"governance_force_required_for_stale_lock":return wh(t);case"telemetry_tracking":return ph(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var ch={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"},EC=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function AC(e,t){let n=[...new Set((e??[]).map(s=>s.trim()).filter(s=>s.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(s=>s.toLowerCase().replaceAll("-","_")),o=r.filter(s=>ch[s]===void 0);if(o.length>0)throw new m(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${EC.join(", ")}`,l.USAGE);return[...new Set(r.map(s=>ch[s]))].sort((s,i)=>s.localeCompare(i))}function TC(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,s)=>o.localeCompare(s));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 CC(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function RC(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 wC(t)}function vh(e){if(!e)throw new m("Config action requires <key>",l.USAGE)}var IC={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",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>Dc(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function Kc(e,t){return IC[t](e)}function Ae(e,t){return t.length===0?e:{...e,warnings:t}}async function xC(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):nt(n),o=ye(r);return e==="project"&&await C(r),{pmRoot:r,settingsPath:o}}function OC(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 dh(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 PC(e,t,n,r,o){let s=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!Ki.includes(c))throw new m(`Context --default-depth must be one of ${Ki.join("|")}`,l.USAGE);i.default_depth!==c&&(i.default_depth=c,s=!0)}if(t.activityLimit!==void 0){let c=dh(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,s=!0)}if(t.staleThresholdDays!==void 0){let c=dh(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,s=!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=OC(d);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,s=!0)}}return s&&await Ie(n.pmRoot,e,"config:set:context"),Ae({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:s},o)}function LC(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 NC(e,t,n,r,o,s){if(o===void 0)return s;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 LC(t,o,s);vh(n);let i=rh(n,o);if(!i.routable)throw new m(i.reason,l.USAGE);if(i.flag==="criterion"){if(s.criterion!==void 0&&s.criterion.length>0)throw new m(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,l.USAGE);return{...s,criterion:i.values}}if(i.flag==="format")return{...s,format:i.value};if(s.policy!==void 0&&ah(n,s.policy)!==ah(n,i.value))throw new m(`Config set ${t} received both positional value "${o}" and --policy "${s.policy}". Pass only one.`,l.USAGE);return{...s,policy:i.value}}function FC(e){let t=Object.keys(mt).map(r=>({key:r,aliases:mt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":Uc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:Uc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:iC[r],value:Kc(e.settings,r)})),n=Ji.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Xi(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 Ae({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function MC(e){let t=Object.fromEntries(Object.keys(mt).map(n=>[n,Kc(e.settings,n)]));return Ae({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function $C(e,t){let n=Kc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Ae({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Ae({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Ae({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Ae({...r,criteria:n},e.warnings):Ae({...r,policy:n},e.warnings)}async function DC(e,t,n,r){if(t==="get"){let a=Xi(e.settings,n);return Ae({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 o=r.value;if(typeof o!="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 s=Km(n,o);if(!s.ok)throw new m(s.error.message,l.USAGE);let i=Co(e.settings,n,s.parsed.value);return i&&await Ie(e.target.pmRoot,e.settings,`config:set:${n.path}`),Ae({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:s.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function X(e,t,n){t&&await Ie(e.target.pmRoot,e.settings,n)}function lh(e,t,n){return e!==n||t!==n}function ie(e,t,n,r){return Ae({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Gc(e,t,n,r){return Ae({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function UC(e,t){let n=vC(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let s=I(e.settings,R()),i=await dp(e.target.pmRoot,n,"config:set:item_format:migrate",s.type_to_folder,e.settings.schema);o={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await Ie(e.target.pmRoot,e.settings,"config:set:item_format")}return Ae({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function GC(e,t,n){if(t==="history_missing_stream_policy"){let s=uh(n.policy),i=e.settings.history.missing_stream!==s;return e.settings.history.missing_stream=s,await X(e,i,"config:set:history_missing_stream_policy"),ie(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let s=wa(n.policy),i=e.settings.validation.sprint_release_format!==s;return e.settings.validation.sprint_release_format=s,await X(e,i,"config:set:sprint_release_format_policy"),ie(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let s=Yo(n.policy),i=e.settings.validation.parent_reference!==s||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==s;return e.settings.validation.parent_reference=s,e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,await X(e,i,"config:set:parent_reference_policy"),ie(e,t,e.settings.validation.parent_reference,i)}let r=qc(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await X(e,o,"config:set:metadata_validation_profile"),ie(e,t,e.settings.validation.metadata_profile,o)}async function jC(e,t,n){if(t==="metadata_required_fields"){let a=AC(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 X(e,c,"config:set:metadata_required_fields"),Gc(e,t,[...e.settings.validation.metadata_required_fields],c)}let o={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],s=TC(t,n.criterion,n.clearCriteria),i=s.length!==o.length||s.some((a,c)=>a!==o[c]);return o.splice(0,o.length,...s),await X(e,i,`config:set:${t}`),Gc(e,t,[...o],i)}async function qC(e,t,n){if(t==="governance_preset"){let c=fh(n.policy),d=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await X(e,d,"config:set:governance_preset"),ie(e,t,e.settings.governance.preset,d)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await X(e,c,"config:set:governance_create_default_type"),ie(e,t,e.settings.governance.create_default_type??"",c)}if(o.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 s=I(e.settings,R()),i=_e(o,s);if(!i)throw new m(Et(o,s.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 X(e,a,"config:set:governance_create_default_type"),ie(e,t,e.settings.governance.create_default_type,a)}async function KC(e,t,n){if(t==="governance_ownership_enforcement"){let s=_h(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==s;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=s,await X(e,i,"config:set:governance_ownership_enforcement"),ie(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let s=hh(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==s;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=s,await X(e,i,"config:set:governance_create_mode_default"),ie(e,t,e.settings.governance.create_mode_default,i)}let r=gh(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await X(e,o,"config:set:governance_close_validation_default"),ie(e,t,e.settings.governance.close_validation_default,o)}async function zC(e,t,n){if(t==="governance_parent_reference_policy"){let s=Yo(n.policy),i=e.settings.governance.preset!=="custom"||lh(e.settings.governance.parent_reference,e.settings.validation.parent_reference,s);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,e.settings.validation.parent_reference=s,await X(e,i,"config:set:governance_parent_reference_policy"),ie(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let s=qc(n.policy),i=e.settings.governance.preset!=="custom"||lh(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,s);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=s,e.settings.validation.metadata_profile=s,await X(e,i,"config:set:governance_metadata_validation_profile"),ie(e,t,e.settings.governance.metadata_profile,i)}let r=yh(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await X(e,o,"config:set:governance_workflow_enforcement"),ie(e,t,e.settings.governance.workflow_enforcement,o)}async function BC(e,t,n){if(t==="governance_require_close_reason"){let a=bh(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"),ie(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let o=wh(n.policy)==="enabled",s=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==o;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=o,await X(e,s,"config:set:governance_force_required_for_stale_lock"),ie(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",s)}async function HC(e,t,n){if(t==="test_result_tracking"){let a=kC(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"),ie(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}if(t==="untrusted_linked_test_execution"){let a=jc(n.policy,"untrusted-linked-test-execution")==="enabled",c=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await X(e,c,"config:set:untrusted_linked_test_execution"),ie(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",c)}let o=ph(n.policy)==="enabled",s=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await X(e,s,"config:set:telemetry_tracking"),ie(e,t,e.settings.telemetry.enabled?"enabled":"disabled",s)}async function VC(e,t,n){let r=bC(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((s,i)=>s!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await X(e,o,"config:set:definition_of_done"),Gc(e,t,[...e.settings.workflow.definition_of_done],o)}function WC(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new m("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",l.USAGE)}function YC(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new m('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',l.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new m("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",l.USAGE);return{legacy_author:t}}if(t!==void 0)throw new m("Config set agent-identity-vocabulary --policy clear does not accept --value",l.USAGE);return{}}async function JC(e,t){let{operation:n,dryRun:r}=WC(t.policy),o=YC(n,t.value),s;try{s=sh(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(i){throw new m(i.message,l.USAGE)}return s.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:s.vocabulary},await X(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${s.preview.version_after}`)),Ae({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:Dc(r?e.settings.agent_identity?.identity_vocabulary:s.vocabulary),vocabulary_mutation:s.preview,settings_path:e.target.settingsPath,changed:s.preview.changed&&!r},e.warnings)}async function XC(e,t,n){if(n.clearCriteria===!0&&!Uc(t))throw new m("--clear-criteria is only supported with config set criteria-list keys",l.USAGE);return t==="item_format"?UC(e,n):t==="context"?PC(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?JC(e,n):t==="definition_of_done"?VC(e,t,n):mh(t)?jC(e,t,n):dC.has(t)?HC(e,t,n):lC.has(t)?BC(e,t,n):fC(t)?KC(e,t,n):_C(t)?zC(e,t,n):hC(t)?qC(e,t,n):GC(e,t,n)}async function kh(e,t,n,r,o,s){let i=gC(e),a=yC(t),c=a==="get"||a==="set"?To(n):void 0,d=c?void 0:RC(a,n),u=NC(a,n,d,c,s,r),p=await xC(i,o),{settings:f,metadata:_,warnings:h}=await Hu(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:CC(h)};return c?DC(y,a,c,u):a==="list"?FC(y):a==="export"?MC(y):(vh(d),a==="get"?$C(y,d):XC(y,d,u))}import RR from"node:fs/promises";import Q from"node:path";import IR from"node:readline/promises";import{stdin as xR,stdout as Le}from"node:process";import Bc from"node:fs/promises";import ae from"node:path";import QC from"node:readline/promises";import{stdin as ZC,stdout as Qs}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 Eh=["ask","add","skip","status"],eR=["AGENTS.md","CLAUDE.md"],tR=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],nR=8,Hc=1,rR="<!-- pm-cli:agent-guidance:start:",oR=`<!-- pm-cli:agent-guidance:start:v${Hc} -->`,zc="<!-- pm-cli:agent-guidance:end -->",br="Add workflow guidance later: pm init --agent-guidance add";var sR=()=>QC.createInterface({input:ZC,output:Qs});function yr(e,t){let n=ae.relative(e,t);return n.length===0?ae.basename(t):n.split(ae.sep).join("/")}function Sh(e){return e.endsWith(`
9
9
  `)?e:`${e}
10
- `}function vC(e){return e.includes(`\r
10
+ `}function iR(e){return e.includes(`\r
11
11
  `)?`\r
12
12
  `:`
13
- `}function nh(e){let t=e.indexOf(yC);if(t===-1)return null;let n=e.indexOf(xc,t);return n===-1?null:{start_index:t,end_index:n+xc.length}}function kC(e){return nh(e)!==null}function SC(e,t="<your project test command>"){return[bC,"## 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.","",xc,""].join(e)}function EC(e,t="<your project test command>"){let n=vC(e),r=SC(n,t),s=nh(e);if(s){let a=e.slice(s.end_index),c=a.startsWith(`\r
13
+ `}function Ah(e){let t=e.indexOf(rR);if(t===-1)return null;let n=e.indexOf(zc,t);return n===-1?null:{start_index:t,end_index:n+zc.length}}function aR(e){return Ah(e)!==null}function cR(e,t="<your project test command>"){return[oR,"## 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.","",zc,""].join(e)}function dR(e,t="<your project test command>"){let n=iR(e),r=cR(n,t),o=Ah(e);if(o){let a=e.slice(o.end_index),c=a.startsWith(`\r
14
14
  `)?a.slice(2):a.startsWith(`
15
- `)?a.slice(1):a,d=eh(`${e.slice(0,s.start_index)}${r}${c}`);return{next_content:d,changed:d!==e}}let o=e.length===0?"":e.endsWith(`
15
+ `)?a.slice(1):a,d=Sh(`${e.slice(0,o.start_index)}${r}${c}`);return{next_content:d,changed:d!==e}}let s=e.length===0?"":e.endsWith(`
16
16
  `)?`
17
17
  `:`
18
18
 
19
- `,i=eh(`${e}${o}${r}`);return{next_content:i,changed:i!==e}}async function AC(e){if(await x(re.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Oc.readFile(re.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=TC(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 x(re.join(e,"pnpm-lock.yaml"))?"pnpm test":await x(re.join(e,"bun.lock"))||await x(re.join(e,"bun.lockb"))?"bun run test":await x(re.join(e,"yarn.lock"))?"yarn test":"npm test"}function TC(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 CC(e,t){let n=re.dirname(e);return re.basename(e)==="pm"&&re.basename(n)===".agents"?re.dirname(n):re.resolve(t,e)}function RC(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 IC(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 xC(e){let t=wC();try{Bo.write(`
19
+ `,i=Sh(`${e}${s}${r}`);return{next_content:i,changed:i!==e}}async function lR(e){if(await P(ae.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Bc.readFile(ae.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=mR(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(ae.join(e,"pnpm-lock.yaml"))?"pnpm test":await P(ae.join(e,"bun.lock"))||await P(ae.join(e,"bun.lockb"))?"bun run test":await P(ae.join(e,"yarn.lock"))?"yarn test":"npm test"}function mR(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 uR(e,t){let n=ae.dirname(e);return ae.basename(e)==="pm"&&ae.basename(n)===".agents"?ae.dirname(n):ae.resolve(t,e)}function pR(e,t){let n=e.find(o=>ae.basename(o.file_path)==="AGENTS.md"&&o.exists);if(n)return n.file_path;let r=e.find(o=>o.exists);return r?r.file_path:ae.join(t,"AGENTS.md")}function fR(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 _R(e){let t=sR();try{Qs.write(`
20
20
  Agent guidance check
21
- `),Bo.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 Bo.write(`
23
- `),IC(n,!0)}finally{t.close()}}function rh(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:Pc,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 sh(e){let t=[];for(let n of _C){let r=re.join(e,n),s=await x(r);if(!s){t.push({file_path:r,exists:s,has_guidance:!1,has_marker:!1});continue}let o=await Oc.readFile(r,"utf8"),i=o.toLowerCase(),a=hC.filter(d=>i.includes(d)),c=kC(o);t.push({file_path:r,exists:s,has_guidance:c||a.length>=gC,has_marker:c})}return t}function hr(e,t){e.includes(t)||e.push(t)}function OC(e,t){let n=rh(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function PC(e,t=re.dirname(e)){let r=await x(e)?await Oc.readFile(e,"utf8"):"",s=EC(r,await AC(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 NC(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=>pr(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>pr(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>pr(e.projectRoot,t.file_path))}}async function LC(e,t,n){return e?await sh(n):t}function fr(e,t,n){e.state={...e.state,...n,template_version:Pc,last_checked_files:t}}async function oh(e,t){if(t.presentBefore)return;let n=await PC(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function FC(e,t){t||(e.warnings.push("agent_guidance:missing"),hr(e.nextSteps,_r))}function MC(e,t){e.skipped=!0,fr(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),hr(e.nextSteps,_r)}async function $C(e,t){await oh(e,t),fr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function DC(e,t){e.state.declined&&fr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function UC(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),hr(e.nextSteps,_r)}async function GC(e,t){if(e.prompted=!0,await xC(t.targetRelativePath)){await oh(e,t),fr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,fr(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),hr(e.nextSteps,_r)}function jC(e){e.warnings.push("agent_guidance:missing_non_interactive"),hr(e.nextSteps,_r)}async function qC(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(FC(n,t.presentBefore),n):t.mode==="skip"?(MC(n,t.checkedFiles),n):t.mode==="add"?(await $C(n,t),n):t.presentBefore?(DC(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(UC(n),n):t.interactive?(await GC(n,t),n):(jC(n),n)}async function ih(e){let t=CC(e.pm_root,e.cwd),n=await sh(t),r=RC(n,t),s=pr(t,r),o=n.map(u=>pr(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await qC(rh(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:s,checkedFiles:o,presentBefore:i,projectRoot:t}),c=OC(e.settings,a.state);return n=await LC(a.applied,n,t),{summary:NC({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 HC=()=>zC.createInterface({input:BC,output:Ie});function VC(){return structuredClone(bt)}var WC=["minimal","default","strict"];function ch(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: ${WC.join(", ")}`,l.USAGE)}function YC(e){if(e!==void 0){if(e.trim().length===0)throw new m("--type-preset must not be empty",l.USAGE);try{return ym(e)}catch{throw new m(`Invalid --type-preset value "${e}". Allowed: ${gm.join(", ")}`,l.USAGE)}}}function JC(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 Nc(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 XC(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||Nc(n))throw new m("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",l.USAGE);let d=V.resolve(e,s),u=V.join(d,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:d}}}if(t.path===void 0&&Nc(n)){let d=V.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let o=E(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 QC(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(Nc(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&&Rt(e)!==Rt(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 ${Rt(e)}`,`pm init --id-prefix ${Rt(t)}`]});return t}function ZC(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: ${th.join(", ")}`,l.USAGE)}function eR(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function dh(e,t){let n=Bd[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function tR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nR(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(tR).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function rR(e,t,n){let r=hs(t.schema),s=st(e,r.files.types,rt.types),i=_m(await q(s)),a=[],c=[];for(let d of bm(n)){let u=hm(i,d);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await Ct({pmRoot:e,filePath:s,raw:fs(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 sR(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",V.join(".agents","pm")];for(let n of t)if(await x(V.join(e,n)))return!0;return!1}async function oR(e,t,n){if(!t||n||await x(V.join(e,"settings.json"))||!await sR(e))return;let r=V.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 lh(e,t){let n=[],r=[];for(let s of t){let o=s?V.join(e,s):e,i=await x(o);await KC.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 iR(e,t){let n=HC();try{Ie.write(`pm init setup wizard (agent-optimized)
24
- `),Ie.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
21
+ `),Qs.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 Qs.write(`
23
+ `),fR(n,!0)}finally{t.close()}}function Th(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:Hc,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 Ch(e){let t=[];for(let n of eR){let r=ae.join(e,n),o=await P(r);if(!o){t.push({file_path:r,exists:o,has_guidance:!1,has_marker:!1});continue}let s=await Bc.readFile(r,"utf8"),i=s.toLowerCase(),a=tR.filter(d=>i.includes(d)),c=aR(s);t.push({file_path:r,exists:o,has_guidance:c||a.length>=nR,has_marker:c})}return t}function vr(e,t){e.includes(t)||e.push(t)}function hR(e,t){let n=Th(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function gR(e,t=ae.dirname(e)){let r=await P(e)?await Bc.readFile(e,"utf8"):"",o=dR(r,await lR(t));return o.changed?(await fe(e,o.next_content),{changed:!0,warnings:await z({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function yR(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=>yr(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>yr(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>yr(e.projectRoot,t.file_path))}}async function wR(e,t,n){return e?await Ch(n):t}function wr(e,t,n){e.state={...e.state,...n,template_version:Hc,last_checked_files:t}}async function Rh(e,t){if(t.presentBefore)return;let n=await gR(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function bR(e,t){t||(e.warnings.push("agent_guidance:missing"),vr(e.nextSteps,br))}function vR(e,t){e.skipped=!0,wr(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),vr(e.nextSteps,br)}async function kR(e,t){await Rh(e,t),wr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function SR(e,t){e.state.declined&&wr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function ER(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),vr(e.nextSteps,br)}async function AR(e,t){if(e.prompted=!0,await _R(t.targetRelativePath)){await Rh(e,t),wr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,wr(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),vr(e.nextSteps,br)}function TR(e){e.warnings.push("agent_guidance:missing_non_interactive"),vr(e.nextSteps,br)}async function CR(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(bR(n,t.presentBefore),n):t.mode==="skip"?(vR(n,t.checkedFiles),n):t.mode==="add"?(await kR(n,t),n):t.presentBefore?(SR(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(ER(n),n):t.interactive?(await AR(n,t),n):(TR(n),n)}async function Ih(e){let t=uR(e.pm_root,e.cwd),n=await Ch(t),r=pR(n,t),o=yr(t,r),s=n.map(u=>yr(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await CR(Th(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:o,checkedFiles:s,presentBefore:i,projectRoot:t}),c=hR(e.settings,a.state);return n=await wR(a.applied,n,t),{summary:yR({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:o,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 OR=()=>IR.createInterface({input:xR,output:Le});function PR(){return structuredClone(bt)}var LR=["minimal","default","strict"];function Oh(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: ${LR.join(", ")}`,l.USAGE)}function NR(e){if(e!==void 0){if(e.trim().length===0)throw new m("--type-preset must not be empty",l.USAGE);try{return Nm(e)}catch{throw new m(`Invalid --type-preset value "${e}". Allowed: ${Lm.join(", ")}`,l.USAGE)}}}function FR(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 Vc(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:Q.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function MR(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new m("--workspace must not be empty",l.USAGE);if(o!==void 0){if(t.path!==void 0||Vc(n))throw new m("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",l.USAGE);let d=Q.resolve(e,o),u=Q.join(d,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:d}}}if(t.path===void 0&&Vc(n)){let d=Q.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let s=E(e,t.path),i=Q.join(Q.resolve(e),".agents","pm"),a=Q.dirname(Q.dirname(s)),c=Q.resolve(s)===i?"current":"ancestor";return{pmRoot:s,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:s,workspace_root:a,discovery:c,requested_cwd:Q.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:s}}}function $R(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(Vc(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 DR(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: ${Eh.join(", ")}`,l.USAGE)}function UR(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Ph(e,t){let n=al[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function GR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jR(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(GR).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function qR(e,t,n){let r=Eo(t.schema),o=st(e,r.files.types,ot.types),i=Om(await q(o)),a=[],c=[];for(let d of Fm(n)){let u=Pm(i,d);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await Rt({pmRoot:e,filePath:o,raw:ko(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:o}}async function KR(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",Q.join(".agents","pm")];for(let n of t)if(await P(Q.join(e,n)))return!0;return!1}async function zR(e,t,n){if(!t||n||await P(Q.join(e,"settings.json"))||!await KR(e))return;let r=Q.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 Lh(e,t){let n=[],r=[];for(let o of t){let s=o?Q.join(e,o):e,i=await P(s);await RR.mkdir(s,{recursive:!0}),i?r.push(`already_exists:${s}`):n.push(s),r.push(...await z({path:s,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function BR(e,t){let n=OR();try{Le.write(`pm init setup wizard (agent-optimized)
24
+ `),Le.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
25
25
 
26
- `),Ie.write(`1/3 Item ID prefix
27
- `),Ie.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?Rt(r):e;Ie.write(`
26
+ `),Le.write(`1/3 Item ID prefix
27
+ `),Le.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
28
+ `);let r=await n.question(`Item ID prefix [${e}]: `),o=r.trim().length>0?It(r):e;Le.write(`
29
29
  2/3 Governance preset
30
- `),Ie.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
31
- `),Ie.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
32
- `),Ie.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=ch(i)}catch{Ie.write(`Unrecognized governance preset "${i}"; using minimal.
34
- `)}Ie.write(`
30
+ `),Le.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
31
+ `),Le.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
32
+ `),Le.write(`strict: ownership blocking, strict create defaults, close validation strict.
33
+ `);let s=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),i=s.trim().length>0?s.trim():"minimal",a="minimal";try{a=Oh(i)}catch{Le.write(`Unrecognized governance preset "${i}"; using minimal.
34
+ `)}Le.write(`
35
35
  3/3 Project telemetry
36
- `),Ie.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=eR(d,t);return Ie.write(`
38
- `),{prefix:s,preset:a,telemetry_enabled:u}}finally{n.close()}}function aR(e){return{presetFromOption:ch(e.preset),useDefaults:e.defaults===!0,authorFromOption:JC(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:ZC(e.agentGuidance),typePreset:YC(e.typePreset)}}function cR(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 dR(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 lR(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&&(dh(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 mR(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=cR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return dR(e.settingsPath,n,e.options.force===!0,e.target),lR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Ae(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function uR(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 iR(t,bt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,s=!0}let o=n??"minimal",i=VC();i.id_prefix=t,dh(i,o);let a=As()?.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 Ae(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:s}}async function ah(e){return e.settingsExists?await mR(e):await uR({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function pR(e){let t=await ih({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 Ae(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function fR(e,t){let n=[],r=[],s=await km(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 _R(e){if(e.typePreset===void 0)return;let t=await rR(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 hR(e){let n=I(e.settings,R()).folders.filter(s=>!Ni.includes(s)),r=await lh(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function gR(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 yR(e,t,n,r){if(!e)return;let s=await Rn("all",{install:!0,project:!0},{...t,path:n});r.push(...s.warnings);let o=nR(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 bR(e){let t=r=>vs([...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 wR(e,t,n,r=yp){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 gr(e,t,n={}){let r=process.cwd(),s=XC(r,t,e,n.workspace),o=s.pmRoot;e=QC(s.prefixArg,n.idPrefix);let i=aR(n);await oR(o,s.target.mode==="tracker-path",n.force===!0);let a=[],c=[],d=V.join(o,"settings.json"),u=await x(d),p;u&&(p=await ah({pmRoot:o,settingsPath:d,settingsExists:u,normalizedPrefix:Rt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target}));let f=await lh(o,Ni);a.push(...f.createdDirs),c.push(...f.warnings),p??=await ah({pmRoot:o,settingsPath:d,settingsExists:u,normalizedPrefix:Rt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target});let{settings:_}=p,h=gR(s.target),y=await hp(h??V.dirname(o)),g=h??y,b=await pR({pmRoot:o,cwd:g??r,agentGuidanceMode:i.agentGuidanceMode,settings:_,warnings:c}),v=await fR(o,_);a.push(...v.createdDirs),c.push(...v.warnings);let S=await _R({pmRoot:o,settings:_,typePreset:i.typePreset,warnings:c});if(S&&(_=await A(o)),await hR({pmRoot:o,settings:_,createdDirs:a,warnings:c}),g&&i.agentGuidanceMode!=="status"){let j=await Wi(g,{pmRoot:o});j.changed&&c.push(`updated:gitignore:${j.path}`)}!u&&n.mergeFence!==!1&&i.agentGuidanceMode!=="status"&&await wR(o,y,c);let N=await yR(i.installBundledPackages,t,o,c),O=bR({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}:{},...N?{installed_packages:N}:{},next_steps:O,agent_guidance:b}}import CR from"node:fs/promises";import Mc 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 uh=10,sn="https://schema.unbrained.dev/pm/eval-query-set/v1";var Ho={schema:sn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},He=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},vR=new Set(["keyword","semantic","hybrid"]);function mh(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 kR(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),s=mh(r,n),o=Array.from({length:t.size},()=>1),i=mh(o,n);return i===0?0:s/i}function SR(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 Lc(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 ER(e,t,n){return n<=0?0:Lc(e,t,n)/n}function AR(e,t,n){return t.size===0?0:Lc(e,t,n)/t.size}function ph(e,t,n){return{ndcg:kR(e,t,n),mrr:SR(e,t,n),precision:ER(e,t,n),recall:AR(e,t,n),relevant_total:t.size,retrieved_relevant:Lc(e,t,n)}}function fh(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 TR(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"||!vR.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 Fc(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==sn)throw new He(`Unsupported eval query set schema; expected "${sn}"`);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:sn,queries:n.map((r,s)=>TR(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 RR=Mc.join("search","eval-queries.json"),$c={schema:sn,examples:[JSON.stringify(Ho)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},IR=new Set(["keyword","semantic","hybrid"]),xR=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!IR.has(t))throw new m("Eval --mode must be one of keyword|semantic|hybrid",l.USAGE);return t},OR=e=>{if(e===void 0||e==="")return uh;let t=Wd(e);if(t===null)throw new m("Eval --k must be a positive integer",l.USAGE);return t},PR=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},Pt=e=>Math.round(e*1e4)/1e4,NR=async e=>{try{return await CR.readFile(e,"utf8")}catch{throw new m(`Eval query set not found at ${e}`,l.NOT_FOUND,{...$c,examples:[`echo '${JSON.stringify(Ho)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},LR=(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,$c)}},FR=e=>{try{return Fc(e)}catch(t){throw new m(t instanceof Error?t.message:String(t),l.USAGE,$c)}},MR=async e=>FR(LR(await NR(e),e)),$R=(e,t)=>t?Mc.resolve(process.cwd(),t):Mc.join(e,RR),DR=async(e,t,n,r)=>{let s=e.mode??t,i=(await ir(e.query,{mode:s,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=ph(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:Pt(a.ndcg),mrr:Pt(a.mrr),precision:Pt(a.precision),recall:Pt(a.recall)}}},UR=(e,t,n,r)=>{let s=fh(n);return{k:e,query_count:t.length,aggregate:{ndcg:Pt(s.ndcg),mrr:Pt(s.mrr),precision:Pt(s.precision),recall:Pt(s.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||s.ndcg>=r}},_h=async(e,t)=>{let n=E(process.cwd(),t.path);await C(n);let r=OR(e.k),s=xR(e.mode),o=PR(e.failUnder),i=$R(n,e.queries),a=await MR(i),c=[],d=[];for(let u of a.queries){let{report:p,metrics:f}=await DR(u,s,r,t);d.push(f),c.push(p)}return UR(r,c,d,o)};import{readFile as JR,writeFile as XR}from"node:fs/promises";import QR 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 Dc(e,t){let n=Cs(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 Nt(e){return J({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function GR(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Nt(e[r])===Nt(t[r]);)r+=1;return r}function hh(e,t,n){Dc(e,"base");let r=Dc(t,"ours"),s=Dc(n,"theirs"),o=GR(r,s);if(o===r.length&&o===s.length)return{merged:ot(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:ot(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:ot(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(Nt)),c=s.slice(o).filter(p=>!a.has(Nt(p))),d=[...i,...c].sort((p,f)=>{let _=bn(p.ts,f.ts);if(_!==0)return _;let h=a.has(Nt(p)),y=a.has(Nt(f));return h!==y?Number(y)-Number(h):Nt(p).localeCompare(Nt(f))}),u=Is([...r.slice(0,o),...d]);return{merged:ot(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 Uc(e,t){let n=Cs(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 Vo(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
36
+ `),Le.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=UR(d,t);return Le.write(`
38
+ `),{prefix:o,preset:a,telemetry_enabled:u}}finally{n.close()}}function HR(e){return{presetFromOption:Oh(e.preset),useDefaults:e.defaults===!0,authorFromOption:FR(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:DR(e.agentGuidance),typePreset:NR(e.typePreset)}}function VR(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 WR(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new m(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,l.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function 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&&(Ph(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 JR(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=VR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return WR(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 Ie(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function XR(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await BR(t,bt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let s=n??"minimal",i=PR();i.id_prefix=t,Ph(i,s);let a=Lo()?.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 Ie(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function xh(e){return e.settingsExists?await JR(e):await XR({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function QR(e){let t=await Ih({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 Ie(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function ZR(e,t){let n=[],r=[],o=await Dm(e,t.schema);for(let s of o.created_paths)n.push(s),r.push(...await z({path:s,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function eI(e){if(e.typePreset===void 0)return;let t=await qR(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 tI(e){let n=I(e.settings,R()).folders.filter(o=>!zi.includes(o)),r=await Lh(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function nI(e){let t=Q.resolve(e.tracker_root),n=Q.dirname(t);return Q.basename(t)==="pm"&&Q.basename(n)===".agents"?Q.dirname(n):e.workspace_root}async function rI(e,t,n,r){if(!e)return;let o=await Pn("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let s=jR(o),i=s.packages.filter(a=>!a.ok).map(a=>a.alias);if(!s.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 s}function oI(e){let t=r=>Io([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function sI(e,t,n,r=Fp){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof m))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function kr(e,t,n={}){let r=process.cwd(),o=MR(r,t,e,n.workspace),s=o.pmRoot;e=$R(o.prefixArg,n.idPrefix);let i=HR(n);await zR(s,o.target.mode==="tracker-path",n.force===!0);let a=[],c=[],d=Q.join(s,"settings.json"),u=await P(d),p;u&&(p=await xh({pmRoot:s,settingsPath:d,settingsExists:u,normalizedPrefix:It(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:o.target}));let f=await Lh(s,zi);a.push(...f.createdDirs),c.push(...f.warnings),p??=await xh({pmRoot:s,settingsPath:d,settingsExists:u,normalizedPrefix:It(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:o.target});let{settings:_}=p,h=nI(o.target),y=await Lp(h??Q.dirname(s)),g=h??y,w=await QR({pmRoot:s,cwd:g??r,agentGuidanceMode:i.agentGuidanceMode,settings:_,warnings:c}),v=await ZR(s,_);a.push(...v.createdDirs),c.push(...v.warnings);let S=await eI({pmRoot:s,settings:_,typePreset:i.typePreset,warnings:c});if(S&&(_=await A(s)),await tI({pmRoot:s,settings:_,createdDirs:a,warnings:c}),g&&i.agentGuidanceMode!=="status"){let D=await sa(g,{pmRoot:s});D.changed&&c.push(`updated:gitignore:${D.path}`)}!u&&n.mergeFence!==!1&&i.agentGuidanceMode!=="status"&&await sI(s,y,c);let x=await rI(i.installBundledPackages,t,s,c),O=oI({installBundledPackages:i.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:w.next_steps,target:o.target});return{ok:!0,path:s,target:o.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:w}}import uI from"node:fs/promises";import Jc 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 Fh=10,dn="https://schema.unbrained.dev/pm/eval-query-set/v1";var Zs={schema:dn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},He=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},iI=new Set(["keyword","semantic","hybrid"]);function Nh(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function aI(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),o=Nh(r,n),s=Array.from({length:t.size},()=>1),i=Nh(s,n);return i===0?0:o/i}function cI(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function Wc(e,t,n){let r=Math.min(n,e.length),o=0;for(let s=0;s<r;s+=1)t.has(e[s])&&(o+=1);return o}function dI(e,t,n){return n<=0?0:Wc(e,t,n)/n}function lI(e,t,n){return t.size===0?0:Wc(e,t,n)/t.size}function Mh(e,t,n){return{ndcg:aI(e,t,n),mrr:cI(e,t,n),precision:dI(e,t,n),recall:lI(e,t,n),relevant_total:t.size,retrieved_relevant:Wc(e,t,n)}}function $h(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function mI(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(s=>typeof s!="string"))throw new He(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(s=>s.trim()).filter(s=>s.length>0))];if(o.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"||!iI.has(n.mode)))throw new He(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Yc(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==dn)throw new He(`Unsupported eval query set schema; expected "${dn}"`);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:dn,queries:n.map((r,o)=>mI(r,o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cc9405b-d2b8-59aa-893f-54892595788a")}catch{}})();var pI=Jc.join("search","eval-queries.json"),Xc={schema:dn,examples:[JSON.stringify(Zs)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},fI=new Set(["keyword","semantic","hybrid"]),_I=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!fI.has(t))throw new m("Eval --mode must be one of keyword|semantic|hybrid",l.USAGE);return t},hI=e=>{if(e===void 0||e==="")return Fh;let t=ll(e);if(t===null)throw new m("Eval --k must be a positive integer",l.USAGE);return t},gI=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},Nt=e=>Math.round(e*1e4)/1e4,yI=async e=>{try{return await uI.readFile(e,"utf8")}catch{throw new m(`Eval query set not found at ${e}`,l.NOT_FOUND,{...Xc,examples:[`echo '${JSON.stringify(Zs)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},wI=(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,Xc)}},bI=e=>{try{return Yc(e)}catch(t){throw new m(t instanceof Error?t.message:String(t),l.USAGE,Xc)}},vI=async e=>bI(wI(await yI(e),e)),kI=(e,t)=>t?Jc.resolve(process.cwd(),t):Jc.join(e,pI),SI=async(e,t,n,r)=>{let o=e.mode??t,i=(await mr(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=Mh(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:Nt(a.ndcg),mrr:Nt(a.mrr),precision:Nt(a.precision),recall:Nt(a.recall)}}},EI=(e,t,n,r)=>{let o=$h(n);return{k:e,query_count:t.length,aggregate:{ndcg:Nt(o.ndcg),mrr:Nt(o.mrr),precision:Nt(o.precision),recall:Nt(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||o.ndcg>=r}},Dh=async(e,t)=>{let n=E(process.cwd(),t.path);await C(n);let r=hI(e.k),o=_I(e.mode),s=gI(e.failUnder),i=kI(n,e.queries),a=await vI(i),c=[],d=[];for(let u of a.queries){let{report:p,metrics:f}=await SI(u,o,r,t);d.push(f),c.push(p)}return EI(r,c,d,s)};import{readFile as UI,writeFile as GI}from"node:fs/promises";import jI 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]="393f6460-bf8b-5479-8e3e-cac6f2680823")}catch{}})();function Qc(e,t){let n=Fo(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[o,s]of e.split(/\r?\n/).entries()){let i=s.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 ${o+1}.`,l.GENERIC_FAILURE)}}return r}function Ft(e){return J({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function AI(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 Uh(e,t,n){Qc(e,"base");let r=Qc(t,"ours"),o=Qc(n,"theirs"),s=AI(r,o);if(s===r.length&&s===o.length)return{merged:it(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===o.length)return{merged:it(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:it(o),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:o.length-s,entries_total:o.length,reanchored:!1};let i=r.slice(s),a=new Set(i.map(Ft)),c=o.slice(s).filter(p=>!a.has(Ft(p))),d=[...i,...c].sort((p,f)=>{let _=Sn(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=$o([...r.slice(0,s),...d]);return{merged:it(u.entries),strategy:"union_reanchor",common_entries:s,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:u.entries.length,reanchored:!0}}function Zc(e,t){let n=Fo(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[o,s]of e.split(/\r?\n/).entries()){let i=s.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{throw new m(`Relationship merge input (${t}) contains invalid JSON at line ${o+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 ${o+1} is not a relationship event (eventId + sequence required).`,l.GENERIC_FAILURE);r.push(a)}return r}function ei(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
39
39
  `)}
40
- `}function jR(e){return e.map((t,n)=>({...t,sequence:n+1}))}function gh(e,t,n){Uc(e,"base");let r=Uc(t,"ours"),s=Uc(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:Vo(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:Vo(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:Vo(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=bn(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=jR([...r.slice(0,i),...u]);return{merged:Vo(p),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:d.length,entries_total:p.length,reanchored:!0}}var qR=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],KR=["updated_at"];function on(e,t){return J(e??null)===J(t??null)}function zR(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))),d=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)&&d.push(u)}return d}function BR(e,t){return bn(String(e),String(t))>=0?e:t}function yh(e,t,n,r){return on(t,n)?{value:t,from_theirs:!1,conflict:!1}:on(e,t)?{value:n,from_theirs:!0,conflict:!1}:on(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function bh(e,t,n,r,s){let o=yh(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 Gc(e){return{...e.metadata}}function jc(e,t,n){try{return Ye(gu(e,n),n)}catch(r){throw new m(`Item merge input (${t}) is not a readable item document: ${String(r)}`,l.GENERIC_FAILURE)}}function HR(e,t,n,r,s){let o=new Set(qR),i=new Set(KR),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=zR(u,p,f);c.merged[d]=h,on(h,p)||c.unionFields.push(d);continue}if(i.has(d)){c.merged[d]=BR(p,f);continue}let _=bh(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 wh(e,t,n,r={}){let s=r.preferred??"ours",o=r.conflictResolution??"preferred_side",i=e.trim().length>0,a=jc(t,"ours",r),c=jc(n,"theirs",r),d=i?jc(e,"base",r):a,u=i?Gc(d):{},p=Gc(a),f=Gc(c),{merged:_,conflictFields:h,fieldsFromTheirs:y,unionFields:g,conflictDecisions:b}=HR(u,p,f,s,o),v=bh(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 qc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kc(e,t){let n=Cs(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 VR(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=J(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=J(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 WR(e,t,n,r,s,o,i){if(!qc(t)||!qc(n))return null;let a=qc(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=YR(a,t,n,u,r,p,o,i);f!==void 0&&(c[u]=f)}return c}function vh(e,t,n,r,s,o,i){if(on(t,n))return t;let a=VR(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(s),a.merged;let c=WR(e,t,n,r,s,o,i);if(c!==null)return c;let d=yh(e,t,n,r);return d.conflict?o.push(s):d.from_theirs&&i.push(s),d.value}function YR(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 vh(e[r],t[r],n[r],s,o,i,a);if(c){if(u&&on(e[r],t[r])){a.push(o);return}return u?(i.push(o),s==="theirs"?void 0:t[r]):t[r]}if(!(u&&on(e[r],n[r])))return u?(i.push(o),s==="theirs"?n[r]:void 0):(a.push(o),n[r])}function kh(e,t,n,r={}){let s=r.preferred??"ours",o=Kc(e,"base"),i=Kc(t,"ours"),a=Kc(n,"theirs"),c=[],d=[],u=vh(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 Sh=["item","history","relationship","json"];function ZR(e){let t=e.trim().toLowerCase();if(Sh.includes(t))return t;throw new m(`Unknown merge artifact "${e}". Supported values: ${Sh.join(", ")}.`,l.USAGE)}function eI(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 zc(e,t){try{return await JR(e,"utf8")}catch{throw new m(`Cannot read merge ${t} file at ${e}.`,l.NOT_FOUND)}}async function tI(e){let t=E(process.cwd(),e.path);return await x(ge(t))?A(t):null}function nI(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Eh(e,t){let n=ZR(e.artifact),r=eI(e.prefer),s=QR.resolve(e.outputPath??e.oursPath),[o,i,a]=await Promise.all([zc(e.basePath,"base"),zc(e.oursPath,"ours"),zc(e.theirsPath,"theirs")]),c,d,u=[],p={};if(n==="history"){let _=hh(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 _=gh(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 tI(t),h=wh(o,i,a,{format:nI(e.itemPath??s,_),schema:_?.schema,extensionFieldNames:wt(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 _=kh(o,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await XR(s,c,"utf8"),d!==void 0){let _=await $p(d);_!==null&&(p.receipt=tr(_))}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 Ch 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 Ah(e,t){return t==="body"?e.body:e.metadata[t]}function Bc(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)&&Bc(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)&&Bc(s,n[r]))}function Th(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 Su(o.patch))i.add(Gs(c.path)),c.from&&i.add(Gs(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 rI(e,t,n){let r=Ch.compare(t,n);if(r.length===0)return;let s=new Set;for(let h of r)s.add(Gs(h.path));let o=new Set([...s].filter(h=>Bc(Ah(t,h),Ah(n,h)))),i=new Set([...s].filter(h=>!o.has(h))),a=Th(e,i),c=Th(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 sI(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=Ht(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 oI(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 iI(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?Ch.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 aI(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 cI(e){return Ls({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})=>Ns({historyPath:e.historyPath,nextHistoryRaw:ot(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function yr(e,t,n){let r=E(process.cwd(),n.path);await C(r);let s=await A(r),o=I(s,R()),i=await Fs(r,e,s,o.type_to_folder);if(!await x(i.historyPath))throw new m(`No history stream exists for ${i.id}.`,l.NOT_FOUND);let a=await q(i.historyPath),c=await At(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=wn(c),u=Eu(c),p=t.normalizeProvenance?Fp(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=Au(p.entries),_=new Set(p.entries.map(ce=>ce.item_hash_version).filter(ce=>ce!==void 0)),h=Is(p.entries,f),y=await sI(i,s,c,f),g=h.finalDocument,b=y.currentItemReplay!==null&&Le(g,f)!==Le(y.currentItemReplay,f),v=b&&y.currentItemReplay?rI(h.entries,g,y.currentItemReplay):void 0,S=[h.entriesRehashed>0,h.entriesPatchRepaired>0,b,t.forceAuditEntry===!0,p.receipt.changed].some(Boolean),N=T(t.author,s.author_default),O=!!t.dryRun,j=oI({message:t.message,entriesRehashed:h.entriesRehashed,entriesPatchRepaired:h.entriesPatchRepaired,reconcileNeeded:b}),{rewrittenEntries:M,auditEntryAdded:Oe}=iI({reanchorEntries:h.entries,changed:S,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=wn(M);if(!te.ok)throw new m(`history-repair produced an invalid rewritten chain (${te.errors.join(", ")}).`,l.GENERIC_FAILURE);let _e=aI(S,h.skippedOps,v);return S&&!O&&_e.push(...await cI({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:M})),{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:Oe,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,Ze)=>ce.localeCompare(Ze)),generated_at:k()}}function Rh(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 Wo(e,t){let n=E(process.cwd(),t.path);await C(n);let r=await A(n),s=I(r,R()),o=[],i=await xs(n,r.item_format,s.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await ip(n,i),c=e.normalizeProvenance?await Mp(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 yr(_,{...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 vu(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 Ih(e,t){let n=e.dryRun===!0,r=await Dp(process.cwd(),{includeLossless:!0}),{pendingDecisions:s}=Up(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(tr)}}])),a=await Wo({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=>yr(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=>Gp(process.cwd(),g))),p=r.length);let f=await eo({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(tr)},validation:f,guidance:y,generated_at:f.generated_at}}import{createHash as dI}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 Ph=1,Nh=/^[A-Za-z0-9_-]+$/,lI=100,xh=1e3;var dj=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 mI(e){return dI("sha256").update(J({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 Oh(e,t){let n={version:Ph,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 uI(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Ph,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 pI(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Nh.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(!uI(r,t))throw new m("Mutation event cursor does not match this query.",l.USAGE,{code:"event_cursor_query_mismatch"});return r}function fI(e){let t=e??lI;if(!Number.isSafeInteger(t)||t<0||t>xh)throw new m(`Mutation event limit must be an integer from 0 to ${xh}.`,l.USAGE,{code:"invalid_event_limit"});return t}function _I(e,t){let n=e?.trim();if(!n)return{};if(Nh.test(n))return{cursor:pI(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 hI(e,t){let n=await ra(e,t);if(n===null){if(!await yu(e))return{...await bu(e,t),source:"authoritative_history"};n=await ra(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 gI(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 Yo(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await C(t);let n=fI(e.limit),r=gI(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=Yu(s.agent_identity.harness_signals),a=Ju({provenance:e.provenanceFilter},i),c=Ve(e.harness),d=mI(e),{cursor:u,sinceTimestamp:p}=_I(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 hI(t,f),h=_.events.map(y=>({...r==="row"?{cursor:Oh(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:Xu(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:Oh(_.events[_.events.length-1],d)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Qu(_.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 yI="1h",bI="now",wI="+1d";function Lt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Lh(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 Fh(e,t,n,r){let s=Lh(e,t,n),o=[];return Lt(o,"start",n.start??bI),n.end!==void 0?Lt(o,"end",n.end):Lt(o,"duration",n.duration??yI),Lt(o,"location",n.location),Lt(o,"timezone",n.timezone),n.allDay===!0&&Lt(o,"all_day","true"),s.event=[o.join(",")],Ot(s,r)}function Mh(e,t,n){return Fh("Meeting",e,t,n)}function $h(e,t,n){return Fh("Event",e,t,n)}function Dh(e,t,n){let r=Lh("Reminder",e,t),s=[];return Lt(s,"at",t.at??wI),Lt(s,"text",t.text??e),r.reminder=[s.join(",")],Ot(r,n)}import wr from"node:crypto";import{cp as Gh,lstat as TI,mkdir as an,readFile as $n,readdir as Vc,rename as Kh,rm as Yc,writeFile as Xo}from"node:fs/promises";import L from"node:path";import{constants as Ft}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 Uh=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"}]]),vI=/^[a-z][a-z0-9_]{0,63}$/u,kI=new Map([[Ft.errno.EACCES,"EACCES"],[Ft.errno.EDQUOT,"EDQUOT"],[Ft.errno.EMFILE,"EMFILE"],[Ft.errno.ENFILE,"ENFILE"],[Ft.errno.ENOMEM,"ENOMEM"],[Ft.errno.ENOSPC,"ENOSPC"],[Ft.errno.EPERM,"EPERM"],[Ft.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),SI={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function EI(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&Uh.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:kI.get(Math.abs(t.errno))??null}function AI(e,t,n={}){let r=EI(e);if(r===null)return null;if(!vI.test(t))throw new m("Host environment operation labels must be bounded identifiers.",l.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let s=Uh.get(r);return new m(`Host filesystem operation ${t} ${s.summary}.`,l.GENERIC_FAILURE,{code:n.codes?.[s.category]??SI[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 Jo(e,t,n={}){try{return await t()}catch(r){throw AI(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 zh="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var Bh=L.join("runtime","workspace-snapshots"),CI=new Set(["checkpoints","locks","runtime","search","transactions"]),RI=/^[a-z0-9][a-z0-9._-]*$/,br="sdk-workspace-transaction",Hc={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Hh={renameEntry:Kh,removeEntry:async e=>{await Yc(e,{recursive:!0,force:!0})}},Wc=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!==br||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 Vh(e,t=""){let n=await Vc(L.join(e,t),{withFileTypes:!0}),r=[];for(let s of n.sort((o,i)=>o.name.localeCompare(i.name))){if(t.length===0&&CI.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 Vh(e,o));else if(s.isFile())r.push(o);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${o}`)}return r}async function Wh(e){let t=await Vh(e),n=wr.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:zh,fingerprint:o,files:t,bytes:s},contents:r}}function jh(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
43
- `).filter(t=>t.trim().length>0).length}async function II(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 Jc(e){if(!RI.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 Yh(e,t){return Jo(`workspace_snapshot_${e}`,t,{codes:{capacity:Hc.capacity.code,permission:Hc.permission.code,resource:Hc.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 cn(e){return L.join(e,Bh)}function Jh(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 Xh(e,t){try{return JSON.parse(await $n(e,"utf8"))}catch(n){throw vt(n)?Jh(t):n}}async function qh(e,t,n){try{await Yc(e,{recursive:n})}catch(r){throw vt(r)?Jh(t):r}}async function xI(e,t,n=Hh){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 OI(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 PI(e,t){return Jc(t),/^[a-f0-9]{64}$/.test(t)?t:(await Xh(L.join(cn(e),"refs",`${t}.json`),t)).fingerprint}async function Xc(e,t={}){if(t.name!==void 0&&(Jc(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 Wh(e),s=cn(e),o=L.join(s,"objects",n.fingerprint),i=!1;try{i=(await TI(o)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&vt(a)))throw a}if(!i){let a=L.join(s,"objects",`.create-${process.pid}-${wr.randomUUID()}`);await Yh("create_object",async()=>{await an(L.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let u=L.join(a,"files",d);await an(L.dirname(u),{recursive:!0}),await Xo(u,r[c])}await Xo(L.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
44
- `,"utf8"),await an(L.dirname(o),{recursive:!0})}),i=await xI(a,o)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=L.join(s,"refs");await an(c,{recursive:!0});let d=L.join(c,`.ref-${process.pid}-${wr.randomUUID()}`);await Xo(d,`${JSON.stringify(a,null,2)}
45
- `,"utf8"),await Kh(d,L.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function vr(e,t){let n=await PI(e,t),r=await Xh(L.join(cn(e),"objects",n,"manifest.json"),t);if(r.schema!==zh||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 Qc(e){let t=cn(e),n=await Vc(L.join(t,"objects")).catch(s=>{if(s instanceof Error&&"code"in s&&vt(s))return[];throw s}),r=await Vc(L.join(t,"refs")).catch(s=>{if(s instanceof Error&&"code"in s&&vt(s))return[];throw s});return{objects:await Promise.all(n.filter(s=>/^[a-f0-9]{64}$/.test(s)).sort().map(s=>vr(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 Zc(e,t){let n=await vr(e,t),{manifest:r,contents:s}=await Wh(e),o=new Map(r.files.map((p,f)=>[p,s[f]])),i=await II(L.join(cn(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=jh(o.get(p)),_=jh(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 Qh(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 Ne(e,br,s,r,!1,!1,o),a=new Wc($r(e,br),r,s);a.start(),await a.refreshNow();let c,d=!1,u=!1;try{let p=await Zc(e,t),f=await vr(e,t),_=await Xc(e),h=f.fingerprint,y=cn(e),g=L.join(y,"objects",h,"files"),b=L.dirname(e),v=L.basename(e);c=L.join(b,`.${v}.restore-${wr.randomUUID()}`);let S=L.join(b,`.${v}.backup-${wr.randomUUID()}`);await Yh("restore_stage",async()=>{await an(c,{recursive:!0}),await Gh(g,c,{recursive:!0,force:!1}),await an(L.join(c,"runtime"),{recursive:!0}),await Gh(y,L.join(c,Bh),{recursive:!0,force:!1})});let N=await Tu({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=$r(c,br);return await an(L.dirname(j),{recursive:!0}),await Xo(j,await $n($r(e,br)),{flag:"wx"}),d=!0,await OI(c,e,S,Hh,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([Yc(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function Zh(e,t){Jc(t);let n=cn(e);if(!/^[a-f0-9]{64}$/.test(t))return await qh(L.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Qc(e);if(r.some(s=>s.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await qh(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 kr(e){return{...e.args,...e.options}}function mt(e,t){let n=w(e,t);if(n!==void 0)return n;throw new m(`Missing required parameter: ${t}`,l.USAGE)}function Dn(e){return typeof e=="string"?[e]:be(e)}function eg(e){return _h(kr(e),e.global)}function tg(e){let t=kr(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 Yo({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Dn(t.type),author:Dn(t.author),item:Dn(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:Dn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Dn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Dn(t.provenanceFilter)}})}function ng(e){let t=kr(e),n=mt(t,"subcommand");if(n==="install")return gp({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return Ih({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return jp({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return Eh({artifact:mt(t,"artifact"),basePath:mt(t,"basePath"),oursPath:mt(t,"oursPath"),theirsPath:mt(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 rg(e){let t=kr(e),n=mt(t,"subcommand");if(n!=="snapshot")throw Te({command_path:"workspace",token:n,allowed:["snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??mt(t,"snapshot_action"),s=E(process.cwd(),e.global.path);if(r==="create")return Xc(s,{name:w(t,"name")});if(r==="list")return Qc(s);let o=mt(t,"target");if(r==="inspect")return vr(s,o);if(r==="delete")return Zh(s,o);if(r==="restore")return t.dryRun===!0?Zc(s,o):Qh(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 Te({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Qo(e){let t=kr(e),n=mt(t,"title");return e.action==="meet"?Mh(n,t,e.global):e.action==="event"?$h(n,t,e.global):Dh(n,t,e.global)}import BI from"node:path";import NI from"node:fs/promises";import sg 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 LI="templates",FI=".json",MI=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,$I=ws.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),DI=new Set($I);function UI(e){let t=e.trim();if(!MI.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 og(e){return sg.join(e,LI)}function ig(e,t){return sg.join(og(e),`${t}${FI}`)}async function GI(e){await C(e)}function ag(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function jI(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(DI.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 ag(t)}function qI(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 ag(r)}function KI(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=qI(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 zI(e,t){let n=await q(ig(e,t));if(n===null)throw new m(`Template "${t}" not found`,l.NOT_FOUND);return KI(n,t)}async function ed(e,t,n){let r=E(process.cwd(),n.path);await GI(r);let s=UI(e),o=jI(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=ig(r,s),c=i;await x(a)&&(c=(await zI(r,s)).created_at);let d={name:s,created_at:c,updated_at:i,options:o},u=await A(r);return await NI.mkdir(og(r),{recursive:!0}),await Ct({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 mg=["list","show","apply","lint"],HI="schema-types",VI="schema-statuses",WI="schema-fields";function Zo(){let e=R();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function ug(){let{profiles:e,warnings:t}=wm(Zo());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:Am(n.definition)})),warnings:t,generated_at:k()}}function pg(e){let t;try{t=_s(e,Zo())}catch(r){throw new m(r instanceof Error?r.message:String(r),l.USAGE)}let{resolved:n}=t;return{action:"show",...Tm(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function fg(e){let t;try{t=_s(e,Zo())}catch(s){throw new m(s instanceof Error?s.message:String(s),l.USAGE)}let{resolved:n}=t,r=Km(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 YI(e,t){return BI.join(e,"templates",`${t}.json`)}async function JI(e,t){let n=await q(YI(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 cg(e,t,n,r){let s=new Map;for(let o of r.templates){let i=await JI(e,o.name);i!==void 0&&s.set(o.name,i)}return{typesRaw:await q(st(e,t.files.types,rt.types)),statusesRaw:await q(st(e,t.files.statuses,rt.statuses)),fieldsRaw:await q(st(e,t.files.fields,rt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:s,installedPackages:new Set}}function Un(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 dg(e,t,n,r,s){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Un(t.types.changes),statuses:Un(t.statuses.changes),fields:Un(t.fields.changes),workflows:Un(t.workflows.changes.map(o=>({key:o.type,status:o.status}))),config:Un(t.config.changes),templates:Un(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 XI(e){await C(e)}function QI(e){try{let t=_s(e,Zo());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new m(t instanceof Error?t.message:String(t),l.USAGE)}}async function _g(e,t,n){let r=E(process.cwd(),n.path);await XI(r);let s=QI(e),o=s.profile,i=s.warnings,a=t.dryRun===!0,c=await A(r),d=hs(c.schema);if(a){let b=await cg(r,d,c,o),v=lg(o,b);return dg(o,v,!1,!0,[...i])}let u=T(t.author,c.author_default),p=Ru(c),f=!!t.force,_=[...i],h=[],y=async b=>{h.push(await Ne(r,b,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(HI),await y(VI),await y(WI);let b=await cg(r,d,c,o);if(g=lg(o,b),g.types.changed){let v=st(r,d.files.types,rt.types);await Ct({pmRoot:r,filePath:v,raw:fs(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=>fm(O).name)),N=g.types.file.definitions.filter(O=>S.has(O.name));await Sp(r,N,_,"profile:apply-type-folder"),_.push(...await z({path:v,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let v=st(r,d.files.statuses,rt.statuses);await Ct({pmRoot:r,filePath:v,raw:Em(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=st(r,d.files.fields,rt.fields);await Ct({pmRoot:r,filePath:v,raw:vm(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=ys(v.key);S!==void 0&&bs(c,S,v.value)}c.schema.type_workflows=g.workflows.result,await Ae(r,c,"profile:apply-config")}for(let v of g.templates.changes)v.status!=="unchanged"&&await ed(v.name,{...v.options},n)}finally{for(let b of h.reverse())try{await b()}catch{}}return dg(o,g,g.changed,!1,_)}function lg(e,t){try{return zm(e,t)}catch(n){throw new m(n instanceof Error?n.message:String(n),l.USAGE)}}import gg from"node:fs/promises";import yg 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 ZI(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 ex(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 hg(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return ZI(t.ids,n,t.minEntries)}return ex(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 tx(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 nx(e,t){let n=Rs(),r=Rs();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=Ps(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 rx(e,t,n){let r=structuredClone(t),s=[];for(let[o,i]of e.entries()){let a=Le(r);r=Ps(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 sx(e,t,n){let r=e.located?await K(e.located,{schema:t.schema}):null;return r?{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:Le(Ht(r.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function ox(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 ix(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 ax(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=nx(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),s=rx(r,t,e.boundary.compactCount),i=[Ke({nowIso:k(),author:e.author,op:"history_compact_baseline",before:Bt(Rs()),after:Bt(t),message:ix(e.boundary)}),...s.entries];return e.dryRun||i.push(Ke({nowIso:k(),author:e.author,op:"history_compact",before:Bt(n),after:Bt(n),message:ox(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function cx(e){return Ls({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})=>Ns({historyPath:e.historyPath,nextHistoryRaw:ot(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function td(e,t,n){let r=E(process.cwd(),n.path);await C(r);let s=await A(r),o=I(s,R()),i=await Fs(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 At(a,i.id);if(d.length===0)throw new m(`No history entries exist for ${i.id}; nothing to compact.`,l.USAGE);let u=wn(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=tx(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 sx(i,s,d);g.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:S}=ax({historyEntries:d,boundary:p,changed:f,dryRun:_,author:h,options:t}),N=wn(b);if(!N.ok)throw new m(`history-compact produced an invalid rewritten chain (${N.errors.join(", ")}).`,l.GENERIC_FAILURE);f&&!_&&y.push(...await cx({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: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,M)=>j.localeCompare(M)),generated_at:k()}}var dx=3;function bg(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 lx(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function mx(e){let t=$(e.settings.schema),n=to(t),r=await oe(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=yg.join(e.pmRoot,"history"),i=[],a=[];if(!await x(o))return{candidates:i,preselectionErrors:a};let c=(await gg.readdir(o)).filter(d=>d.endsWith(".jsonl")).sort((d,u)=>d.localeCompare(u));for(let d of c){let u=yg.join(o,d),p=d.slice(0,-6);try{let f=await gg.readFile(u,"utf8");await hn({path:u,scope:"project"}),i.push({id:p,entries:lx(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 ux(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 td(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 wg(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 mx({pmRoot:n,settings:r,typeToFolder:s.type_to_folder}),a=e.ids!==void 0&&e.ids.length>0?"ids":"scan",c=e.minEntries??dx,d=r.history.compact_policy,u=a==="scan"&&e.allOver===void 0&&d.enabled,p=e.allOver??(u?d.max_entries:void 0),f=hg(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 ux({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 vg(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return Rh(n,t),t?Wo(e.options,e.global):yr(n,e.options,e.global)}function kg(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 bg(e.id,{ids:n,allOver:r,scope:c}),e.id!==void 0?td(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):wg({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 ei(e){return gs("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 nd(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=ei(i),d=n.status??a,u=W(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 f_(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 Sg(e,t){let n=e.id??w(t,"id");if(!n)throw new m("Missing required argument: id",64);return n}function Eg(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function Ag(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return je(await at(Sg(e,r),Eg(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Tg(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return je(await nd(Sg(e,r),Eg(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 Cg(e,t,n){let r;if(typeof e.lines=="string")r=Xs(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=Xs(`${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 px=Vi("list").properties.outputSession,fx={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:{...px},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Rg={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."},_x=`Operation name (one of): ${Ki.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,hx={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."}},gx={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{...Rg,properties:{...Rg.properties,...e},required:t}}var yx=[{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:[...Ki],description:_x},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."},...fx},["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"},...gx},["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"},...hx})},{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:[...$m]},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:[...Ti]},description:`Lifecycle roles for add-status: ${Ti.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."}})}],bx={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"},wx=yx.map(e=>{let t=bx[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Vi(t,{properties:n,required:r})}});function Ig(){return wx.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 xg=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"]]]),vx=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Gg=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ni=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"]),Sr=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"]),jg=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"]]),qg=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"]]),Kg=new Map([...qg.entries()].flatMap(([e,t])=>ut(t).map(n=>[n,e]))),zg=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],Bg=new Map(zg.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),kx=10,Sx=20,Og=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."]]),Hg=[["init",Cl],["install",Il],["uninstall",xl],["explore",Ol],["manage",$l],["describe",Pl],["reload",Dl],["doctor",Ul],["catalog",Gl],["adopt",jl],["adopt-all",Nl],["activate",Ll],["deactivate",Fl],["migrate",Ml]],Ex=Hg.map(([e,t])=>e==="init"?[e,Rl]:[e,t]),Ax=[...Hg.map(([e,t])=>[`extension ${e}`,t]),...Ex.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Vr],["config",Tl],["extension",Wr],["package",Hn],["packages",Hn],["install",ql],["create",es],["item mutate",cm],["item complete",dm],["item reopen",lm],["copy",ts],["focus",ns],["update",rs],["update-many",ss],["upgrade",Kl],["calendar",Vn],["cal",Vn],["context",Wn],["ctx",Wn],["get",is],["search",ms],["eval",um],["workspace",kt],["workspace snapshot",kt],["workspace snapshot create",kt],["workspace snapshot list",kt],["workspace snapshot inspect",kt],["workspace snapshot restore",kt],["workspace snapshot delete",kt],["next",ls],["aggregate",Kr],["deps",cs],["graph",ds],["guide",as],["reindex",zl],["history",zr],["history-compact",Sl],["history-redact",vl],["history-repair",kl],["history-author-acknowledge",Br],["merge",wl],["schema",El],["profile",Al],["plan",Hr],["restore",Vl],["delete",Wl],["close",Bl],["close-many",Yr],["append",Jr],["claim",Hl],["release",Yl],["start-task",Jl],["pause-task",Xl],["close-task",Ql],["comments",_l],["notes",hl],["learnings",gl],["files",yl],["docs",bl],["test",tm],["test-all",nm],["telemetry",rm],["test-runs",sm],["gc",om],["stats",Xr],["duplicates",Qr],["validate",im],["health",Zr],["assurance",am],...pm,["contracts",us],["completion",ps],["activity",os],...[...Gg].map(e=>[e,qr])],id=new Map(Ax);function Tx(e){let t=Kg.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Pg(e){return ji.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)}`):ni.has(e)?qg.get(e)??fe(e):null}function Cx(e,t){return e.command_path===null?!1:ut(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `)||t.startsWith(`${n} `))}function ut(e){return e.split("|").map(t=>fe(t)).filter(t=>t.length>0)}function Rx(e,t){let n=new Set(t),r=new Set;for(let s of e)if(s.command_path)for(let o of ut(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 ti(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Er(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function Ix(e,t){if(!t)return{...e};let r=Er(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 rd(e,t){let r=Er(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 Vg(e){return e.replace(/\s+/g,"-")}function Xe(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ng(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=Xe(r);!s||n.has(s)||(n.add(s),t.push(s))}return t}function sd(e,t,n){n&&(e[t]=!0)}function Lg(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 xx(e){let t=Lg(e.long,"long"),n=Lg(e.short,"short"),r=t??n;if(!r)return null;let s={flag:r};n&&t&&(s.short=n),sd(s,"required",e.required===!0),sd(s,"repeatable",e.repeatable===!0),sd(s,"list",e.list===!0);let o=Xe(e.description);o&&(s.description=o);let i=Xe(e.value_name);i&&(s.value_name=i);let a=[Xe(e.value_type),Xe(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(s.value_type=a),s}function Wg(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=xx(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 Ox(e){let t=Wg(e.flagRegistrations),n=new Map;for(let o of e.commandDefinitions){let i=fe(o.command);if(i.length===0)continue;let a=Xe(o.action)??Vg(i),c=Array.isArray(o.arguments)?o.arguments.map(d=>{let u=Xe(d.name);return u?{name:u,required:d.required===!0,variadic:d.variadic===!0,description:Xe(d.description)}:null}).filter(d=>d!==null):[];n.set(i,{command:i,action:a,source:{layer:o.layer,name:o.name},description:Xe(o.description),intent:Xe(o.intent),arguments:c,flags:t.get(i)?.flags??[],examples:Ng(o.examples),failure_hints:Ng(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(Px(o,i,t.get(o)?.flags??[]))}return s}function Px(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Vg(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function Nx(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 Lx(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 Fx(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 Mx(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]=Lx(s,e.action),s.required&&r.push(s.name);for(let s of e.flags){let o=Nx(s);!o||n[o]!==void 0||(n[o]=Fx(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 $x(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 Dx(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&&$x(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 Ux(e,t=A){let n={mode:bt.extensions.policy.mode,trust_mode:bt.extensions.policy.trust_mode,default_sandbox_profile:bt.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 x(ge(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let s=await t(r),o=await Ur({pmRoot:r,settings:s,cwd:process.cwd(),noExtensions:!1}),i=await Gr({...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 Gx(e,t={}){let n=new Map;for(let r of qi){let s=ni.has(r);if(s&&!t.includePackageOwnedActions)continue;let o=Pg(r);n.set(r,{action:r,provider:s?"extension":"core",requires_extension:s,command_path:o})}if(t.includePackageOwnedActions)for(let r of ni)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Pg(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 jx(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?ut(e.command_path):[],r=n.some(i=>t.handlers.has(i)),s=n.map(i=>jg.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 Yg(e){return id.get(e)??jr}function qx(e){return Sr.has(e)?!1:id.has(e)}function Kx(e){return Gg.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Fg(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function zx(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function Bx(e){let t=new Map;for(let r of e.definitions){let s=Fg(r.cli_flag);if(!s)continue;let o=r.cli_aliases.map(a=>zx(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>Fg(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,Di(s.flags));return n}function Mg(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 Di(n)}function Hx(e,t,n,r){return e.map(s=>{let o=qx(s),i=o?Yg(s):[],a=n.get(Kx(s))??[],c=t.get(s),d=Mg(i,a),u=Mg(d,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":o?"core":"extension";return{command:s,flags:u,...r?{canonical_command:od(s),visibility:tu(od(s)),positionals:ul(s)?.slots??[],flag_invocations:eu(s,u)}:{},provider:p,extension_sources:c?.sources}}).sort((s,o)=>s.command.localeCompare(o.command))}function Vx(e,t=Yn){let n=new Set(e),r=new Map;for(let s of zg){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 Wx(){return{create_string_options:Bm,create_repeatable_options:ws,update_string_options:Hm,update_repeatable_options:Vm,list_string_options:al,search_string_options:cl,calendar_string_options:dl,context_string_options:ll,activity_string_options:ml}}function $g(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=un(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 Yx(e){let t={},n={};for(let r of[...e.types].sort((s,o)=>s.localeCompare(o))){let s=e.by_type[r];t[r]=$g(s,"strict"),n[r]=$g(s,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Jx(e,t){let n=Er(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 Xx(e){let t=ti(e.action)!==void 0||ti(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=ti(e.action),u=ti(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 Qx(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 Zx(e,t=A){try{return await t(e)}catch{return structuredClone(bt)}}async function eO(e,t){let n=await Zx(t),r=await Ux(e),s=I(n,r.registrations??R()),o=We(n.schema),i=Ox(r);return{settings:n,runtimeProbe:r,typeRegistry:s,statusRegistry:$(n.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:Bx(o),createRequiredOptionContracts:Yx(s),extensionContracts:i,mergedExtensionContracts:Dx(i),extensionFlagMap:Wg(r.flagRegistrations)}}function Dg(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ni.has(e.selectedAction)||e.selectedCommand!==void 0&&Sr.has(e.selectedCommand))}function tO(e,t){let n=Gx(t,{includePackageOwnedActions:Dg(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Um);return n.filter(s=>!r.has(s.action))}return Dg(e)&&e.selectedCommand!==void 0&&Sr.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:Tx(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function nO(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 rO(e,t){return[...new Set([...ji.filter(n=>!Sr.has(n)),...[...id.keys()].filter(n=>!Sr.has(n)),...e.flatMap(n=>n.command_path?ut(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 sO(e,t){let n=t.slice(0,kx),r=t.length-n.length,s=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),o=t.slice(0,Sx),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 oO(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 iO(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 aO(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 sO(e.selectedCommand,r);let s=jg.get(e.selectedCommand);throw s?oO(e.selectedCommand,s):iO(e.selectedCommand)}function cO(e,t){let n=tO(e,t.mergedExtensionContracts);nO(e,n);let r=rO(n,t.mergedExtensionContracts);aO(e,r);let s=e.selectedCommand?Kg.get(e.selectedCommand):void 0,o=e.selectedCommand?n.filter(d=>s?d.action===s:Cx(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=>jx(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 dO(e){return new Set(Er(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 lO(e){let t=qm,n=Er(t),r=dO(t),s=e.filter(o=>!r.has(o.action)).map(o=>Mx(o));return s.length>0?{...t,oneOf:[...n,...s]}:t}function Ug(e,t,n){let r=new Set(t.actionDescriptors.map(o=>o.action)),s=e.selectedAction?Ix(n,e.selectedAction):e.selectedCommand?rd(n,new Set(t.scopedActionDescriptors.map(o=>o.action))):rd(n,r);return e.runtimeOnly&&!e.selectedAction?rd(s,new Set(t.actions)):s}function mO(e,t,n){let r=lO(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?Jx(Ug(e,n,r),t.createRequiredOptionContracts):Ug(e,n,r);return{mergedSchema:r,filteredSchema:o}}function uO(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?Rx(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function pO(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Yn.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function od(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":Bg.get(t)??t}var fO=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"]]),_O=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function hO(e,t){let n=Og.get(e)??(e.includes(" ")?void 0:Og.get(od(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>ut(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=fO.get(o),c=_O.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function gO(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=zi(o,{generateFallback:!0}),a=o.split(" ")[0],c=Bg.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...Yg(o).map(f=>f.flag),...t.filter(f=>ut(f.command).includes(o)).flatMap(f=>f.flags.map(_=>_.flag))]),u=(xg.get(o)??xg.get(c)??vx).filter(f=>d.has(f)),p=hO(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 yO(e){return e.map(t=>({budget:zi(t,{generateFallback:!0}),envelope:ru(t)}))}function bO(e){let t=new Map;for(let n of e){let r=Ym(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 wO(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>ut(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(s=>ut(s.command).some(o=>r.has(o)))}return t.extensionContracts}function vO(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 kO(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:[...Om],services:[...Pm],policy_modes:[...Nm],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Mm],trust_modes:[...Lm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Fm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Ud],create_modes:[...Gd],close_validation_modes:[...jd],workflow_enforcement_modes:[...qd]},e.relationship_kind_contracts=[...Yd,...(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 SO(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 EO(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=Hx(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let o=new Set(r);e.list_projections=Object.entries(iu).filter(([i])=>o.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...ou],compact_fields:[...su]}))}e.command_aliases=s}}function AO(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=Wx();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function TO(e,t,n,r){e.command_summaries=gO(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Gm],allows_unbounded_opt_out:!0},e.grammar_contracts={nouns:qt.nouns,shared_verbs:qt.shared_verbs,scope_before_verb:qt.scope_before_verb,visible_top_level_ceiling:qt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:qt.ceiling_raise_requires_pm_item,positional_shape_budget:qt.positional_shape_budget,positional_shape_count:new Set($i.map(({slots:s})=>fl(s))).size,positional_action_count:Mi.length,positional_action_parents:[...new Set(Mi.map(({parent:s})=>s))].sort((s,o)=>s.localeCompare(o)),...r.includePositionalSignatures?{positional_signatures:$i}:{}}}async function Jg(e,t){let n=Xx(e);Qx(n);let r=E(process.cwd(),t.path),s=await eO(t,r),o=cO(n,s),i=mO(n,s,o),a=uO(n,o),c=pO(n,a),d=vO(n,i,o,c),u=wO(n,s,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&TO(d,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p}),n.summary)return d;let f=Vx(o.commandCatalog);return n.flagsOnly&&!n.fullOutput||kO(d,s,n),SO(d,n,i,u),EO(d,n,s,c,f),AO(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...np],gate_triggers:[...tp]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=pl),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=Ig(),d.context_intents=Jm(),d.read_output_dimensions=Bi,d.error_codes=Zm,d.command_output_contracts=yO(c),d.command_exit_contracts={vocabulary:Wm,command_sets:bO(c)}),d}import dP from"node:fs/promises";import fy 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 ri(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 CO(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)||(ri(f,i,p,s,"min")&&(i=f,s=p),ri(f,a,p,o,"max","max")&&(a=f,o=p))}return{id:e,bytes:n,lines:r,oldest_ts:s,newest_ts:o}}function Xg(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),s=e.map(({id:_,raw:h})=>CO(_,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);ri(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);ri(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 IO}from"node:crypto";import{execFile as xO}from"node:child_process";import ey from"node:path";import{promisify as OO}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 Qg=1;function RO(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 ad(e){if(e===null)return{format_version:Qg,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!==Qg||!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(!RO(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 PO=OO(xO),NO=50,Zg=1e3,LO=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function ty(e){let t=e.trim().toLowerCase();if(!LO.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 FO(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 Ar(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 MO(e){let t=e??NO;if(!Number.isSafeInteger(t)||t<0||t>Zg)throw new m(`Improvement observation limit must be an integer from 0 to ${Zg}.`,l.USAGE,{code:"invalid_improvement_observation_limit"});return t}function ny(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 $O(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=ty(n.metric),s=FO(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 UO(e,n.revision),i=Ar(n.source,"source"),a=Ar(n.itemId,"itemId"),c=Ar(n.unit,"unit"),d=Ar(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:ny(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:IO("sha256").update(J(u)).digest("hex").slice(0,24),...u}}function DO(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 UO(e,t){let n=Ar(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await PO("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Vd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function GO(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 ry(e,t={}){let n=E(process.cwd(),t.path);await C(n);let r=await A(n),s=await $O(n,r,e),o=ey.join(n,"improvement-ledger.json"),i=await Cu({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=ad(a),d=DO(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:`${J(c)}
47
- `,result:s})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function sy(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await C(t);let n=e.metric===void 0?void 0:ty(e.metric),r=e.since===void 0?void 0:ny(e.since,"since"),s=MO(e.limit),i=ad(await q(ey.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])=>GO(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 oy(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 jO(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 qO(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 cd(e=Jn,t=gn){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 KO(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 dd(e,t=gn,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 zO(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 BO(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=oy(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&&jO(o,i,r)?i.children.push(o):s.push(o)}return qO(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 HO=1e4,iy=1e5,VO=1e3,WO=30,YO=["append","comment","docs","file","learning","note","test_run"];function JO(e){let t=e??HO;if(!Number.isSafeInteger(t)||t<1||t>iy)throw new m(`History analytics event limit must be an integer from 1 to ${iy}.`,l.USAGE,{code:"invalid_history_analytics_limit"});return t}function ay(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 XO(e){let t=e?.trim();if(!t)return new Date(Date.now()-WO*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 cy(e,t){let n=JO(t.eventLimit),r=XO(t.since),s=[],o=r,i=!1;for(;s.length<n;){let a=await Yo({pmRoot:e,since:o,limit:Math.min(VO,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 QO(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function ZO(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 eP(e){return YO.some(t=>e.startsWith(t))}function dy(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 tP(e,t,n){let r=new Map,s=new Map,o=new Map;for(let i of t){let a=QO(i.entry,e),c=ZO(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=dy(r,a);p.events+=1,eP(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 nP(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&&(dy(e,i).defectEscapes+=1)}}}function rP(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 sP(e,t,n,r,s,o){let{buckets:i,lastCloseValue:a}=tP(e,t,r);return nP(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,d])=>rP(c,d,s,o)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function oP(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 iP(e,t,n){let r=cd(t),s=dd(e,gn,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 ly(e,t=Jn,n={}){let r=ay(n.minimumSample);return{...iP(e.events.map(s=>s.entry),t,r),window:e.receipt}}function my(e,t,n,r={}){let s=ay(r.minimumSample),o=oP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>sP(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 aP=32;function cP(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 Tr(e,t){let n=cP(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,aP)}function uy(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 py(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 lP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function mP(e,t,n,r,s){let o=sr(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=lP([...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 uP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function pP(e){let t=fy.join(e,"history");if(!await x(t))return[];await hn({path:t,scope:"project"});let n=(await dP.readdir(t)).filter(s=>s.endsWith(".jsonl")).sort((s,o)=>s.localeCompare(o)),r=[];for(let s of n){let o=fy.join(t,s),i=await q(o);i!==null&&(await hn({path:o,scope:"project"}),r.push({id:s.slice(0,-6),raw:i}))}return r}async function fP(e,t){let n=[],r=k();for(let s of Tr(t.observe,r))n.push(await ry({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 _P(e,t,n){let r={};return t.byAssignee&&(r.assignee=sr(e,"assignee",n)),t.byTag&&(r.tag=sr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=sr(e,"priority",n)),r}async function hP(e,t,n,r,s){let o={since:s.since,eventLimit:s.eventLimit,minimumSample:s.minimumSample},i=s.provenanceCoverage||s.fleetAttribution?await cy(e,o):void 0;return{provenanceCoverage:s.provenanceCoverage&&i?ly(i,n.agent_identity?.harness_signals,o):void 0,fleetAttribution:s.fleetAttribution&&i?my(i,t,r,o):void 0}}function gP(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 ld(e,t={}){let n=E(process.cwd(),e.path);await C(n);let r=await A(n),s=await fP(e,t),o=I(r,R()),i=$(r.schema),a=t.fieldUtilization?await xs(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 Ou({pmRoot:n,settings:r,itemIds:a.map(S=>S.id),commandLabel:"stats"});let c=to(i),d=mP(a,o.types,i.definitions.map(S=>S.id),c,t.includeEmpty===!0),u=await pP(n),p=0;for(let S of u)p+=uP(S.raw);let f=t.storage?Xg(u):void 0,_=t.metadataCoverage?nf(a,c):void 0,h=_P(a,t,c),y=t.fieldUtilization?rf(a):void 0,g=t.measurements===!0||s.length>0?await sy({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:b,fleetAttribution:v}=await hP(n,a,r,i.terminal_statuses,t);return gP({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 _y(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:be(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 yP from"node:fs/promises";import Mt 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 wy=Mt.join("runtime","telemetry","events.jsonl"),vy=Mt.join("runtime","telemetry","state.json"),bP=Mt.join("runtime","telemetry"),wP=20,hy=["status","flush","stats","clear"],gy=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},md=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,yy=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},vP=e=>({command:md(e.event.command,"<unknown>"),eventType:md(e.event.event_type,"unknown"),eventSchemaVersion:yy(e.event.schema_version),clientSchemaVersion:yy(e.client_schema_version)}),kP=()=>({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:{}}),SP=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},EP=e=>{let t=e?.command_resolution;return md(t,"")||void 0},ky=(e,t)=>{e[t]=(e[t]??0)+1},AP=(e,t)=>{let n=SP(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=EP(t);r!==void 0&&ky(e.resolution_counts,r)},TP=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,by=(e,t)=>{t!==void 0&&e.add(t)},CP=(e,t)=>{let n=vP(t),r=e.get(n.command)??kP();r.count+=1,r.max_attempts=Math.max(r.max_attempts,TP(t.attempts)),ky(r.event_type_counts,n.eventType),by(r.event_schema_versions,n.eventSchemaVersion),by(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&AP(r,t.event.payload),e.set(n.command,r)},RP=(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:gy(r,.5),duration_p95_ms:gy(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)}:{}}},IP=e=>{let t=(e??"status").trim().toLowerCase();if(hy.includes(t))return t;throw Te({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:hy,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},ud=()=>{throw new m("--limit must be a positive integer",l.USAGE)},Sy=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?ud():e,xP=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?ud():Sy(Number.parseInt(t,10))},OP=e=>e===void 0?wP:typeof e=="number"?Sy(e):typeof e=="string"?xP(e):ud(),PP=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},NP=e=>{try{let t=JSON.parse(e);return PP(t)?t:void 0}catch{return}},LP=e=>e===null?[]:e.split(`
48
- `).map(t=>t.trim()).filter(t=>t.length>0),Ey=e=>{let t=LP(e),n=[],r=0;for(let s of t){let o=NP(s);o===void 0?r+=1:n.push(o)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},FP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),MP=e=>{try{let t=JSON.parse(e);return FP(t)?t:{}}catch{return{}}},$P=async e=>{let t=await q(e);return t===null||t.trim().length===0?{}:MP(t)},si=e=>e??null,oi=async e=>{let t=await A(e),n=Mt.join(e,wy),r=Mt.join(e,vy),s=await q(n),o=Ey(s),i=await $P(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:si(i.last_attempted_flush_at),last_successful_flush_at:si(i.last_successful_flush_at),last_failed_flush_at:si(i.last_failed_flush_at),last_failed_flush_error:si(i.last_failed_flush_error)}},DP=e=>{let t=new Map;for(let n of e)CP(t,n);return[...t.entries()].map(([n,r])=>RP(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},UP=async(e,t)=>({action:"telemetry",subcommand:"status",status:await oi(t.globalPmRoot),generated_at:k()}),GP=async(e,t)=>{let n=await oi(t.globalPmRoot);await Wu(t.globalPmRoot);let r=await oi(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()}},jP=async(e,t)=>{let n=OP(e.limit),r=await q(t.queuePath),s=Ey(r),o=DP(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()}},qP=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 Ae(t.globalPmRoot,n,"telemetry:clear");let s=Mt.join(t.globalPmRoot,bP),o=await x(s);return await yP.rm(s,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:o&&!await x(s),queue_exists_after:await x(t.queuePath),state_exists_after:await x(t.statePath),status:await oi(t.globalPmRoot),generated_at:k()}},KP={status:UP,flush:GP,stats:jP,clear:qP};async function Ay(e,t){let n=IP(e.subcommand),r=tt(process.cwd());return KP[n](e,{globalPmRoot:r,queuePath:Mt.join(r,wy),statePath:Mt.join(r,vy)})}import{spawn as zy}from"node:child_process";import{cp as xy,mkdir as WP,mkdtemp as By,open as hd,readdir as gd,rm as Hy}from"node:fs/promises";import{tmpdir as Vy}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 Ty=20;function zP(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return Ty;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?Ty:t}function pd(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=bn(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=zP();return t.length>n?t.slice(t.length-n):t}async function ii(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=pd([...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 Cy=100;function fd(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 BP(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Cy?n:`${n.slice(0,Cy-3)}...`}function Ry(e){return e.map((t,n)=>`${n+1}. ${BP(t)}`).join("; ")}function HP(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 VP(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Iy(e,t){let n=HP(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)VP(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: ${Ry(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=fd(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: ${Ry(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]="2354c553-3a81-59d8-9c0a-3d19cd3cedd2")}catch{}})();var ci=20*1024*1024,YP=3e3,JP=1e4,XP=5e3,Oy=120,QP=new Set(["locks","extensions","runtime"]),ZP=new Set(["history","index","search","extensions","locks","runtime"]),eN=[/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],tN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,nN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,rN=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 wd(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 sN(){return wd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",YP)}function oN(){return wd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",JP)}function iN(){return wd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",XP)}function aN(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 cN(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 vd(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 dN(e){let t=e??"project";if(!et.includes(t))throw new m(`Invalid scope "${e}"`,l.USAGE);return t}function di(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Qt.includes(t))return t;throw new m(`Invalid --pm-context value "${e}". Expected one of: ${Qt.join(", ")}`,l.USAGE)}function Wy(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:di(e.pm_context_mode)}function Yy(e,t){return e==="auto"?t?"tracker":"schema":e}function lN(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 mN(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 uN(e,t){let n={};if(!e)return n;for(let r of e){let s=mr(r,t);if(s)for(let[o,i]of Object.entries(s))n[o]=i}return n}function pN(e,t){if(!e)return[];let n=[];for(let r of e){let s=ur(r,t);s&&n.push(...s)}return[...new Set(n)]}function fN(e){let t=li(e);return nr(t).some(n=>ba(n)!==null)}function Jy(e){let t=li(e);return nr(t).some(n=>{let r=ba(n);if(!r)return!1;let s=Zp(r);return s?rN.has(s.subcommand):!1})}function ai(e){if(e)return Jp.has(e.subcommand)?In(e.args,Xp)?.subcommand:e.subcommand}function Py(e,t){if(e==="npx"||e==="bunx")return Zs(t)?.command;if(e==="pnpm")return ai(In(t,Hp));if(e==="npm")return ai(In(t,Vp));if(e==="yarn")return ai(In(t,Wp));if(e==="bun")return ai(In(t,Yp))}function Ny(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function _d(e){return!e||!va(e.command)&&!Qp(e.command)?!1:Qs(e.args)==="test-all"}var _N=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])]),hN=new Set(["npx","bunx"]);function Xy(e){let t=e.split(" ").filter(i=>i.length>0),n=wa(t);if(n.length===0)return!1;let[r,...s]=n,o=_N.get(r);if(o){let i=s.findIndex(a=>o.test(a));return i>=0?Xy(s.slice(i+1).join(" ")):!1}return va(r)||ka(r)?Qs(s)==="test-all":r==="node"&&s.length>0&&ka(s[0])?Qs(s.slice(1))==="test-all":hN.has(r)?_d(Zs(s)):r==="pnpm"?_d(Sa(s)):r==="npm"?_d(Ea(s)):!1}function Qy(e){let t=li(e);return nr(t).some(n=>Xy(n))}function Zy(e){if(Qy(e))throw new m('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',l.USAGE)}function li(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function gN(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 yN(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 bN(e){let t=e.split(" ").filter(o=>o.length>0),n=wa(t);if(n.length===0)return!1;let[r,...s]=n;return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?wN(s):vN(r,s)}function wN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function vN(e,t){return e==="npx"||e==="bunx"?Ny(Zs(t)?.command):e==="pnpm"||e==="npm"?Ny((e==="pnpm"?Sa(t):Ea(t))?.command)||Py(e,t)==="vitest":(e==="yarn"||e==="bun")&&Py(e,t)==="vitest"}function eb(e){let t=li(e);if(nr(t).some(s=>!gN(s)&&bN(s)&&!yN(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 kN(e){if(Qy(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function SN(e){return e?e.map(EN):[]}function EN(e){let t=e.trim(),n=So(t)?Eo(ne(e,"--add"),"--add"):{command:t},r=le(n.command);if(!r)throw new m("--add requires command=<value> or a bare command (path=<value> is optional metadata)",l.USAGE);return Zy(r),eb(r),{command:r,path:le(n.path),scope:dN(n.scope),timeout_seconds:AN(le(n.timeout_seconds),le(n.timeout)),pm_context_mode:Io(le(n.pm_context_mode),"--add"),env_set:mr(le(n.env_set),"--add"),env_clear:ur(le(n.env_clear),"--add"),shared_host_safe:Ro(le(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:en(le(n.assert_stdout_contains)),assert_stdout_regex:Ln(le(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:en(le(n.assert_stderr_contains)),assert_stderr_regex:Ln(le(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:xo(le(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Oo(le(n.assert_json_field_equals),"--add"),assert_json_field_gte:Po(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 AN(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(ie(n,"timeout_seconds"));if(r<=0)throw new m("--add timeout_seconds must be a positive integer",l.USAGE);return r}function TN(e){return e?e.flatMap(t=>{let n=zf(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);Zy(s),eb(s)}return n}):[]}function CN(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=ne(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 RN(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 IN(e){try{e.stdin?.end()}catch{}}function tb(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=Oy?t:`${t.slice(0,Oy-3)}...`}function nb(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function yd(e){try{process.stderr.write(`${e}
49
- `)}catch{}}function xN(e,t){if(!nb(t))return null;let n=tb(e.command),r=Date.now();yd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let s=setInterval(()=>{let o=Date.now()-r;yd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${o} command="${n}"`)},oN());return s.unref?.(),s}function ON(e,t,n,r){if(!nb(r))return;let s=tb(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(" ")}`:"";yd(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${d} elapsed_ms=${o}${u} command="${s}"`)}async function Ly(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=zy("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 PN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function NN(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 Ly(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{Ly(r)},sN()),t.forceKillTimer.unref?.()}}function LN(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)},iN()),r.unref?.())}),e.on("close",(o,i)=>{s({code:o,signal:i})})})}function FN(e,t,n,r){return zy(e,{cwd:process.cwd(),env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function Fy(e){let t=await hd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,ci),s=Buffer.alloc(r);return r>0&&await t.read(s,0,r,0),{text:s.toString("utf8"),truncated:n>ci}}finally{await t.close()}}async function MN(e,t,n,r,s){let o=Date.now(),i=await By(me.join(Vy(),"pm-linked-test-output-"));try{let a=me.join(i,"stdout.log"),c=me.join(i,"stderr.log"),[d,u]=await Promise.all([hd(a,"w"),hd(c,"w")]),p;try{p=FN(e,n,d.fd,u.fd)}finally{await Promise.all([d.close(),u.close()])}IN(p);let f={heartbeat:xN(r,s),forceKillTimer:null,timedOutTimer:null},_=NN(p,f),h=!1,y;p.on("error",M=>{y=M.message}),f.timedOutTimer=setTimeout(()=>{h=!0,_()},t),f.timedOutTimer.unref?.();let{code:g,signal:b}=await LN(p);PN(f);let[v,S]=await Promise.all([Fy(a),Fy(c)]),N=v.truncated||S.truncated,O=N?`
50
- [pm linked-test output truncated at ${ci} 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:N,spawnError:y};return ON(r,j,o,s),j}finally{await Hy(i,{recursive:!0,force:!0})}}function $N(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${ci} 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 DN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
52
- `);return eN.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>tN.test(n)&&nN.test(n))}function UN(e){return DN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function GN(){return{infra_collision:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function mi(e){let t=GN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function My(e,t){for(let[n,r]of Object.entries(t.env_set))Zt.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)Zt.has(n.toUpperCase())||delete e[n]}function jN(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 qN(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 KN(e,t,n){return{env_set:uN(e,"--env-set"),env_clear:pN(t,"--env-clear"),shared_host_safe:n===!0}}async function jn(e,t,n=!1,r=WP){if(await x(e))try{await Jo("seed_linked_test",async()=>{if(await r(me.dirname(t),{recursive:!0}),n){await xy(e,t,{recursive:!0,force:!0});return}await xy(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&&vt(s))return;throw s}}async function $y(e,t,n){await jn(ge(n.projectPmRoot),ge(e)),await jn(me.join(n.projectPmRoot,"extensions"),me.join(e,"extensions"),!0),await jn(ge(n.globalPmRoot),ge(t)),await jn(me.join(n.globalPmRoot,"extensions"),me.join(t,"extensions"),!0)}async function Dy(e,t){if(!await x(e))return;let n=await gd(e,{withFileTypes:!0});for(let r of n){if(QP.has(r.name))continue;let s=me.join(e,r.name),o=me.join(t,r.name);if(r.isDirectory()){await jn(s,o,!0);continue}r.isFile()&&await jn(s,o)}}async function Gn(e){if(!await x(e))return 0;let t=0,n=await gd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||ZP.has(r.name))continue;let s=me.join(e,r.name),o;try{o=await gd(s,{withFileTypes:!0})}catch{continue}for(let i of o)i.isFile()&&Hd.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function zN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function BN(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 Uy(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=BN(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 HN(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 VN(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?nt(e,t):Object.is(e,t)}function WN(e,t,n){let r=[];r.push(...Gy("stdout",t,e.assert_stdout_contains)),r.push(...jy("stdout",t,e.assert_stdout_regex)),r.push(...Gy("stderr",n,e.assert_stderr_contains)),r.push(...jy("stderr",n,e.assert_stderr_regex)),r.push(...YN(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=Uy(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=HN(d);VN(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=Uy(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 Gy(e,t,n){let r=[];for(let s of n??[])t.includes(s)||r.push(`${e} missing required text: "${s}"`);return r}function jy(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 YN(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 JN=[{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 XN(e,t){let n=`${e}
53
- ${t}`;for(let r of JN)if(r.regex.test(n))return r.code;return null}function QN(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 ZN(e,t=gr,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 eL(e,t,n){t&&(await $y(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await $y(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Dy(t.projectPmRoot,e.trackerProjectPmPath),await Dy(t.globalPmRoot,e.trackerGlobalPmPath)))}function tL(e,t,n){return e.some(r=>{let s=r.command??"",o=s.length>0&&Jy(s),i=n?.autoPmContext===!0&&o?"auto":Wy(r,t,n?.overrideLinkedPmContext===!0);return Yy(i,o)==="tracker"})}async function nL(e,t){return{sourceProjectItemCount:t?await Gn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Gn(t.globalPmRoot):0,schemaProjectItemCount:await Gn(e.schemaProjectPmPath),schemaGlobalItemCount:await Gn(e.schemaGlobalPmPath),trackerProjectItemCount:await Gn(e.trackerProjectPmPath),trackerGlobalItemCount:await Gn(e.trackerGlobalPmPath)}}function rL(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 sL(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?di(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?fN(n):!1,s=r&&n?Jy(n):!1,o=e.options?.autoPmContext===!0&&s,i=o?"auto":Wy(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Yy(i,s);return{linkedOverridePmContextMode:t,executionContext:rL({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:s,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:o})}}function qy(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function bd(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 oL(e){if(!e.linkedTest.command)return qy(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=kN(e.linkedTest.command);if(t)return qy(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=mN({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 bd(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&&!lN(e.linkedTest)?bd(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function iL(e){let t=qN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return My(n,e.runtimeDirectives),My(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&jN(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[Js]="read_only",n}function aL(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 cL(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 dL(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:zN(e.execution),failure_category:UN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:$N(e.execution,e.timeoutMs)}}function lL(e){if(e.options?.failOnEmptyTestRun===!0){let n=XN(e.execution.stdout,e.execution.stderr);if(n)return cL({...e,emptyRunSignal:n})}let t=WN(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?bd(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):aL(e.linkedTest,e.executionContext,e.execution)}async function mL(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await MN(t,n,iL(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?lL({...e,execution:r}):dL({...e,execution:r,timeoutMs:n})}async function kd(e,t,n){let r=[],s=await By(me.join(Vy(),"pm-linked-test-")),o=QN(s),i=di(n?.pmContext),a=n?.progress===!0?"always":"auto",c=KN(n?.envSet,n?.envClear,n?.sharedHostSafe),d=n?.sourceRoots,u=tL(e,i,n);try{await ZN(o,gr,u),await eL(o,d,u);let p=await nL(o,d);for(let f=0;f<e.length;f+=1){let _=e[f],h=sL({linkedTest:_,layout:o,counts:p,sourceRoots:d,runLevelPmContextMode:i,options:n}),y=oL({linkedTest:_,executionContext:h.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:h.linkedOverridePmContextMode,options:n});if(y){r.push(y);continue}r.push(await mL({linkedTest:_,index:f,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:c,progressMode:a,executionContext:h.executionContext,options:n}))}}finally{await Hy(o.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function uL(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 pL(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode}function fL(e,t){let n=[...e];for(let r of t)n.some(s=>pL(s,r))||n.push(r);return n}function _L(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 hL(e,t,n,r){return _L(fL(e,t),n,r)}function gL(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 yL(e){if(gL(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 bL(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 uL({id:t,pmRoot:r,settings:s,typeToFolder:o});let d=0,u=await Z({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??[],_=hL(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:nt(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 wL(e,t){yL(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:fd(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?Iy(t,n):void 0,s=e.timeout===void 0?void 0:ie(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:di(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function vL(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await kd(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:tt(process.cwd())}})}function kL(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=vd(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 SL(e){let t=cN(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=Tr(e.options.measure,s);return{run_id:aN("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 EL(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=SL({options:t,runStartedAt:o,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return d;try{return await ii({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 Ky(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=uy(t,o,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:py(t,e.metricDiff)}}async function ui(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);Tr(t.measure,"validation"),Ky(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=[...SN(a),...TN(c)],p=CN(d),f=RN(t.removeIndex),_=await bL({id:e,options:t,pmRoot:s,settings:o,typeToFolder:i.type_to_folder,adds:u,removes:p,removeIndexes:f}),h=wL(t,_.tests),y=t.run===!0?k():void 0,g=await vL({options:t,runOptions:h,pmRoot:s}),b=mi(g),v=t.run===!0&&t.failOnSkipped===!0&&g.some(M=>M.status==="skipped"),S=kL(t,h.runSelection,g),N=await EL({options:t,pmRoot:s,settings:o,itemId:_.itemId,runStartedAt:y,runResults:g,failOnSkippedTriggered:v,warnings:S}),O=N?pd([..._.testRuns,N]):_.testRuns,j=Ky(t,O,N);return{ok:g.every(M=>M.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]="aeb0a1a7-bc73-5c56-bbed-9472c651b5f6")}catch{}})();var AL=(e,t)=>{if(e===void 0)return;let n=W(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},TL=e=>{if(e===void 0)return;let t=ie(e,"timeout");if(t<=0)throw new m("timeout must be a positive number",l.USAGE);return t},rb=(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},CL=e=>e instanceof Error?e.message:String(e),RL=()=>{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)}`},IL=e=>e.trim().replaceAll(/\s+/g," "),xL=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),OL=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),PL=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},pi=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),sb=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),NL=e=>typeof e=="number"?e:void 0,LL=e=>{let t={assert_stdout_contains:pi(e.assert_stdout_contains),assert_stdout_regex:pi(e.assert_stdout_regex),assert_stderr_contains:pi(e.assert_stderr_contains),assert_stderr_regex:pi(e.assert_stderr_regex),assert_stdout_min_lines:NL(e.assert_stdout_min_lines),assert_json_field_equals:sb(e.assert_json_field_equals),assert_json_field_gte:sb(e.assert_json_field_gte)};return JSON.stringify(t)},FL=e=>{let t=Sd(e.command);return t!==void 0?`command:${e.scope}:${IL(t)}`:`path:${e.scope}:${Sd(e.path)??""}`},ob=e=>{let t=xL(e.env_set),n=OL(e.env_clear),r=PL(e.pm_context_mode),s=e.shared_host_safe===!0?"true":"false",o=LL(e);return`${FL(e)}:${t}:${n}:${r}:${s}:${o}`},ML=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,$L=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}},DL=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},fi=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
54
- `)}catch{}},UL=async(e,t,n)=>{let r=[],s=0;for(let o of e){let i=await ui(o.id,{run:!1},{...t,path:n});s+=i.tests.length,r.push({item:o,tests:i.tests})}return{itemTests:r,linkedTests:s}},GL=async e=>{let t=$(e.settings.schema),n=I(e.settings,R()),r=AL(e.options.status,t),s=rb(e.options.limit,"--limit"),o=rb(e.options.offset,"--offset")??0,a=(await oe(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}},jL=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let s=ob(r);if(!t.has(s)){t.set(s,r.timeout_seconds);continue}t.set(s,ML(t.get(s),r.timeout_seconds))}return t},qL=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=ob(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 kd(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=$L(i),c=mi(i),d=await BL(e,a,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}}},KL=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),zL=e=>e?!0:void 0,BL=async(e,t,n)=>{if(!n.trackingEnabled)return[];try{let r=KL(t,n.options);await ii({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:k(),recorded_at:k(),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:zL(n.options.failOnSkipped===!0&&t.skipped>0)}})}catch(r){return[`test_result_tracking_failed:${e.item.id}:${CL(r)}`]}return[]},HL=()=>{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},Sd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},VL=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:tt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:jL(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:T(e.options.author,e.settings.author_default),trackingRunId:RL(),trackingAttempt:HL(),trackingResumedFrom:Sd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),WL=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:mi([]),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}},YL=async(e,t,n)=>{for(let[r,s]of e.entries()){fi(t.options,`item ${r+1}/${e.length} start id=${s.item.id} linked_tests=${s.tests.length}`);let o=await qL(s,t);DL(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),fi(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}`)}},JL=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(s=>s.run_results),r=vd(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}`)},XL=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}),QL=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(" "),ZL=async(e,t)=>{let n=E(process.cwd(),t.path);await C(n);let r=await A(n),s=await GL({pmRoot:n,settings:r,options:e}),o=TL(e.timeout),i=k(),a=await UL(s.filteredItems,t,n);return fi(e,QL({...s,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:s.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:o,runStartedAt:i}},eF=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}},ib=async(e,t)=>{let n=await ZL(e,t),{accumulation:r,failOnEmptyTestRunTriggered:s}=WL(e,n.linkedTests,n.filteredItems),o=VL({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await YL(n.itemTests,o,r),JL(e,r);let i=eF({options:e,accumulation:r,failOnEmptyTestRunTriggered:s});return fi(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),XL({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 ab(){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 db=[{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"]}],cb=new Map;for(let e of db){cb.set(e.id,e);for(let t of e.aliases)cb.set(t,e)}function Ed(){return db.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=[...xr],AB=[...Or],tF=new Set(Yn.filter(e=>e.hidden).map(e=>e.alias)),TB=nu("full").filter(e=>!tF.has(e)),CB=F(qr),RB=F(Kr),IB=F(Jr),xB=F(ts),OB=F(ns),PB=F(Zl),NB=F(em),LB=F(es),FB=F(is),MB=F(rs),$B=F(ss),DB=F(Yr),UB=F(os),GB=F(zr),jB=F(Br,!1),qB=F(mm),KB=F(Vn),zB=F(Wn),BB=F(ls),HB=F(cs),VB=F(Qr),WB=F(ds),YB=F(as),JB=F(ms),XB=F(Xr),QB=F(Zr),ZB=F(Vr),eH=F(us),tH=F(Hr);var nF=F(ps),nH=`${nF} bash zsh fish`,rH=rF(Ed());var sH=F(Wr),oH=F(Hn);var iH=jr.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function rF(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]="c770afea-3eb6-5476-ba07-8ec1c5d9c699")}catch{}})();var pb=Symbol("pm.active-extension-host-context");function xe(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[pb]=!0,n}run(t,n={}){return fb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return df(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return ia(await this.list(oa(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,...xe({...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",xe(t))}update(t,n={}){return this.runTyped("update",{id:t,...xe(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,...xe(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...xe(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...xe(t)})}release(t,n={}){return this.runTyped("release",{id:t,...xe(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...xe(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...xe(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},...xe(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...xe(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...xe(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...xe(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 oF(e={},t={}){return new G(t).context(e)}function iF(e={},t={}){return new G(t).list(e)}function aF(e={},t={}){return new G(t).listAllComplete(e)}function cF(e,t={},n={}){return new G(n).search(e,t)}function dF(e,t={},n={}){return new G(n).get(e,t)}function lF(e={},t={}){return new G(t).next(e)}function mF(e={},t={}){return new G(t).aggregate(e)}function uF(e,t={},n={}){return new G(n).comments(e,t)}function pF(e,t={},n={}){return new G(n).notes(e,t)}function fF(e,t={},n={}){return new G(n).learnings(e,t)}function _F(e,t={},n={}){return new G(n).files(e,t)}function hF(e,t={},n={}){return new G(n).filesDiscover(e,t)}function gF(e,t={},n={}){return new G(n).docs(e,t)}function yF(e,t={},n={}){return new G(n).deps(e,t)}function bF(e,t={},n={},r={}){return new G(r).graph(e,t,n)}function wF(e,t,n={},r={}){return new G(r).append(e,t,n)}function vF(e={},t={}){return new G(t).create(e)}function kF(e,t={},n={}){return new G(n).update(e,t)}function SF(e,t,n={},r={}){return new G(r).reopen(e,t,n)}function EF(e,t,n={},r={}){return new G(r).close(e,t,n)}function AF(e,t={},n={}){return new G(n).claim(e,t)}function TF(e={},t={}){return new G(t).claimNext(e)}function CF(e,t={},n={}){return new G(n).release(e,t)}function RF(e,t={},n={}){return new G(n).copy(e,t)}function IF(e,t={},n={}){return new G(n).delete(e,t)}function xF(e,t,n={},r={}){return new G(r).restore(e,t,n)}function OF(e,t={},n={}){return new G(n).focus(e,t)}function Qe(e,t){let n=w(e,t);if(!n)throw new m(`Missing required argument: ${t}`,64);return n}var lb=au(),PF=new sF;function _i(){Yi(Zd()),Ji(el()),Xi(tl()),Qi(nl()),Zi(rl()),ea(sl()),ta(ol())}async function NF(e,t,n,r){return cu(()=>t===void 0?lb.read(()=>mb(e,n,r)):lb.write(()=>FF(t,()=>mb(e,n,r))))}async function mb(e,t,n){let r=E(t,e.path);if(e.noExtensions)return _i(),Ma({pmRoot:r},()=>n(null));if(!await x(ge(r)))return _i(),n(null);let s=null,o;try{let i=await A(r),a=await Ur({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Gr({...a,loaded:a.loaded});o={loadResult:a,activationResult:c},Yi(c.hooks),Ji(c.commands),Xi(c.parsers),Qi(c.preflight),Zi(c.services),ea(c.renderers),ta(c.registrations),s={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){_i(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Ma({pmRoot:r,packages:s?.packages},()=>n(s))}finally{_i(),o&&await il(o.loadResult,o.activationResult).catch(()=>{})}}async function LF(e,t,n,r,s){if(!s)throw new m(`Unsupported native pm action: ${e}`,l.USAGE);let o=Vt(e),a=s.registrations.commands.find(d=>Vt(d.action)===o)?.command??s.commands.handlers.find(d=>Vt(d.command)===o)?.command;if(!a)throw new m(`Unsupported native pm action: ${e}`,l.USAGE);let c=await Ss({command:fa(a),args:be(n.args??t.args),options:_a(t,n),global:r,pm_root:s.pmRoot,sdk:pf(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 FF(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var MF=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function $F(e){let t=Qe(e,"action"),n=Vt(t),r=gi(mf,n),s=r?.action??n,o={...e,action:s};return r?.options!==void 0&&(o.options={...r.options,...Fi(e.options)}),s==="package"&&(o.options={...Fi(o.options),vocabulary:"package"}),{action:s,args:o}}function DF(e){return!MF.has(Vt(e))}async function fb(e){let t=$F(e),n=ma(t.args),r=DF(t.action),s=w(t.args,"cwd"),o=s??process.cwd();try{return e[pb]===!0||PF.getStore()===!0?await ub(t.action,t.args,n,null):await NF(n,s,o,i=>ub(t.action,t.args,n,i))}finally{r&&Pa()}}function gi(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function hi(e){return w(e.args,"target")??w(e.options,"target")}function Y(e,t=e.options){return e.id??Qe(t,"id")}async function UF(e){let t=fn("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),Oa(await xt(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function GF(e){let t=Qe(e.args,"query"),n=fn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Oa(await ir(t,n,e.global),n)}async function jF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return je(await Ot(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function qF(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 Sc(Y(e,s),s,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function KF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return je(await ct(Y(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function zF(e){let t=co(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")),If(Y(e),t,e.global)}function _b(e,t){return Bp(Cg(e.options,t,Me),e.global)}function BF(e){let t=be(e.options.lookupPath);if(t&&t.length>0)return _b(e,t);let n=Y(e);return e.options.discover===!0?ya(n,pa(e.options),e.global):zp(n,Ys(e.options),e.global)}function HF(e){return Ay({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:dp(e.args,e.options)},e.global)}function VF(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),qp(e.global,t)}function WF(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 Z_(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 YF(e){let t=e.options;return ep(Zu(t),e.global)}function JF(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 XF(e){let t=w(e.args,"subcommand")??Qe(e.options,"subcommand"),n=e.options;return O_({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:QF(e),reorderTo:JF(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function QF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function ZF(e){let t=w(e.args,"subcommand")??Qe(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:be(n)}}function eM(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,a=gi({list:()=>Tp(t.global),show:()=>Cp(r,t.global),"show-status":()=>Rp(r,t.global),"list-fields":()=>Op(t.global),"show-field":()=>Pp(r,t.global),"remove-type":()=>kp(r,{author:s,force:o},t.global),"remove-field":()=>xp(r,{author:s,force:o},t.global),"remove-status":()=>Ap(r,{author:s,force:o},t.global),"apply-preset":()=>Np(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:s,force:o},t.global)},n);return a?a():null}function tM(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 Ip(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:be(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:be(a),author:r,force:s},t.global)}function nM(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e,i=t.args.role??t.options.role;return Ep(n,{role:i===void 0?void 0:be(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 rM(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e;return vp(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 sM(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,i=w(t.args,"to")??Qe(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 bp(d,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:s,force:o},t.global)}function oM(e){let t=ZF(e),n=eM(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return sM(t);if(t.subcommand==="add-field")return tM(t);if(t.subcommand==="add-status")return nM(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Lp({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):rM(t);throw Te({command_path:"schema",token:t.subcommand,allowed:wp,exit_code:64})}function iM(e){let t=w(e.args,"subcommand")??Qe(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),o=gi({list:()=>ug(),show:()=>pg(r),lint:()=>fg(r),apply:()=>_g(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:mg,exit_code:64});return o()}async function aM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return je(await _f(Y(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function cM(e){let{changedFields:t,runnerOptions:n}=$e(e.args,e.options);return je(await b_(ga(n),e.global),{changedFields:t})}async function dM(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 Rf(ha(s),e.global),{changedFields:t})}async function lM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options),s=w(r,"target")??Qe(e.args,"target");return je(await Yt(Y(e,r),s,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function hb(e){let t={...e};return delete t.assignee,t}async function mM(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=ei($(n.schema)),s=Y(e),o=await mo(s,e.force,e.global,e.options),i=await ct(s,{...hb(e.options),status:r,force:e.force},e.global);return{id:s,action:"start_task",claim:o,update:i}}async function uM(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=Y(e),s=$(n.schema).open_status,o=await ct(r,{...hb(e.options),status:s,force:e.force},e.global),i=await uo(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:o,release:i}}async function pM(e){let t=Y(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await at(t,n,{...e.options,force:e.force},e.global),s=await uo(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:s}}function fM(e){let t={...e.args,...e.options};return op(Qe(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),up(t),e.global)}function _M(e){return fp(E(process.cwd(),e.global.path),{...e.args,...e.options})}var hM={init:e=>gr(w(e.args,"prefix"),e.global,e.options),context:e=>Ra(fn("context",e.options),e.global),next:e=>or(fn("next",e.options),e.global),eval:eg,events:tg,merge:ng,workspace:rg,meet:Qo,event:Qo,remind:Qo,list:UF,get:e=>{let t=Y(e);return Ia(t,e.global,fn("get",e.options,[t]))},search:GF,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:be(e.options.status);return xa(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:jF,copy:qF,focus:e=>Ac(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:KF,"item-reopen":Tg,restore:lM,claim:e=>e.options.next===!0||e.args.next===!0?kf(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):mo(Y(e),e.force,e.global,e.options),release:e=>uo(Y(e),e.force,e.global,e.options),"start-task":mM,"pause-task":uM,"close-task":pM,close:Ag,comments:zF,notes:e=>Of(Y(e),co(e.options),e.global),learnings:e=>xf(Y(e),co(e.options),e.global),files:BF,docs:e=>Kp(Y(e),Ys(e.options),e.global),test:e=>ui(Y(e),e.options,e.global),"test-all":e=>ib(e.options,e.global),telemetry:HF,validate:e=>eo(e.options,e.global,{runUpdate:(t,n,r)=>ct(t,n,r)}),health:VF,assurance:e=>ef(e.args,e.options,e.global),contracts:e=>Jg(e.options,e.global),config:WF,activity:YF,aggregate:e=>Aa(e.options,e.global),extension:e=>Rn(hi(e),e.options,e.global),package:e=>Rn(hi(e),e.options,e.global),install:e=>Rn(hi(e),{...e.options,install:!0},e.global),upgrade:e=>of(hi(e),e.options,e.global),delete:e=>Ec(Y(e),e.options,e.global),deps:e=>sp(Y(e),e.options,e.global),graph:fM,"files-discover":e=>ya(Y(e),e.options,e.global),"files-lookup":e=>_b(e,be(e.options.paths)),history:e=>sf(Y(e),e.options,e.global),"history-redact":e=>$u(Y(e),e.options,e.global),"history-repair":vg,"history-compact":kg,"history-author-acknowledge":_M,plan:XF,schema:oM,profile:iM,stats:e=>ld(e.global,_y(e.options)),append:aM,"update-many":cM,"close-many":dM,gc:e=>af(e.global,e.options)};async function ub(e,t,n,r){let s=ua(t,e);Hi(e,s),jm(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=gi(hM,e),a=i?await i(o):await LF(e,t,s,n,r);return s.resolvedOutputFormat="json",Qm(e,s,a)}var gM={closeManyOptionsFromFlat:ha,extensionOptionsFromArgs:_a,globalOptions:ma,mutationListOptions:mp,normalizeActionName:Vt,normalizeCommandPath:fa,normalizeMcpUpdateOptions:pp,normalizeMcpOptionsArrays:lp,optionsWithAuthor:ua,readRequiredString:Qe,readScalarString:ap,readScalarStringAllowBlank:cp,readStringArray:be,updateManyOptionsFromFlat:ga,withAddNoteOption:Ys,withFilesDiscoveryOptions:pa,withMutationCompaction:$e};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=gM);(function(){try{var e=typeof window<"u"?window:typeof 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{gn as AGENT_PROVENANCE_DIMENSIONS,uu as BASELINE_ITEM_FORMAT_VERSION,Jn as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,xr as BUILTIN_ITEM_TYPE_VALUES,Pr as CONFIDENCE_TEXT_VALUES,pu as CURRENT_ITEM_FORMAT_VERSION,Ut as DEPENDENCY_KIND_VALUES,l as EXIT_CODE,ln as ISSUE_SEVERITY_VALUES,Dd as ITEM_TYPE_VALUES,Na as PM_CLI_EXPECTED_ERROR_NAME,lw as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,cw as PM_READ_OUTPUT_DIMENSIONS,dw as PM_READ_OUTPUT_OPTION_FLAGS,Bi as PM_READ_OUTPUT_SURFACE_CONTRACTS,m as PmCliError,G as PmClient,dn as RISK_VALUES,Ow as SEMANTIC_ATTRIBUTION_LIMITS,Or as STATUS_VALUES,ww as agentSessionEnvironment,mF as aggregate,cd as analyzeAgentProvenanceDescriptorCoverage,hw as analyzeSdkCliParameterCompleteness,wF as append,pw as applyReadOutputDimensions,rw as applyReadOutputSessionReferences,sw as attachReadOutputSessionReceipt,gw as boundAgentEpisodeIdentity,Ye as canonicalDocument,AF as claim,TF as claimNext,hu as classifyItemFormatVersion,EF as close,uF as comments,oF as context,RF as copy,vF as create,uf as createPmCliExpectedError,aw as decodeReadOutputContinuationCursor,IF as deleteItem,yF as deps,Ew as detectAgentIdentity,Cw as detectHarnessIdentity,Aw as diagnoseAgentIdentity,gF as docs,fu as effectiveItemFormatVersion,ab as emptyImportedDocument,iw as encodeReadOutputContinuationCursor,zO as evaluateSemanticAttributionCoverage,Iw as explainSourceTraceability,_F as files,hF as filesDiscover,OF as focus,dF as get,bF as graph,BO as groupHistoryByEpisode,vf as isAlreadyClaimedError,oo as isPmCliExpectedError,fw as isReadOutputBudgetExceeded,fF as learnings,iF as list,aF as listAllComplete,lF as next,_u as normalizeItemFormatVersion,ye as normalizeItemId,W as normalizeStatusInput,pF as notes,k as nowIso,nw as parseReadOutputSession,Xs as parseSourceLineRange,As as readAuthorEnvironment,ow as readOutputSessionRemainingTokens,Ta as recordClaimSemanticAttribution,no as recordFocusSemanticAttribution,Ca as recordReleaseSemanticAttribution,vw as registerHarnessSignalDescriptors,CF as release,SF as reopen,yw as resolveAgentSessionContextFromSignals,Rw as resolveAuthorIdentity,oy as resolveHistoryEpisodeGroupIdentity,uw as resolveReadOutputDimensions,_w as resolveReadOutputEncoding,mw as resolveReadOutputSurface,xw as resolveSemanticLineageIds,xF as restore,fb as runAction,bw as runWithAgentSessionContext,kw as runWithHarnessDetectionSignals,Sw as runWithWorkspaceHarnessSignalDescriptors,cF as search,Pw as semanticAttributionAffinity,qe as serializeItemDocument,KO as summarizeAgentModelProvenance,dd as summarizeAgentProvenance,kF as update,Hi as validateReadOutputOptions,Tw as writeAuthorEnvironment};
40
+ `}function TI(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Gh(e,t,n){Zc(e,"base");let r=Zc(t,"ours"),o=Zc(n,"theirs"),s=Math.min(r.length,o.length),i=0;for(;i<s&&r[i].eventId===o[i].eventId;)i+=1;if(i===r.length&&i===o.length)return{merged:ei(r),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===o.length)return{merged:ei(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:ei(o),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:o.length-i,entries_total:o.length,reanchored:!1};let a=r.slice(i),c=new Set(a.map(f=>f.eventId)),d=o.slice(i).filter(f=>!c.has(f.eventId)),u=[...a,...d].sort((f,_)=>{if(f.timestamp!==void 0&&_.timestamp!==void 0){let g=Sn(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=TI([...r.slice(0,i),...u]);return{merged:ei(p),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:d.length,entries_total:p.length,reanchored:!0}}var CI=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],RI=["updated_at"];function ln(e,t){return J(e??null)===J(t??null)}function II(e,t,n){let r=u=>Array.isArray(u)?u:[],o=new Set(r(e).map(u=>J(u))),s=r(t),i=new Set(s.map(u=>J(u))),a=r(n),c=new Set(a.map(u=>J(u))),d=s.filter(u=>{let p=J(u);return!o.has(p)||c.has(p)});for(let u of a){let p=J(u);!i.has(p)&&!o.has(p)&&d.push(u)}return d}function Sr(e){if(typeof e!="object"||e===null||Array.isArray(e))return J(e);let{provenance:t,...n}=e;return J(n)}function xI(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function OI(e,t,n){let r=u=>Array.isArray(u)?u:[],o=new Set(r(e).map(Sr)),s=r(t),i=new Set(s.map(Sr)),a=r(n),c=new Set(a.map(Sr)),d=s.filter(u=>{let p=Sr(u);return!o.has(p)||c.has(p)});for(let u of a){let p=Sr(u);!i.has(p)&&!o.has(p)&&d.push(xI(u))}return d}function PI(e,t){return Sn(String(e),String(t))>=0?e:t}function jh(e,t,n,r){return ln(t,n)?{value:t,from_theirs:!1,conflict:!1}:ln(e,t)?{value:n,from_theirs:!0,conflict:!1}:ln(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function qh(e,t,n,r,o){let s=jh(e,t,n,r);if(!s.conflict||o==="preferred_side")return s;let i=J(n).localeCompare(J(t))<0;return{value:i?n:t,from_theirs:i,conflict:!0}}function ed(e){return{...e.metadata}}function td(e,t,n){try{return Je(Nu(e,n),n)}catch(r){throw new m(`Item merge input (${t}) is not a readable item document: ${String(r)}`,l.GENERIC_FAILURE)}}function LI(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?OI(e.baseValue,e.oursValue,e.theirsValue):II(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,ln(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function NI(e){let t=qh(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:e.baseValue,ours:e.oursValue,theirs:e.theirsValue,retained:t.value,discarded:t.from_theirs?e.oursValue:e.theirsValue})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function FI(e,t,n,r,o){let s=new Set(CI),i=new Set(RI),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(!LI({field:d,baseValue:u,oursValue:p,theirsValue:f,unionFieldSet:s,accumulator:c})){if(i.has(d)){c.merged[d]=PI(p,f);continue}NI({field:d,baseValue:u,oursValue:p,theirsValue:f,preferred:r,conflictResolution:o,accumulator:c})}}return c}function Kh(e,t,n,r={}){let o=r.preferred??"ours",s=r.conflictResolution??"preferred_side",i=e.trim().length>0,a=td(t,"ours",r),c=td(n,"theirs",r),d=i?td(e,"base",r):a,u=i?ed(d):{},p=ed(a),f=ed(c),{merged:_,conflictFields:h,fieldsFromTheirs:y,unionFields:g,conflictDecisions:w}=FI(u,p,f,o,s),v=qh(i?d.body:"",a.body,c.body,o,s);return v.conflict?(h.push("body"),w.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:w,requested_preference:o,conflict_resolution:s}}function nd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rd(e,t){let n=Fo(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 MI(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=J(p);u.set(f,(u.get(f)??0)+1)}return u},o=r(e),s=r(t),i=r(n);for(let[d,u]of o)if((s.get(d)??0)<u||(i.get(d)??0)<u)return null;let a=new Map(s),c=[];for(let d of n){let u=J(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 $I(e,t,n,r,o,s,i){if(!nd(t)||!nd(n))return null;let a=nd(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=o.length>0?`${o}.${u}`:u,f=DI(a,t,n,u,r,p,s,i);f!==void 0&&(c[u]=f)}return c}function zh(e,t,n,r,o,s,i){if(ln(t,n))return t;let a=MI(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(o),a.merged;let c=$I(e,t,n,r,o,s,i);if(c!==null)return c;let d=jh(e,t,n,r);return d.conflict?s.push(o):d.from_theirs&&i.push(o),d.value}function DI(e,t,n,r,o,s,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 zh(e[r],t[r],n[r],o,s,i,a);if(c){if(u&&ln(e[r],t[r])){a.push(s);return}return u?(i.push(s),o==="theirs"?void 0:t[r]):t[r]}if(!(u&&ln(e[r],n[r])))return u?(i.push(s),o==="theirs"?n[r]:void 0):(a.push(s),n[r])}function Bh(e,t,n,r={}){let o=r.preferred??"ours",s=rd(e,"base"),i=rd(t,"ours"),a=rd(n,"theirs"),c=[],d=[],u=zh(s,i,a,o,"",c,d);return{merged:`${JSON.stringify(u??null,null,2)}
41
+ `,conflict_paths:c,paths_from_theirs:d,preferred:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d79e3a4-6104-5855-837f-69a041b87b27")}catch{}})();var Hh=["item","history","relationship","json"];function qI(e){let t=e.trim().toLowerCase();if(Hh.includes(t))return t;throw new m(`Unknown merge artifact "${e}". Supported values: ${Hh.join(", ")}.`,l.USAGE)}function KI(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 od(e,t){try{return await UI(e,"utf8")}catch{throw new m(`Cannot read merge ${t} file at ${e}.`,l.NOT_FOUND)}}async function zI(e){let t=E(process.cwd(),e.path);return await P(ye(t))?A(t):null}function BI(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Vh(e,t){let n=qI(e.artifact),r=KI(e.prefer),o=jI.resolve(e.outputPath??e.oursPath),[s,i,a]=await Promise.all([od(e.basePath,"base"),od(e.oursPath,"ours"),od(e.theirsPath,"theirs")]),c,d,u=[],p={};if(n==="history"){let _=Uh(s,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 _=Gh(s,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 zI(t),h=Kh(s,i,a,{format:BI(e.itemPath??o,_),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 _=Bh(s,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await GI(o,c,"utf8"),d!==void 0){let _=await ef(d);_!==null&&(p.receipt=ir(_))}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:o,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:k()}}import Jh 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 Wh(e,t){return t==="body"?e.body:e.metadata[t]}function sd(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(o=>{let s=t.findIndex((i,a)=>!r.has(a)&&sd(o,i));return s<0?!1:(r.add(s),!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,o])=>Object.hasOwn(n,r)&&sd(o,n[r]))}function Yh(e,t){let n=new Set(t),r=[];for(let o=e.length-1;o>=0&&n.size>0;o-=1){let s=e[o],i=new Set;for(let c of Gu(s.patch))i.add(Wo(c.path)),c.from&&i.add(Wo(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:o+1,ts:s.ts,author:s.author,op:s.op,fields:a.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function HI(e,t,n){let r=Jh.compare(t,n);if(r.length===0)return;let o=new Set;for(let h of r)o.add(Wo(h.path));let s=new Set([...o].filter(h=>sd(Wh(t,h),Wh(n,h)))),i=new Set([...o].filter(h=>!s.has(h))),a=Yh(e,i),c=Yh(e,s),d=[...o].sort((h,y)=>h.localeCompare(y)),u=[...i].sort((h,y)=>h.localeCompare(y)),p=[...s].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:o.size,reconciled_fields:d,reverted_field_count:i.size,reverted_fields:u,discarded_events:a,discarded_authors:f,preserved_field_count:s.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 VI(e,t,n,r){let o=e.located?.itemPath??null,s=e.located?await K(e.located,{schema:t.schema}):null;if(!s)return{currentItemReplay:null,currentItemPath:o,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let i=Wt(s.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:i,currentItemPath:o,matchedChainBefore:Me(i,r)===a,currentItemRawBeforeLock:s.raw,loadedItem:s}}function WI(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 YI(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?Jh.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Me(e.finalReplay,e.itemHashVersion),after_hash:Me(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 JI(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 XI(e){return qo({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})=>jo({historyPath:e.historyPath,nextHistoryRaw:it(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function Er(e,t,n){let r=E(process.cwd(),n.path);await C(r);let o=await A(r),s=I(o,R()),i=await Ko(r,e,o,s.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=En(c),u=ju(c),p=t.normalizeProvenance?Qp(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=qu(p.entries),_=new Set(p.entries.map(Y=>Y.item_hash_version).filter(Y=>Y!==void 0)),h=$o(p.entries,f),y=await VI(i,o,c,f),g=h.finalDocument,w=y.currentItemReplay!==null&&Me(g,f)!==Me(y.currentItemReplay,f),v=w&&y.currentItemReplay?HI(h.entries,g,y.currentItemReplay):void 0,S=[h.entriesRehashed>0,h.entriesPatchRepaired>0,w,t.forceAuditEntry===!0,p.receipt.changed].some(Boolean),x=T(t.author,o.author_default),O=!!t.dryRun,D=WI({message:t.message,entriesRehashed:h.entriesRehashed,entriesPatchRepaired:h.entriesPatchRepaired,reconcileNeeded:w}),{rewrittenEntries:N,auditEntryAdded:ce}=YI({reanchorEntries:h.entries,changed:S,reconcileNeeded:w,currentItemReplay:y.currentItemReplay,finalReplay:g,author:x,message:D,auditOperation:t.auditOperation??"history_repair",auditContext:p.receipt.changed?{...t.auditContext,provenance_normalization:p.receipt}:t.auditContext,itemHashVersion:f,explicitItemHashVersion:h.explicitItemHashVersion}),V=En(N);if(!V.ok)throw new m(`history-repair produced an invalid rewritten chain (${V.errors.join(", ")}).`,l.GENERIC_FAILURE);let de=JI(S,h.skippedOps,v);return S&&!O&&de.push(...await XI({pmRoot:r,subject:i,settings:o,typeRegistry:s,historyRawBeforeLock:a,currentItemRawBeforeLock:y.currentItemRawBeforeLock,author:x,force:t.force,loadedItem:y.loadedItem,historyPath:i.historyPath,rewrittenEntries:N})),{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:w,audit_entry_added:ce,verify_ok:V.ok,verify_errors:V.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(de)].sort((Y,Te)=>Y.localeCompare(Te)),generated_at:k()}}function Xh(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 ti(e,t){let n=E(process.cwd(),t.path);await C(n);let r=await A(n),o=I(r,R()),s=[],i=await Do(n,r.item_format,o.type_to_folder,s,r.schema,{forceSourceScan:!0}),a=await Sp(n,i),c=e.normalizeProvenance?await Zp(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 Er(_,{...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 Du(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([...s,...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 Qh(e,t){let n=e.dryRun===!0,r=await tf(process.cwd(),{includeLossless:!0}),{pendingDecisions:o}=nf(r);if(!n&&e.force!==!0&&o.length>0)throw new m(`Merge reconciliation would accept ${o.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:o.map(g=>`Review receipt ${g.id} for ${g.item_id}: ${g.decisions.map(w=>w.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let s=r.reduce((g,w)=>((g[w.item_id]??=[]).push(w),g),{}),i=Object.fromEntries(Object.entries(s).map(([g,w])=>[g,{merge:{receipts:w.map(ir)}}])),a=await ti({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(s).filter(g=>!c.has(g));(await Promise.allSettled(d.map(g=>Er(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,w)=>{let v=d[w];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=>rf(process.cwd(),g))),p=r.length);let f=await cs({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(ir)},validation:f,guidance:y,generated_at:f.generated_at}}import{createHash as QI}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 tg=1,ng=/^[A-Za-z0-9_-]+$/,ZI=100,Zh=1e3;var yq=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,o)=>r.localeCompare(o));return n.length===0?void 0:n}function ex(e){return QI("sha256").update(J({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 eg(e,t){let n={version:tg,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 tx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===tg,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 nx(e,t){let n=e.trim();if(n.length===0||n.length>4096||!ng.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(!tx(r,t))throw new m("Mutation event cursor does not match this query.",l.USAGE,{code:"event_cursor_query_mismatch"});return r}function rx(e){let t=e??ZI;if(!Number.isSafeInteger(t)||t<0||t>Zh)throw new m(`Mutation event limit must be an integer from 0 to ${Zh}.`,l.USAGE,{code:"invalid_event_limit"});return t}function ox(e,t){let n=e?.trim();if(!n)return{};if(ng.test(n))return{cursor:nx(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 sx(e,t){let n=await fa(e,t);if(n===null){if(!await Fu(e))return{...await Mu(e,t),source:"authoritative_history"};n=await fa(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 ix(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 ni(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await C(t);let n=rx(e.limit),r=ix(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 o=await A(t),s=o.agent_identity.identity_vocabulary,i=up(o.agent_identity.harness_signals),a=pp({provenance:e.provenanceFilter},i),c=Ve(e.harness),d=ex(e),{cursor:u,sinceTimestamp:p}=ox(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(s.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 sx(t,f),h=_.events.map(y=>({...r==="row"?{cursor:eg(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:fp(y.entry,s,{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:eg(_.events[_.events.length-1],d)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:_p(_.events.map(y=>y.entry),s,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 ax="1h",cx="now",dx="+1d";function Mt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function rg(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 og(e,t,n,r){let o=rg(e,t,n),s=[];return Mt(s,"start",n.start??cx),n.end!==void 0?Mt(s,"end",n.end):Mt(s,"duration",n.duration??ax),Mt(s,"location",n.location),Mt(s,"timezone",n.timezone),n.allDay===!0&&Mt(s,"all_day","true"),o.event=[s.join(",")],Lt(o,r)}function sg(e,t,n){return og("Meeting",e,t,n)}function ig(e,t,n){return og("Event",e,t,n)}function ag(e,t,n){let r=rg("Reminder",e,t),o=[];return Mt(o,"at",t.at??dx),Mt(o,"text",t.text??e),r.reminder=[o.join(",")],Lt(r,n)}import Tr from"node:crypto";import{cp as dg,lstat as _x,mkdir as mn,readFile as qn,readdir as ad,rename as ug,rm as dd,writeFile as oi}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 cg=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"}]]),lx=/^[a-z][a-z0-9_]{0,63}$/u,mx=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))),ux={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function px(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&cg.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:mx.get(Math.abs(t.errno))??null}function fx(e,t,n={}){let r=px(e);if(r===null)return null;if(!lx.test(t))throw new m("Host environment operation labels must be bounded identifiers.",l.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=cg.get(r);return new m(`Host filesystem operation ${t} ${o.summary}.`,l.GENERIC_FAILURE,{code:n.codes?.[o.category]??ux[o.category].code,reason:r,required:o.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[o.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function ri(e,t,n={}){try{return await t()}catch(r){throw fx(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 pg="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var fg=F.join("runtime","workspace-snapshots"),hx=new Set(["checkpoints","locks","runtime","search","transactions"]),gx=/^[a-z0-9][a-z0-9._-]*$/,Ar="sdk-workspace-transaction",id={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},_g={renameEntry:ug,removeEntry:async e=>{await dd(e,{recursive:!0,force:!0})}},cd=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 qn(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!==Ar||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await fe(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
42
+ `)}};async function hg(e,t=""){let n=await ad(F.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((s,i)=>s.name.localeCompare(i.name))){if(t.length===0&&hx.has(o.name))continue;let s=F.posix.join(t.replaceAll(F.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${s}`);if(o.isDirectory())r.push(...await hg(e,s));else if(o.isFile())r.push(s);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${s}`)}return r}async function gg(e){let t=await hg(e),n=Tr.createHash("sha256"),r=[],o=0;for(let i of t){let a=await qn(F.join(e,i));r.push(a),o+=a.byteLength,n.update(i),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let s=n.digest("hex");return{manifest:{schema:pg,fingerprint:s,files:t,bytes:o},contents:r}}function lg(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
43
+ `).filter(t=>t.trim().length>0).length}async function yx(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),s=await Promise.all(o.map(async i=>[i,await qn(F.join(e,i))]));for(let[i,a]of s)n.set(i,a)}return n}function ld(e){if(!gx.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 yg(e,t){return ri(`workspace_snapshot_${e}`,t,{codes:{capacity:id.capacity.code,permission:id.permission.code,resource:id.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 un(e){return F.join(e,fg)}function wg(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 bg(e,t){try{return JSON.parse(await qn(e,"utf8"))}catch(n){throw kt(n)?wg(t):n}}async function mg(e,t,n){try{await dd(e,{recursive:n})}catch(r){throw kt(r)?wg(t):r}}async function wx(e,t,n=_g){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 bx(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(s){throw await r.renameEntry(n,t),await r.removeEntry(e),s}await r.removeEntry(n)}async function vx(e,t){return ld(t),/^[a-f0-9]{64}$/.test(t)?t:(await bg(F.join(un(e),"refs",`${t}.json`),t)).fingerprint}async function md(e,t={}){if(t.name!==void 0&&(ld(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 gg(e),o=un(e),s=F.join(o,"objects",n.fingerprint),i=!1;try{i=(await _x(s)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&kt(a)))throw a}if(!i){let a=F.join(o,"objects",`.create-${process.pid}-${Tr.randomUUID()}`);await yg("create_object",async()=>{await mn(F.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let u=F.join(a,"files",d);await mn(F.dirname(u),{recursive:!0}),await oi(u,r[c])}await oi(F.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
44
+ `,"utf8"),await mn(F.dirname(s),{recursive:!0})}),i=await wx(a,s)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=F.join(o,"refs");await mn(c,{recursive:!0});let d=F.join(c,`.ref-${process.pid}-${Tr.randomUUID()}`);await oi(d,`${JSON.stringify(a,null,2)}
45
+ `,"utf8"),await ug(d,F.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function Cr(e,t){let n=await vx(e,t),r=await bg(F.join(un(e),"objects",n,"manifest.json"),t);if(r.schema!==pg||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 ud(e){let t=un(e),n=await ad(F.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&kt(o))return[];throw o}),r=await ad(F.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&kt(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Cr(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await qn(F.join(t,"refs",o),"utf8"))))}}async function pd(e,t){let n=await Cr(e,t),{manifest:r,contents:o}=await gg(e),s=new Map(r.files.map((p,f)=>[p,o[f]])),i=await yx(F.join(un(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=s.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=lg(s.get(p)),_=lg(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 vg(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",o=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,i=await we(e,Ar,o,r,!1,!1,s),a=new cd(zr(e,Ar),r,o);a.start(),await a.refreshNow();let c,d=!1,u=!1;try{let p=await pd(e,t),f=await Cr(e,t),_=await md(e),h=f.fingerprint,y=un(e),g=F.join(y,"objects",h,"files"),w=F.dirname(e),v=F.basename(e);c=F.join(w,`.${v}.restore-${Tr.randomUUID()}`);let S=F.join(w,`.${v}.backup-${Tr.randomUUID()}`);await yg("restore_stage",async()=>{await mn(c,{recursive:!0}),await dg(g,c,{recursive:!0,force:!1}),await mn(F.join(c,"runtime"),{recursive:!0}),await dg(y,F.join(c,fg),{recursive:!0,force:!1})});let x=await Ku({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:o,lockWaitMs:s}),O=F.relative(c,x.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let D=zr(c,Ar);return await mn(F.dirname(D),{recursive:!0}),await oi(D,await qn(zr(e,Ar)),{flag:"wx"}),d=!0,await bx(c,e,S,_g,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([dd(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function kg(e,t){ld(t);let n=un(e);if(!/^[a-f0-9]{64}$/.test(t))return await mg(F.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await ud(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await mg(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 Rr(e){return{...e.args,...e.options}}function ut(e,t){let n=b(e,t);if(n!==void 0)return n;throw new m(`Missing required parameter: ${t}`,l.USAGE)}function Kn(e){return typeof e=="string"?[e]:ve(e)}function Sg(e){return Dh(Rr(e),e.global)}function Eg(e){let t=Rr(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 ni({cwd:b(t,"cwd"),pmRoot:b(t,"path"),since:b(t,"since"),type:Kn(t.type),author:Kn(t.author),item:Kn(t.item),limit:t.limit===void 0?void 0:De(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:Kn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Kn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Kn(t.provenanceFilter)}})}function Ag(e){let t=Rr(e),n=ut(t,"subcommand");if(n==="install")return Np({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return Qh({dryRun:t.dryRun===!0,author:b(t,"author"),message:b(t,"message"),force:t.force===!0},e.global);if(n==="report")return of({includeReconciled:t.includeReconciled===!0,cwd:b(t,"cwd")});if(n==="driver")return Vh({artifact:ut(t,"artifact"),basePath:ut(t,"basePath"),oursPath:ut(t,"oursPath"),theirsPath:ut(t,"theirsPath"),outputPath:b(t,"outputPath")??b(t,"output"),itemPath:b(t,"itemPath"),prefer:b(t,"prefer")},e.global);throw xe({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Tg(e){let t=Rr(e),n=ut(t,"subcommand");if(n!=="snapshot")throw xe({command_path:"workspace",token:n,allowed:["snapshot"],display_name:"workspace"});let r=b(t,"snapshotAction")??ut(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return md(o,{name:b(t,"name")});if(r==="list")return ud(o);let s=ut(t,"target");if(r==="inspect")return Cr(o,s);if(r==="delete")return kg(o,s);if(r==="restore")return t.dryRun===!0?pd(o,s):vg(o,s,{force:t.force===!0,author:b(t,"author"),message:b(t,"message"),lockTtlSeconds:De(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:De(t.lockWaitMs,"lockWaitMs")});throw xe({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function si(e){let t=Rr(e),n=ut(t,"title");return e.action==="meet"?sg(n,t,e.global):e.action==="event"?ig(n,t,e.global):ag(n,t,e.global)}import Nx from"node:path";import kx from"node:fs/promises";import Cg 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 Sx="templates",Ex=".json",Ax=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Tx=Ro.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),Cx=new Set(Tx);function Rx(e){let t=e.trim();if(!Ax.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 Rg(e){return Cg.join(e,Sx)}function Ig(e,t){return Cg.join(Rg(e),`${t}${Ex}`)}async function Ix(e){await C(e)}function xg(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function xx(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(Cx.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(s=>typeof s=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return xg(t)}function Ox(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[o,s]of Object.entries(n)){let i=o.trim();if(i.length===0)throw new m(`Template "${t}" contains an empty option key.`,l.GENERIC_FAILURE);if(typeof s=="string"){r[i]=s;continue}if(Array.isArray(s)&&s.every(a=>typeof a=="string")){r[i]=[...s];continue}throw new m(`Template "${t}" contains invalid value for option "${i}".`,l.GENERIC_FAILURE)}return xg(r)}function Px(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,o=Ox(r.options,t),s=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:s,updated_at:typeof r.updated_at=="string"?r.updated_at:s,options:o}}async function Lx(e,t){let n=await q(Ig(e,t));if(n===null)throw new m(`Template "${t}" not found`,l.NOT_FOUND);return Px(n,t)}async function fd(e,t,n){let r=E(process.cwd(),n.path);await Ix(r);let o=Rx(e),s=xx(t);if(Object.keys(s).length===0)throw new m("templates save requires at least one create option flag",l.USAGE);let i=k(),a=Ig(r,o),c=i;await P(a)&&(c=(await Lx(r,o)).created_at);let d={name:o,created_at:c,updated_at:i,options:s},u=await A(r);return await kx.mkdir(Rg(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 Ng=["list","show","apply","lint"],Fx="schema-types",Mx="schema-statuses",$x="schema-fields";function ii(){let e=R();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Fg(){let{profiles:e,warnings:t}=Mm(ii());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:jm(n.definition)})),warnings:t,generated_at:k()}}function Mg(e){let t;try{t=So(e,ii())}catch(r){throw new m(r instanceof Error?r.message:String(r),l.USAGE)}let{resolved:n}=t;return{action:"show",...qm(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function $g(e){let t;try{t=So(e,ii())}catch(o){throw new m(o instanceof Error?o.message:String(o),l.USAGE)}let{resolved:n}=t,r=iu(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 Dx(e,t){return Nx.join(e,"templates",`${t}.json`)}async function Ux(e,t){let n=await q(Dx(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function Og(e,t,n,r){let o=new Map;for(let s of r.templates){let i=await Ux(e,s.name);i!==void 0&&o.set(s.name,i)}return{typesRaw:await q(st(e,t.files.types,ot.types)),statusesRaw:await q(st(e,t.files.statuses,ot.statuses)),fieldsRaw:await q(st(e,t.files.fields,ot.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function zn(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function Pg(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:zn(t.types.changes),statuses:zn(t.statuses.changes),fields:zn(t.fields.changes),workflows:zn(t.workflows.changes.map(s=>({key:s.type,status:s.status}))),config:zn(t.config.changes),templates:zn(t.templates.changes.map(s=>({key:s.name,status:s.status}))),packages:t.packages,warnings:[...new Set(o)].sort((s,i)=>s.localeCompare(i)),generated_at:k()}}async function Gx(e){await C(e)}function jx(e){try{let t=So(e,ii());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new m(t instanceof Error?t.message:String(t),l.USAGE)}}async function Dg(e,t,n){let r=E(process.cwd(),n.path);await Gx(r);let o=jx(e),s=o.profile,i=o.warnings,a=t.dryRun===!0,c=await A(r),d=Eo(c.schema);if(a){let w=await Og(r,d,c,s),v=Lg(s,w);return Pg(s,v,!1,!0,[...i])}let u=T(t.author,c.author_default),p=Bu(c),f=!!t.force,_=[...i],h=[],y=async w=>{h.push(await we(r,w,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(Fx),await y(Mx),await y($x);let w=await Og(r,d,c,s);if(g=Lg(s,w),g.types.changed){let v=st(r,d.files.types,ot.types);await Rt({pmRoot:r,filePath:v,raw:ko(g.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(s.types.map(O=>xm(O).name)),x=g.types.file.definitions.filter(O=>S.has(O.name));await Gp(r,x,_,"profile:apply-type-folder"),_.push(...await z({path:v,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let v=st(r,d.files.statuses,ot.statuses);await Rt({pmRoot:r,filePath:v,raw:Gm(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=st(r,d.files.fields,ot.fields);await Rt({pmRoot:r,filePath:v,raw:$m(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=To(v.key);S!==void 0&&Co(c,S,v.value)}c.schema.type_workflows=g.workflows.result,await Ie(r,c,"profile:apply-config")}for(let v of g.templates.changes)v.status!=="unchanged"&&await fd(v.name,{...v.options},n)}finally{for(let w of h.reverse())try{await w()}catch{}}return Pg(s,g,g.changed,!1,_)}function Lg(e,t){try{return au(e,t)}catch(n){throw new m(n instanceof Error?n.message:String(n),l.USAGE)}}import Gg from"node:fs/promises";import jg 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 qx(e,t,n){let r=new Set,o=[];for(let s of e){let i=s.trim();if(i.length===0||r.has(i))continue;r.add(i);let a=t.get(i);if(a===void 0){o.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){o.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return o}function Kx(e,t){let n=[...e].sort((o,s)=>s.entries-o.entries||o.id.localeCompare(s.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function Ug(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return qx(t.ids,n,t.minEntries)}return Kx(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 zx(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 s=Number.parseInt(n,10);if(!Number.isSafeInteger(s)||s<1||s>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,s-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 o=0;for(let[s,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 ${s+1}.`,l.GENERIC_FAILURE);if(a>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function Bx(e,t){let n=Mo(),r=Mo();for(let o=0;o<e.length;o+=1){let s=e[o];if(Me(n)!==s.before_hash)throw new m(`history-compact detected before-hash drift at entry ${o+1}; run pm history-repair first.`,l.CONFLICT);if(n=Go(n,s.patch,o+1,s.op),Me(n)!==s.after_hash)throw new m(`history-compact detected after-hash drift at entry ${o+1}; run pm history-repair first.`,l.CONFLICT);o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function Hx(e,t,n){let r=structuredClone(t),o=[];for(let[s,i]of e.entries()){let a=Me(r);r=Go(r,i.patch,n+s+1,i.op),o.push({...i,before_hash:a,after_hash:Me(r)})}return{entries:o,finalReplay:r}}async function Vx(e,t,n){let r=e.located?await K(e.located,{schema:t.schema}):null;return r?{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:Me(Wt(r.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function Wx(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 Yx(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 Jx(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=Bx(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Hx(r,t,e.boundary.compactCount),i=[Ke({nowIso:k(),author:e.author,op:"history_compact_baseline",before:Vt(Mo()),after:Vt(t),message:Yx(e.boundary)}),...o.entries];return e.dryRun||i.push(Ke({nowIso:k(),author:e.author,op:"history_compact",before:Vt(n),after:Vt(n),message:Wx(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Xx(e){return qo({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})=>jo({historyPath:e.historyPath,nextHistoryRaw:it(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function _d(e,t,n){let r=E(process.cwd(),n.path);await C(r);let o=await A(r),s=I(o,R()),i=await Ko(r,e,o,s.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=En(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=zx(t.before,d),f=p.compactCount>0,_=!!t.dryRun,h=T(t.author,o.author_default),y=[];f||y.push("history_compact_noop_before_boundary");let g=await Vx(i,o,d);g.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:w,baselineEntryAdded:v,auditEntryAdded:S}=Jx({historyEntries:d,boundary:p,changed:f,dryRun:_,author:h,options:t}),x=En(w);if(!x.ok)throw new m(`history-compact produced an invalid rewritten chain (${x.errors.join(", ")}).`,l.GENERIC_FAILURE);f&&!_&&y.push(...await Xx({pmRoot:r,subject:i,settings:o,typeRegistry:s,historyRawBeforeLock:c,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:h,force:t.force,loadedItem:g.loadedItem,historyPath:a,rewrittenEntries:w}));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:w.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((D,N)=>D.localeCompare(N)),generated_at:k()}}var Qx=3;function qg(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 Zx(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function eO(e){let t=$(e.settings.schema),n=ds(t),r=await le(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(d=>[d.id,n.classify(d.status)])),s=jg.join(e.pmRoot,"history"),i=[],a=[];if(!await P(s))return{candidates:i,preselectionErrors:a};let c=(await Gg.readdir(s)).filter(d=>d.endsWith(".jsonl")).sort((d,u)=>d.localeCompare(u));for(let d of c){let u=jg.join(s,d),p=d.slice(0,-6);try{let f=await Gg.readFile(u,"utf8");await bn({path:u,scope:"project"}),i.push({id:p,entries:Zx(f),bucket:o.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 tO(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 _d(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 Kg(e,t){let n=E(process.cwd(),t.path);await C(n);let r=await A(n),o=I(r,R()),{candidates:s,preselectionErrors:i}=await eO({pmRoot:n,settings:r,typeToFolder:o.type_to_folder}),a=e.ids!==void 0&&e.ids.length>0?"ids":"scan",c=e.minEntries??Qx,d=r.history.compact_policy,u=a==="scan"&&e.allOver===void 0&&d.enabled,p=e.allOver??(u?d.max_entries:void 0),f=Ug(s,{ids:e.ids,scope:e.scope,minEntries:c,allOver:p}),_=!!e.dryRun,h=[...i],y={streams_considered:s.length+i.length,selected:0,items_compacted:0,items_skipped:0,items_errored:i.length};for(let g of f){let w=await tO({row:g,options:e,dryRun:_,global:t});if(h.push(w.result),!w.selected){y.items_skipped+=1;continue}y.selected+=1,w.compacted&&(y.items_compacted+=1),w.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 zg(e){let t=e.options.all===!0,n=e.id??b(e.options,"id");return Xh(n,t),t?ti(e.options,e.global):Er(n,e.options,e.global)}function Bg(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=De(e.options.allOver??e.options.all_over,"history-compact allOver"),o=De(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),s=b(e.options,"scope"),i=[];e.options.closed===!0&&i.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&i.push("all-streams"),(s==="closed"||s==="all-streams")&&i.push(s);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 qg(e.id,{ids:n,allOver:r,scope:c}),e.id!==void 0?_d(e.id,{before:b(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global):Kg({ids:n,scope:c,allOver:r,minEntries:o,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global)}(function(){try{var e=typeof window<"u"?window:typeof 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 ai(e){return Ao("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 hd(e,t,n,r){let o=t.trim();if(o.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 s=E(process.cwd(),r.path),i=$((await A(s)).schema),a=i.open_status,c=ai(i),d=n.status??a,u=Z(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} "${o}" --status ${a}`,suggested_retry_args:["item","reopen",e,o,"--status",a]}});let p=await M_(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);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 Hg(e,t){let n=e.id??b(t,"id");if(!n)throw new m("Missing required argument: id",64);return n}function Vg(e,t){return b(e.args,"reason")??b(e.args,"text")??b(t,"reason")??b(t,"text")}async function Wg(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options);return je(await ct(Hg(e,r),Vg(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Yg(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options);return je(await hd(Hg(e,r),Vg(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 Jg(e,t,n){let r;if(typeof e.lines=="string")r=ss(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=ss(`${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 nO=oa("list").properties.outputSession,rO={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:{...nO},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Xg={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},oe={type:"string",description:"pm item id, for example pm-abc1."},oO=`Operation name (one of): ${ea.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,sO={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."}},iO={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function G(e,t=[]){return{...Xg,properties:{...Xg.properties,...e},required:t}}var aO=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:G({action:{type:"string",enum:[...ea],description:oO},id:oe,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."},...rO},["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:G({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:G({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid, options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:G({query:{type:"string"},options:{type:"object"},...iO},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:G({options:{type:"object"},...sO})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:G({id:oe,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:G({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:G({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:oe,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:G({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:G({id:oe,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:G({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:oe,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:G({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:G({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:oe,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:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:G({id:oe,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:G({id:oe,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:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:G({subcommand:{type:"string",enum:[...Zm]},id:oe,target:oe,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:G({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:G({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:G({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Schema mutations write workspace config files, not item history.",inputSchema:G({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:[...$i]},description:`Lifecycle roles for add-status: ${$i.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:G({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:G({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:G({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],cO={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"},dO=aO.map(e=>{let t=cO[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:oa(t,{properties:n,required:r})}});function Qg(){return dO.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e8f1efca-4e83-570f-8c33-96f0405035b0")}catch{}})();var Zg=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"]]]),lO=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],dy=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),di=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"]),Ir=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"]),ly=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"]]),my=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"]]),uy=new Map([...my.entries()].flatMap(([e,t])=>pt(t).map(n=>[n,e]))),py=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],fy=new Map(py.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),mO=10,uO=20,ey=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."]]),_y=[["init",Kl],["install",Bl],["uninstall",Hl],["explore",Vl],["manage",Zl],["describe",Wl],["reload",em],["doctor",tm],["catalog",nm],["adopt",rm],["adopt-all",Yl],["activate",Jl],["deactivate",Xl],["migrate",Ql]],pO=_y.map(([e,t])=>e==="init"?[e,zl]:[e,t]),fO=[..._y.map(([e,t])=>[`extension ${e}`,t]),...pO.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",eo],["config",ql],["extension",to],["package",Jn],["packages",Jn],["install",om],["create",ao],["item mutate",Em],["item complete",Am],["item reopen",Tm],["copy",co],["focus",lo],["update",mo],["update-many",uo],["upgrade",sm],["calendar",Xn],["cal",Xn],["context",Qn],["ctx",Qn],["get",fo],["search",wo],["eval",Rm],["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",yo],["aggregate",Jr],["deps",ho],["graph",go],["guide",_o],["reindex",im],["history",Xr],["history-compact",Ul],["history-redact",$l],["history-repair",Dl],["history-author-acknowledge",Qr],["merge",Ml],["schema",Gl],["profile",jl],["plan",Zr],["restore",dm],["delete",lm],["close",am],["close-many",no],["append",ro],["claim",cm],["release",mm],["start-task",um],["pause-task",pm],["close-task",fm],["comments",Ol],["notes",Pl],["learnings",Ll],["files",Nl],["docs",Fl],["test",gm],["test-all",ym],["telemetry",wm],["test-runs",bm],["gc",vm],["stats",oo],["duplicates",so],["validate",km],["health",io],["assurance",Sm],...Im,["contracts",bo],["completion",vo],["activity",po],...[...dy].map(e=>[e,Yr])],bd=new Map(fO);function _O(e){let t=uy.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function ty(e){return Qi.includes(e)?he(e):e.startsWith("extension-")?he(`extension ${e.slice(10)}`):e.startsWith("package-")?he(`package ${e.slice(8)}`):e.startsWith("item-")?he(`item ${e.slice(5)}`):e.startsWith("test-runs-")?he(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?he(`templates ${e.slice(10)}`):di.has(e)?my.get(e)??he(e):null}function hO(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=>he(t)).filter(t=>t.length>0)}function gO(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let s of pt(o.command_path)){let i=s.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((o,s)=>o.localeCompare(s))}function ci(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function xr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function yO(e,t){if(!t)return{...e};let r=xr(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:r}}function gd(e,t){let r=xr(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.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 he(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function hy(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 ny(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=Qe(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function yd(e,t,n){n&&(e[t]=!0)}function ry(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 wO(e){let t=ry(e.long,"long"),n=ry(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),yd(o,"required",e.required===!0),yd(o,"repeatable",e.repeatable===!0),yd(o,"list",e.list===!0);let s=Qe(e.description);s&&(o.description=s);let i=Qe(e.value_name);i&&(o.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&&(o.value_type=a),o}function gy(e){let t=new Map;for(let r of e){let o=he(r.target_command);if(o.length===0)continue;let s=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;s.sourceDedupe.has(i)||(s.sourceDedupe.add(i),s.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=wO(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;s.dedupe.has(d)||(s.dedupe.add(d),s.flags.push(c))}t.set(o,s)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((s,i)=>{let a=s.layer.localeCompare(i.layer);return a!==0?a:(s.name??"").localeCompare(i.name??"")})});return n}function bO(e){let t=gy(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let i=he(s.command);if(i.length===0)continue;let a=Qe(s.action)??hy(i),c=Array.isArray(s.arguments)?s.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:s.layer,name:s.name},description:Qe(s.description),intent:Qe(s.intent),arguments:c,flags:t.get(i)?.flags??[],examples:ny(s.examples),failure_hints:ny(s.failure_hints)})}let r=new Set;for(let s of e.handlers)r.add(he(s));for(let s of n.keys())r.add(s);for(let s of t.keys())r.add(s);let o=[];for(let s of[...r].sort((i,a)=>i.localeCompare(a))){let i=n.get(s);o.push(vO(s,i,t.get(s)?.flags??[]))}return o}function vO(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:hy(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function kO(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(o,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function SO(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 EO(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function AO(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=SO(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let s=kO(o);!s||n[s]!==void 0||(n[s]=EO(o,e.action),o.required===!0&&r.push(s))}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 TO(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 CO(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((s,i)=>s.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let i=`${s.flag}|${s.short??""}`;if(!o.has(i))o.add(i),r.flags.push(s);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);a&&TO(a,s)}}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 RO(e,t=A){let n={mode:bt.extensions.policy.mode,trust_mode:bt.extensions.policy.trust_mode,default_sandbox_profile:bt.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(ye(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),s=await Hr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),i=await Vr({...s,loaded:s.loaded});return{handlers:new Set(i.commands.handlers.map(c=>he(c.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function IO(e,t={}){let n=new Map;for(let r of Zi){let o=di.has(r);if(o&&!t.includePackageOwnedActions)continue;let s=ty(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:s})}if(t.includePackageOwnedActions)for(let r of di)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:ty(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:he(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function xO(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)),o=n.map(i=>ly.get(i)).find(i=>typeof i=="string"),s=t.disabledReason===null&&r;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function yy(e){return bd.get(e)??Wr}function OO(e){return Ir.has(e)?!1:bd.has(e)}function PO(e){return dy.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function oy(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function LO(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function NO(e){let t=new Map;for(let r of e.definitions){let o=oy(r.cli_flag);if(!o)continue;let s=r.cli_aliases.map(a=>LO(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>oy(a)).filter(a=>a!==null&&a!==o);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},d=s?{flag:o,short:s}:{flag:o},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,o]of t.entries())n.set(r,Yi(o.flags));return n}function sy(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let s=`${o.flag}|${o.short??""}`;r.has(s)||(r.add(s),n.push(o))}return Yi(n)}function FO(e,t,n,r){return e.map(o=>{let s=OO(o),i=s?yy(o):[],a=n.get(PO(o))??[],c=t.get(o),d=sy(i,a),u=sy(d,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:o,flags:u,...r?{canonical_command:wd(o),visibility:yu(wd(o)),positionals:Rl(o)?.slots??[],flag_invocations:gu(o,u)}:{},provider:p,extension_sources:c?.sources}}).sort((o,s)=>o.command.localeCompare(s.command))}function MO(e,t=Zn){let n=new Set(e),r=new Map;for(let o of py){let s=o.aliases.filter(i=>n.has(i));r.set(o.canonical,{canonical:o.canonical,aliases:s,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let s=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};s.aliases.includes(o.alias)||s.aliases.push(o.alias),s.contracts.push(o),r.set(o.canonical,s)}return[...r.values()].map(({contracts:o,...s})=>o.length===0?s:{...s,contracts:o}).sort((o,s)=>o.canonical.localeCompare(s.canonical))}function $O(){return{create_string_options:cu,create_repeatable_options:Ro,update_string_options:du,update_repeatable_options:lu,list_string_options:Sl,search_string_options:El,calendar_string_options:Al,context_string_options:Tl,activity_string_options:Cl}}function iy(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=hn(e,"create",n),o=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(o.map(a=>ge("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:o,required_flags:s,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function DO(e){let t={},n={};for(let r of[...e.types].sort((o,s)=>o.localeCompare(s))){let o=e.by_type[r];t[r]=iy(o,"strict"),n[r]=iy(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function UO(e,t){let n=xr(e);if(n.length===0)return e;let r=!1,o=n.map(s=>{let i=s.properties;if(typeof i!="object"||i===null)return s;let a=i.action;return typeof a!="object"||a===null||a.const!=="create"?s:(r=!0,{...s,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function GO(e){let t=ci(e.action)!==void 0||ci(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,s=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=ci(e.action),u=ci(e.command),p=!r&&!c&&!o&&!s&&!i&&!d&&!u;return{selectedAction:d,selectedCommand:u,summary:r,schemaOnly:o,flagsOnly:s,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function jO(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 qO(e,t=A){try{return await t(e)}catch{return structuredClone(bt)}}async function KO(e,t){let n=await qO(t),r=await RO(e),o=I(n,r.registrations??R()),s=Ye(n.schema),i=bO(r);return{settings:n,runtimeProbe:r,typeRegistry:o,statusRegistry:$(n.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:NO(s),createRequiredOptionContracts:DO(o),extensionContracts:i,mergedExtensionContracts:CO(i),extensionFlagMap:gy(r.flagRegistrations)}}function ay(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&di.has(e.selectedAction)||e.selectedCommand!==void 0&&Ir.has(e.selectedCommand))}function zO(e,t){let n=IO(t,{includePackageOwnedActions:ay(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(tu);return n.filter(o=>!r.has(o.action))}return ay(e)&&e.selectedCommand!==void 0&&Ir.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:_O(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function BO(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 HO(e,t){return[...new Set([...Qi.filter(n=>!Ir.has(n)),...[...bd.keys()].filter(n=>!Ir.has(n)),...e.flatMap(n=>n.command_path?pt(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>he(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function VO(e,t){let n=t.slice(0,mO),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),s=t.slice(0,uO),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: ${o}.`,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:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function WO(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 YO(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 JO(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(s=>s.startsWith(`${e.selectedCommand} `));if(r.length>0)throw VO(e.selectedCommand,r);let o=ly.get(e.selectedCommand);throw o?WO(e.selectedCommand,o):YO(e.selectedCommand)}function XO(e,t){let n=zO(e,t.mergedExtensionContracts);BO(e,n);let r=HO(n,t.mergedExtensionContracts);JO(e,r);let o=e.selectedCommand?uy.get(e.selectedCommand):void 0,s=e.selectedCommand?n.filter(d=>o?d.action===o:hO(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.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?s.filter(d=>d.action===e.selectedAction):s,a=[...new Map(i.map(d=>xO(d,t.runtimeProbe)).map(d=>[o?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:s,scopedActionDescriptors:i,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function QO(e){return new Set(xr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function ZO(e){let t=su,n=xr(t),r=QO(t),o=e.filter(s=>!r.has(s.action)).map(s=>AO(s));return o.length>0?{...t,oneOf:[...n,...o]}:t}function cy(e,t,n){let r=new Set(t.actionDescriptors.map(s=>s.action)),o=e.selectedAction?yO(n,e.selectedAction):e.selectedCommand?gd(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):gd(n,r);return e.runtimeOnly&&!e.selectedAction?gd(o,new Set(t.actions)):o}function eP(e,t,n){let r=ZO(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?UO(cy(e,n,r),t.createRequiredOptionContracts):cy(e,n,r);return{mergedSchema:r,filteredSchema:s}}function tP(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?gO(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function nP(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Zn.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function wd(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":fy.get(t)??t}var rP=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"]]),oP=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function sP(e,t){let n=ey.get(e)??(e.includes(" ")?void 0:ey.get(wd(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 o=e.split(" "),s=o.at(-1),i=o.slice(0,-1).join(" "),a=rP.get(s),c=oP.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function iP(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(he))].filter(s=>s.length>0).sort((s,i)=>s.localeCompare(i)).map(s=>{let i=ta(s,{generateFallback:!0}),a=s.split(" ")[0],c=fy.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...yy(s).map(f=>f.flag),...t.filter(f=>pt(f.command).includes(s)).flatMap(f=>f.flags.map(_=>_.flag))]),u=(Zg.get(s)??Zg.get(c)??lO).filter(f=>d.has(f)),p=sP(s,t);return{command:s,intent:p.intent,...o||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 aP(e){return e.map(t=>({budget:ta(t,{generateFallback:!0}),envelope:bu(t)}))}function cP(e){let t=new Map;for(let n of e){let r=uu(n),o=r===void 0?[l.SUCCESS,l.GENERIC_FAILURE,l.USAGE,l.NOT_FOUND,l.CONFLICT,l.DEPENDENCY_FAILED]:r.exit_codes,s=o.join(","),i=t.get(s)??{commands:[],exit_codes:o};i.commands.push(n),t.set(s,i)}return[...t.values()]}function dP(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(o=>pt(o.command).some(s=>r.has(s)))}return t.extensionContracts}function lP(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 mP(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,s])=>[o,[...new Set(s.map(i=>`--${i.cli_flag}`))].sort((i,a)=>i.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Vm],services:[...Wm],policy_modes:[...Ym],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Qm],trust_modes:[...Jm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Xm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...tl],create_modes:[...nl],close_validation_modes:[...rl],workflow_enforcement_modes:[...ol]},e.relationship_kind_contracts=[...ml,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,s)=>o.kind.localeCompare(s.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function uP(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 pP(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=FO(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let s=new Set(r);e.list_projections=Object.entries(Su).filter(([i])=>s.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...ku],compact_fields:[...vu]}))}e.command_aliases=o}}function fP(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=$O();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function _P(e,t,n,r){e.command_summaries=iP(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...nu],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(Wi.map(({slots:o})=>xl(o))).size,positional_action_count:Vi.length,positional_action_parents:[...new Set(Vi.map(({parent:o})=>o))].sort((o,s)=>o.localeCompare(s)),...r.includePositionalSignatures?{positional_signatures:Wi}:{}}}async function wy(e,t){let n=GO(e);jO(n);let r=E(process.cwd(),t.path),o=await KO(t,r),s=XO(n,o),i=eP(n,o,s),a=tP(n,s),c=nP(n,a),d=lP(n,i,s,c),u=dP(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&_P(d,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p}),n.summary)return d;let f=MO(s.commandCatalog);return n.flagsOnly&&!n.fullOutput||mP(d,o,n),uP(d,n,i,u),pP(d,n,o,c,f),fP(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...wp],gate_triggers:[...yp]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=Il),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=Qg(),d.context_intents=pu(),d.read_output_dimensions=na,d.error_codes=hu,d.command_output_contracts=aP(c),d.diagnostic_output_contracts=ru,d.command_exit_contracts={vocabulary:mu,command_sets:cP(c)}),d}import QP from"node:fs/promises";import $y 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 li(e,t,n,r,o,s="min"){let i=o==="min"?e-t:t-e,a=s==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&a<0}function hP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,s=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)||(li(f,i,p,o,"min")&&(i=f,o=p),li(f,a,p,s,"max","max")&&(a=f,s=p))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:s}}function by(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:h})=>hP(_,h)),s=0,i=0,a=null,c=null,d=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of o){if(s+=_.lines,i+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);li(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);li(h,u,_.id,c?.id??null,"max")&&(u=h,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...o].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...o].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:s,total_bytes:i,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as yP}from"node:crypto";import{execFile as wP}from"node:child_process";import Sy from"node:path";import{promisify as bP}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 vy=1;function gP(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 vd(e){if(e===null)return{format_version:vy,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!==vy||!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(!gP(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 vP=bP(wP),kP=50,ky=1e3,SP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Ey(e){let t=e.trim().toLowerCase();if(!SP.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 EP(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 Or(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 AP(e){let t=e??kP;if(!Number.isSafeInteger(t)||t<0||t>ky)throw new m(`Improvement observation limit must be an integer from 0 to ${ky}.`,l.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Ay(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 TP(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=Ey(n.metric),o=EP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new m("Target-directed observations require a finite threshold.",l.USAGE,{code:"invalid_improvement_observation"});let s=await RP(e,n.revision),i=Or(n.source,"source"),a=Or(n.itemId,"itemId"),c=Or(n.unit,"unit"),d=Or(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,r,i??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Ay(n.observedAt??k(),"observedAt"),...s,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:yP("sha256").update(J(u)).digest("hex").slice(0,24),...u}}function CP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new 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(o=>o.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 RP(e,t){let n=Or(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await vP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:dl(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function IP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function Ty(e,t={}){let n=E(process.cwd(),t.path);await C(n);let r=await A(n),o=await TP(n,r,e),s=Sy.join(n,"improvement-ledger.json"),i=await zu({pmRoot:n,filePath:s,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=vd(a),d=CP(c,o);return d?{raw:a,result:d}:(c.observations.push(o),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:o})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function Cy(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await C(t);let n=e.metric===void 0?void 0:Ey(e.metric),r=e.since===void 0?void 0:Ay(e.since,"since"),o=AP(e.limit),i=vd(await q(Sy.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,o),total:i.length,truncated:i.length>o,trends:[...a].map(([,c])=>IP(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 Ry(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 xP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function OP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function kd(e=er,t=vn){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function PP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function Sd(e,t=vn,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let s of t){let i=`${o.agent_harness}\0${s}`,a=r.get(i)??{harness:o.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=o.agent_provenance?.[s];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(o=>{let s=o.observed+o.unavailable;return{...o,coverage:s===0?null:o.observed/s,inert:s>=n&&o.observed===0}}).sort((o,s)=>o.harness.localeCompare(s.harness)||o.dimension.localeCompare(s.dimension))}function LP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let u=`${c.agent_harness}\0${d}`,p=o.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),o.set(u,p)}let s=[...o.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=s.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:s,failures:a}}function NP(e){let t=[...e].sort((s,i)=>s.ts.localeCompare(i.ts)||s.author.localeCompare(i.author)||s.op.localeCompare(i.op)||s.before_hash.localeCompare(i.before_hash)||s.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let s of t){let i=s.agent_episode,a=Ry(s),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(s);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:[s],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let o=[];for(let s of n.values()){let i=s.parent_id?r.get(s.parent_id):void 0;i&&xP(s,i,r)?i.children.push(s):o.push(s)}return OP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var FP=1e4,Iy=1e5,MP=1e3,$P=30,DP=["append","comment","docs","file","learning","note","test_run"];function UP(e){let t=e??FP;if(!Number.isSafeInteger(t)||t<1||t>Iy)throw new m(`History analytics event limit must be an integer from 1 to ${Iy}.`,l.USAGE,{code:"invalid_history_analytics_limit"});return t}function xy(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 GP(e){let t=e?.trim();if(!t)return new Date(Date.now()-$P*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new m("History analytics --since duration must be positive.",l.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*s).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 Oy(e,t){let n=UP(t.eventLimit),r=GP(t.since),o=[],s=r,i=!1;for(;o.length<n;){let a=await ni({pmRoot:e,since:s,limit:Math.min(MP,n-o.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(o.push(...c),i=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:i,...i?{next_cursor:s}:{},source:"history_event_index"}}}function jP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function qP(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 KP(e){return DP.some(t=>e.startsWith(t))}function Py(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 zP(e,t,n){let r=new Map,o=new Map,s=new Map;for(let i of t){let a=jP(i.entry,e),c=qP(i.entry),d=o.get(i.item_id)===!0,u=c===void 0?d:n.has(c);if(c!==void 0&&o.set(i.item_id,u),!a)continue;let p=Py(r,a);p.events+=1,KP(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!d&&u?(p.closes+=1,s.set(i.item_id,a)):c!==void 0&&d&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:s}}function BP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of o){let i=t.get(s);i&&(Py(e,i).defectEscapes+=1)}}}function HP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function VP(e,t,n,r,o,s){let{buckets:i,lastCloseValue:a}=zP(e,t,r);return BP(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,d])=>HP(c,d,o,s)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function WP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),s=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(s)?1:Math.max(1,(s-o)/864e5)}function YP(e,t,n){let r=kd(t),o=Sd(e,vn,n),s=o.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:o,inert:s,undeclared:i,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...i.map(a=>`provenance_dimension_undeclared:${a}`)]}}function Ly(e,t=er,n={}){let r=xy(n.minimumSample);return{...YP(e.events.map(o=>o.entry),t,r),window:e.receipt}}function Ny(e,t,n,r={}){let o=xy(r.minimumSample),s=WP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>VP(i,e.events,t,n,o,s)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var JP=32;function XP(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let s=o.slice(0,o.indexOf("=")).trim();r.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Pr(e,t){let n=XP(e).map(o=>{let[s,...i]=o.split(","),a=s.indexOf("="),c=s.slice(0,a).trim(),d=s.slice(a+1).trim(),u=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(u))throw new m(`Invalid --measure "${o}"; 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(o=>[o.name,o])).values()].sort((o,s)=>o.name.localeCompare(s.name)).slice(0,JP)}function Fy(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function My(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,i)=>i.recorded_at.localeCompare(s.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b56db1fc-d989-5d18-8b29-336a03f1e525")}catch{}})();function ZP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function eL(e,t,n,r,o){let s=dr(e,"type",r),i=new Set(s.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),d=(o?[...s.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}}))]:s.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=ZP([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>o||f>0));return{byType:d,byStatus:p,omitted:o?0:a.length+Object.values(u).filter(f=>f===0).length}}function tL(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function nL(e){let t=$y.join(e,"history");if(!await P(t))return[];await bn({path:t,scope:"project"});let n=(await QP.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,s)=>o.localeCompare(s)),r=[];for(let o of n){let s=$y.join(t,o),i=await q(s);i!==null&&(await bn({path:s,scope:"project"}),r.push({id:o.slice(0,-6),raw:i}))}return r}async function rL(e,t){let n=[],r=k();for(let o of Pr(t.observe,r))n.push(await Ty({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function oL(e,t,n){let r={};return t.byAssignee&&(r.assignee=dr(e,"assignee",n)),t.byTag&&(r.tag=dr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=dr(e,"priority",n)),r}async function sL(e,t,n,r,o){let s={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},i=o.provenanceCoverage||o.fleetAttribution?await Oy(e,s):void 0;return{provenanceCoverage:o.provenanceCoverage&&i?Ly(i,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:o.fleetAttribution&&i?Ny(i,t,r,s):void 0}}function iL(e,t,n,r,o){let s=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...s?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:k()}}async function Ed(e,t={}){let n=E(process.cwd(),e.path);await C(n);let r=await A(n),o=await rL(e,t),s=I(r,R()),i=$(r.schema),a=t.fieldUtilization?await Do(n,r.item_format,s.type_to_folder,void 0,r.schema):await le(n,r.item_format,s.type_to_folder,void 0,r.schema);await Wu({pmRoot:n,settings:r,itemIds:a.map(S=>S.id),commandLabel:"stats"});let c=ds(i),d=eL(a,s.types,i.definitions.map(S=>S.id),c,t.includeEmpty===!0),u=await nL(n),p=0;for(let S of u)p+=tL(S.raw);let f=t.storage?by(u):void 0,_=t.metadataCoverage?Sf(a,c):void 0,h=oL(a,t,c),y=t.fieldUtilization?Ef(a):void 0,g=t.measurements===!0||o.length>0?await Cy({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:v}=await sL(n,a,r,i.terminal_statuses,t);return iL({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:o,provenanceCoverage:w,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 Dy(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:b(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ve(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:b(e,"measurementSource"),measurementItem:b(e,"measurementItem"),measurementRevision:b(e,"measurementRevision"),author:b(e,"author"),message:b(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:b(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import aL 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 Ky=Dt.join("runtime","telemetry","events.jsonl"),zy=Dt.join("runtime","telemetry","state.json"),cL=Dt.join("runtime","telemetry"),dL=20,Uy=["status","flush","stats","clear"],Gy=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Ad=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,jy=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},lL=e=>({command:Ad(e.event.command,"<unknown>"),eventType:Ad(e.event.event_type,"unknown"),eventSchemaVersion:jy(e.event.schema_version),clientSchemaVersion:jy(e.client_schema_version)}),mL=()=>({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:{}}),uL=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},pL=e=>{let t=e?.command_resolution;return Ad(t,"")||void 0},By=(e,t)=>{e[t]=(e[t]??0)+1},fL=(e,t)=>{let n=uL(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=pL(t);r!==void 0&&By(e.resolution_counts,r)},_L=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,qy=(e,t)=>{t!==void 0&&e.add(t)},hL=(e,t)=>{let n=lL(t),r=e.get(n.command)??mL();r.count+=1,r.max_attempts=Math.max(r.max_attempts,_L(t.attempts)),By(r.event_type_counts,n.eventType),qy(r.event_schema_versions,n.eventSchemaVersion),qy(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&fL(r,t.event.payload),e.set(n.command,r)},gL=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((s,i)=>s-i),o=Object.entries(t.resolution_counts).sort((s,i)=>s[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,i)=>s[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,i)=>s-i),client_schema_versions:[...t.client_schema_versions].sort((s,i)=>s-i),...r.length>0?{duration_p50_ms:Gy(r,.5),duration_p95_ms:Gy(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},yL=e=>{let t=(e??"status").trim().toLowerCase();if(Uy.includes(t))return t;throw xe({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Uy,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Td=()=>{throw new m("--limit must be a positive integer",l.USAGE)},Hy=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Td():e,wL=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Td():Hy(Number.parseInt(t,10))},bL=e=>e===void 0?dL:typeof e=="number"?Hy(e):typeof e=="string"?wL(e):Td(),vL=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},kL=e=>{try{let t=JSON.parse(e);return vL(t)?t:void 0}catch{return}},SL=e=>e===null?[]:e.split(`
48
+ `).map(t=>t.trim()).filter(t=>t.length>0),Vy=e=>{let t=SL(e),n=[],r=0;for(let o of t){let s=kL(o);s===void 0?r+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},EL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),AL=e=>{try{let t=JSON.parse(e);return EL(t)?t:{}}catch{return{}}},TL=async e=>{let t=await q(e);return t===null||t.trim().length===0?{}:AL(t)},mi=e=>e??null,ui=async e=>{let t=await A(e),n=Dt.join(e,Ky),r=Dt.join(e,zy),o=await q(n),s=Vy(o),i=await TL(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:mi(i.last_attempted_flush_at),last_successful_flush_at:mi(i.last_successful_flush_at),last_failed_flush_at:mi(i.last_failed_flush_at),last_failed_flush_error:mi(i.last_failed_flush_error)}},CL=e=>{let t=new Map;for(let n of e)hL(t,n);return[...t.entries()].map(([n,r])=>gL(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},RL=async(e,t)=>({action:"telemetry",subcommand:"status",status:await ui(t.globalPmRoot),generated_at:k()}),IL=async(e,t)=>{let n=await ui(t.globalPmRoot);await mp(t.globalPmRoot);let r=await ui(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),s=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:s,queue_drained:s,status:r,generated_at:k()}},xL=async(e,t)=>{let n=bL(e.limit),r=await q(t.queuePath),o=Vy(r),s=CL(o.entries),i=s.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:s.length>i.length,stats:i,generated_at:k()}},OL=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 Ie(t.globalPmRoot,n,"telemetry:clear");let o=Dt.join(t.globalPmRoot,cL),s=await P(o);return await aL.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:s&&!await P(o),queue_exists_after:await P(t.queuePath),state_exists_after:await P(t.statePath),status:await ui(t.globalPmRoot),generated_at:k()}},PL={status:RL,flush:IL,stats:xL,clear:OL};async function Wy(e,t){let n=yL(e.subcommand),r=nt(process.cwd());return PL[n](e,{globalPmRoot:r,queuePath:Dt.join(r,Ky),statePath:Dt.join(r,zy)})}import{spawn as uw}from"node:child_process";import{cp as xd,mkdir as hi,mkdtemp as pw,open as Od,readdir as Pd,rm as Fd,symlink as fw}from"node:fs/promises";import{tmpdir as _w}from"node:os";import H 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 Yy=20;function LL(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return Yy;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?Yy:t}function Cd(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let s=Sn(r.recorded_at,o.recorded_at);if(s!==0)return s;let i=r.run_id.localeCompare(o.run_id);return i!==0?i:r.kind.localeCompare(o.kind)}),n=LL();return t.length>n?t.slice(t.length-n):t}async function pi(e){await re({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=Cd([...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 Jy=100;function Rd(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 NL(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Jy?n:`${n.slice(0,Jy-3)}...`}function Xy(e){return e.map((t,n)=>`${n+1}. ${NL(t)}`).join("; ")}function FL(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 ML(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Qy(e,t){let n=FL(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,s)=>s+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(o=>`--${o}`).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 o=t.match.trim().toLowerCase();if(o.length===0)throw new m("--match requires a non-empty substring to match against linked-test command/path values",l.USAGE);let s=[],i=[];for(let a=0;a<e.length;a+=1)ML(e[a],o)&&(i.push(e[a]),s.push(a+1));if(i.length===0)throw new m(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Xy(e)}`,l.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:s,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let o=Rd(t.onlyIndex);if(o>e.length)throw new m(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${Xy(e)}`,l.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7659721c-21f5-55da-8cce-31b290de5bfb")}catch{}})();var _i=20*1024*1024,$L=3e3,DL=1e4,UL=5e3,Zy=120,GL=new Set(["locks","extensions","runtime"]),jL=new Set(["history","index","search","extensions","locks","runtime"]),qL=[/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],KL=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,zL=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,BL=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 Md(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 HL(){return Md("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",$L)}function VL(){return Md("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",DL)}function WL(){return Md("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",UL)}function YL(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 JL(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function $d(e){let t=0,n=0,r=0,o=0;for(let s of e){let i=s.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&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function XL(e){let t=e??"project";if(!tt.includes(t))throw new m(`Invalid scope "${e}"`,l.USAGE);return t}function gi(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(tn.includes(t))return t;throw new m(`Invalid --pm-context value "${e}". Expected one of: ${tn.join(", ")}`,l.USAGE)}function QL(e){return rn(e??"source","--workspace-context")}function hw(e,t,n){return n?t:rn(e.workspace_context_mode,"linked test")??t}function gw(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:gi(e.pm_context_mode)}function yw(e,t){return e==="auto"?t?"tracker":"schema":e}function ZL(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 eN(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 tN(e,t){let n={};if(!e)return n;for(let r of e){let o=hr(r,t);if(o)for(let[s,i]of Object.entries(o))n[s]=i}return n}function nN(e,t){if(!e)return[];let n=[];for(let r of e){let o=gr(r,t);o&&n.push(...o)}return[...new Set(n)]}function rN(e){let t=yi(e);return ar(t).some(n=>Ia(n)!==null)}function ww(e){let t=yi(e);return ar(t).some(n=>{let r=Ia(n);if(!r)return!1;let o=gf(r);return o?BL.has(o.subcommand):!1})}function fi(e){if(e)return ff.has(e.subcommand)?Ln(e.args,_f)?.subcommand:e.subcommand}function ew(e,t){if(e==="npx"||e==="bunx")return as(t)?.command;if(e==="pnpm")return fi(Ln(t,lf));if(e==="npm")return fi(Ln(t,mf));if(e==="yarn")return fi(Ln(t,uf));if(e==="bun")return fi(Ln(t,pf))}function tw(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function Id(e){return!e||!Oa(e.command)&&!hf(e.command)?!1:is(e.args)==="test-all"}var oN=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])]),sN=new Set(["npx","bunx"]);function bw(e){let t=e.split(" ").filter(i=>i.length>0),n=xa(t);if(n.length===0)return!1;let[r,...o]=n,s=oN.get(r);if(s){let i=o.findIndex(a=>s.test(a));return i>=0?bw(o.slice(i+1).join(" ")):!1}return Oa(r)||Pa(r)?is(o)==="test-all":r==="node"&&o.length>0&&Pa(o[0])?is(o.slice(1))==="test-all":sN.has(r)?Id(as(o)):r==="pnpm"?Id(La(o)):r==="npm"?Id(Na(o)):!1}function vw(e){let t=yi(e);return ar(t).some(n=>bw(n))}function kw(e){if(vw(e))throw new m('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',l.USAGE)}function yi(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function iN(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 aN(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(s=>s.length>0),n=xa(t);if(n.length===0)return!1;let[r,...o]=n;return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?dN(o):lN(r,o)}function dN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function lN(e,t){return e==="npx"||e==="bunx"?tw(as(t)?.command):e==="pnpm"||e==="npm"?tw((e==="pnpm"?La(t):Na(t))?.command)||ew(e,t)==="vitest":(e==="yarn"||e==="bun")&&ew(e,t)==="vitest"}function Sw(e){let t=yi(e);if(ar(t).some(o=>!iN(o)&&cN(o)&&!aN(o)))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 mN(e){if(vw(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function uN(e){return e?e.map(pN):[]}function pN(e){let t=e.trim(),n=Os(t)?Ps(se(e,"--add"),"--add"):{command:t},r=ue(n.command);if(!r)throw new m("--add requires command=<value> or a bare command (path=<value> is optional metadata)",l.USAGE);return kw(r),Sw(r),{command:r,path:ue(n.path),scope:XL(n.scope),timeout_seconds:fN(ue(n.timeout_seconds),ue(n.timeout)),pm_context_mode:$s(ue(n.pm_context_mode),"--add"),workspace_context_mode:rn(ue(n.workspace_context_mode),"--add"),env_set:hr(ue(n.env_set),"--add"),env_clear:gr(ue(n.env_clear),"--add"),shared_host_safe:Ms(ue(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:on(ue(n.assert_stdout_contains)),assert_stdout_regex:Dn(ue(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:on(ue(n.assert_stderr_contains)),assert_stderr_regex:Dn(ue(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Ds(ue(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Us(ue(n.assert_json_field_equals),"--add"),assert_json_field_gte:Gs(ue(n.assert_json_field_gte),"--add"),note:ue(n.note)}}function ue(e){let t=e?.trim();return t&&t.length>0?t:void 0}function fN(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(me(n,"timeout_seconds"));if(r<=0)throw new m("--add timeout_seconds must be a positive integer",l.USAGE);return r}function _N(e){return e?e.flatMap(t=>{let n=m_(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new m("--add-json requires a non-empty command string",l.USAGE);kw(o),Sw(o)}return n}):[]}function hN(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 o=n.slice(r[0].length).trim();if(!o)throw new m("--remove requires a non-empty command=<value> or path=<value>",l.USAGE);return{kind:r[1].toLowerCase(),value:o}}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 o=se(n,"--remove"),s=o.path!==void 0?"path":"command",i=o.path??o.command;if(!i?.trim())throw new m("--remove requires command=<value> and/or path=<value>",l.USAGE);return{kind:s,value:i.trim()}}return{kind:"either",value:n}}):[]}function gN(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 yN(e){try{e.stdin?.end()}catch{}}function Ew(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=Zy?t:`${t.slice(0,Zy-3)}...`}function Aw(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Ld(e){try{process.stderr.write(`${e}
49
+ `)}catch{}}function wN(e,t){if(!Aw(t))return null;let n=Ew(e.command),r=Date.now();Ld(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let s=Date.now()-r;Ld(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},VL());return o.unref?.(),o}function bN(e,t,n,r){if(!Aw(r))return;let o=Ew(e.command),s=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(" ")}`:"";Ld(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${d} elapsed_ms=${s}${u} command="${o}"`)}async function nw(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=uw("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 vN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function kN(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 nw(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{nw(r)},HL()),t.forceKillTimer.unref?.()}}function SN(e){return new Promise(t=>{let n=!1,r=null,o=(s,i=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,i)=>{n||(r=setTimeout(()=>{o({code:s,signal:i},!0)},WL()),r.unref?.())}),e.on("close",(s,i)=>{o({code:s,signal:i})})})}function EN(e,t,n,r,o){return uw(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function rw(e){let t=await Od(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,_i),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>_i}}finally{await t.close()}}async function AN(e,t,n,r,o,s=process.cwd()){let i=Date.now(),a=await pw(H.join(_w(),"pm-linked-test-output-"));try{let c=H.join(a,"stdout.log"),d=H.join(a,"stderr.log"),[u,p]=await Promise.all([Od(c,"w"),Od(d,"w")]),f;try{f=EN(e,n,u.fd,p.fd,s)}finally{await Promise.all([u.close(),p.close()])}yN(f);let _={heartbeat:wN(r,o),forceKillTimer:null,timedOutTimer:null},h=kN(f,_),y=!1,g;f.on("error",ce=>{g=ce.message}),_.timedOutTimer=setTimeout(()=>{y=!0,h()},t),_.timedOutTimer.unref?.();let{code:w,signal:v}=await SN(f);vN(_);let[S,x]=await Promise.all([rw(c),rw(d)]),O=S.truncated||x.truncated,D=O?`
50
+ [pm linked-test output truncated at ${_i} bytes per stream; the child process continued to completion]
51
+ `:"",N={stdout:`${S.text}${D}`,stderr:x.text,exitCode:w,signal:v,timedOut:y,maxBufferExceeded:!1,outputTruncated:O,spawnError:g};return bN(r,N,i,o),N}finally{await Fd(a,{recursive:!0,force:!0})}}function TN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${_i} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function CN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
52
+ `);return qL.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>KL.test(n)&&zL.test(n))}function RN(e){return CN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function IN(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function wi(e){let t=IN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function ow(e,t){for(let[n,r]of Object.entries(t.env_set))nn.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)nn.has(n.toUpperCase())||delete e[n]}function xN(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 ON(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function PN(e,t,n){return{env_set:tN(e,"--env-set"),env_clear:nN(t,"--env-clear"),shared_host_safe:n===!0}}async function Hn(e,t,n=!1,r=hi){if(await P(e))try{await ri("seed_linked_test",async()=>{if(await r(H.dirname(t),{recursive:!0}),n){await xd(e,t,{recursive:!0,force:!0});return}await xd(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&kt(o))return;throw o}}async function sw(e,t,n){await Hn(ye(n.projectPmRoot),ye(e)),await Hn(H.join(n.projectPmRoot,"extensions"),H.join(e,"extensions"),!0),await Hn(ye(n.globalPmRoot),ye(t)),await Hn(H.join(n.globalPmRoot,"extensions"),H.join(t,"extensions"),!0)}async function iw(e,t){if(!await P(e))return;let n=await Pd(e,{withFileTypes:!0});for(let r of n){if(GL.has(r.name))continue;let o=H.join(e,r.name),s=H.join(t,r.name);if(r.isDirectory()){await Hn(o,s,!0);continue}r.isFile()&&await Hn(o,s)}}async function Bn(e){if(!await P(e))return 0;let t=0,n=await Pd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||jL.has(r.name))continue;let o=H.join(e,r.name),s;try{s=await Pd(o,{withFileTypes:!0})}catch{continue}for(let i of s)i.isFile()&&cl.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function LN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function NN(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let r of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isInteger(o)||o<0)return[];t.push(o);continue}t.push(r)}return t}function aw(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=NN(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let s of r){if(typeof s=="number"){if(!Array.isArray(o)||s>=o.length)return{found:!1,value:void 0};o=o[s];continue}if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,s))return{found:!1,value:void 0};o=o[s]}return{found:!0,value:o}}function FN(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 MN(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?rt(e,t):Object.is(e,t)}function $N(e,t,n){let r=[];r.push(...cw("stdout",t,e.assert_stdout_contains)),r.push(...dw("stdout",t,e.assert_stdout_regex)),r.push(...cw("stderr",n,e.assert_stderr_contains)),r.push(...dw("stderr",n,e.assert_stderr_regex)),r.push(...DN(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(s).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(o)){let u=aw(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=FN(d);MN(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(s)){let u=aw(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 cw(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function dw(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(s){r.push(`${e} regex assertion is invalid: /${o}/ (${s instanceof Error?s.message:String(s)})`)}return r}function DN(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 UN=[{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 GN(e,t){let n=`${e}
53
+ ${t}`;for(let r of UN)if(r.regex.test(n))return r.code;return null}function jN(e){return{root:e,schemaProjectPmPath:H.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:H.join(e,"schema","global"),trackerProjectPmPath:H.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:H.join(e,"tracker","global"),workspaceSnapshotRoot:H.join(e,"workspace","project"),workspaceIsolatedRoot:H.join(e,"workspace","isolated")}}function qN(e,t,n){return e.some(r=>hw(r,t,n)==="snapshot")}async function KN(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await hi(H.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await xd(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(o){let s=H.relative(t,o);return s?!s.split(H.sep).some(i=>n.has(i)):!0}});let r=H.join(t,"node_modules");await P(r)&&await fw(r,H.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function zN(e,t){let n=H.join(e,".agents"),r=H.join(n,"pm");await hi(n,{recursive:!0}),await Fd(r,{recursive:!0,force:!0}),await fw(t,r,process.platform==="win32"?"junction":"dir")}async function BN(e,t=kr,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 HN(e,t,n){t&&(await sw(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await sw(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await iw(t.projectPmRoot,e.trackerProjectPmPath),await iw(t.globalPmRoot,e.trackerGlobalPmPath)))}function VN(e,t,n){return e.some(r=>{let o=r.command??"",s=o.length>0&&ww(o),i=n?.autoPmContext===!0&&s?"auto":gw(r,t,n?.overrideLinkedPmContext===!0);return yw(i,s)==="tracker"})}async function WN(e,t){return{sourceProjectItemCount:t?await Bn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Bn(t.globalPmRoot):0,schemaProjectItemCount:await Bn(e.schemaProjectPmPath),schemaGlobalItemCount:await Bn(e.schemaGlobalPmPath),trackerProjectItemCount:await Bn(e.trackerProjectPmPath),trackerGlobalItemCount:await Bn(e.trackerGlobalPmPath)}}function YN(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:a,trust:e.trust}}async function JN(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?gi(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?rN(n):!1,o=r&&n?ww(n):!1,s=e.options?.autoPmContext===!0&&o,i=s?"auto":gw(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=yw(i,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await zN(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await Fa(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Fa(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:YN({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function lw(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Nd(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 XN(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function QN(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return XN(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function ZN(e){if(!e.linkedTest.command)return lw(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=mN(e.linkedTest.command);return t?lw(e.linkedTest,e.executionContext,t):null}function eF(e){let t=ZN(e);if(t)return t;let n=QN(e);if(n)return n;let r=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,o=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(r||o){let s=eN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),i=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Nd(e.linkedTest,e.executionContext,`${i} (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&&!ZL(e.linkedTest)?Nd(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function tF(e){let t=ON(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return ow(n,e.runtimeDirectives),ow(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&xN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[sr]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[sr]="read_only"),n}function nF(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 rF(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 oF(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:LN(e.execution),failure_category:RN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:TN(e.execution,e.timeoutMs)}}function sF(e){if(e.options?.failOnEmptyTestRun===!0){let n=GN(e.execution.stdout,e.execution.stderr);if(n)return rF({...e,emptyRunSignal:n})}let t=$N(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Nd(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):nF(e.linkedTest,e.executionContext,e.execution)}async function iF(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await AN(t,n,tF(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?sF({...e,execution:r}):oF({...e,execution:r,timeoutMs:n})}async function Dd(e,t,n){let r=[],o=await pw(H.join(_w(),"pm-linked-test-")),s=jN(o),i=gi(n?.pmContext),a=QL(n?.workspaceContext),c=n?.progress===!0?"always":"auto",d=PN(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,p=wf(),f=VN(e,i,n),_=qN(e,a,n?.overrideLinkedWorkspaceContext===!0),h=await yf(p);try{await BN(s,kr,f),await hi(s.workspaceIsolatedRoot,{recursive:!0}),await HN(s,u,f),_&&await KN(s,p);let y=await WN(s,u);for(let g=0;g<e.length;g+=1){let w=e[g],v=hw(w,a,n?.overrideLinkedWorkspaceContext===!0),S=await JN({linkedTest:w,layout:s,counts:y,sourceRoots:u,runLevelPmContextMode:i,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:v,currentSourceRef:h,sourceWorkspaceRoot:p}),x=eF({linkedTest:w,executionContext:S.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:S.linkedOverridePmContextMode,options:n});if(x){r.push(x);continue}r.push(await iF({linkedTest:w,index:g,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:d,progressMode:c,executionContext:S.executionContext,options:n}))}}finally{await Fd(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function aF(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,s=await U(n,t,r.id_prefix,r.item_format,o);if(!s)throw new m(`Item ${t} not found`,l.NOT_FOUND);let i=await K(s,{schema:r.schema});return{itemId:s.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function cF(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function dF(e,t){let n=[...e];for(let r of t)n.some(o=>cF(o,r))||n.push(r);return n}function lF(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((s,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:o,removed:e.length-o.length}}function mF(e,t,n,r){return lF(dF(e,t),n,r)}function uF(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,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function pF(e){if(uF(e)&&e.run!==!0)throw new m("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",l.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new m("--acknowledge-linked-tests records trust without executing commands; run it separately before --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 fF(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:s,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return aF({id:t,pmRoot:r,settings:o,typeToFolder:s});let d=0,u=await re({pmRoot:r,settings:o,id:t,op:i.length>0?"tests_add":"tests_remove",author:T(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=mF(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 _F(e,t){pF(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Rd(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?Qy(t,n):void 0,o=e.timeout===void 0?void 0:me(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new m("Test timeout must be a positive number",l.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:gi(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function hF(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Dd(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,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:nt(process.cwd())}})}function gF(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 o=$d(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function yF(e){let t=JL(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=k(),s=Pr(e.options.measure,o);return{run_id:YL("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s: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,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function wF(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:s,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let d=yF({options:t,runStartedAt:s,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return d;try{return await pi({pmRoot:n,settings:r,itemId:o,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:${o}:${u instanceof Error?u.message:String(u)}`),d}}function mw(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,o).trim(),i=e.metricBelow.slice(o+1).trim(),a=Number(i);if(o<=0||s.length===0||i.length===0||!Number.isFinite(a))throw new m("--metric-below must use name=value",l.USAGE);r=Fy(t,s,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:My(t,e.metricDiff)}}async function bF(e,t,n){if(e.acknowledgeLinkedTests===!0)return bf(t,n,k())}async function bi(e,t,n){let r=$e(),o=E(process.cwd(),n.path);await C(o);let s=await A(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new m("--measure requires --run",l.USAGE);Pr(t.measure,"validation"),mw(t,[],void 0);let i=I(s,R()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),d=await r.resolveList(t.remove,"--remove"),u=[...uN(a),..._N(c)],p=await Nn(u,T(t.author,s.author_default),k())??[],f=hN(d),_=gN(t.removeIndex),h=await fF({id:e,options:t,pmRoot:o,settings:s,typeToFolder:i.type_to_folder,adds:p,removes:f,removeIndexes:_}),y=_F(t,h.tests),g=await bF(t,o,h.tests),w=t.run===!0?k():void 0,v=await hF({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests}),S=wi(v),x=t.run===!0&&t.failOnSkipped===!0&&v.some(V=>V.status==="skipped"),O=gF(t,y.runSelection,v);g&&O.push(`linked_test_trust_acknowledged:${g.acknowledged}`);let D=await wF({options:t,pmRoot:o,settings:s,itemId:h.itemId,runStartedAt:w,runResults:v,failOnSkippedTriggered:x,warnings:O}),N=D?Cd([...h.testRuns,D]):h.testRuns,ce=mw(t,N,D);return{ok:v.every(V=>V.status!=="failed")&&x!==!0,id:h.itemId,tests:h.tests,run_results:v,failure_categories:S,selection:y.runSelection?{selector:y.runSelection.selector,requested:y.runSelection.requested,selected_indexes:y.runSelection.selected_indexes,selected_count:y.runSelection.selected_count,skipped_count:y.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:x?!0:void 0,warnings:O.length>0?O:void 0,changed:h.changed,count:h.tests.length,...h.removed>0?{removed:h.removed}:{},...ce}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d3405c0-14e6-51f5-97a1-355438fd0199")}catch{}})();var vF=(e,t)=>{if(e===void 0)return;let n=Z(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new m(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n},kF=e=>{if(e===void 0)return;let t=me(e,"timeout");if(t<=0)throw new m("timeout must be a positive number",l.USAGE);return t},Tw=(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},SF=e=>e instanceof Error?e.message:String(e),EF=()=>{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)}`},AF=e=>e.trim().replaceAll(/\s+/g," "),TF=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),CF=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),RF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},IF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},vi=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Cw=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),xF=e=>typeof e=="number"?e:void 0,OF=e=>{let t={assert_stdout_contains:vi(e.assert_stdout_contains),assert_stdout_regex:vi(e.assert_stdout_regex),assert_stderr_contains:vi(e.assert_stderr_contains),assert_stderr_regex:vi(e.assert_stderr_regex),assert_stdout_min_lines:xF(e.assert_stdout_min_lines),assert_json_field_equals:Cw(e.assert_json_field_equals),assert_json_field_gte:Cw(e.assert_json_field_gte)};return JSON.stringify(t)},PF=e=>{let t=Ud(e.command);return t!==void 0?`command:${e.scope}:${AF(t)}`:`path:${e.scope}:${Ud(e.path)??""}`},Rw=e=>{let t=TF(e.env_set),n=CF(e.env_clear),r=RF(e.pm_context_mode),o=IF(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",i=OF(e);return`${PF(e)}:${t}:${n}:${r}:${o}:${s}:${i}`},LF=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,NF=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},FF=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},ki=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
54
+ `)}catch{}},MF=async(e,t,n)=>{let r=[],o=0;for(let s of e){let i=await bi(s.id,{run:!1},{...t,path:n});o+=i.tests.length,r.push({item:s,tests:i.tests})}return{itemTests:r,linkedTests:o}},$F=async e=>{let t=$(e.settings.schema),n=I(e.settings,R()),r=vF(e.options.status,t),o=Tw(e.options.limit,"--limit"),s=Tw(e.options.offset,"--offset")??0,a=(await le(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:o===void 0?a.slice(s):a.slice(s,s+o),statusFilter:r,limitFilter:o,offsetFilter:s}},DF=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=Rw(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,LF(t.get(o),r.timeout_seconds))}return t},UF=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=Rw(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}}),o=n.length>0?await Dd(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,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],s=0,i=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=o[s];return s+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=NF(i),c=wi(i),d=await qF(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}}},GF=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),jF=e=>e?!0:void 0,qF=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=GF(t,r.options);await pi({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at: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:jF(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${SF(o)}`]}return[]},KF=()=>{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},Ud=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},zF=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:DF(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:T(e.options.author,e.settings.author_default),trackingRunId:EF(),trackingAttempt:KF(),trackingResumedFrom:Ud(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),BF=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:wi([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},HF=async(e,t,n)=>{for(let[r,o]of e.entries()){ki(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let s=await UF(o,t);FF(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),ki(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}},VF=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=$d(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}`)},WF=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}),YF=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(" "),JF=async(e,t)=>{let n=E(process.cwd(),t.path);await C(n);let r=await A(n),o=await $F({pmRoot:n,settings:r,options:e}),s=kF(e.timeout),i=k(),a=await MF(o.filteredItems,t,n);return ki(e,YF({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:s,runStartedAt:i}},XF=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}},Iw=async(e,t)=>{let n=await JF(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=BF(e,n.linkedTests,n.filteredItems),s=zF({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await HF(n.itemTests,s,r),VF(e,r);let i=XF({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return ki(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),WF({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="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 xw(){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 Pw=[{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"]}],Ow=new Map;for(let e of Pw){Ow.set(e.id,e);for(let t of e.aliases)Ow.set(t,e)}function Gd(){return Pw.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 NH=[...$r],FH=[...Dr],QF=new Set(Zn.filter(e=>e.hidden).map(e=>e.alias)),MH=wu("full").filter(e=>!QF.has(e)),$H=M(Yr),DH=M(Jr),UH=M(ro),GH=M(co),jH=M(lo),qH=M(_m),KH=M(hm),zH=M(ao),BH=M(fo),HH=M(mo),VH=M(uo),WH=M(no),YH=M(po),JH=M(Xr),XH=M(Qr,!1),QH=M(Cm),ZH=M(Xn),eV=M(Qn),tV=M(yo),nV=M(ho),rV=M(so),oV=M(go),sV=M(_o),iV=M(wo),aV=M(oo),cV=M(io),dV=M(eo),lV=M(bo),mV=M(Zr);var ZF=M(vo),uV=`${ZF} bash zsh fish`,pV=eM(Gd());var fV=M(to),_V=M(Jn);var hV=Wr.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function eM(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]="600f391a-c960-5dda-a85a-04d3fa8b1a51")}catch{}})();var Mw=Symbol("pm.active-extension-host-context");function Ne(e){return{fullChangedFields:!0,options:e}}var j=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[Mw]=!0,n}run(t,n={}){return $w({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return If(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return ga(await this.list(ha(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,...Ne({...r,body:n})})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,s={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:s})}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,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,s){return this.runTyped("plan",{...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...s===void 0?{}:{reorderTo:s},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,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Ne(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ne(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,...Ne(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ne(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ne(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ne(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ne(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ne(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},...Ne(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ne(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ne(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ne(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 nM(e={},t={}){return new j(t).context(e)}function rM(e={},t={}){return new j(t).list(e)}function oM(e={},t={}){return new j(t).listAllComplete(e)}function sM(e,t={},n={}){return new j(n).search(e,t)}function iM(e,t={},n={}){return new j(n).get(e,t)}function aM(e={},t={}){return new j(t).next(e)}function cM(e={},t={}){return new j(t).aggregate(e)}function dM(e,t={},n={}){return new j(n).comments(e,t)}function lM(e,t={},n={}){return new j(n).notes(e,t)}function mM(e,t={},n={}){return new j(n).learnings(e,t)}function uM(e,t={},n={}){return new j(n).files(e,t)}function pM(e,t={},n={}){return new j(n).filesDiscover(e,t)}function fM(e,t={},n={}){return new j(n).docs(e,t)}function _M(e,t={},n={}){return new j(n).deps(e,t)}function hM(e,t={},n={},r={}){return new j(r).graph(e,t,n)}function gM(e,t,n={},r={}){return new j(r).append(e,t,n)}function yM(e={},t={}){return new j(t).create(e)}function wM(e,t={},n={}){return new j(n).update(e,t)}function bM(e,t,n={},r={}){return new j(r).reopen(e,t,n)}function vM(e,t,n={},r={}){return new j(r).close(e,t,n)}function kM(e,t={},n={}){return new j(n).claim(e,t)}function SM(e={},t={}){return new j(t).claimNext(e)}function EM(e,t={},n={}){return new j(n).release(e,t)}function AM(e,t={},n={}){return new j(n).copy(e,t)}function TM(e,t={},n={}){return new j(n).delete(e,t)}function CM(e,t,n={},r={}){return new j(r).restore(e,t,n)}function RM(e,t={},n={}){return new j(n).focus(e,t)}function Ze(e,t){let n=b(e,t);if(!n)throw new m(`Missing required argument: ${t}`,64);return n}var Lw=Eu(),IM=new tM;function Si(){ia(_l()),aa(hl()),ca(gl()),da(yl()),la(wl()),ma(bl()),ua(vl())}async function xM(e,t,n,r){return Au(()=>t===void 0?Lw.read(()=>Nw(e,n,r)):Lw.write(()=>PM(t,()=>Nw(e,n,r))))}async function Nw(e,t,n){let r=E(t,e.path);if(e.noExtensions)return Si(),Va({pmRoot:r},()=>n(null));if(!await P(ye(r)))return Si(),n(null);let o=null,s;try{let i=await A(r),a=await Hr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Vr({...a,loaded:a.loaded});s={loadResult:a,activationResult:c},ia(c.hooks),aa(c.commands),ca(c.parsers),da(c.preflight),la(c.services),ma(c.renderers),ua(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){Si(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Va({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Si(),s&&await kl(s.loadResult,s.activationResult).catch(()=>{})}}async function OM(e,t,n,r,o){if(!o)throw new m(`Unsupported native pm action: ${e}`,l.USAGE);let s=Yt(e),a=o.registrations.commands.find(d=>Yt(d.action)===s)?.command??o.commands.handlers.find(d=>Yt(d.command)===s)?.command;if(!a)throw new m(`Unsupported native pm action: ${e}`,l.USAGE);let c=await Oo({command:Ea(a),args:ve(n.args??t.args),options:Aa(t,n),global:r,pm_root:o.pmRoot,sdk:Lf(o.pmRoot,j.forActiveExtensionHost({pmRoot:o.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 PM(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var LM=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function NM(e){let t=Ze(e,"action"),n=Yt(t),r=Ai(Of,n),o=r?.action??n,s={...e,action:o};return r?.options!==void 0&&(s.options={...r.options,...Hi(e.options)}),o==="package"&&(s.options={...Hi(s.options),vocabulary:"package"}),{action:o,args:s}}function FM(e){return!LM.has(Yt(e))}async function $w(e){let t=NM(e),n=va(t.args),r=FM(t.action),o=b(t.args,"cwd"),s=o??process.cwd();try{return e[Mw]===!0||IM.getStore()===!0?await Fw(t.action,t.args,n,null):await xM(n,o,s,i=>Fw(t.action,t.args,n,i))}finally{r&&Ka()}}function Ai(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ei(e){return b(e.args,"target")??b(e.options,"target")}function ee(e,t=e.options){return e.id??Ze(t,"id")}async function MM(e){let t=yn("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),qa(await Pt(b(e.args,"status")??b(t,"status"),t,e.global),t)}async function $M(e){let t=Ze(e.args,"query"),n=yn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),qa(await mr(t,n,e.global),n)}async function DM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options);return je(await Lt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function UM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return je(await Nc(ee(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function GM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options);return je(await dt(ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function jM(e){let t=hs(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")),Yf(ee(e),t,e.global)}function Dw(e,t){return df(Jg(e.options,t,De),e.global)}function qM(e){let t=ve(e.options.lookupPath);if(t&&t.length>0)return Dw(e,t);let n=ee(e);return e.options.discover===!0?Ra(n,Sa(e.options),e.global):cf(n,os(e.options),e.global)}function KM(e){return Wy({subcommand:b(e.args,"subcommand")??b(e.options,"subcommand"),limit:Tp(e.args,e.options)},e.global)}function zM(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),sf(e.global,t)}function BM(e){let t=b(e.args,"configAction")??b(e.options,"configAction")??b(e.options,"action");if(t===void 0)throw new m("Missing required argument: configAction",64);let n=b(e.args,"value")??b(e.options,"value"),r=b(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return kh(b(e.args,"scope")??b(e.options,"scope")??"project",t,b(e.args,"key")??b(e.options,"key"),r,e.global,b(e.options,"policy")===void 0?n:void 0)}function HM(e){let t=e.options;return gp(hp(t),e.global)}function VM(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 WM(e){let t=b(e.args,"subcommand")??Ze(e.options,"subcommand"),n=e.options;return Z_({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:YM(e),reorderTo:VM(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function YM(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function JM(e){let t=b(e.args,"subcommand")??Ze(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:b(e.args,"name")??b(e.options,"name"),author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ve(n)}}function XM(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,a=Ai({list:()=>Kp(t.global),show:()=>zp(r,t.global),"show-status":()=>Bp(r,t.global),"list-fields":()=>Wp(t.global),"show-field":()=>Yp(r,t.global),"remove-type":()=>Up(r,{author:o,force:s},t.global),"remove-field":()=>Vp(r,{author:o,force:s},t.global),"remove-status":()=>qp(r,{author:o,force:s},t.global),"apply-preset":()=>Jp(b(t.args,"typePreset")??b(t.options,"typePreset"),{author:o,force:s},t.global)},n);return a?a():null}function QM(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return Hp(n,{type:b(t.args,"fieldType")??b(t.options,"fieldType"),commands:i===void 0?void 0:ve(i),description:b(t.args,"description")??b(t.options,"description"),cliFlag:b(t.args,"cliFlag")??b(t.options,"cliFlag"),alias:s,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:ve(a),author:r,force:o},t.global)}function ZM(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.role??t.options.role;return jp(n,{role:i===void 0?void 0:ve(i),alias:s,description:b(t.args,"description")??b(t.options,"description"),order:De(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function e$(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e;return Dp(n,{description:b(t.args,"description")??b(t.options,"description"),defaultStatus:b(t.args,"defaultStatus")??b(t.args,"default_status")??b(t.options,"defaultStatus")??b(t.options,"default_status"),folder:b(t.args,"folder")??b(t.options,"folder"),alias:s,author:r,force:o},t.global)}function t$(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,i=b(t.args,"to")??Ze(t.options,"to"),a=b(t.args,"migrationId")??b(t.args,"migration_id")??b(t.options,"migrationId")??b(t.options,"migration_id"),c=b(t.args,"fieldTypeScope")??b(t.options,"fieldTypeScope")??b(t.args,"type")??b(t.options,"type"),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 Mp(d,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:s},t.global)}function n$(e){let t=JM(e),n=XM(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return t$(t);if(t.subcommand==="add-field")return QM(t);if(t.subcommand==="add-status")return ZM(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Xp({minCount:De(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):e$(t);throw xe({command_path:"schema",token:t.subcommand,allowed:$p,exit_code:64})}function r$(e){let t=b(e.args,"subcommand")??Ze(e.options,"subcommand"),n=t.trim().toLowerCase(),r=b(e.args,"name")??b(e.options,"name"),s=Ai({list:()=>Fg(),show:()=>Mg(r),lint:()=>$g(r),apply:()=>Dg(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!s)throw xe({command_path:"profile",token:t,allowed:Ng,exit_code:64});return s()}async function o$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options);return je(await Ff(ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function s$(e){let{changedFields:t,runnerOptions:n}=Ue(e.args,e.options);return je(await j_(Ca(n),e.global),{changedFields:t})}async function i$(e){let{changedFields:t,runnerOptions:n}=Ue(e.args,e.options),r=b(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),je(await Wf(Ta(o),e.global),{changedFields:t})}async function a$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options),o=b(r,"target")??Ze(e.args,"target");return je(await Xt(ee(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Uw(e){let t={...e};return delete t.assignee,t}async function c$(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=ai($(n.schema)),o=ee(e),s=await ys(o,e.force,e.global,e.options),i=await dt(o,{...Uw(e.options),status:r,force:e.force},e.global);return{id:o,action:"start_task",claim:s,update:i}}async function d$(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=ee(e),o=$(n.schema).open_status,s=await dt(r,{...Uw(e.options),status:o,force:e.force},e.global),i=await ws(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:s,release:i}}async function l$(e){let t=ee(e),n=b(e.args,"reason")??b(e.args,"text")??b(e.options,"reason")??b(e.options,"text"),r=await ct(t,n,{...e.options,force:e.force},e.global),o=await ws(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:o}}function m$(e){let t={...e.args,...e.options};return kp(Ze(t,"subcommand"),b(t,"id")??e.id,b(t,"target"),Ip(t),e.global)}function u$(e){return Op(E(process.cwd(),e.global.path),{...e.args,...e.options})}var p$={init:e=>kr(b(e.args,"prefix"),e.global,e.options),context:e=>Ua(yn("context",e.options),e.global),next:e=>lr(yn("next",e.options),e.global),eval:Sg,events:Eg,merge:Ag,workspace:Tg,meet:si,event:si,remind:si,list:MM,get:e=>{let t=ee(e);return Ga(t,e.global,yn("get",e.options,[t]))},search:$M,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ve(e.options.status);return ja(e.global,{...t.length===0?{}:{status:t},since:b(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:De(e.options.limit,"limit")})},create:DM,copy:UM,focus:e=>Mc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:GM,"item-reopen":Yg,restore:a$,claim:e=>e.options.next===!0||e.args.next===!0?qf(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):ys(ee(e),e.force,e.global,e.options),release:e=>ws(ee(e),e.force,e.global,e.options),"start-task":c$,"pause-task":d$,"close-task":l$,close:Wg,comments:jM,notes:e=>Xf(ee(e),hs(e.options),e.global),learnings:e=>Jf(ee(e),hs(e.options),e.global),files:qM,docs:e=>af(ee(e),os(e.options),e.global),test:e=>bi(ee(e),e.options,e.global),"test-all":e=>Iw(e.options,e.global),telemetry:KM,validate:e=>cs(e.options,e.global,{runUpdate:(t,n,r)=>dt(t,n,r)}),health:zM,assurance:e=>vf(e.args,e.options,e.global),contracts:e=>wy(e.options,e.global),config:BM,activity:HM,aggregate:e=>Ma(e.options,e.global),extension:e=>Pn(Ei(e),e.options,e.global),package:e=>Pn(Ei(e),e.options,e.global),install:e=>Pn(Ei(e),{...e.options,install:!0},e.global),upgrade:e=>Tf(Ei(e),e.options,e.global),delete:e=>Fc(ee(e),e.options,e.global),deps:e=>vp(ee(e),e.options,e.global),graph:m$,"files-discover":e=>Ra(ee(e),e.options,e.global),"files-lookup":e=>Dw(e,ve(e.options.paths)),history:e=>Af(ee(e),e.options,e.global),"history-redact":e=>ep(ee(e),e.options,e.global),"history-repair":zg,"history-compact":Bg,"history-author-acknowledge":u$,plan:WM,schema:n$,profile:r$,stats:e=>Ed(e.global,Dy(e.options)),append:o$,"update-many":s$,"close-many":i$,gc:e=>Cf(e.global,e.options)};async function Fw(e,t,n,r){let o=ka(t,e);ra(e,o),ou(e,o);let s={action:e,args:t,options:o,id:b(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},i=Ai(p$,e),a=i?await i(s):await OM(e,t,o,n,r);return o.resolvedOutputFormat="json",_u(e,o,a)}var f$={closeManyOptionsFromFlat:Ta,extensionOptionsFromArgs:Aa,globalOptions:va,mutationListOptions:Rp,normalizeActionName:Yt,normalizeCommandPath:Ea,normalizeMcpUpdateOptions:xp,normalizeMcpOptionsArrays:Cp,optionsWithAuthor:ka,readRequiredString:Ze,readScalarString:Ep,readScalarStringAllowBlank:Ap,readStringArray:ve,updateManyOptionsFromFlat:Ca,withAddNoteOption:os,withFilesDiscoveryOptions:Sa,withMutationCompaction:Ue};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=f$);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cea03617-5e90-5683-a9d1-289087ed4646")}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{vn as AGENT_PROVENANCE_DIMENSIONS,Iu as BASELINE_ITEM_FORMAT_VERSION,Gb as BUILTIN_AGENT_PROVENANCE_ADAPTERS,er as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,$r as BUILTIN_ITEM_TYPE_VALUES,Ur as CONFIDENCE_TEXT_VALUES,xu as CURRENT_ITEM_FORMAT_VERSION,jt as DEPENDENCY_KIND_VALUES,l as EXIT_CODE,fn as ISSUE_SEVERITY_VALUES,el as ITEM_TYPE_VALUES,za as PM_CLI_EXPECTED_ERROR_NAME,Ib as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,Cb as PM_READ_OUTPUT_DIMENSIONS,Rb as PM_READ_OUTPUT_OPTION_FLAGS,na as PM_READ_OUTPUT_SURFACE_CONTRACTS,m as PmCliError,j as PmClient,pn as RISK_VALUES,ev as SEMANTIC_ATTRIBUTION_LIMITS,Dr as STATUS_VALUES,Ub as agentSessionEnvironment,cM as aggregate,kd as analyzeAgentProvenanceDescriptorCoverage,Fb as analyzeSdkCliParameterCompleteness,gM as append,Pb as applyReadOutputDimensions,kb as applyReadOutputSessionReferences,Sb as attachReadOutputSessionReceipt,Mb as boundAgentEpisodeIdentity,Je as canonicalDocument,kM as claim,SM as claimNext,Lu as classifyItemFormatVersion,vM as close,dM as comments,nM as context,AM as copy,yM as create,Pf as createPmCliExpectedError,Tb as decodeReadOutputContinuationCursor,TM as deleteItem,_M as deps,Vb as detectAgentIdentity,Jb as detectHarnessIdentity,Wb as diagnoseAgentIdentity,fM as docs,Ou as effectiveItemFormatVersion,xw as emptyImportedDocument,Ab as encodeReadOutputContinuationCursor,LP as evaluateSemanticAttributionCoverage,Qb as explainSourceTraceability,uM as files,pM as filesDiscover,RM as focus,iM as get,hM as graph,NP as groupHistoryByEpisode,jf as isAlreadyClaimedError,ps as isPmCliExpectedError,Lb as isReadOutputBudgetExceeded,mM as learnings,rM as list,qb as listAgentProvenanceAdapters,oM as listAllComplete,aM as next,zb as normalizeAgentProvenanceAdapterValue,Pu as normalizeItemFormatVersion,be as normalizeItemId,Z as normalizeStatusInput,lM as notes,k as nowIso,vb as parseReadOutputSession,ss as parseSourceLineRange,Lo as readAuthorEnvironment,Eb as readOutputSessionRemainingTokens,$a as recordClaimSemanticAttribution,ls as recordFocusSemanticAttribution,Da as recordReleaseSemanticAttribution,Kb as registerAgentProvenanceAdapters,jb as registerHarnessSignalDescriptors,EM as release,bM as reopen,$b as resolveAgentSessionContextFromSignals,Xb as resolveAuthorIdentity,Ry as resolveHistoryEpisodeGroupIdentity,Ob as resolveReadOutputDimensions,Nb as resolveReadOutputEncoding,xb as resolveReadOutputSurface,Zb as resolveSemanticLineageIds,CM as restore,$w as runAction,Db as runWithAgentSessionContext,Bb as runWithHarnessDetectionSignals,Hb as runWithWorkspaceHarnessSignalDescriptors,sM as search,tv as semanticAttributionAffinity,qe as serializeItemDocument,PP as summarizeAgentModelProvenance,Sd as summarizeAgentProvenance,wM as update,ra as validateReadOutputOptions,Yb as writeAuthorEnvironment};
55
55
  //# sourceMappingURL=sdk-core.js.map