@unbrained/pm-cli 2026.8.17 → 2026.8.18

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 (157) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/AGENTS.md +4 -3
  3. package/CHANGELOG.md +35 -3
  4. package/README.md +3 -3
  5. package/dist/cli/error-guidance.js +7 -4
  6. package/dist/cli/register-list-query.js +132 -51
  7. package/dist/cli-bundle/bundle-manifest.json +146 -146
  8. package/dist/cli-bundle/chunks/chunk-5UZZAJKR.js +3 -0
  9. package/dist/cli-bundle/chunks/{chunk-YM2YAMF7.js → chunk-ALDJGKAK.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-HBJAS566.js → chunk-BSK2IN3C.js} +2 -2
  11. package/dist/cli-bundle/chunks/chunk-DY4DMUMC.js +197 -0
  12. package/dist/cli-bundle/chunks/{chunk-JOKATURE.js → chunk-GNFAFIJI.js} +9 -9
  13. package/dist/cli-bundle/chunks/chunk-L5Q2CLPE.js +35 -0
  14. package/dist/cli-bundle/chunks/{chunk-TPXZIBIV.js → chunk-PVRUN5ZS.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-7IBRGCHX.js → chunk-RZQTVMRQ.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-SARFF5H5.js +3 -0
  17. package/dist/cli-bundle/chunks/chunk-UYCLQVL2.js +13 -0
  18. package/dist/cli-bundle/chunks/{chunk-3UEGXBMR.js → chunk-YRGOLZA7.js} +58 -54
  19. package/dist/cli-bundle/chunks/register-list-query-I23LALEE.js +11 -0
  20. package/dist/cli-bundle/chunks/{register-mutation-4WBRPXLV.js → register-mutation-6YGU3GPH.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-operations-SSENDH5B.js → register-operations-4HTFC6J7.js} +2 -2
  22. package/dist/cli-bundle/chunks/{register-setup-DOSFBGKE.js → register-setup-PPPEF3SN.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/chunk-2PN4TJXH.js +2 -0
  24. package/dist/cli-bundle/focused-chunks/{chunk-ZQPGZZWQ.js → chunk-3TKWMNKF.js} +3 -3
  25. package/dist/cli-bundle/focused-chunks/chunk-5AF3ZBNB.js +155 -0
  26. package/dist/cli-bundle/focused-chunks/chunk-C5IW2NDA.js +2 -0
  27. package/dist/cli-bundle/focused-chunks/{chunk-SYZENPIT.js → chunk-EUEGXZ2A.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-XKAMP5OU.js → chunk-EX6MKP2X.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-CYFK5UPB.js → chunk-K43KKAFS.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-ATEY76SX.js → chunk-M62NO7EI.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-SALH6B6K.js → chunk-ODOVCP45.js} +5 -5
  32. package/dist/cli-bundle/focused-chunks/chunk-RNDNMARJ.js +16 -0
  33. package/dist/cli-bundle/focused-chunks/chunk-TN4AE665.js +26 -0
  34. package/dist/cli-bundle/focused-chunks/chunk-TVV2DONO.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/chunk-UI6AJ5TD.js +4 -0
  36. package/dist/cli-bundle/focused-chunks/{chunk-MHPIL773.js → chunk-V5XTGLK7.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-KP2VQQVQ.js → chunk-WGHQVU6P.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/chunk-XYNBXTDQ.js +2 -0
  39. package/dist/cli-bundle/focused-chunks/chunk-Z56ECT7I.js +2 -0
  40. package/dist/cli-bundle/main.js +7 -7
  41. package/dist/cli-bundle/sdk-authoring.js +1 -1
  42. package/dist/cli-bundle/sdk-contracts.js +1 -1
  43. package/dist/cli-bundle/sdk-core.js +31 -31
  44. package/dist/cli-bundle/sdk-governance.js +1 -1
  45. package/dist/cli-bundle/sdk-graph.js +1 -1
  46. package/dist/cli-bundle/sdk-merge.js +32 -32
  47. package/dist/cli-bundle/sdk-query.js +1 -1
  48. package/dist/cli-bundle/sdk-runtime.js +1 -1
  49. package/dist/cli-bundle/sdk-testing.js +1 -1
  50. package/dist/cli-bundle/sdk.js +4 -4
  51. package/dist/core/config/nested-settings.js +8 -2
  52. package/dist/core/extensions/exporter-output-contract.d.ts +12 -0
  53. package/dist/core/extensions/exporter-output-contract.js +67 -0
  54. package/dist/core/extensions/extension-types.d.ts +36 -1
  55. package/dist/core/extensions/extension-types.js +2 -2
  56. package/dist/core/extensions/loader.js +35 -44
  57. package/dist/core/history/event-index.d.ts +5 -0
  58. package/dist/core/history/event-index.js +133 -27
  59. package/dist/core/sentry/helpers.js +3 -3
  60. package/dist/core/shared/constants.js +5 -2
  61. package/dist/core/store/settings-validator.d.ts +4 -0
  62. package/dist/core/store/settings-validator.js +3 -2
  63. package/dist/core/store/settings.js +8 -2
  64. package/dist/mcp/tool-definitions.js +12 -7
  65. package/dist/sdk/agent/refusal-reachability.js +4 -4
  66. package/dist/sdk/authoring.d.ts +1 -1
  67. package/dist/sdk/authoring.js +2 -2
  68. package/dist/sdk/cli-bootstrap.d.ts +2 -2
  69. package/dist/sdk/cli-bootstrap.js +4 -4
  70. package/dist/sdk/cli-contracts/command-aliases.d.ts +34 -2
  71. package/dist/sdk/cli-contracts/command-aliases.js +64 -13
  72. package/dist/sdk/cli-contracts/enum-contracts.d.ts +4 -0
  73. package/dist/sdk/cli-contracts/enum-contracts.js +9 -2
  74. package/dist/sdk/cli-contracts/flag-contracts.js +11 -7
  75. package/dist/sdk/cli-contracts/grammar-contracts.d.ts +70 -0
  76. package/dist/sdk/cli-contracts/grammar-contracts.js +345 -0
  77. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +19 -2
  78. package/dist/sdk/cli-contracts/runtime-contracts.js +61 -14
  79. package/dist/sdk/cli-contracts/tool-parameter-tables.js +7 -2
  80. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  81. package/dist/sdk/cli-contracts/tool-schema.js +20 -11
  82. package/dist/sdk/cli-contracts.d.ts +2 -2
  83. package/dist/sdk/cli-contracts.js +4 -4
  84. package/dist/sdk/completion.js +13 -15
  85. package/dist/sdk/compose.d.ts +3 -3
  86. package/dist/sdk/compose.js +2 -2
  87. package/dist/sdk/contracts.d.ts +1 -0
  88. package/dist/sdk/contracts.js +3 -2
  89. package/dist/sdk/core.d.ts +1 -1
  90. package/dist/sdk/core.js +3 -3
  91. package/dist/sdk/environment/host-environment-errors.js +3 -3
  92. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +54 -14
  93. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +50 -14
  94. package/dist/sdk/guide-topics.js +5 -5
  95. package/dist/sdk/index.d.ts +4 -3
  96. package/dist/sdk/index.js +6 -5
  97. package/dist/sdk/init-agent-guidance.js +3 -3
  98. package/dist/sdk/mutation-events.d.ts +18 -2
  99. package/dist/sdk/mutation-events.js +59 -16
  100. package/dist/sdk/output.d.ts +44 -0
  101. package/dist/sdk/output.js +28 -2
  102. package/dist/sdk/query/complete-list.d.ts +94 -0
  103. package/dist/sdk/query/complete-list.js +173 -0
  104. package/dist/sdk/query/list.js +5 -2
  105. package/dist/sdk/query.d.ts +1 -0
  106. package/dist/sdk/query.js +3 -2
  107. package/dist/sdk/read-output-contracts.d.ts +2 -2
  108. package/dist/sdk/read-output-contracts.js +36 -9
  109. package/dist/sdk/runtime-extended-actions.js +10 -2
  110. package/dist/sdk/runtime.d.ts +8 -2
  111. package/dist/sdk/runtime.js +11 -8
  112. package/dist/types.d.ts +5 -0
  113. package/dist/types.js +2 -2
  114. package/docs/AGENT_GUIDE.md +25 -9
  115. package/docs/CLI_GRAMMAR.md +106 -0
  116. package/docs/COMMANDS.md +23 -23
  117. package/docs/ONBOARDING.md +4 -4
  118. package/docs/QUICKSTART.md +1 -1
  119. package/docs/README.md +2 -0
  120. package/docs/RELEASING.md +30 -6
  121. package/docs/SDK.md +36 -2
  122. package/docs/SDK_ARTIFACT_OUTPUT.md +72 -0
  123. package/docs/SDK_CONTEXT_COORDINATION.md +46 -12
  124. package/docs/agent-task-token-baseline.json +5 -5
  125. package/marketplace.json +2 -2
  126. package/package.json +3 -2
  127. package/packages/pm-beads/package.json +1 -1
  128. package/packages/pm-calendar/package.json +1 -1
  129. package/packages/pm-command-kit/package.json +1 -1
  130. package/packages/pm-digital-twin/package.json +1 -1
  131. package/packages/pm-governance-audit/package.json +1 -1
  132. package/packages/pm-guide-shell/package.json +1 -1
  133. package/packages/pm-kanban/package.json +1 -1
  134. package/packages/pm-lifecycle-hooks/package.json +1 -1
  135. package/packages/pm-linked-test-adapters/package.json +1 -1
  136. package/packages/pm-search-advanced/package.json +1 -1
  137. package/packages/pm-templates/package.json +1 -1
  138. package/packages/pm-todos/package.json +1 -1
  139. package/packages/pm-vcs/package.json +1 -1
  140. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  141. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  142. package/sdk/public-surface.json +652 -31
  143. package/dist/cli-bundle/chunks/chunk-2QLOXC3V.js +0 -3
  144. package/dist/cli-bundle/chunks/chunk-4JPYF536.js +0 -35
  145. package/dist/cli-bundle/chunks/chunk-6VDLG2FC.js +0 -13
  146. package/dist/cli-bundle/chunks/chunk-ION3E43Q.js +0 -197
  147. package/dist/cli-bundle/chunks/chunk-OAC5NIV4.js +0 -3
  148. package/dist/cli-bundle/chunks/register-list-query-Q7KII4G5.js +0 -10
  149. package/dist/cli-bundle/focused-chunks/chunk-267MUUS6.js +0 -16
  150. package/dist/cli-bundle/focused-chunks/chunk-2NNFLLNG.js +0 -2
  151. package/dist/cli-bundle/focused-chunks/chunk-2QSAKMIH.js +0 -2
  152. package/dist/cli-bundle/focused-chunks/chunk-BUCG4ZI2.js +0 -2
  153. package/dist/cli-bundle/focused-chunks/chunk-EHXIKD6K.js +0 -2
  154. package/dist/cli-bundle/focused-chunks/chunk-KGEXTMPG.js +0 -2
  155. package/dist/cli-bundle/focused-chunks/chunk-POEEAD2V.js +0 -4
  156. package/dist/cli-bundle/focused-chunks/chunk-XPIC53VA.js +0 -26
  157. package/dist/cli-bundle/focused-chunks/chunk-ZT2DJS27.js +0 -155
@@ -1,26 +1,26 @@
1
- import{n as tm,o as ls,p as im,q as am,r as Pi,s as ps,t as cm,u as Ni,v as fs,y as Sm,z as Em}from"./focused-chunks/chunk-XPIC53VA.js";import{a as Rm,f as Im,h as Dt,m as Nm,o as Lm,s as Fm}from"./focused-chunks/chunk-BUCG4ZI2.js";import{$ as oa,$a as vp,Aa as np,Ba as rp,Ca as sp,Cb as Ap,Da as op,Db as Lp,Ea as ip,Eb as Fp,Fa as En,G as Pu,Ga as ap,Ha as cp,I as w,J as Nu,Ja as Yn,K as Lu,Ka as dp,L as Le,La as lp,M as Fu,Ma as mp,N as Zi,Na as up,O as $u,Oa as pp,P as ea,Pa as fp,Q as Ks,R as ta,S as qt,Sa as _p,T as na,Ta as Hs,U as he,Ua as sw,V as ra,Va as hp,W as Ve,Wa as gp,X as Mu,Xa as ia,Y as Du,Ya as yp,Z as sa,Za as bp,_ as Uu,_a as wp,a as Di,ab as kp,b as fu,bb as Sp,cb as Jn,db as aa,eb as ca,fb as Vs,gb as da,ha as Gu,hb as Ep,i as Cu,ib as la,j as Ru,ja as zs,jb as Ws,ka as Bs,kb as Tn,la as ju,lb as ma,ma as qu,mb as ua,na as Ku,nb as Tp,oa as zu,pa as Bu,qa as Hu,qb as Ys,ra as Vu,sa as Wu,ta as Yu,ua as Ju,va as Xu,wa as Qu,xa as Zu,ya as ep,za as tp}from"./focused-chunks/chunk-SALH6B6K.js";import{e as Ql,g as Zl,h as em,k as nm,q as om}from"./focused-chunks/chunk-SYZENPIT.js";import{c as Tm,d as _s,f as Am,g as Cm,h as Bb}from"./focused-chunks/chunk-KGEXTMPG.js";import{G as Mi,K as km,a as Vd,b as Wd,c as Yd,d as Jd,f as Xd}from"./focused-chunks/chunk-2NNFLLNG.js";import{a as mu,b as uu,c as Qs}from"./focused-chunks/chunk-CYFK5UPB.js";import{Z as Ou,b as pu,e as Iu,f as Vn,g as Wn,i as Qi,t as xu}from"./focused-chunks/chunk-MHPIL773.js";import{A as Ip,Aa as _a,Ba as Xs,Ca as iw,Da as aw,F as xp,G as Op,H as Pp,L as Et,N as pa,Va as ha,_a as Zn,a as au,ab as Np,b as As,c as Yi,d as cu,e as Cs,eb as ga,f as Rs,g as Is,h as du,i as lu,m as vu,n as ku,o as Su,p as Eu,q as Tu,r as Au,rb as er,s as Xn,sb as ya,x as Js,y as Rp,ya as ow,z as Qn,za as fa}from"./focused-chunks/chunk-267MUUS6.js";import{A as Ji,B as qs,Ca as wu,D as hu,E as gu,Ea as Zs,F as Hn,Ia as An,a as xs,b as Os,c as Ps,d as Ns,h as Ls,j as Fs,k as $s,l as _u,m as Ms,n as Ds,o as St,p as bn,q as Us,r as wn,s as Gs,t as te,u as js,v as Ue,va as Sn,w as Ne,wa as yu,x as se,xa as Xi,y as vn,ya as bu,z as kn}from"./focused-chunks/chunk-ZQPGZZWQ.js";import{c as Yl,f as Jl,g as Xl,i as ds,j as gt,k as dm,l as lm,m as mm}from"./focused-chunks/chunk-XKAMP5OU.js";import{$ as Fl,A as Gn,Aa as rs,B as ml,Ba as ss,C as ul,Ca as Wl,D as pl,Da as ht,E as fl,Ea as os,F as _l,Fa as is,G as hl,Ga as as,H as gl,Ha as cs,I as yl,J as bl,K as wl,L as vl,La as F,M as kl,N as Sl,O as El,P as Tl,Q as Al,R as Cl,S as Rl,T as zr,U as Br,V as Il,W as xl,X as Ol,Y as Pl,Z as Nl,_ as Ll,aa as $l,c as Oi,ca as Ml,da as Dl,e as $r,ea as Ul,f as Mr,fa as Gl,g as Dr,ga as jl,h as Qd,ha as ql,i as Zd,ia as Hr,j as el,ja as Vr,k as tl,ka as Wr,l as nl,la as Kl,m as Ur,ma as zl,n as rl,na as Yr,o as sl,oa as Bl,p as ol,pa as Hl,q as Gr,qa as Jr,r as il,ra as Xr,s as al,sa as Qr,t as cl,ta as Zr,u as jr,ua as jn,v as qr,va as es,w as dl,wa as Vl,x as Kr,xa as qn,ya as ts,z as ll,za as ns}from"./focused-chunks/chunk-2QSAKMIH.js";import{c as Cp}from"./focused-chunks/chunk-ATEY76SX.js";import{$a as A,Ca as De,Da as wt,F as ys,Fa as ks,G as Dm,Ga as Pe,H as Um,Ha as Gt,I as pn,Ia as Jm,J as zn,Ja as jt,K as Jb,Ka as Xm,L as Xb,M as Qb,Ma as Qm,N as Zb,Na as hn,O as ew,Oa as Zm,P as bs,Pa as Ss,Q as tw,Qa as ot,R as nw,S as rw,T as fn,U as R,V as S,Va as eu,Wa as tu,X as _n,Xa as vt,Z as Q,Za as nu,_ as xe,_a as ru,a as $m,ab as Se,ba as Gm,bb as su,c as Mm,ca as ws,cb as ou,da as jm,db as kt,e as Ui,ea as qm,eb as Wi,f as Gi,fa as Km,fb as _e,g as ji,ga as zm,gb as Bn,h as qi,ha as Bm,i as Ki,j as zi,ja as ne,k as Bi,l as I,la as Oe,m as mn,ma as vs,mb as gn,n as Ut,na as Hi,o as z,oa as Hm,ob as yn,p as hs,pa as Me,q as un,qa as He,qb as M,ra as bt,rb as K,sa as Vm,t as gs,ta as Vi,tb as re,ub as Es,v as st,va as Wm,vb as Ts,w as Hb,wa as Ym,wb as it,x as Vb,xb as Y,y as Wb,yb as iu,z as Yb,zb as Ee}from"./focused-chunks/chunk-ZT2DJS27.js";import{$ as Ld,B as Ii,C as Dn,D as fe,G as x,Ga as Lr,H as ue,Ha as Hd,I as Or,Ia as Fr,J as an,K as Un,L as Pd,La as nt,M as T,N as Nd,Na as ms,O as et,Oa as rt,P as C,Pa as yt,Q as Mt,Qa as rm,S as ke,Sa as G,T as Pr,Ta as us,Ua as Be,Wa as sm,Z as cn,ba as xi,ca as Fd,ea as $d,ga as Nr,h as ft,i as Ir,ia as Md,j as xr,ja as Dd,la as Ud,ma as Gd,na as jd,oa as qd,pa as Kd,q as k,qa as zd,r as $t,ra as Bd,s as _t,t as q,u as me,w as on}from"./focused-chunks/chunk-POEEAD2V.js";import{f as xm,g as Om,j as ln,n as Pm}from"./focused-chunks/chunk-KP2VQQVQ.js";import{A as Cd,Aa as wm,B as Rd,C as Id,D as xd,E as ki,F as Si,G as Ei,Ga as Li,H as Ti,I as Ai,Ia as Fb,J as Ci,Ja as $b,Q as Ri,S as Rr,T as Od,Ta as Mb,Va as Db,W as pt,Wa as Ub,Xa as Fi,Y as d,Ya as Gb,Z as l,Za as $i,aa as J,ab as vm,ba as tt,bb as jb,db as qb,ea as um,eb as Kb,fa as pm,fb as zb,ga as fm,ha as _m,ia as hm,ja as gm,ka as Kn,l as Tr,la as ym,m as Ed,ma as bm,n as Ar,o as vi,oa as dn,s as Ft,t as Ze,u as rn,v as sn,w as Cr,wa as Ob,xa as Pb,y as Td,ya as Nb,z as Ad,za as Lb}from"./focused-chunks/chunk-EHXIKD6K.js";import{AsyncLocalStorage as OL}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 $p(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function cw(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 ba(e,t){let n=cw(t),r=n==="brief"?n:$p(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:$p(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 Mp(e,t){let n=T(t??process.cwd(),e),r=await A(n);return re(n,r.item_format,x(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9eae1a3-3eb6-5415-86c3-a8e8e1fedd1f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c898a52-eba4-5626-8207-5ffefd4990ba")}catch{}})();var dw=new Map;function wa(){dw.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f62939a-7b99-5687-93ae-834e0032f1d5")}catch{}})();var lw={"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 Dp(e){return Object.fromEntries(bm.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Up={ctx:{action:"context"},...lw,...Dp("extension"),...Dp("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 va="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<=d.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function Gp(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new l(e,mw(t.exitCode??d.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function eo(e){if(!(e instanceof Error)||e.name!==va)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 ka(e){let t=$d();for(let n of e)t.register(n);return t}function jp(e,t){return{client:t,isItemNotFoundError:n=>eo(n)&&n.exitCode===d.NOT_FOUND,getItemAt:(n,r)=>lu(n,r,{pmRoot:e}),openRelationshipEventStore:n=>uu.open({pmRoot:e,nodes:n.nodes,registry:ka(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new Dd(n.nodes,n.edges,ka(n.definitions)),analyzeRelationshipImpact:(n,r,s)=>pu(n,r,s),validateRelationshipEvents:n=>{let r=new mu(n.nodes,{registry:ka(n.definitions)});return n.events.map(s=>r.append({...s,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>fu({...n,pmRoot:e})}}import{readFile as uw}from"node:fs/promises";import pw from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ba0243e-98d1-5aef-bd47-54f0b630be58")}catch{}})();var Sa="context-intents.json";function to(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fw(e,t,n){if(!to(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 qp(e,t){let n=Array.isArray(e)?e:to(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,s)=>fw(r,t,s))}async function _w(e){let t=pw.join(e,Sa),n;try{n=await uw(t,"utf8")}catch(s){if($t(s))return[];throw s}let r;try{r=JSON.parse(n)}catch(s){let o=s instanceof Error?s.message:String(s);throw new TypeError(`Invalid ${Sa}: ${o}`,{cause:s})}return qp(r,Sa)}function hw(e){if(!to(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return to(n)?n.contextIntents??n.context_intents:void 0}function gw(e){return e.flatMap(t=>{let n=hw(t.module);return n===void 0?[]:qp(n,`package ${t.name}`)})}async function yw(e){let t=await _w(e.pmRoot),n=gw(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Ea(e,t){let n=await yw(e);return await Om(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e3ba7e9-8822-53ba-981e-e177be5219f3")}catch{}})();async function Kp(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=Ne(),s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=R(t.author,o.author_default),c=(await r.resolveValue(t.body,"--body")).trim();if(c.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",d.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let m=await Y({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 im,o as ms,p as mm,q as um,r as Ni,s as fs,t as pm,u as Li,v as _s,y as Im,z as xm}from"./focused-chunks/chunk-TN4AE665.js";import{c as Lm,d as dn,f as Fm,k as Mm,m as Dt,r as Gm,t as jm,x as qm}from"./focused-chunks/chunk-Z56ECT7I.js";import{$ as la,$a as Ip,Aa as lp,Ba as mp,Ca as up,Cb as Lp,Da as pp,Db as qp,Ea as fp,Eb as Kp,Fa as En,G as Gu,Ga as _p,Ha as hp,I as w,J as ju,Ja as Jn,K as qu,Ka as gp,L as Le,La as yp,M as Ku,Ma as bp,N as sa,Na as wp,O as zu,Oa as vp,P as oa,Pa as kp,Q as zs,R as ia,S as qt,Sa as Sp,T as aa,Ta as Vs,U as he,Ua as pw,V as ca,Va as Ep,W as Ve,Wa as Tp,X as Bu,Xa as ma,Y as Hu,Ya as Ap,Z as da,Za as Cp,_ as Vu,_a as Rp,a as ji,ab as xp,b as ku,bb as Op,cb as Xn,db as ua,eb as pa,fb as Ws,gb as fa,ha as Wu,hb as Pp,i as Fu,ib as _a,j as Mu,ja as Bs,jb as Ys,ka as Hs,kb as Tn,la as Yu,lb as ha,ma as Ju,mb as ga,na as Xu,nb as Np,oa as Qu,pa as Zu,qa as ep,qb as Js,ra as tp,sa as np,ta as rp,ua as sp,va as op,wa as ip,xa as ap,ya as cp,za as dp}from"./focused-chunks/chunk-ODOVCP45.js";import{e as rm,g as sm,h as om,k as am,q as lm}from"./focused-chunks/chunk-EUEGXZ2A.js";import{b as Om,c as hs,e as Pm,f as Nm,g as ew}from"./focused-chunks/chunk-XYNBXTDQ.js";import{G as Gi,K as Rm,a as Qd,b as Zd,c as el,d as tl,f as nl}from"./focused-chunks/chunk-C5IW2NDA.js";import{a as bu,b as wu,c as Zs}from"./focused-chunks/chunk-K43KKAFS.js";import{Z as Uu,b as vu,e as $u,f as Wn,g as Yn,i as ra,t as Du}from"./focused-chunks/chunk-V5XTGLK7.js";import{$a as va,D as Xs,E as Mp,Ea as fw,F as Zn,Fa as ba,G as $p,Ga as wa,Ha as Qs,Ia as _w,Ja as hw,L as Dp,M as Up,N as Gp,R as Et,T as ya,c as Qi,e as Zi,eb as er,g as _u,gb as jp,h as Cs,i as ea,j as hu,k as Rs,kb as ka,l as Is,m as xs,n as gu,o as yu,s as Iu,t as xu,u as Ou,v as Pu,w as Nu,x as Lu,xb as tr,y as Qn,yb as Sa}from"./focused-chunks/chunk-RNDNMARJ.js";import{A as ta,B as Ks,Ca as Ru,D as Eu,E as Tu,Ea as eo,F as Vn,Ia as An,a as Os,b as Ps,c as Ns,d as Ls,h as Fs,j as Ms,k as $s,l as Su,m as Ds,n as Us,o as St,p as bn,q as Gs,r as wn,s as js,t as te,u as qs,v as Ue,va as Sn,w as Ne,wa as Au,x as se,xa as na,y as vn,ya as Cu,z as kn}from"./focused-chunks/chunk-3TKWMNKF.js";import{c as em,f as tm,g as nm,i as ls,j as gt,k as fm,l as _m,m as hm}from"./focused-chunks/chunk-EX6MKP2X.js";import{$ as Gl,A as Gn,Aa as ss,B as hl,Ba as os,C as gl,Ca as Zl,D as yl,Da as ht,E as bl,Ea as is,F as wl,Fa as as,G as vl,Ga as cs,H as kl,Ha as ds,I as Sl,J as El,K as Tl,L as Al,La as F,M as Cl,N as Rl,O as Il,P as xl,Q as Ol,R as Pl,S as Nl,T as Br,U as Hr,V as Ll,W as Fl,X as Ml,Y as $l,Z as Dl,_ as Ul,aa as jl,c as Pi,ca as ql,da as Kl,e as $r,ea as zl,f as Dr,fa as Bl,g as Ur,ga as Hl,h as rl,ha as Vl,i as sl,ia as Vr,j as ol,ja as Wr,k as il,ka as Yr,l as al,la as Wl,m as Gr,ma as Yl,n as cl,na as Jr,o as dl,oa as Jl,p as ll,pa as Xl,q as jr,qa as Xr,r as ml,ra as Qr,s as ul,sa as Zr,t as pl,ta as es,u as qr,ua as jn,v as Kr,va as ts,w as fl,wa as Ql,x as zr,xa as qn,ya as ns,z as _l,za as rs}from"./focused-chunks/chunk-TVV2DONO.js";import{c as Fp}from"./focused-chunks/chunk-M62NO7EI.js";import{$a as mu,Ab as Ee,Da as De,Ea as wt,F as bs,G as Bm,Ga as Ss,H as Hm,Ha as Pe,I as pn,Ia as Gt,J as Bn,Ja as su,K as ow,Ka as jt,L as iw,La as ou,M as aw,N as cw,Na as iu,O as dw,Oa as hn,P as ws,Pa as au,Q as lw,Qa as Es,R as mw,Ra as ot,S as uw,T as fn,U as R,V as S,Wa as cu,X as _n,Xa as du,Ya as vt,Z as Q,_ as xe,_a as lu,a as Km,ab as A,ba as Vm,bb as Se,c as zm,ca as vs,cb as uu,da as Wm,db as pu,e as qi,ea as Ym,eb as kt,f as Ki,fa as Jm,fb as Xi,g as zi,ga as Xm,gb as _e,h as Bi,ha as Qm,hb as Hn,i as Hi,j as Vi,ja as ne,k as Wi,l as I,la as Oe,m as mn,ma as ks,n as Ut,na as Yi,nb as gn,o as z,oa as Zm,p as gs,pa as $e,pb as yn,q as un,qa as He,ra as bt,rb as $,sa as eu,sb as K,t as ys,ta as tu,ua as Ji,ub as re,v as st,vb as Ts,w as tw,wa as nu,wb as As,x as nw,xa as ru,xb as it,y as rw,yb as Y,z as sw,zb as fu}from"./focused-chunks/chunk-5AF3ZBNB.js";import{$ as Ud,B as xi,C as Dn,D as fe,G as x,Ga as Fr,H as ue,Ha as Xd,I as Pr,Ia as Mr,J as an,K as Un,L as $d,La as nt,M as T,N as Dd,Na as us,O as et,Oa as rt,P as C,Pa as yt,Q as $t,Qa as cm,S as ke,Sa as j,T as Nr,Ta as ps,Ua as Be,Wa as dm,Z as cn,ba as Oi,ca as Gd,ea as jd,ga as Lr,h as ft,i as xr,ia as qd,j as Or,ja as Kd,la as zd,ma as Bd,na as Hd,oa as Vd,pa as Wd,q as k,qa as Yd,r as Mt,ra as Jd,s as _t,t as q,u as me,w as on}from"./focused-chunks/chunk-UI6AJ5TD.js";import{f as $m,g as Dm,j as ln,n as Um}from"./focused-chunks/chunk-WGHQVU6P.js";import{$a as Vb,A as Pd,B as Nd,C as Ld,Ca as Gb,D as Fd,Da as jb,E as Si,Ea as qb,F as Ei,Fa as Kb,G as Ti,Ga as Am,H as Ai,I as Ci,J as Ri,Ma as $i,Oa as zb,Pa as Bb,Q as Ii,S as Ir,T as Md,W as pt,Y as d,Z as l,Za as Hb,aa as J,ab as Wb,ba as tt,bb as Di,cb as Yb,db as Ui,ea as Kn,gb as Cm,hb as Jb,ia as gm,ja as ym,jb as Xb,ka as bm,kb as Qb,l as Ar,la as wm,lb as Zb,m as Id,ma as vm,n as Cr,na as km,o as ki,oa as zn,pa as Sm,qa as Em,s as Ft,sa as Fi,t as Ze,ta as Tm,u as rn,ua as Mi,v as sn,w as Rr,y as xd,z as Od}from"./focused-chunks/chunk-2PN4TJXH.js";import{AsyncLocalStorage as jL}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 zp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function gw(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 Ea(e,t){let n=gw(t),r=n==="brief"?n:zp(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:zp(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 Bp(e,t){let n=T(t??process.cwd(),e),r=await A(n);return re(n,r.item_format,x(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9eae1a3-3eb6-5415-86c3-a8e8e1fedd1f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c898a52-eba4-5626-8207-5ffefd4990ba")}catch{}})();var yw=new Map;function Ta(){yw.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 bw={"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 Hp(e){return Object.fromEntries(Em.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Vp={ctx:{action:"context"},...bw,...Hp("extension"),...Hp("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 Aa="PmCliError";function ww(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=d.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function Wp(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new l(e,ww(t.exitCode??d.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function to(e){if(!(e instanceof Error)||e.name!==Aa)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 Ca(e){let t=jd();for(let n of e)t.register(n);return t}function Yp(e,t){return{client:t,isItemNotFoundError:n=>to(n)&&n.exitCode===d.NOT_FOUND,getItemAt:(n,r)=>yu(n,r,{pmRoot:e}),openRelationshipEventStore:n=>wu.open({pmRoot:e,nodes:n.nodes,registry:Ca(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new Kd(n.nodes,n.edges,Ca(n.definitions)),analyzeRelationshipImpact:(n,r,s)=>vu(n,r,s),validateRelationshipEvents:n=>{let r=new bu(n.nodes,{registry:Ca(n.definitions)});return n.events.map(s=>r.append({...s,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>ku({...n,pmRoot:e})}}import{readFile as vw}from"node:fs/promises";import kw from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ba0243e-98d1-5aef-bd47-54f0b630be58")}catch{}})();var Ra="context-intents.json";function no(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sw(e,t,n){if(!no(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 Jp(e,t){let n=Array.isArray(e)?e:no(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)=>Sw(r,t,s))}async function Ew(e){let t=kw.join(e,Ra),n;try{n=await vw(t,"utf8")}catch(s){if(Mt(s))return[];throw s}let r;try{r=JSON.parse(n)}catch(s){let o=s instanceof Error?s.message:String(s);throw new TypeError(`Invalid ${Ra}: ${o}`,{cause:s})}return Jp(r,Ra)}function Tw(e){if(!no(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return no(n)?n.contextIntents??n.context_intents:void 0}function Aw(e){return e.flatMap(t=>{let n=Tw(t.module);return n===void 0?[]:Jp(n,`package ${t.name}`)})}async function Cw(e){let t=await Ew(e.pmRoot),n=Aw(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Ia(e,t){let n=await Cw(e);return await Dm(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e3ba7e9-8822-53ba-981e-e177be5219f3")}catch{}})();async function Xp(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=Ne(),s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=R(t.author,o.author_default),c=(await r.resolveValue(t.body,"--body")).trim();if(c.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",d.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let m=await Y({pmRoot:s,settings:o,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
2
2
 
3
3
  `:"";return u.body=`${u.body.trimEnd()}${p}${c}
4
- `,{changedFields:["body"]}}});return{item:m.item,appended:c,changed_fields:m.changedFields}}import{readFile as bw}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0af9967c-ca72-563a-9518-2e68da0c0fe0")}catch{}})();function ro(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,t}function zp(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,d.USAGE,{code:"structured_event_immutable"})}function Ta(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Kt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Cn(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=te(n,"--add");return Object.keys(o).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:o.text?.trim()||n}catch{return n}}function Aa(e){return typeof e=="object"&&e!==null&&"code"in e}async function ww(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,d.USAGE);let r=Ne();if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add")??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new l("--file path cannot be empty",d.USAGE);try{return{value:await bw(s,"utf8"),emptyFlag:"--file"}}catch(o){if(Aa(o)&&$t(o))throw new l(`--file path not found: ${s}`,d.USAGE);let i=o instanceof Error?o.message:String(o);throw new l(`Failed to read --file path "${s}": ${i}`,d.USAGE)}}async function so(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",d.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",d.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",d.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",d.USAGE);let n=await ww(e,t);if(e.edit!==void 0){if(!n)throw new l("--edit requires replacement text from --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function nr(e,t){throw e instanceof l&&e.exitCode===d.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Hp(e){return e==="comments"?"--stdin":"--add -"}function vw(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=Hp(t.collectionKey),o=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new l(`--add value "${r}" looks like an option, not annotation text. Use ${s} to read stdin, or use text=${r} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${s} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${o} ${s}`,`${o} --add text=${r}`]})}function kw(e,t){if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,d.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${Hp(e.collectionKey)}`]})}async function Rn(e,t,n,r){kw(r,t);let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=x(o,I()),a=Hn(t.limit);if(r.input.mode==="list"){let _=await M(s,e,o.id_prefix,o.item_format,i.type_to_folder);if(!_)throw new l(`Item ${e} not found`,d.NOT_FOUND);let h=await K(_,{schema:o.schema}),y=Kt(h.document.metadata,r.collectionKey);return no(_.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=R(t.author,o.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,h;try{h=await Y({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Kt(g.metadata,r.collectionKey),v=Bp(r.input.index,b.length,r.collectionKey);return zp(b[v],"deleted"),b.splice(v,1),g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){nr(g,r.conflictGuidance)}let y=Kt(h.item,r.collectionKey);return no(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";vw(m,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,d.USAGE);if(r.input.mode==="edit"){let _=r.editOp??r.op,h;try{h=await Y({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Kt(g.metadata,r.collectionKey),v=Bp(r.input.index,b.length,r.collectionKey),E=b[v];return zp(E,"edited"),b[v]={...E,text:u,edited_at:S()},g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){nr(g,r.conflictGuidance)}let y=Kt(h.item,r.collectionKey);return no(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 Y({pmRoot:s,settings:o,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(_){let h=Kt(_.metadata,r.collectionKey),y={created_at:S(),author:c,text:u};return h.push(r.createEntry(y)),_.metadata[r.collectionKey]=h,{changedFields:[r.collectionKey]}}})}catch(_){nr(_,r.conflictGuidance)}let f=Kt(p.item,r.collectionKey);return no(p.item.id,r.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:f.length,entry:f.at(-1)},t.fullHistory===!0)}function Bp(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),s=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,o=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${s} index ${e??"(missing)"} out of range (item has ${o})`,d.USAGE)}return e-1}function no(e,t,n,r,s,o,i=!1){let a=o===void 0||i?Ta(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 Vp(e,t,n){return[...await bt(ke(e,t),t).catch(()=>[])].reverse().find(o=>o.patch.some(i=>i.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f70f1329-4dfb-5625-ae0a-66c858d88f7b")}catch{}})();var Wp="no_available_next_item";function Yp(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 oo(e,t,n,r={}){let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=G(o.schema),a=R(r.author,o.author_default),c=fn(a),m=null,u=!1,p=[],f=await Y({pmRoot:s,settings:o,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,sm(_.metadata.status,i)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&g!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let v=await Vp(s,_.metadata.id,y);throw new l(`Item ${_.metadata.id} is already ${v}. Use --force to take over, or --if-available to skip without failing.`,d.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}p.push(`claim_takeover:${m}->${a}`)}return _.metadata.assignee=a,_.metadata.claim_principal=c,{changedFields:["assignee","claim_principal"],warnings:p}}});return u||await fa({pmRoot:s,settings:o,principal:c,itemId:f.item.id}),{item:f.item,claimed_by:u&&m!==null?m:a,previous_assignee:m,forced:t,...u?{skipped:!0}:{},...p.length>0?{warnings:p}:{}}}async function Jp(e,t,n={},r={}){let s=Sw(n.maxAttempts),o=await A(T(process.cwd(),t.path)),i={...n,author:R(n.author,o.author_default)},a=await Zn({...r,callerAuthor:i.author,limit:String(s)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return Ew(c.slice(0,s),e,t,i)}function Sw(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new l("--max-attempts must be an integer from 1 to 100",d.USAGE);return t}async function Ew(e,t,n,r={},s=oo){let o=0;for(let a of e){o+=1;try{let c=await s(a.id,t,n,r),m={...c,recommendation:a,attempts:o,available:!0};if(!c.skipped)return m}catch(c){if(!Yp(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:R(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:o,warnings:[Wp]};let i=o===0;throw new l(i?"No actionable items matched the selection filters":"No actionable item remained available to claim",i?d.NOT_FOUND:d.CONFLICT,{code:Wp,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 io(e,t,n,r={}){let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=R(r.author,o.author_default),a=fn(i),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await Y({pmRoot:s,settings:o,id:e,op:"release",author:i,message:r.message,force:t,bypassAssigneeConflict:c,mutate(p){return m=p.metadata.assignee??null,!m&&!p.metadata.claim_principal?{changedFields:[]}:(delete p.metadata.assignee,delete p.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(p){nr(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 _a({pmRoot:s,principal:a,itemId:u.item.id}),{item:u.item,released_by:i,previous_assignee:m,forced:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7ae3c89-b50b-5e4f-8273-8318bc976d84")}catch{}})();var Tw=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function Xp(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 Ca(e,t){return Ra(e,t,{operation:"close"})}function Ra(e,t,n){let r=Xp(e);if(!t||r.closeReason!==void 0)return r;let s=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",d.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:s,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function Ia(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,s=e.dependencies??[],o=s.filter(m=>m.kind==="blocked_by"),i=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),i&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&o.length>0){let m=s.filter(u=>u.kind!=="blocked_by");m.length>0?e.dependencies=m:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...o.map(m=>m.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[t.orderingEdges==="preserve"?`closed_preserved_predecessors:${e.id}:${c.join(",")}`:`closed_removed_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="83affe54-a56c-5d84-b6b0-9634d4238ff5")}catch{}})();var Aw=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function Cw(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new l(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,d.USAGE)}function Rw(e){let t=[];for(let n of Aw){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function Iw(e,t,n){let r=new Set,s=t;for(;typeof s=="string"&&s.trim().length>0;){let o=s.trim();if(o===n)return!0;if(r.has(o))return!1;r.add(o),s=(await e(o))?.duplicate_of}return!1}function xw(e){return typeof e!="string"||e.trim().length===0}async function Ow(e,t,n,r){let s=n?.trim();if(!s)return;if(s===r)throw new l("An item cannot be closed as a duplicate of itself.",d.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let o=x(t,I()),i=new Map,a=async m=>{if(i.has(m))return i.get(m)??null;let u=await M(e,m,t.id_prefix,t.item_format,o.type_to_folder);if(!u)return i.set(m,null),null;let{document:p}=await K(u,{schema:t.schema});return i.set(m,p.metadata),p.metadata},c=await a(s);if(!c)throw new l(`Duplicate target "${s}" was not found. Create or locate the canonical item first.`,d.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${s}" --duplicate-of ${s}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await Iw(a,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${s}" points back to "${r}".`,d.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new l(`Duplicate target "${s}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,d.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function Pw(e,t,n){return e.filter(r=>r.parent===t&&!Oe(r.status,n)).map(r=>r.id).sort((r,s)=>r.localeCompare(s))}function Nw(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),s=Cp(e),o=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:s.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(o)).filter(({blockerIds:a})=>a.every(c=>{if(c===o)return!0;let m=r.get(c);return m!==void 0&&Oe(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function Lw(e,t,n,r,s,o){let i=Nw(n,r,o),a=[];for(let c of i)try{let m=await Y({pmRoot:e,settings:t,id:c.id,op:"update",author:s,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(h=>{let y=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=o.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let u=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${u}`)}return a}function Fw(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 $w(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:s,value:o}of r)xw(e[s])&&(e[s]=o,n.push(s));return n}function Mw(e,t,n,r){let s=[];if(t!=="off"){let o=Rw(e);if(o.length>0){let i=o.map(a=>a.label);if(t==="strict"){let a=o.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(m=>[m,"<value>"])];throw new l(`Cannot close item ${e.id}: missing ${i.join(", ")}. Populate fields or use --validate-close warn.`,d.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:zs(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}s.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new l(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,d.USAGE);s.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return s}return n.length>0&&s.push(`closed_with_active_children:${e.id}:${n.join(",")}`),s}function Dw(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function Uw(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function Gw(e,t){if(Oe(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use --force to close again.`,d.CONFLICT);let n=Fw(e,t.options),r=$w(e,t.duplicateOf),s=Mw(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"]:[],...Dw(e,t.closeReason),...n];if(bu(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(...Uw(e));let a=Ia(e,t.lifecyclePolicy);return i.push(...a.changedFields),s.push(...a.warnings),{changedFields:i,...s.length>0?{warnings:s}:{}}}async function Qp(e,t,n,r){let s=T(process.cwd(),r.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=G(o.schema),a=R(n.author,o.author_default),c=x(o,I()).type_to_folder,m=await M(s,e,o.id_prefix,o.item_format,c);if(!m)throw await it(s,e,o.id_prefix,c);let u=await Ow(s,o,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Ca({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=Cw(n.validateClose)??o.governance.close_validation_default,h=await re(s,o.item_format,c,void 0,o.schema),y=Pw(h,m.id,i),g=new Date().toISOString(),b=n.completedAt===void 0?g:Q(n.completedAt,new Date(g),"completed-at"),v=await Y({pmRoot:s,settings:o,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(E){return Gw(E.metadata,{pmRoot:s,statusRegistry:i,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:g,completedAt:b,lifecyclePolicy:p})}});return{item:v.item,changed_fields:v.changedFields,warnings:[...v.warnings,...await Lw(s,o,h,m.id,a,i)]}}function Tt(e,t,n,r){return Qp(e,t,n,r)}import jw from"fast-json-patch";import xa from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="353be665-9f67-5d0e-99c9-6bbb7e927e0b")}catch{}})();function qw(e,t){return au(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Kw(e){let t=Yi(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:He(Gt(t))}async function zw(e,t,n,r){let s=await M(e,t,n.id_prefix,n.item_format,r);if(s){let c=ke(e,s.id),m=await su({pmRoot:e,settings:n,itemId:s.id,commandLabel:"restore"});return{id:s.id,historyPath:c,located:s,historyPolicyWarnings:m.warnings}}let o=_e(t,n.id_prefix),i=Wi(t),a=o===i?[o]:[o,i];for(let c of a){let m=ke(e,c);if(await k(m))return{id:c,historyPath:m,located:null,historyPolicyWarnings:[]}}throw new l(`Item ${t} not found`,d.NOT_FOUND)}function Bw(e,t){let n=jt(e),r=jt(t),s=jw.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 Hw(e){if(await q(e.subject.historyPath)!==e.historyRawBeforeLock)throw new l(`History for ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);let n=await M(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),r=n?await K(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==e.currentItemRawBeforeLock)throw new l(`Item ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);return{loadedItemUnderLock:r,existingItemPath:n?.itemPath??null}}function Vw(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Kw(t),originalRaw:null}}function Ww(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new l(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,d.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function Yw(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await me(e.existingItemPath,e.resolvedOriginalRaw),await xa.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await me(e.existingItemPath,e.resolvedOriginalRaw);return}await xa.rm(e.restoredItemPath,{force:!0})}async function Jw(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 zt(e,t,n,r){let s=T(process.cwd(),r.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=x(o,I()),a=await zw(s,e,o,i.type_to_folder),c=a.id,m=await q(a.historyPath),u=await bt(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let p=qw(t,u),f=cu(Yi(u,p.historyIndex),p),_=Jm(f,{schema:o.schema});if(_.metadata.id!==c)throw new l(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let y=(a.located?await K(a.located,{schema:o.schema}):null)?.raw??null,g=R(n.author,o.author_default),b=await xe(s,c,o.locks.ttl_seconds,g,!!n.force,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let{loadedItemUnderLock:v,existingItemPath:E}=await Hw({pmRoot:s,resolvedId:c,subject:a,settings:o,typeToFolder:i.type_to_folder,historyRawBeforeLock:m,currentItemRawBeforeLock:y}),N="toon",P=Vw(v,u),$=Ww({document:P.document,author:g,force:n.force,enforcement:o.governance.ownership_enforcement,resolvedId:c}),U=Bw(P.document,_);await hs({pm_root:s,operation:"restore",before:P.document,after:_,changed_fields:U,sdk:Ts({pmRoot:s,settings:o,typeToFolder:i.type_to_folder})});let Ie=Me(_,{format:N,schema:o.schema}),ee=Mt(s,_.metadata.type,c,N,i.type_to_folder),pe=await gn(s,g),ie=[];try{await me(ee,Ie),E&&ee!==E&&await xa.rm(E);let Pt=De({nowIso:S(),author:g,op:"restore",before:P.document,after:_,message:n.message});try{await wt(a.historyPath,Pt)}catch(ut){throw await Yw({existingItemPath:E,resolvedOriginalRaw:P.originalRaw,restoredItemPath:ee}),ut}ie=await yn({pmRoot:s,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:ee,previousItemPath:E??void 0,document:_})}finally{await pe()}let Xe=await Jw({restoredItemPath:ee,historyPath:a.historyPath,before:P.document,after:_});mn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:P.document.metadata.status,status:_.metadata.status,previous:Ut(P.document.metadata,U),current:Ut(_.metadata,U),changed_fields:U});let ze=u[p.historyIndex];return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,entry_ts:ze.ts,entry_op:ze.op},changed_fields:U,warnings:[...a.historyPolicyWarnings,...$,...ie,...Xe]}}finally{await b()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4da07a98-855e-59cf-a6a4-2f59a8b3c0bd")}catch{}})();var ef=1,Oa="close-many",Xw=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function Qw(e,t){return Xn(e,t,{includePagination:!1})}function Zw(e,t){return Xn(e,t)}function ev(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)}function 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 nv(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new l("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",d.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function rv(e,t){let n=G(t.schema),r=x(t,I()),s=await re(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),Oe(a.status,n)))continue;let c=o.get(a.parent);c?c.push(a.id):o.set(a.parent,[a.id])}for(let a of o.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:o,parentByChild:i}}function Zp(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let s=0,o=t.get(e),i=[],a=new Set,c=!1;for(;o!==void 0&&!a.has(o);){let m=n?.get(o);if(m!==void 0){s+=m+1;break}a.add(o),i.push(o),s+=1,o=t.get(o)}if(o!==void 0&&a.has(o)&&(c=!0),!c){n?.set(e,s);for(let[m,u]of i.entries())n?.set(u,s-m-1)}return s}async function sv(e){let t=await Ps(e.pmRoot,Oa,e.rollbackId,ef),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Ns(t.items,(s,o)=>zt(s,o,{author:e.options.author,message:n,force:!0},e.global));return{...Dt({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 ov(e,t,n,r,s){return e.map(o=>{let i=(t.get(o.id)??[]).filter(c=>!n.has(c)),a=!tf(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 iv(e){let t=await Os(e.pmRoot,Oa,e.checkpointId,{schema_version:ef,id:e.checkpointId,created_at:e.nowValue,author:R(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function av(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 Tt(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:cn(s)})}}return{rows:t,closedIds:n}}function cv(e){return typeof e.rollback=="string"?e.rollback:void 0}function dv(e,t){if(t.trim().length===0)throw new l("--rollback requires a checkpoint id",d.USAGE);if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Zw(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function lv(e){if(!Qw(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${Xw}). Refusing to match every item.`,d.USAGE)}function mv(e,t){let n=new Map;return[...e].sort((r,s)=>{let o=Zp(s.id,t,n)-Zp(r.id,t,n);return o!==0?o:r.id.localeCompare(s.id)})}function tf(e,t,n){return n||!Oe(e.status,t)}function uv(e,t,n){return new Set(e.filter(r=>tf(r,t,n)).map(r=>r.id))}async function pv(e){lv(e.options);let t=G(e.settings.schema),n=nv(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,s=await Et(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))],m=new Set(a.map(p=>p.id)),u=uv(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:s,matched:a,unmatchedIds:c.filter(p=>!m.has(p)),planRows:ov(a,o,u,t,r)}}function fv(e){return{outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds.length>0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function _v(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return iv({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 nf(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=e.dryRun===!0,o=cv(e);if(ev(e.list),o!==void 0)return dv(e,o),sv({pmRoot:n,rollbackId:o,options:e,global:t});let i=await pv({pmRoot:n,settings:r,options:e,global:t});if(s)return fv(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=S(),m=xs(Oa,c),u=await _v({context:i,options:e,closableIds:a,checkpointId:m,nowValue:c}),p={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:i.validateCloseMode,force:i.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await av({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{...Dt({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 hv}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 Pa(e,t){let n=e.add!==void 0,r=e.stdin===!0,s=typeof e.file=="string",o=Number(n)+Number(r)+Number(s);if(o===0)return;if(o>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",d.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add")??"",emptyFlag:"--add"};if(r)return{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);try{return{value:await hv(i,"utf8"),emptyFlag:"--file"}}catch(a){if(Aa(a)&&$t(a))throw new l(`--file path not found: ${i}`,d.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${i}": ${c}`,d.USAGE)}}async function gv(e,t){let n=e.edit,r=e.delete,s=n!==void 0,o=r!==void 0;if(s&&o)throw new l("Specify only one of --edit or --delete",d.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",d.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",d.USAGE);if(o){if(await Pa(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(s){let c=await Pa(e,t);if(c===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let i=await Pa(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 rf(e,t,n){let r=Ne(),s=await gv(t,r),o=s.mode==="add"||s.mode==="edit",i=s.value??"";return Rn(e,t,n,{input:{...s,rawValue:t.add??i,value:o?Cn(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 sf(e,t,n){return Rn(e,t,n,{input:await so(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Cn(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 yv(e){if(e===void 0)return;if(e.trim().length===0)throw new l("--add-json must contain a JSON value",d.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new l("--add-json must be valid JSON",d.USAGE,{code:"structured_event_json_invalid"})}return t}function bv(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 wv(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new l("--since must be a valid ISO timestamp",d.USAGE,{code:"structured_event_since_invalid"});return t}async function of(e,t,n){let r=yv(t.addJson),s=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&s)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let o=r===void 0?void 0:J(r),i=[t.since,t.eventType].some(h=>h!==void 0),a=wv(t.since),c=Hn(t.limit),m=await Rn(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await so(o===void 0?t:{add:o},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>Cn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:bv(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm notes pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}}),u=t.eventType?.trim(),p=m.notes.filter(h=>{let y=[h.format==="json",h.data!==void 0].every(Boolean),g=[a===void 0,Date.parse(h.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),b=[!u,h.event_type===u].includes(!0);return[!i,[y,g,b].every(Boolean)].includes(!0)}),f=i?Ta(p,c):p,_=f.filter(h=>h.format==="json").length;return{...m,notes:f,count:f.length,...i?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f9c9b926-c912-548e-a9c7-64c2c69767cd")}catch{}})();function ao(e,t){if(!t&&/[:,=]/.test(e))throw new l(`Invalid --dep value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE)}function rr(e,t,n=Qi()){for(let r of t??[])try{Md(e,r.id,r.kind,n)}catch(s){throw new l(cn(s),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function af(e,t){return(await K(e,{schema:t})).document.metadata.created_at}async function vv(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await M(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:af(n,t.schema)}function kv(e){let t=e.registry.require(e.dependency.kind);return new l(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,d.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function Sv(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 af(n.get(s),e.context.schema)])));for(let s of e.holders){let o=await vv(s,e.context);if(o!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(o),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw kv({holder:s,dependency:i,sourceCreatedAt:o,targetCreatedAt:a,registry:e.registry})}}}async function Bt(e){let t=e.registry??Qi(),n=(e.dependencies??[]).filter(i=>!Iu(i.source_kind)),r=[...new Set(n.map(i=>i.id))],s=await Promise.all(r.map(async i=>({target:i,located:await M(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),o=s.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(o.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${o.length===1?"":"s"} not found: ${o.join(", ")}`,d.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:o,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${o.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:o,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${o[0]}" --limit 10`}});return await Sv({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 co(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function lo(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function mo(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Cr.includes(t))return t;let n=se(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new l("Confidence must be an integer 0..100 or one of low|med|medium|high",d.USAGE);return n}function uo(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new l("Regression must be one of true|false|1|0",d.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="afc4f3d5-ba5e-5dd7-abc9-531b319cdb4e")}catch{}})();var Ev=new Set(["none","null"]);function po(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 Ge(e){return e===void 0?!1:Ev.has(e.trim().toLowerCase())}function fo(e,t,n){if(!Ge(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function ge(e,t,n){if(!e||e.length===0||!e.some(o=>Ge(o)))return;let s=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${s}`.trim(),d.USAGE)}function _o(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new l(`${n.valueFlag} entries must be strings.`,d.USAGE);let s=r;if(!s.some(a=>Ge(a)))continue;if(s.filter(a=>!Ge(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2fcfbe50-039b-5031-8b18-a208908a0d87")}catch{}})();function df(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,d.USAGE)}function Na(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function ye(e,t,n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE);return e}var lf=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Tv(e,t){return t==="defined"?e!==void 0:!!e}function cf(e,t,n){if(!Tv(e,n))return;let r=se(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function Av(e,t,n){let r=e?Q(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new l("--event recur_until must be at or after start",d.USAGE);return r}function Cv(e){return Array.from(new Set(Na(e).map(t=>ye(t.toLowerCase(),xd,"event weekday")))).sort((t,n)=>ki(t)-ki(n))}function Rv(e){return Array.from(new Set(Na(e).map(t=>{let n=se(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new l("--event recur_by_month_day values must be integers 1..31",d.USAGE);return n}))).sort((t,n)=>t-n)}function Iv(e,t){return Array.from(new Set(Na(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(),m=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![s,o,i,a,c,m,u].some(E=>E!==void 0))return;if(!s)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let f=ye(s.toLowerCase(),Id,"event recurrence frequency"),_=cf(o,"recur_interval",r),h=cf(i,"recur_count",r),y=Av(a,t,n),g=Cv(c),b=Rv(m),v=Iv(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 uf="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",xv="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",Ov=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,Pv=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,ff=1e3,La=60*ff,Nv=60*La;function pf(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new l(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,d.USAGE);return n.toISOString()}function Lv(e,t){let n=new Date(e),r=t.trim(),s=Ov.exec(r);if(s){let a=s[1]==="-"?-1:1,c=Number.parseInt(s[2],10)*a;return pf(n.getTime()+c*La,r)}let o=Pv.exec(r);if(o){let[,a,c,m,u]=o;if(c||m||u){let f=a==="-"?-1:1,_=Number.parseInt(c??"0",10),h=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),g=_*Nv+h*La+y*ff;return pf(n.getTime()+f*g,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return Q(i,n,"event.duration")}function _f(e,t,n,r){if(t&&n)throw new l(xv,d.USAGE);if(n){let o=Lv(e,n);if(o<e)throw new l(uf,d.USAGE);return o===e?void 0:o}if(!t)return;let s=Q(t,r,"event.end");if(s<e)throw new l(uf,d.USAGE);if(s!==e)return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var Fv=["at","date","text","title"],$v=["start","date","end","duration","title","description","location","timezone","all_day",...lf],Mv=["key","value"];function hf(e,t){return t==="trimmed"?e?.trim():e}function Dv(e,t){return t==="defined"?e!==void 0:!!e}function ho(e,t,n){return e.map(r=>{let s=te(r,"--reminder");Ue(s,"--reminder",Fv);let o=hf(s.at??s.date,n.valueMode),i=hf(s.text??s.title,n.valueMode);if(!o||!i)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let a=i.trim();if(!a)throw new l("--reminder text must not be empty",d.USAGE);return{at:Q(o,t,"reminder.at"),text:a}})}function go(e,t,n){return e.map(r=>{let s=te(r,"--event");Ue(s,"--event",$v);let o=(s.start??s.date)?.trim();if(!o)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let i=Q(o,t,"event.start"),a=s.end?.trim(),c=s.duration?.trim(),m=_f(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[$,U,Ie]of v)if(U!==void 0&&!Ie)throw new l(`--event ${$} must not be empty`,d.USAGE);let E=s.all_day?.trim(),N=mf(s,i,t,n.recurrenceEmptyNumericGuard),P=Dv(E,n.allDayEmptyGuard)?df(E,"--event all_day"):void 0;return{start_at:i,end_at:m,title:h,description:y,location:g,all_day:P,timezone:b,recurrence:N}})}function yo(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new l("--type-option values must not be empty",d.USAGE);let s,o;if(r.includes(",")||r.includes(`
5
- `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=te(r,"--type-option");Ue(a,"--type-option",Mv),s=a.key?.trim(),o=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),m=a;if(a<=0&&c>0&&(m=c),m<=0||m===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);s=r.slice(0,m).trim(),o=r.slice(m+1).trim()}if(!s||!o)throw new l("--type-option requires key and value",d.USAGE);t[s]=o}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var Uv=new Set(["event","meeting","reminder","milestone","decision","adr"]);function gf(e,t,n,r){if(Uv.has(t.trim().toLowerCase())||n!==r.open_status)return;let s=us("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 Ht=["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"],Gv=new Set(Ht),jv=Ht.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),qv=new RegExp(`^(?:[-*+]\\s+)?(?:${jv})\\s*[:=]`,"i");function bo(e){return e.startsWith("```")||e.includes(`
6
- `)?!0:qv.test(e)}function wo(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!Gv.has(i)){r.push(s);continue}if(Object.hasOwn(n,i))throw new l(`${t} provides key "${s}" more than once after case normalization`,d.USAGE);n[i]=o}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(s=>`"${s}"`).join(", ")}. Allowed keys: ${Ht.join(", ")}.`,d.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new l(`${t} command and cmd must match when both are provided`,d.USAGE);let{cmd:s,...o}=n;return{...o,command:o.command??s}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="74163bed-a473-543e-ae6a-0d5091b3b3a9")}catch{}})();var Wt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Bs,ju,"FORCE_COLOR"]),So=/^[A-Za-z_][A-Za-z0-9_]*$/,Vt=["schema","tracker","auto"];function sr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1);if(!So.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(Wt.has(i.toUpperCase()))throw new l(`${t} env_set key "${i}" is reserved for sandbox safety`,d.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function or(e,t){if(!e)return;let n=Sn(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,d.USAGE);for(let r of n){if(!So.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(Wt.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function Eo(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,d.USAGE)}function To(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Vt.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${Vt.join(", ")}`,d.USAGE)}function Yt(e){if(!e)return;let t=Sn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function xn(e,t,n){let r=Yt(e);if(!(!r||r.length===0)){for(let s of r)try{new RegExp(s,"m")}catch(o){throw new l(`${t} ${n} includes invalid regex "${s}": ${o instanceof Error?o.message:String(o)}`,d.USAGE)}return r}}function Ao(e,t){if(!e)return;let n=se(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,d.USAGE);return n}function Co(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function Ro(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,d.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${i}" must be numeric`,d.USAGE);r[i]=c}return Object.keys(r).length>0?r:void 0}var Kv=new Set(Ht);function Io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zv(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!Kv.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: ${Ht.join(", ")}.`);return n}function In(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 vo(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 yf(e,t,n){let r=vo(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 ko(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 Bv(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:ko(n,"timeout_seconds",t),o=r===void 0?void 0:ko(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 Hv(e,t){let n=In(e,"scope",t);if(n===void 0)return"project";if(!Ze.includes(n))throw t(`field "scope" must be one of: ${Ze.join(", ")}`);return n}function Vv(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Io(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(!So.test(s))throw t(`field "env_set" key "${s}" is invalid`);if(Wt.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 Wv(e,t){let n=vo(e,"env_clear",t);if(n){for(let r of n){if(!So.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(Wt.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function Yv(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 Jv(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=ko(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 Xv(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Io(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 Qv(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Io(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]=ko(o,`assert_json_field_gte.${s}`,t)}return Object.keys(r).length>0?r:void 0}function Zv(e,t,n){let r=p=>new l(`${n} ${t} ${p}`,d.USAGE);if(!Io(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Ht.join(", ")}.`);let s=zv(e,r),o=In(s,"command",r),i=In(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=In(s,"path",r),m=In(s,"pm_context_mode",r);if(m!==void 0&&!Vt.includes(m))throw r(`field "pm_context_mode" must be one of: ${Vt.join(", ")}`);let u=In(s,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:Hv(s,r),timeout_seconds:Bv(s,r),pm_context_mode:m,env_set:Vv(s,r),env_clear:Wv(s,r),shared_host_safe:Yv(s,"shared_host_safe",r),assert_stdout_contains:vo(s,"assert_stdout_contains",r),assert_stdout_regex:yf(s,"assert_stdout_regex",r),assert_stderr_contains:vo(s,"assert_stderr_contains",r),assert_stderr_regex:yf(s,"assert_stderr_regex",r),assert_stdout_min_lines:Jv(s,r),assert_json_field_equals:Xv(s,r),assert_json_field_gte:Qv(s,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function bf(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,d.USAGE);let r;try{r=JSON.parse(n)}catch(o){throw new l(`${t} value is not valid JSON: ${o instanceof Error?o.message:String(o)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let s=Array.isArray(r)?r:[r];if(s.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return s.map((o,i)=>Zv(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 Fa=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],$a=[{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"}],wf=[...Fa,...$a],xo=[{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 Oo(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let s=r.trim().toLowerCase();if(!s)throw new l("--unset values must not be empty",d.USAGE);if(Ge(s))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let o=e.resolveDefinition(s);if(!o)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(o.metadataKey),n.add(o.optionKey)}return{metadataKeys:t,optionKeys:n}}function Po(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 ek={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 ek[e]}function Ma(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]="7d69bb56-9fab-5059-9357-5b6bea2078b9")}catch{}})();var nk=["strict","progressive"],rk=["lightweight"],Ef=new Set(["Reminder","Meeting","Event"]),sk=new Set(["author","created_at","text"]),Ua=[...wf,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...xo],ok=(()=>{let e=new Map;for(let t of Ua)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),No=new Map(Ua.map(e=>[e.optionKey,e.canonical])),ik=Ua.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function ak(e,t){let n=ne(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function ck(e,t){let n=e.default_status;if(n!==void 0){let r=ne(n,t);if(r)return r}return t.open_status}function Da(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}var dk=po();function Tf(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};Ge(t.template)&&(t.template=void 0);let r=new Set([...No.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Ge(o))continue;let i=s==="rank"?"order":No.get(s)??s;n(i),t[s]=void 0}return _o(t,dk)}function ce(e){if(e!==void 0)return e}function lk(e,t){return Oo({raw:e,supportedFields:ik,resolveDefinition:n=>ok.get(n)??Po(n,"create",t)})}var vf=["id","kind","type","author","created_at","source_kind"],Lo=["path","scope","note"];function mk(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let i=o.trim(),a=Ga(i,vf);ao(i,a);let c=a?te(o,"--dep"):{id:i,kind:"related"};a&&Ue(c,"--dep",vf);let m=ce(c.id),u=uk(ce(c.kind??c.type));if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",d.USAGE);if(m.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=Vn(ce(c.source_kind)),f=ce(c.author);return{id:Wn(m,n,p),kind:ye(u,Ft,"dependency kind"),created_at:Da(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function uk(e){return typeof e=="string"?Nr(e)??e.trim():e}function Ga(e,t){if(e.startsWith("```")||e.includes(`
7
- `))return!0;let n=t.map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${n})\\s*[:=]`,"i").test(e)?!0:js(e)}function Xt(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(ge(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(i=>{let a=i.trim(),c=()=>{if(a.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:a}},m;try{m=te(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!sk.has(f)).length>0)return{created_at:Da(m.created_at,n),author:ce(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:Da(m.created_at,n),author:ce(m.author)??r,text:p}}),explicitEmpty:!1})}function ja(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),s=Ga(r,Lo),o=s?te(n,"--file"):{path:r};if(s&&Ue(o,"--file",Lo),!o.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:o.path,scope:ye(o.scope??"project",Ze,"file scope"),note:ce(o.note)}}),explicitEmpty:!1})}function qa(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),s=bo(r)?wo(te(n,"--test"),"--test"):{command:r},o=ce(s.command),i=ce(s.path);if(!o)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let a=ce(s.timeout_seconds),c=ce(s.timeout);if(a&&c&&a!==c)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let m=a??c;return{command:o,path:i,scope:ye(s.scope??"project",Ze,"test scope"),timeout_seconds:m?se(m,"timeout_seconds"):void 0,pm_context_mode:To(s.pm_context_mode,"--test"),env_set:sr(s.env_set,"--test"),env_clear:or(s.env_clear,"--test"),shared_host_safe:Eo(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Yt(s.assert_stdout_contains),assert_stdout_regex:xn(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Yt(s.assert_stderr_contains),assert_stderr_regex:xn(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Ao(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:Co(s.assert_json_field_equals,"--test"),assert_json_field_gte:Ro(s.assert_json_field_gte,"--test"),note:ce(s.note)}}),explicitEmpty:!1})}function Ka(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),s=Ga(r,Lo),o=s?te(n,"--doc"):{path:r};if(s&&Ue(o,"--doc",Lo),!o.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:o.path,scope:ye(o.scope??"project",Ze,"doc scope"),note:ce(o.note)}}),explicitEmpty:!1})}function pk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--reminder","Use --clear-reminders to clear reminders."),{values:ho(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function fk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--event","Use --clear-events to clear linked events."),{values:go(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function _k(e,t,n,r=[]){let s=[...Rr.filter(o=>e[o]!==void 0),...r.filter(o=>e[o]!==void 0),...t.length>0?["body"]:[],...n.map(o=>`unset:${o}`)];return Array.from(new Set(s))}function hk(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function kf(e,t,n){let r=Dn("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function gk(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 Af(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 yk(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(kf(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(kf(r,e.name,"required_create_repeatables"));return n}function bk(e,t,n,r){for(let s of e)if(!(!Af(t,s)&&!n.has(s)))throw new l(`Option ${fe("create",s)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function wk(e,t,n){if(t!=="strict")return;let r=e.filter(o=>n.has(o)&&!Ma(o));if(r.length===0)return;let s=[...new Set(r.map(o=>fe("create",o)))].sort((o,i)=>o.localeCompare(i));throw new l(`Strict create mode requires concrete values for ${s.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function vk(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:yo(e),explicitEmpty:!1})}async function kk(e){let t=Ne();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 Sk(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${nk.join(", ")}`,d.USAGE)}function Ek(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new l("--schedule-preset must not be empty",d.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new l(`Invalid --schedule-preset value "${e}". Allowed: ${rk.join(", ")}`,d.USAGE)}function Tk(e,t,n){let r=Sk(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",d.USAGE);return"progressive"}function Ak(e,t,n,r){let s=e.name,o=gk(t),i=yk(e,n),a=an(e,"create",i);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);bk(a.disabled,o,r,s),wk(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&Ma(u)?!0:Af(o,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>fe("create",u)))].sort((u,p)=>u.localeCompare(p))}var Cf=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function Ck(e,t){let n=[];for(let r of e){let s=r.match(Cf);s&&s[2]===t&&n.push(s[1])}return[...new Set(n)].sort((r,s)=>r.localeCompare(s))}function Rk(e,t){return e.filter(n=>{let r=n.match(Cf);return!r||r[2]!==t})}function Ik(e,t,n,r){let s=Rk(e,t);if(s.length===0)return;let o=Rf(n,[],[],r.open_status);throw new l(s.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[o],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function xk(e,t){let r=e.options.find(s=>s.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function Ok(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 Rf(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(...Ok(c,e.name,r)),a.add(c));for(let c of n){let m=xk(e,c);s.push("--type-option",`${c}=${m}`)}return s.join(" ")}function za(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new l("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",d.USAGE):new l('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',d.USAGE):new l(`Missing required option ${t}`,d.USAGE);return n}function Pk(e){return kn(e)}function Nk(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 Lk(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Fk(){let e=I();return e?e.commands.some(t=>t.action==="templates-show"||Lk(t.command)==="templates show"):!1}function $k(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new l(`Templates package returned invalid payload for template "${t}". Expected an options object.`,d.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Templates package returned invalid options for template "${t}".`,d.GENERIC_FAILURE);let r={};for(let[s,o]of Object.entries(n)){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"){r[s]=o;continue}if(Array.isArray(o)&&o.every(i=>typeof i=="string")){r[s]=[...o];continue}throw new l(`Templates package returned unsupported option value for "${s}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function Mk(e,t,n){if(!Fk())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await gs({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let s=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${s}`,d.USAGE)}return $k(r.result,e)}function Dk(e){return k(C(e)).then(t=>{if(!t)throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)})}function B(e,t,n){return e.has(t)||n===void 0?void 0:ce(n)}function Jt(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var Uk=new Set(["milestone","meeting","reminder","event"]);function If(e,t,n,r){let s=t!==void 0,o=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return Uk.has(e.toLowerCase())&&!s&&!o&&!i}function Gk(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`),If(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 jk(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let s=await ys(r);return s===void 0?{parent:e,parentSource:void 0}:{parent:s,parentSource:"focus"}}async function qk(e,t,n,r,s,o){let i=$s(s);if(Ds(r,i,t.id_prefix),await M(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let c=_e(i,t.id_prefix);return{parent:i,warnings:Ms(c,o).warnings}}async function Kk(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await qk(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function zk(e){if(e.explicitId===void 0)return Bn(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||_u(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=_e(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",d.USAGE);return n}function Sf(e,t,n,r,s){let o=B(e,t,n);if(o===void 0)return{value:void 0,warnings:[]};let i=qs(r,o,s);return{value:i.value,warnings:i.warnings}}async function Bk(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:s,blockedBy:o,status:i,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(o===void 0)return{dependencyValues:u,status:i};let p=_e(o,n.id_prefix),f=await M(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:i};if((u??[]).some(y=>y.id===f.id&&y.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:i};let h=s.blocked_statuses.has("blocked")?"blocked":[...s.blocked_statuses].sort((y,g)=>y.localeCompare(g))[0]??s.open_status;return{dependencyValues:u,status:h}}function Hk(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&&ue(s,n)){e.type=s;return}ue("Task",n)&&(e.type="Task")}function Vk(e,t){return e.options.filter(n=>Dn("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function Wk(e,t,n,r,s){let o=e,i=[];if(o.template!==void 0){let h=o.template.trim();if(h.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let y=await Mk(h,t,n);o=Tf(Nk(y,o))}if(o.type===void 0&&Hk(o,r,s),o.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let a=ue(o.type,s);if(!a){let h=gu(o.type),y=h?ue(h,s):void 0;if(y)i.push(`type_coercion:${o.type.trim()}:${y}`),o.type=y,a=y;else throw new l(gt(o.type,s.types,yt(n,r.schema)),d.USAGE)}let c=Or(a,s);if(!c)throw new l(`Invalid type value "${o.type}"`,d.USAGE);let m=c.name,u=Vk(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=Ek(o.schedulePreset);if(f!==void 0&&!Ef.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=Tk(o.createMode,f,r.governance.create_mode_default);return{resolvedOptions:o,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function Yk(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),s=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let o of s)if(o.enabled){if(o.values&&o.values.length>0)throw new l(`Cannot combine ${o.clearFlag} with ${o.valueFlag}`,d.USAGE);n.add(o.metadataKey),r.add(o.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function Jk(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=No.get(r)??r;throw new l(`Cannot combine --unset ${o} with ${fe("create",r)}`,d.USAGE)}}function Xk(e){let t=(n,r)=>{let s=No.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;fo(n,fe("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 Qk(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,d.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,d.USAGE)}function Zk(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:s,openStatus:o,type:i,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(_=>{let h=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${h}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),u=[Rf(n,r,s,o),...m.map(_=>_.example)].join(" "),p=[`Run "pm create --help --type ${i}" for type-aware required option guidance.`];t.includes("--title")&&p.push('Title can also be passed as the first positional argument (example: pm create "Your title" --type '+i+")."),a==="strict"&&(p.push('For staged onboarding, retry with "--create-mode progressive".'),Ef.has(i)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&p.push(`Required custom field formats: ${m.map(_=>_.description).join("; ")}.`);let f=t.length===1?`Missing required option ${t[0]} for type "${i}"`:`Missing required options ${t.join(", ")} for type "${i}"`;throw new l(f,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${i}" in one invocation.`,examples:[u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:["--create-mode progressive",...t]}:void 0})}function eS(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?St(t.tags):[];return wn(n,t.addTags)}function tS(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new l("--order and --rank must match when both are provided",d.USAGE);let n=t.order??t.rank,r=Jt(e,"order",n,s=>se(s,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function nS(e,t,n,r,s,o){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",d.USAGE);let i=e!==t.close_status?void 0:r.completedAt===void 0?o:Q(r.completedAt,new Date(o),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:i,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:s}:{explicit:r.closeReason};return{closeReason:Ra(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:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=Mt(t,n,r,s.item_format,o.type_to_folder),g=ke(t,r),b=await xe(t,r,s.locks.ttl_seconds,i,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),v=[];try{let E=c.metadata.dependencies&&c.metadata.dependencies.length>0?await re(t,s.item_format,o.type_to_folder,void 0,s.schema):void 0;if(await M(t,r,s.id_prefix,s.item_format,o.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);await hs({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:Ts({pmRoot:t,settings:s,typeToFolder:o.type_to_folder})});let P=await gn(t,i,{required:s.governance.duplicate_detection_mode==="strict"&&h!==!0}),$=[];try{s.governance.duplicate_detection_mode==="strict"&&h!==!0&&await An(_,{pmRoot:t,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1}),await me(y,Me(c,{format:s.item_format,schema:s.schema,extensionFieldNames:a}));try{let U=De({nowIso:f,author:i,op:"create",before:m,after:c,message:u});await wt(g,U)}catch(U){throw await on(y),U}$=await yn({pmRoot:t,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:y,document:c})}finally{await P()}v=[...E?Qs(E,[...E,c.metadata],r):[],...$,...await z({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await z({path:g,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],mn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Ut(c.metadata,p),changed_fields:p})}finally{await b()}return v}async function At(e,t){let n=Tf(await kk(e)),r=T(process.cwd(),t.path);await Dk(r);let s=await A(r),o=G(s.schema),i=Be(s.schema),a=x(s,I()),c=await Wk(n,t,r,s,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=lk(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=Yk(n,f);Jk(n,f),Xk(n);let y=Ak(m,n,p,h),g=S(),b=R(ce(n.author),s.author_default),v=mk(n.dep,g,s.id_prefix,b),E=Xt("--comment",n.comment,g,b),N=Xt("--note",n.note,g,b),P=Xt("--learning",n.learning,g,b),$=ja(n.file),U=qa(n.test),Ie=Ka(n.doc),ee=pk(n.reminder,g),pe=fk(n.event,g),ie=vk(n.typeOption),Xe=Un(u,ie.values,a),ze=I(),Pt=ft(ze),ut=Ir(n.field,ze),Nt=Gm(n,i,u),ui=new Set(Nt.missing_required_flags),wr=i.definitions.filter(H=>ui.has(`--${H.cli_flag}`));Qk(ut,Nt,f);let Qe=Ck(Xe.errors,u),md=Qe.map(H=>`--type-option ${H}=<value>`),vr=[...new Set([...y,...md,...Nt.missing_required_flags])].sort((H,wi)=>H.localeCompare(wi));Zk({combinedMissingFlags:vr,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:Qe,openStatus:o.open_status,type:u,createMode:p,missingRequiredRuntimeFields:wr}),Ik(Xe.errors,u,m,o);let ae=await zk({pmRoot:r,settings:s,typeRegistry:a,explicitId:n.id}),ve=n.status!==void 0?ak(n.status,o):ck(m,o),pi=n.priority!==void 0?Pk(n.priority):2,O=f.metadataKeys,kr=eS(O,n),fi=Jt(O,"deadline",n.deadline,H=>Q(H,new Date(g),"deadline")),zy=Jt(O,"estimated_minutes",n.estimatedMinutes,H=>vn(H,"estimated-minutes")),By=B(O,"acceptance_criteria",n.acceptanceCriteria),Hy=B(O,"definition_of_ready",n.definitionOfReady),Vy=tS(O,n),Wy=B(O,"goal",n.goal),Yy=B(O,"objective",n.objective),Jy=B(O,"value",n.value),Xy=B(O,"impact",n.impact),Qy=B(O,"outcome",n.outcome),Zy=B(O,"why_now",n.whyNow),eb=B(O,"assignee",n.assignee),tb=O.has("author")?void 0:ce(n.author)??b,nb=B(O,"parent",n.parent),ud=await jk(nb,n,O,r),_i=ud.parent,rb=ud.parentSource,sb=B(O,"reviewer",n.reviewer),ob=Jt(O,"risk",n.risk,H=>ye(co(H),rn,"risk")),ib=Jt(O,"confidence",n.confidence,H=>mo(H)),ab=n.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,pd=s.validation.sprint_release_format,Lt=[...c.warnings,...Gk(u,ae,fi,ee.values,pe.values)],fd=await Kk({itemId:ae,parent:_i,pmRoot:r,settings:s,typeRegistry:a,policy:ab});_i=fd.parent,Lt.push(...fd.warnings);let _d=Sf(O,"sprint",n.sprint,"sprint",pd),cb=_d.value;Lt.push(..._d.warnings);let hd=Sf(O,"release",n.release,"release",pd),db=hd.value;Lt.push(...hd.warnings);let gd=B(O,"blocked_by",n.blockedBy),yd=await Bk({pmRoot:r,settings:s,typeRegistry:a,statusRegistry:o,blockedBy:gd,dependencyValues:v.values,status:ve,statusExplicit:n.status!==void 0,nowValue:g,author:b}),hi=yd.dependencyValues;rr(ae,hi),Lt.push(...await Bt({pmRoot:r,dependencies:hi,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:ae,createdAt:g}],schema:s.schema})),ve=yd.status;let lb=B(O,"blocked_reason",n.blockedReason),mb=B(O,"unblock_note",n.unblockNote),ub=B(O,"reporter",n.reporter),pb=Jt(O,"severity",n.severity,H=>ye(lo(H),sn,"severity")),fb=B(O,"environment",n.environment),_b=B(O,"repro_steps",n.reproSteps),bd=B(O,"resolution",n.resolution),hb=B(O,"expected_result",n.expectedResult),gb=B(O,"actual_result",n.actualResult),yb=B(O,"affected_version",n.affectedVersion),bb=B(O,"fixed_version",n.fixedVersion),wb=B(O,"component",n.component),vb=Jt(O,"regression",n.regression,H=>uo(H)),kb=B(O,"customer_impact",n.customerImpact),gi=za(n.title,"--title"),yi=n.description??"",Sr=n.body??"",wd=await An({title:gi,description:yi,body:Sr},{pmRoot:r,mode:s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Lt.push(...Zs(wd));let bi=nS(ve,o,s,n,bd,g),Sb=bi.closeReason,Eb=ve===o.close_status?g:void 0,Tb=bi.completedAt;Lt.push(...bi.warnings);let Er=Hi({id:ae,title:gi,description:yi,type:u,type_options:Xe.normalized,status:ve,closed_at:Eb,completed_at:Tb,close_reason:Sb,priority:pi,tags:kr,created_at:g,updated_at:g,deadline:fi,assignee:eb,author:tb,estimated_minutes:zy,acceptance_criteria:By,definition_of_ready:Hy,order:Vy,goal:Wy,objective:Yy,value:Jy,impact:Xy,outcome:Qy,why_now:Zy,parent:_i,reviewer:sb,risk:ob,confidence:ib,sprint:cb,release:db,blocked_by:gd,blocked_reason:lb,unblock_note:mb,reporter:ub,severity:pb,environment:fb,repro_steps:_b,resolution:bd,expected_result:hb,actual_result:gb,affected_version:yb,fixed_version:bb,component:wb,regression:vb,customer_impact:kb,dependencies:hi,comments:E.values,notes:N.values,learnings:P.values,files:$.values,tests:U.values,docs:Ie.values,reminders:ee.values,events:pe.values,...ut,...Nt.values});try{xr(Er,ze)}catch(H){throw new l(H instanceof Error?H.message:"Invalid extension item field values",d.USAGE)}let Ab=He({metadata:Er,body:Sr},{schema:s.schema,extensionFieldNames:Pt}),Cb={metadata:{},body:""},vd=[..._].sort((H,wi)=>H.localeCompare(wi)),Rb=hk(n.message,vd),kd=_k(Er,Sr,vd,[...Object.keys(ut),...Object.keys(Nt.values??{})]),Ib=await rS({pmRoot:r,type:u,id:ae,settings:s,typeRegistry:a,author:b,extensionFieldNames:Pt,afterDocument:Ab,beforeDocument:Cb,historyMessage:Rb,changedFields:kd,nowValue:g,similarityCandidate:{title:gi,description:yi,body:Sr},allowDuplicate:n.allowDuplicate}),Sd=structuredClone(Er);p==="strict"&&_.has("dependencies")&&(Sd.dependencies=[]);let xb=gf(ae,u,ve,o);return If(u,fi,ee.values,pe.values)&&Wm(`[pm] warning: ${u} '${ae}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${ae} --deadline <ISO>' or 'pm update ${ae} --event "start=<ISO>,end=<ISO>"'.`),{item:Sd,changed_fields:kd,warnings:[...Lt,...Ib],...Object.fromEntries([["parent_source",rb],["next_transition",xb],["similarity_advisory",wd]].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]="a421c150-13a9-5334-85a4-5b3199a5d2c7")}catch{}})();var Wa=[...Fa,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...$a,...xo],sS=(()=>{let e=new Map;for(let t of Wa)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Fo=new Map(Wa.map(e=>[e.optionKey,e.canonical])),oS=Wa.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),iS=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),aS=po({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function cS(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([...Fo.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Ge(o))continue;let i=s==="rank"?"order":Fo.get(s)??s;n(i),t[s]=void 0}return _o(t,aS)}function Df(e,t,n=[]){return Oo({raw:e,supportedFields:oS,resolveDefinition:r=>{let s=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return sS.get(r)??Po(r,"update",t)??(s?{optionKey:"field",metadataKey:s}:void 0)}})}var xf=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 Of(e){let t=e.disallowedFlags.flatMap(r=>{let s=xf.get(r);return s?[s(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let s=xf.get(r);return s?[`Replace ${r} with: ${s(e.id)}`]:[]});return new l(e.message,d.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function dS(e,t,n){let r=t.ownershipMetadataBypass===!0,s=t.ownershipDependencyBypass===!0;if(!r&&!s)return;if(r&&s)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let o=(c,m,u)=>{c&&u.push(m)};if(s){let c=[];if(o(t.title!==void 0,"--title",c),o(t.description!==void 0,"--description",c),o(t.body!==void 0,"--body",c),o(t.status!==void 0,"--status",c),o(t.closeReason!==void 0,"--close-reason",c),o(t.priority!==void 0,"--priority",c),o(t.type!==void 0,"--type",c),o(t.tags!==void 0,"--tags",c),o(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),o(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),o(t.deadline!==void 0,"--deadline",c),o(t.estimatedMinutes!==void 0,"--estimate",c),o(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),o(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),o(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),o(t.definitionOfReady!==void 0,"--definition-of-ready",c),o(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),o(t.goal!==void 0,"--goal",c),o(t.objective!==void 0,"--objective",c),o(t.value!==void 0,"--value",c),o(t.impact!==void 0,"--impact",c),o(t.outcome!==void 0,"--outcome",c),o(t.whyNow!==void 0,"--why-now",c),o(t.assignee!==void 0,"--assignee",c),o(t.parent!==void 0,"--parent",c),o(t.reviewer!==void 0,"--reviewer",c),o(t.risk!==void 0,"--risk",c),o(t.confidence!==void 0,"--confidence",c),o(t.sprint!==void 0,"--sprint",c),o(t.release!==void 0,"--release",c),o(t.blockedBy!==void 0,"--blocked-by",c),o(t.blockedReason!==void 0,"--blocked-reason",c),o(t.unblockNote!==void 0,"--unblock-note",c),o(t.reporter!==void 0,"--reporter",c),o(t.severity!==void 0,"--severity",c),o(t.environment!==void 0,"--environment",c),o(t.reproSteps!==void 0,"--repro-steps",c),o(t.resolution!==void 0,"--resolution",c),o(t.expectedResult!==void 0,"--expected-result",c),o(t.actualResult!==void 0,"--actual-result",c),o(t.affectedVersion!==void 0,"--affected-version",c),o(t.fixedVersion!==void 0,"--fixed-version",c),o(t.component!==void 0,"--component",c),o(t.regression!==void 0,"--regression",c),o(t.customerImpact!==void 0,"--customer-impact",c),o(t.depRemove!==void 0,"--dep-remove",c),o(t.replaceDeps===!0,"--replace-deps",c),o(t.replaceTests===!0,"--replace-tests",c),o(t.replaceFiles===!0,"--replace-files",c),o(t.replaceDocs===!0,"--replace-docs",c),o(t.comment!==void 0,"--comment",c),o(t.note!==void 0,"--note",c),o(t.learning!==void 0,"--learning",c),o(t.file!==void 0,"--file",c),o(t.test!==void 0,"--test",c),o(t.doc!==void 0,"--doc",c),o(t.reminder!==void 0,"--reminder",c),o(t.event!==void 0,"--event",c),o(t.typeOption!==void 0,"--type-option",c),o(t.clearDeps===!0,"--clear-deps",c),o(t.clearComments===!0,"--clear-comments",c),o(t.clearNotes===!0,"--clear-notes",c),o(t.clearLearnings===!0,"--clear-learnings",c),o(t.clearFiles===!0,"--clear-files",c),o(t.clearTests===!0,"--clear-tests",c),o(t.clearDocs===!0,"--clear-docs",c),o(t.clearReminders===!0,"--clear-reminders",c),o(t.clearEvents===!0,"--clear-events",c),o(t.clearTypeOptions===!0,"--clear-type-options",c),o(t.force===!0,"--force",c),o(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw Of({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=>iS.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw Of({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 lS(e,t){let n=ne(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function mS(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=lm({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=ne(e.fromStatus,e.statusRegistry)??e.fromStatus,r=ne(e.toStatus,e.statusRegistry)??e.toStatus,s=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${mm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(s,d.USAGE);return`workflow_transition_not_allowed: ${s}`}function uS(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}function $o(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var pS=["id","kind","type","author","created_at","source_kind"],fS=["id","kind","type","source_kind"];function _S(e){return e.startsWith("```")||e.includes(`
8
- `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:js(e)}function Uf(e){return typeof e=="string"?Nr(e)??e.trim():e}function Mo(e,t,n,r){return e?(ge(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=_S(i);ao(i,a);let c=a?te(o,"--dep"):{id:i,kind:"related"};a&&Ue(c,"--dep",pS);let m=c.id?.trim(),u=Uf((c.kind??c.type)?.trim());if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",d.USAGE);if(m.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=Vn($o(c.source_kind)),f=$o(c.author);return{id:Wn(m,t,p),kind:ye(u,Ft,"dependency kind"),created_at:uS(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function hS(e,t){return e?(ge(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new l("--dep-remove requires id or key/value selectors",d.USAGE);if(r.includes("=")||/^(?:[-*+]\s+)?(?:id|kind|type|source_kind)\s*[:=]/i.test(r)||r.startsWith("```")){let s=te(r,"--dep-remove");Ue(s,"--dep-remove",fS);let o=s.id?.trim();if(!o)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(o.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${o}"`,d.USAGE);let i=Uf($o(s.kind??s.type)),a=Vn($o(s.source_kind));return{id:Wn(o,t,a),kind:i?ye(i,Ft,"dependency kind"):void 0,source_kind:a}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:_e(r,t)}})):[]}function Pf(e){let t=e.source_kind?.trim().toLowerCase()??"";return`${e.id.trim().toLowerCase()}::${e.kind}::${t}`}function gS(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 yS(e,t,n,r,s,o){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await M(n,_e(i,r),r,s,o);return a?{id:a.id}:{unresolved:i}}function bS(e,t,n,r,s){let o=gS(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 wS(e){return`${e.path}::${e.scope}`}function vS(e){return`${e.path}::${e.scope}`}function kS(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}`}function SS(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 ES(e){return kn(e)}function Nf(e,t){let n=Dn("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function TS(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=Df(e.unset,t,n);for(let i of o.optionKeys)s(i,!0)}return r}function AS(e,t,n,r,s){let o=Or(e,n);if(!o)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=an(o,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let a=TS(t,r,s);for(let c of i.disabled)if(a.has(Nf(c,e)))throw new l(`Option ${fe("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of i.required)if(!a.has(Nf(c,e)))throw new l(`Missing required option ${fe("update",c)} for type "${e}"`,d.USAGE)}var CS=new Set(["order","rank"]),RS=Ii.filter(e=>!CS.has(e)),Gf=["tags","closeReason",...RS],IS=["title","description","body","status","closeReason","completedAt","priority","type",...Ii,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],xS=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>Q(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>vn(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"}],OS=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>ye(co(e),rn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>mo(e)}],PS=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>ye(lo(e),sn,"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=>uo(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Va(e,t,n){for(let r of e){let s=t[r.optionKey],o=n.clearItemMetadataKeys.has(r.metadataKey);if(!(s===void 0&&!o)){if(o){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof s!="string")throw new l(`${fe("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(s,n):s.trim(),n.changedFields.push(r.metadataKey)}}}async function NS(e){let t=Ne();return cS({...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 LS(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 Ba(e){if(e.enabled&&(!e.values||e.values.length===0))throw new l(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,d.USAGE);if(e.enabled&&e.clearEnabled)throw new l(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,d.USAGE)}function Ya(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new l("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",d.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new l("--replace-deps requires at least one --dep entry",d.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new l("--replace-deps cannot be combined with --dep-remove",d.USAGE);Ba({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Ba({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Ba({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function FS(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new l(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,d.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function $S(e){let t={};for(let n of Gf)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function MS(e,t){let n=$S(e);for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=Fo.get(r)??r;throw new l(`Cannot combine --unset ${o} with ${fe("update",r)}`,d.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --add-ac",d.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --remove-ac",d.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new l("Cannot combine --unset tags with --remove-tags",d.USAGE)}}function DS(e){let t=(n,r)=>{let s=Fo.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;fo(n,fe("update",r),o)};for(let n of Gf)t(e[n],String(n));t(e.order??e.rank,"order"),ge(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),ge(e.event,"--event","Use --clear-events to clear linked events.")}function US(e,t){let n={};for(let r of IS)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 GS(e){let t=await M(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 jS(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function qS(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new l("--order and --rank must match when both are provided",d.USAGE)}async function KS(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=$s(e.options.parent);if(Ds(e.id,t,e.settings.id_prefix),await M(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=_e(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:Ms(r,e.parentReferencePolicy).warnings}}function zS(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function BS(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await M(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?ue(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 HS(e){if(!e.fieldFlags.status||ne(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],s=[];if(n.length>0){let a=await at(e.id,{...e.options,status:void 0,closeReason:void 0,message:void 0},e.global);s=a.changed_fields,r.push(...a.warnings)}let o=await Tt(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 VS(e,t,n,r){return t.title!==void 0&&(e.metadata.title=za(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")),ne(e.metadata.status,n)??e.metadata.status}function WS(e,t,n,r,s){let o=lS(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}o!==t.statusRegistry.close_status&&r===t.statusRegistry.close_status&&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 YS(e,t,n,r){if(t.options.status!==void 0&&WS(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!Oe(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=Q(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function JS(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let s=t.options.closeReason?.trim()??"";if(s.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=s}r.push("close_reason");return}t.options.status!==void 0&&n===t.statusRegistry.close_status&&e.metadata.status!==t.statusRegistry.canceled_status&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function XS(e,t,n,r){YS(e,t,n,r),JS(e,t,n,r)}function QS(e,t,n){let r=ue(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=ES(t.options.priority),n.push("priority")),t.options.type!==void 0){let s=ue(t.options.type,t.typeRegistry);if(!s)throw new l(gt(t.options.type,t.typeRegistry.types,yt(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=s,r=s,n.push("type")}return AS(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),ZS(e,t,r,n),r}function ZS(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=yo(t.options.typeOption??[]),i=Un(n,o,t.typeRegistry);if(i.errors.length>0)throw new l(i.errors.join("; "),d.USAGE);e.metadata.type_options=i.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let s=Un(n,e.metadata.type_options,t.typeRegistry);if(s.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${s.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=s.normalized}function eE(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){let s=new Set(r.map(o=>Pf(o)));for(let o of t.dependencyUpdates.additions){let i=Pf(o);s.has(i)||(r.push(o),s.add(i))}}t.dependencyRemovals.length>0&&(r=r.filter(s=>!t.dependencyRemovals.some(o=>SS(s,o)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function tE(e,t,n){Ha(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Ha(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Ha(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Ha(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 nE(e,t,n){Lf(e,"files",t.options.file,t.fileUpdates.values,wS,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),rE(e,t,n),Lf(e,"docs",t.options.doc,t.docUpdates.values,vS,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Lf(e,t,n,r,s,o,i,a){if(!(n===void 0&&!i.has(t))){if(o)e.metadata[t]=r;else if(i.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(u=>s(u)));for(let u of r){let p=s(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function rE(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Ff(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Ff([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Ff(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let s=kS(r);n.has(s)||(t.push(r),n.add(s))}return t}function sE(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?St(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Gs(wn(i,r),s),n.changedFields.push("tags")}Va(xS,t.options,n),iE(e,t,n.changedFields)}function oE(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=Us(bn(e.metadata.acceptance_criteria),r,s);if(o.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${o.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:o.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let i=o.criteria.join("; ");e.metadata.acceptance_criteria!==i&&(i===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=i,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function iE(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=se(r??"","order");if(!Number.isInteger(s))throw new l("Order must be an integer",d.USAGE);e.metadata.order=s}n.push("order")}}function aE(e,t,n,r){cE(e,t,n.changedFields),dE(e,t,n.changedFields),Va(OS,t.options,n),$f(e,t,"sprint",r,n.changedFields),$f(e,t,"release",r,n.changedFields),lE(e,t,n.changedFields),Va(PS,t.options,n)}function cE(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new l("--assignee must not be empty. Use --unset assignee to clear it.",d.USAGE);e.metadata.assignee=r}n.push("assignee")}}function dE(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 $f(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=qs(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=o.value,r.push(...o.warnings)}s.push(n)}}function lE(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)&&bS(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=ho(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=go(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function uE(e,t,n){Mf(e,t.runtimeFieldRegistry.definitions.map(s=>s.metadata_key),t.clearItemMetadataKeys,n),Mf(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[s,o]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(s)){let i=s.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===s)?.cli_flag??i;throw new l(`Cannot combine --unset ${i} with --${c}`,d.USAGE)}tt(e[s],o)||(e[s]=o,n.push(s))}let r=Ir(t.options.field,t.extensionRegistrations);for(let s of Object.keys(r))if(t.clearItemMetadataKeys.has(s))throw new l(`Cannot combine --unset ${s.replaceAll("_","-")} with --field ${s}=...`,d.USAGE);for(let[s,o]of Object.entries(r))tt(e[s],o)||(e[s]=o,n.push(s))}function Mf(e,t,n,r){for(let s of t)!n.has(s)||e[s]===void 0||(delete e[s],r.push(s))}function pE(e,t){let n=structuredClone(e.metadata),r=e.body,s=[],o=[],i=VS(e,t.options,t.statusRegistry,s),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:s,nowValue:t.nowValue};XS(e,t,i,s),QS(e,t,s),eE(e,t,s),tE(e,t,s),nE(e,t,s),sE(e,t,c),oE(e,t,c),aE(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"))&&rr(e.metadata.id,e.metadata.dependencies),ne(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),uE(a,t,s);try{xr(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(p){throw new l(p instanceof Error?p.message:"Invalid extension item field values",d.USAGE)}let m=e.metadata,u=[...new Set(s)].filter(p=>p==="body"?e.body!==r:!tt(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&o.push(`acceptance_criteria_replaced:${bn(n.acceptance_criteria).length}:${bn(m.acceptance_criteria).length}`),{changedFields:u,warnings:o}}async function at(e,t,n){t=await NS(t);let r=T(process.cwd(),n.path);await jS(r);let s=await A(r),o=G(s.schema),i=Be(s.schema),a=I(),c=ft(a),m=x(s,a),u=s.governance.workflow_enforcement??"off",p=u==="off"?[]:dm(s.schema),f=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],_=Df(t.unset,i,c),h=new Set(_.optionKeys),y=new Set(_.metadataKeys);Ya(t),FS({definitions:LS(t),options:t,clearOptionKeys:h,clearItemMetadataKeys:y}),dS(e,t,y),MS(t,_),DS(t);let g=R(t.author,s.author_default),b=new Date,v=b.toISOString(),E=Mo(t.dep,s.id_prefix,v,g);rr(e,E.additions);let N=await Bt({pmRoot:r,dependencies:E.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:m.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),P=hS(t.depRemove,s.id_prefix),$=Xt("--comment",t.comment,v,g),U=t.ownershipMetadataBypass===!0&&$.values?{...$,values:$.values.map(O=>({...O,author:g}))}:$,Ie=Xt("--note",t.note,v,g),ee=Xt("--learning",t.learning,v,g),pe=ja(t.file),ie=qa(t.test),Xe=Ka(t.doc),ze=[],Pt=await KS({id:e,options:t,unsetTargets:_,pmRoot:r,settings:s,typeRegistry:m,parentReferencePolicy:f}),ut=await yS(t.blockedBy,y.has("blocked_by"),r,s.id_prefix,s.item_format,m.type_to_folder),Nt=ut.id,ui=[...Pt.warnings,...zS(ut)],wr=ws(t,i,t.runtimeFieldCommands),Qe=US(t,wr);if(!Object.values(Qe).some(Boolean))return GS({pmRoot:r,id:e,settings:s,typeRegistry:m});ze.push(...await BS({options:t,fieldFlags:Qe,workflowEnforcement:u,typeWorkflows:p,statusRegistry:o,typeRegistry:m,pmRoot:r,id:e,settings:s}));let vr=await HS({options:t,fieldFlags:Qe,statusRegistry:o,workflowTransitionWarnings:ze,global:n,id:e});if(vr)return vr;qS(t);let ae=Qe.dep||Qe.depRemove||Qe.blockedBy?await re(r,s.item_format,m.type_to_folder,void 0,s.schema):void 0,ve=await Y({pmRoot:r,settings:s,typeToFolder:m.type_to_folder,id:e,op:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0?"update_ownership_bypass":"update",author:g,message:t.message,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:c,skipNoop:!0,mutate(O){return ae=ae?.map(kr=>kr.id===O.metadata.id?structuredClone(O.metadata):kr),pE(O,{options:t,settings:s,typeRegistry:m,statusRegistry:o,runtimeFieldRegistry:i,extensionRegistrations:a,extensionFieldNames:c,clearItemMetadataKeys:y,dependencyUpdates:E,dependencyRemovals:P,commentUpdates:U,noteUpdates:Ie,learningUpdates:ee,fileUpdates:pe,testUpdates:ie,docUpdates:Xe,resolvedParentValue:Pt.resolvedParentValue,resolvedBlockedByDependencyId:Nt,runtimeFieldUpdates:wr,nowValue:b,nowIso:v,author:g,pmRoot:r})}}),pi=ae?Qs(ae,ae.map(O=>O.id===ve.item.id?ve.item:O),ve.item.id):[];return{item:ve.item,changed_fields:ve.changedFields,warnings:[...ze,...ui,...N,...pi,...ve.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]="e797d654-df89-554b-876b-cb2faa350bd0")}catch{}})();var qf=1,Xa="update-many",fE=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),_E=["--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(", "),hE={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},gE=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],yE={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"},Kf=e=>{let t={};for(let[n,r]of Object.entries(e))fE.has(n)||r!==void 0&&(t[n]=r);return t},bE=e=>Object.keys(Kf(e)).length>0,zf=e=>typeof e=="string"?e.trim():e,wE=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Ja=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},vE=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??zf(e)},kE={priority:wE,estimatedMinutes:Ja,order:Ja,rank:Ja,regression:vE},SE=(e,t)=>{if(t!==void 0)return(kE[e]??zf)(t)},EE=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return yE[t]??t},Do=(e,t)=>tt(e,t),TE=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],AE=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,CE=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",jf=(e,t)=>t===void 0?void 0:e[t],On=e=>Array.isArray(e)?e.length:0,RE=(e,t,n)=>{let r=n[e.addKey],s=jf(n,e.removeKey),o=On(r),i=On(s),a=n[e.clearKey]===!0,c=jf(n,e.replaceKey)===!0;if(![a,c,o>0,i>0].includes(!0))return;let m=TE(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:CE({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:o,remove_count:i,before_count:AE(e.field,m)}}},IE=(e,t)=>{let n=[];for(let r of gE){let s=RE(r,e,t);s!==void 0&&n.push(s)}return n},xE=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],OE=(e,t)=>{if(![t.tags!==void 0,On(t.addTags)>0,On(t.removeTags)>0].includes(!0))return;let n=xE(e.tags),r=t.tags===void 0?n:St(t.tags),s=wn(r,t.addTags),o=Gs(s,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!Do(i,o))return{field:"tags",before:n,after:o}},PE=(e,t)=>{let n=e.acceptance_criteria,r=Us(bn(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let s=r.criteria.join("; ");if(!Do(typeof n=="string"?n:"",s))return{field:"acceptance_criteria",before:n,after:s}},NE=(e,t,n)=>{for(let[r,s]of Object.entries(hE)){let o=n[r];if(o===void 0)continue;let i=t[s],a=SE(r,o);Do(i,a)||e.push({field:s,before:i,after:a})}},LE=(e,t,n,r)=>{let s=ws(n,r,["update_many"]);for(let[o,i]of Object.entries(s)){let a=t[o];Do(a,i)||e.push({field:o,before:a,after:i})}},FE=(e,t,n)=>{for(let r of n??[]){let s=EE(r),o=t[s];o!==void 0&&e.push({field:s,before:o,after:null})}},$E=(e,t,n={})=>{let r=e,s=[],o=OE(r,n);if(o&&s.push(o),NE(s,r,n),On(n.addAc)>0||On(n.removeAc)>0){let i=PE(r,n);i!==void 0&&s.push(i)}return s.push(...IE(r,n)),LE(s,r,n,t),FE(s,r,n.unset),{id:e.id,changes:s}},ME=(e,t)=>hu(e,t,{strict:!0,flagLabel:"--filter-status"}),DE=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)},UE=[({update:e})=>{e.priority!==void 0&&kn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,I());if(!ue(e.type,r))throw new l(gt(e.type,r.types,yt(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!ne(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,d.USAGE)}},({update:e})=>{e.deadline!==void 0&&Q(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&vn(e.estimatedMinutes,"estimated-minutes")}],GE=(e,t,n,r)=>{let s={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let o of UE)o(s)},jE=async e=>{let t=await Ps(e.pmRoot,Xa,e.rollbackId,qf),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Ns(t.items,(s,o)=>zt(s,o,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...Dt({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}},qE=async e=>{let t={schema_version:qf,id:e.checkpointId,created_at:e.nowValue,author:R(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Os(e.pmRoot,Xa,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},KE=(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))},Qa=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},zE=async e=>{let t=T(process.cwd(),e.path);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:G(n.schema),runtimeFieldRegistry:Be(n.schema)}},BE=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Xn(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",d.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",d.USAGE);return jE({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},HE=async e=>{ME(e.options.status,e.runtime.statusRegistry);let t=await Et(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=$E(s,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?o:{...o,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await Et(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:KE(e.options.list?.ids,r)}},VE=e=>({outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...Qa(e)}),WE=e=>({...Dt({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:[],...Qa(e)}),YE=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,s=new Set(e.plans.filter(o=>o.changes.length>0).map(o=>o.id));for(let o of e.items){if(!s.has(o.id)){t.push({id:o.id,status:"skipped"});continue}try{let i=await at(o.id,{...e.options.update,message:r,runtimeFieldCommands:["update_many"]},e.global);t.push({id:o.id,status:"updated",changed_fields:i.changed_fields,warnings:i.warnings}),n.push(o.id)}catch(i){t.push({id:o.id,status:"failed",error:cn(i)})}}return{rows:t,updatedIds:n}},JE=async e=>{if(e.plan.actionable.length===0)return WE(e.plan);let t=S(),n=xs(Xa,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 qE({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 YE({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=p=>i.rows.filter(f=>f.status===p).length,c=a("updated"),m=a("skipped"),u=a("failed");return{...Dt({applied:c,skipped:m,failed:u,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...o?{checkpoint:o}:{},updated_count:c,skipped_count:m,failed_count:u,rows:i.rows,ids:i.updatedIds,...Qa(e.plan)}},Bf=async(e,t)=>{let n=await zE(t),r=typeof e.rollback=="string"?e.rollback:void 0,s=Kf(e.update);if(DE(e.list),r!==void 0)return BE({runtime:n,rollbackId:r,options:e,global:t,updateSummary:s});if(!bE(e.update))throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${_E}).`,d.USAGE);GE(e.update,n.settings,n.statusRegistry,n.pmRoot),Ya(e.update);let o=await Bt({pmRoot:n.pmRoot,dependencies:Mo(e.update.dep,n.settings.id_prefix,S(),R(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await HE({options:e,global:t,runtime:n,updateSummary:s,dependencyWarnings:o});return await Bt({pmRoot:n.pmRoot,dependencies:Mo(e.update.dep,n.settings.id_prefix,S(),R(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:i.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:n.settings.schema}),e.dryRun===!0?VE(i):JE({runtime:n,options:e,global:t,plan:i})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d5ea029-26ef-51bc-bacc-b1d4d807a024")}catch{}})();var XE=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Hf=["brief","standard","deep"],Yf="plan-step-",sc="draft",rc=["bug-investigation","feature-implementation","refactoring-sprint"],Vf={"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 QE(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(Vf,t)?Vf[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${rc.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${rc[0]}`]});return n.map(r=>({...r}))}function ZE(e,t){return t>0?Math.round(e/t*100):0}function Jf(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 Fe(e){return Array.isArray(e)?e.flatMap(t=>Sn(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Sn(e,{unique:!1}):[]}function be(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function Xf(e,t=sc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Si.find(s=>s===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${Si.join(", ")}`,d.USAGE);return r}function oc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ei.find(s=>s===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${Ei.join(", ")}`,d.USAGE);return r}function Qf(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ai.find(s=>s===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${Ai.join(", ")}`,d.USAGE);return r}function eT(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ti.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${Ti.join(", ")}`,d.USAGE);return n}function tT(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=Hf.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${Hf.join(", ")}`,d.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 l("Plan --fields requires a comma-separated list of plan field names",d.USAGE);return t}var Za=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={},s=[];for(let o of t){let i=o.startsWith("plan.")?o.slice(5):o;if(i.length!==0){if(!Za.has(i)){s.push(o);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(s.length>0)throw new l(`Unknown Plan --fields value(s): ${s.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...Za].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:s,suggested_retry:`pm plan show <id> --fields ${[...Za].join(",")}`}});return r}function ic(e,t){let n={};for(let r of e.split(",")){let s=r.trim();if(s.length===0)continue;let o=s.indexOf("=");if(o<=0)throw new l(`Invalid ${t} entry "${s}"; expected key=value`,d.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[s.slice(0,o).trim().toLowerCase()]=s.slice(o+1).trim()}return n}function ac(e){let t=ic(e,"--file");if(!t.path)throw new l("--file requires path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function cc(e){let t=ic(e,"--test");if(!t.command&&!t.path)throw new l("--test requires at least command=<value> or path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function dc(e){let t=ic(e,"--doc");if(!t.path)throw new l("--doc requires path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function sT(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=ZE(t.completed,t.total),t}function oT(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${Yf}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new l("Could not allocate step id (limit reached)",d.GENERIC_FAILURE)}function Pn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(s=>s.id===n);if(r)return r;if(/^\d+$/.test(n)){let s=Number.parseInt(n,10),o=e.find(i=>i.order===s);if(o)return o}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function Wf(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function iT(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],s=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",d.USAGE);for(let i of e.slice().sort((a,c)=>a.order-c.order)){let a=Wf(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=Pn(e,i);if(o.has(a.id))continue;o.add(a.id);let c=Wf(a);if(c){s.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:s}}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 Te(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=sT(n),s=cT(n),o={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??sc,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:dT(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 Ae(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&&!Xi(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function Zf(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new l(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,d.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function lT(e){let t=T(process.cwd(),e.path);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=await A(t);return{pmRoot:t,settings:n}}async function e_(e,t){let n=x(e.settings,I()),r=await M(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,d.NOT_FOUND);let s=await K(r,{schema:e.settings.schema});return Zf(s.document.metadata),{document:s.document,itemId:r.id}}function mT(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of Fe(e.related))t.push(`id=${n},kind=related`);for(let n of Fe(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of Fe(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()||Fe(e.dependsOn).length>0||Fe(e.link).length>0}function fT(e){let t=e.stepTitle?.trim()||void 0,n=Jf(e.step),r=e.template?.trim()?QE(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(s=>s.title)],templateSteps:r}}function _T(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",d.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${rc[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",d.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function hT(e,t){let n=oc(e.stepStatus,"pending"),r=lc(e,"depends_on"),s=be(e.file).map(ac),o=be(e.test).map(cc),i=be(e.doc).map(dc),a=S();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:s.length>0?s:void 0,tests:o.length>0?o:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function gT(e){let t=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=S();return{steps:t.stepTitles.map((s,o)=>({id:`${Yf}${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 yT(e,t,n){let r=e.title?.trim();if(!r)throw new l("pm plan create requires --title",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let s=Xf(e.mode,sc),o=eT(e.harness),i=e.fromSearch?.trim(),a=uT(e),{steps:c,hasPerStepDetailOptions:m}=gT(e);if(c.length===0&&m)throw new l("pm plan create step options require --step-title (or a single --step)",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?R(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:be(e.file),test:be(e.test),doc:be(e.doc),field:be(e.field),assignee:R(e.author,n.settings.author_default),blockedBy:void 0,dep:mT(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")},_=await At(f,t),h=await Y({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:R(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let b=["plan_mode"];g.metadata.plan_mode=s,o&&(g.metadata.plan_harness=o,b.push("plan_harness"));let v=e.scope?.trim();v&&(g.metadata.plan_scope=v,b.push("plan_scope"));let E=e.resumeContext?.trim();return E&&(g.metadata.plan_resume_context=E,b.push("plan_resume_context")),g.metadata.plan_steps=c,b.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],b.push("plan_validation")),p&&(g.metadata.assignee=p,b.push("assignee")),{changedFields:b}}}),y=Te(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Ae(_.item.id,y),warnings:[..._.warnings],generated_at:S()}}async function bT(e,t,n){let r=tT(t.depth),s=nT(t.fields),{document:o,itemId:i}=await e_(n,e),a=Te(o.metadata,s===null?r:"deep");return{action:"show",plan:s===null?a:rT(a,s),next_actions:Ae(i,a),warnings:[],generated_at:S()}}function wT(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 We(e){let t=R(e.options.author,e.ctx.settings.author_default),n,r=await Y({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){Zf(s.metadata);let o=G(e.ctx.settings.schema);if(Oe(s.metadata.status,o)||Xi(s.metadata.plan_mode))throw new l(`Plan ${s.metadata.id} is terminal (status=${s.metadata.status}, plan_mode=${s.metadata.plan_mode??"unset"}) and cannot be mutated.`,d.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let i=(s.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(s.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,s);n=c.resultStep;let m=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));s.metadata.plan_steps=m;let u=wT(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 vT(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let s=oc(t.stepStatus,"pending"),o=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await We({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;t_(u,void 0,s,o);let f=kT(u,t,{order:p,title:r,status:s});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Te(i.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Ae(c,m),warnings:[],generated_at:S()}}function t_(e,t,n,r){if(n!=="in_progress"||r)return;let s=e.find(o=>o.id!==t&&o.status==="in_progress");if(s)throw new l(`Plan already has step ${s.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function kT(e,t,n){let r=lc(t,"depends_on"),s=be(t.file).map(ac),o=be(t.test).map(cc),i=be(t.doc).map(dc),a=S();return{id:oT(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 lc(e,t){let n=Fe(e.dependsOn).map(u=>({id:u,kind:t})),r=Fe(e.related).map(u=>({id:u,kind:"related"})),s=Fe(e.blocks).map(u=>({id:u,kind:"blocks"})),o=Fe(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=Fe(e.link),a=Qf(e.linkKind,t),c=e.linkNote?.trim(),m=i.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...s,...o,...m]}async function ec(e,t,n,r){let{document:s,resultStep:o,itemId:i}=await We({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=Pn(c,r.stepRef),p=S(),f=r.finalStatus??oc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return t_(c,u.status==="in_progress"?u.id:void 0,f,_),ST(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Te(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:Ae(i,a),warnings:[],generated_at:S()}}function ST(e,t,n,r){ET(e,t,n),TT(e,t),e.status=n,e.updated_at=r,AT(e,n,r)}function ET(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new l("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",d.USAGE)}function TT(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=be(t.file).map(ac),s=be(t.test).map(cc),o=be(t.doc).map(dc);r.length>0&&(e.files=tc(e.files,r)),s.length>0&&(e.tests=tc(e.tests,s)),o.length>0&&(e.docs=tc(e.docs,o))}function tc(e,t){let n=[...e??[]],r=new Set(n.map(s=>JSON.stringify(s)));for(let s of t){let o=JSON.stringify(s);r.has(o)||(r.add(o),n.push(s))}return n}function AT(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function CT(e,t,n,r,s){let{document:o,itemId:i}=await We({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${s}`,mutator(c){let m=Pn(c,r),u=c.filter(f=>f.id!==m.id),p=Math.max(1,Math.min(s,u.length+1));return u.splice(p-1,0,m),u.forEach((f,_)=>{f.order=_+1,f.updated_at=S()}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=Te(o.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Ae(i,a),warnings:[],generated_at:S()}}async function RT(e,t,n,r){let{document:s,itemId:o}=await We({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=Pn(a,r),m=a.filter(u=>u.id!==c.id);return m.forEach((u,p)=>{u.order=p+1}),a.length=0,a.push(...m),{changedSteps:[c.id]}}}),i=Te(s.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Ae(o,i),warnings:[],generated_at:S()}}async function IT(e,t,n,r){let s=lc(t,Qf(t.linkKind,"related"));if(s.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let o=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await We({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Pn(u,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of s){let b=h(g);y.has(b)||(_.push(g),y.add(b))}if(f.linked_items=_,f.updated_at=S(),o){let g=p.metadata.dependencies??[],b=E=>`${E.kind}:${E.id}`,v=new Set(g.map(b));for(let E of s){let N=E.kind==="depends_on"?"blocked_by":E.kind,P={id:E.id,kind:N,created_at:S(),author:R(t.author,n.settings.author_default)};v.has(b(P))||(g.push(P),v.add(b(P)))}p.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),m=Te(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ae(a,m),warnings:[],generated_at:S()}}async function xT(e,t,n,r){let s=Fe(t.link);if(s.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:o,itemId:i,resultStep:a}=await We({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=Pn(m,r),p=(u.linked_items??[]).filter(f=>!s.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=S(),{changedSteps:[u.id],resultStep:u}}}),c=Te(o.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Ae(i,c),warnings:[],generated_at:S()}}async function nc(e,t,n,r){let s=aT(r,t);if(!s){let m=`--${r}-text`,u=`--${r}`;throw new l(`pm plan ${r} requires ${m}`,d.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${m} "..."`,`pm plan ${r} <plan-id> ${u} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${m} <value>`}})}let o=R(t.author,n.settings.author_default),{document:i,itemId:a}=await We({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,u){let p=S();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:o,decision:s,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:o,text:s}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:s,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Te(i.metadata,"deep");return{action:r,plan:c,next_actions:Ae(a,c),warnings:[],generated_at:S()}}async function OT(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:s,itemId:o}=await We({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Te(s.metadata,"brief");return{action:"resume",plan:i,next_actions:Ae(o,i),warnings:[],generated_at:S()}}async function PT(e,t,n){let r=Xf(t.mode??"approved","approved"),{document:s,itemId:o}=await We({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(a,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Te(s.metadata,"brief");return{action:"approve",plan:i,next_actions:Ae(o,i),warnings:[],generated_at:S()}}function n_(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function NT(e,t){let n=Te(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ae(e.itemId,n),warnings:n_(t),generated_at:S()}}function LT(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 FT(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let s of be(e.options.field)){let o=s.indexOf("=");if(o<=0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.USAGE);let c=i.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.USAGE);let[m,...u]=c,p=`${m}${u.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(p))throw new l(`Invalid --field entry "${s}"; "${p}" is reserved by materialize and cannot be overridden`,d.USAGE);n[p]=a}for(let s of e.targets){let o=await At({...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:LT(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 $T(e,t,n){for(let r of t){let s=n.find(a=>a.from_step===r.id);if(!s)continue;let o=e.find(a=>a.id===r.id);if(!o)continue;let i=o.linked_items??[];i.push({id:s.id,kind:"implements",note:`materialized as ${s.type}`}),o.linked_items=i,o.updated_at=S()}}async function MT(e,t,n){let r=Fe(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let s=t.materializeType?.trim()||"Task",o=x(n.settings,I()),i=ue(s,o);if(!i)throw new l(`Invalid --materialize-type "${s}"`,d.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await e_(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=iT(u,r);if(p.length===0){if(f.length>0)return NT(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await FT({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await We({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(b){return $T(b,p,_),{changedSteps:p.map(v=>v.id)}}}),g=Te(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ae(y,g),warnings:n_(f),generated_at:S()}}function DT(e){if(e.subcommand==="create")return e;let t=Jf(e.options.step);if(t.length>1)throw new l(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,d.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:{...e.options,stepTitle:t[0]}}:e}function ct(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function Qt(e,t){let n=ct(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function UT(e){let t=Qt(e,"reorder-step");if(e.reorderTo===void 0)throw new l("pm plan reorder-step requires <plan-id> <step> <new-order>",d.USAGE);return{...t,reorderTo:e.reorderTo}}var GT={create:(e,t)=>yT(e.options,e.global,t),show:(e,t)=>bT(ct(e,"show"),e.options,t),"add-step":(e,t)=>vT(ct(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=Qt(e,"update-step");return ec(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=Qt(e,"complete-step");return ec(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=Qt(e,"block-step");return ec(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=Qt(e,"remove-step");return RT(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=Qt(e,"link");return IT(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=Qt(e,"unlink");return xT(n.id,e.options,t,n.stepRef)},decision:(e,t)=>nc(ct(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>nc(ct(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>nc(ct(e,"validation"),e.options,t,"validation"),resume:(e,t)=>OT(ct(e,"resume"),e.options,t),approve:(e,t)=>PT(ct(e,"approve"),e.options,t),materialize:(e,t)=>MT(ct(e,"materialize"),e.options,t)};function jT(e){let t=GT[e];if(!t)throw Ee({command_path:"plan",token:e,allowed:XE});return t}async function r_(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]="4eb2056a-4444-514a-a0db-79b8875c3d65")}catch{}})();function qT(e,t){return[...new Set([...Rr.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 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 mc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await M(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,m=S(),u=R(t.author,s.author_default),p=await Bn(r,s.id_prefix,{tokenLength:s.ids.token_length,typeToFolder:o.type_to_folder,probeExisting:!1}),f=G(s.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let h={...c,id:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let y=ft(I()),g=He({metadata:h,body:a.document.body},{schema:s.schema,extensionFieldNames:y}),b=await An({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=qT(g.metadata,g.body),E=Mt(r,g.metadata.type,p,s.item_format,o.type_to_folder),N=ke(r,p),P=await xe(r,p,s.locks.ttl_seconds,u,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),$={metadata:{},body:""},U,Ie;try{let ee=await gn(r,u,{required:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await An({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 pe=await M(r,p,s.id_prefix,s.item_format,o.type_to_folder);if(pe)throw new l(`Cannot copy to ${p}: an item with that id already exists at ${pe.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${pe.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await me(E,Me(g,{format:s.item_format,schema:s.schema,extensionFieldNames:y}));try{let ie=De({nowIso:m,author:u,op:"create",before:$,after:g,message:KT(i.id,t.message)});await wt(N,ie)}catch(ie){throw await on(E),ie}Ie=await yn({pmRoot:r,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:E,document:g})}finally{await ee()}U=[...await z({path:E,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:$,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:$,after:g,changed_fields:v})],mn({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Ut(g.metadata,v),changed_fields:v})}finally{await P()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:v,warnings:[...Zs(b),...Ie,...U],...b===void 0?{}:{similarity_advisory:b}}}import Uo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="14aa55e1-cb5f-55ea-bf4c-412217d87449")}catch{}})();async function uc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=R(t.author,s.author_default),i=await iu({pmRoot:r,settings:s,id:e,author:o,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?Uo.relative(r,i.targetPath).split(Uo.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:Uo.relative(r,ke(r,i.item.id)).split(Uo.sep).join("/"),tombstone_retention:"retain_append_only",warnings:i.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f43df79-0b27-53b3-b8bd-9f2a35561733")}catch{}})();async function zT(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}async function pc(e,t,n){let r=T(process.cwd(),n.path);if(await zT(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",d.USAGE);let p=await A(r),f=fn(R(void 0,p.author_default));return await Um(r),await Xs({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 ys(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 o=await A(r),i=x(o,I()),a=await M(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=_e(a.id,o.id_prefix),m=await K(a,{schema:o.schema}),u=s_(m.document.metadata.title);return await Dm(r,c),await Xs({pmRoot:r,settings:o,principal:fn(R(void 0,o.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function BT(e,t){let n=await A(e),r=x(n,I()),s=await M(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 s_(o.document.metadata.title)}function s_(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 o_=new Set(["item_format"]),i_=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","telemetry_tracking"]),VT=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","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(o_.has(t)||i_.has(t)||HT.has(t)||t==="context")return t}function JT(e){let t=e.trim().toLowerCase();return WT[t]??e}function a_(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."}:o_.has(n)?{routable:!0,flag:"format",value:t}:i_.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]="a9a8d99c-df4e-55b3-81f5-27124d598c5f")}catch{}})();var c_=["project","global"],dt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],context:["context"]},XT=Object.keys(dt).map(e=>dt[e][0]),QT=Object.fromEntries(Object.keys(dt).flatMap(e=>dt[e].map(t=>[t,e]))),ZT={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)."},eA=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],tA=new Set(["metadata_required_fields",...eA]),nA=new Set(["test_result_tracking","telemetry_tracking"]),rA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),sA=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),oA=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),iA=new Set(["governance_preset","governance_create_default_type"]),p_=e=>tA.has(e),aA=e=>sA.has(e),cA=e=>oA.has(e),dA=e=>iA.has(e);function fc(e){return e==="definition_of_done"||p_(e)}function lA(e){if(c_.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${c_.join(", ")}`,d.USAGE)}function mA(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Ee({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function uA(e){let t=QT[e];if(t)return t;let n=Pi.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${XT.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function pA(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,s)=>r.localeCompare(s));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",d.USAGE);return n}function fA(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",d.USAGE):new l("Config set item-format requires --format toon",d.USAGE)}function f_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",d.USAGE)}function __(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set test-result-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function h_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function hc(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",d.USAGE)}function g_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",d.USAGE)}function y_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",d.USAGE)}function b_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",d.USAGE)}function 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 l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",d.USAGE)}function v_(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-workflow-enforcement requires one of: off, warn, strict",d.USAGE)}function k_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",d.USAGE)}function S_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",d.USAGE)}function d_(e,t){switch(e){case"history_missing_stream_policy":return f_(t);case"sprint_release_format_policy":return Ji(t);case"parent_reference_policy":case"governance_parent_reference_policy":return Fs(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return hc(t);case"governance_preset":return g_(t);case"governance_ownership_enforcement":return y_(t);case"governance_create_mode_default":return b_(t);case"governance_close_validation_default":return w_(t);case"governance_require_close_reason":return S_(t);case"governance_workflow_enforcement":return v_(t);case"governance_force_required_for_stale_lock":return k_(t);case"test_result_tracking":return __(t);case"telemetry_tracking":return h_(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var l_={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},_A=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function hA(e,t){let n=[...new Set((e??[]).map(o=>o.trim()).filter(o=>o.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",d.USAGE);let r=n.map(o=>o.toLowerCase().replaceAll("-","_")),s=r.filter(o=>l_[o]===void 0);if(s.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${s.join(", ")}. Supported values: ${_A.join(", ")}`,d.USAGE);return[...new Set(r.map(o=>l_[o]))].sort((o,i)=>o.localeCompare(i))}function gA(e,t,n){let r=[...new Set((t??[]).map(s=>s.trim().toLowerCase()).filter(s=>s.length>0))].sort((s,o)=>s.localeCompare(o));if(n){if(r.length>0)throw new l(`Config set ${dt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${dt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function yA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function bA(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,d.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,d.USAGE);return uA(t)}function E_(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var wA={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 gc(e,t){return wA[t](e)}function $e(e,t){return t.length===0?e:{...e,warnings:t}}async function vA(e,t){let n=process.cwd(),r=e==="project"?T(n,t.path):et(n),s=C(r);if(e==="project"&&!await k(s))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);return{pmRoot:r,settingsPath:s}}function kA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,d.USAGE)}function m_(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new l(`Context ${t} must be a positive integer`,d.USAGE)}async function SA(e,t,n,r,s){let o=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!Ci.includes(c))throw new l(`Context --default-depth must be one of ${Ci.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,o=!0)}if(t.activityLimit!==void 0){let c=m_(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,o=!0)}if(t.staleThresholdDays!==void 0){let c=m_(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,o=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of a){let u=kA(m);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,o=!0)}}return o&&await Se(n.pmRoot,e,"config:set:context"),$e({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 EA(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,d.USAGE);return{...n,value:t}}function TA(e,t,n,r,s,o){if(s===void 0)return o;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,d.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',d.USAGE);if(r)return EA(t,s,o);E_(n);let i=a_(n,s);if(!i.routable)throw new l(i.reason,d.USAGE);if(i.flag==="criterion"){if(o.criterion!==void 0&&o.criterion.length>0)throw new l(`Config set ${t} received both positional value "${s}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...o,criterion:i.values}}if(i.flag==="format")return{...o,format:i.value};if(o.policy!==void 0&&d_(n,o.policy)!==d_(n,i.value))throw new l(`Config set ${t} received both positional value "${s}" and --policy "${o.policy}". Pass only one.`,d.USAGE);return{...o,policy:i.value}}function AA(e){let t=Object.keys(dt).map(r=>({key:r,aliases:dt[r],value_kind:r==="context"?"object":fc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:fc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:ZT[r],value:gc(e.settings,r)})),n=Pi.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Ni(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 $e({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function CA(e){let t=Object.fromEntries(Object.keys(dt).map(n=>[n,gc(e.settings,n)]));return $e({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function RA(e,t){let n=gc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?$e({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?$e({...r,context_settings:n},e.warnings):Array.isArray(n)?$e({...r,criteria:n},e.warnings):$e({...r,policy:n},e.warnings)}async function IA(e,t,n,r){if(t==="get"){let a=Ni(e.settings,n);return $e({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let s=r.value;if(typeof s!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let o=cm(n,s);if(!o.ok)throw new l(o.error.message,d.USAGE);let i=fs(e.settings,n,o.parsed.value);return i&&await Se(e.target.pmRoot,e.settings,`config:set:${n.path}`),$e({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 Se(e.target.pmRoot,e.settings,n)}function u_(e,t,n){return e!==n||t!==n}function oe(e,t,n,r){return $e({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function _c(e,t,n,r){return $e({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function xA(e,t){let n=fA(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,s;if(r){let o=x(e.settings,I()),i=await yu(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 Se(e.target.pmRoot,e.settings,"config:set:item_format")}return $e({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 OA(e,t,n){if(t==="history_missing_stream_policy"){let o=f_(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"),oe(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let o=Ji(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"),oe(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let o=Fs(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"),oe(e,t,e.settings.validation.parent_reference,i)}let r=hc(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"),oe(e,t,e.settings.validation.metadata_profile,s)}async function PA(e,t,n){if(t==="metadata_required_fields"){let a=hA(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((m,u)=>m!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await X(e,c,"config:set:metadata_required_fields"),_c(e,t,[...e.settings.validation.metadata_required_fields],c)}let s={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],o=gA(t,n.criterion,n.clearCriteria),i=o.length!==s.length||o.some((a,c)=>a!==s[c]);return s.splice(0,s.length,...o),await X(e,i,`config:set:${t}`),_c(e,t,[...s],i)}async function NA(e,t,n){if(t==="governance_preset"){let c=g_(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await X(e,m,"config:set:governance_preset"),oe(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",s=r?n.policy.trim():"";if(r&&s.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await X(e,c,"config:set:governance_create_default_type"),oe(e,t,e.settings.governance.create_default_type??"",c)}if(s.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let o=x(e.settings,I()),i=ue(s,o);if(!i)throw new l(gt(s,o.types,yt(e.target.pmRoot,e.settings.schema)),d.USAGE);let a=e.settings.governance.create_default_type!==i;return e.settings.governance.create_default_type=i,await X(e,a,"config:set:governance_create_default_type"),oe(e,t,e.settings.governance.create_default_type,a)}async function LA(e,t,n){if(t==="governance_ownership_enforcement"){let o=y_(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"),oe(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let o=b_(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"),oe(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"),oe(e,t,e.settings.governance.close_validation_default,s)}async function FA(e,t,n){if(t==="governance_parent_reference_policy"){let o=Fs(n.policy),i=e.settings.governance.preset!=="custom"||u_(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"),oe(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let o=hc(n.policy),i=e.settings.governance.preset!=="custom"||u_(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"),oe(e,t,e.settings.governance.metadata_profile,i)}let r=v_(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"),oe(e,t,e.settings.governance.workflow_enforcement,s)}async function $A(e,t,n){if(t==="governance_require_close_reason"){let a=S_(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"),oe(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let s=k_(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"),oe(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function MA(e,t,n){if(t==="test_result_tracking"){let a=__(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"),oe(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}let s=h_(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"),oe(e,t,e.settings.telemetry.enabled?"enabled":"disabled",o)}async function DA(e,t,n){let r=pA(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"),_c(e,t,[...e.settings.workflow.definition_of_done],s)}async function UA(e,t,n){if(n.clearCriteria===!0&&!fc(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?xA(e,n):t==="context"?SA(e.settings,n,e.target,e.scope,e.warnings):t==="definition_of_done"?DA(e,t,n):p_(t)?PA(e,t,n):nA.has(t)?MA(e,t,n):rA.has(t)?$A(e,t,n):aA(t)?LA(e,t,n):cA(t)?FA(e,t,n):dA(t)?NA(e,t,n):OA(e,t,n)}async function T_(e,t,n,r,s,o){let i=lA(e),a=mA(t),c=a==="get"||a==="set"?ps(n):void 0,m=c?void 0:bA(a,n),u=TA(a,n,m,c,o,r),p=await vA(i,s),{settings:f,metadata:_,warnings:h}=await ru(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:yA(h)};return c?IA(y,a,c,u):a==="list"?AA(y):a==="export"?CA(y):(E_(m),a==="get"?RA(y,m):UA(y,m,u))}import fC from"node:fs/promises";import V from"node:path";import _C from"node:readline/promises";import{stdin as hC,stdout as Ce}from"node:process";import C_ from"node:fs/promises";import je from"node:path";import GA from"node:readline/promises";import{stdin as jA,stdout as Go}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]="a4403557-1cbf-5bfe-94ab-cf07c32d5147")}catch{}})();var R_=["ask","add","skip","status"],qA=["AGENTS.md","CLAUDE.md"],KA=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],zA=8,bc=1,BA="<!-- pm-cli:agent-guidance:start:",HA=`<!-- pm-cli:agent-guidance:start:v${bc} -->`,yc="<!-- pm-cli:agent-guidance:end -->",cr="Add workflow guidance later: pm init --agent-guidance add";var VA=()=>GA.createInterface({input:jA,output:Go});function ir(e,t){let n=je.relative(e,t);return n.length===0?je.basename(t):n.split(je.sep).join("/")}function A_(e){return e.endsWith(`
4
+ `,{changedFields:["body"]}}});return{item:m.item,appended:c,changed_fields:m.changedFields}}import{readFile as Rw}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0af9967c-ca72-563a-9518-2e68da0c0fe0")}catch{}})();function so(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,t}function Qp(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,d.USAGE,{code:"structured_event_immutable"})}function xa(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Kt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Cn(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=te(n,"--add");return Object.keys(o).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:o.text?.trim()||n}catch{return n}}function Oa(e){return typeof e=="object"&&e!==null&&"code"in e}async function Iw(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,d.USAGE);let r=Ne();if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add")??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new l("--file path cannot be empty",d.USAGE);try{return{value:await Rw(s,"utf8"),emptyFlag:"--file"}}catch(o){if(Oa(o)&&Mt(o))throw new l(`--file path not found: ${s}`,d.USAGE);let i=o instanceof Error?o.message:String(o);throw new l(`Failed to read --file path "${s}": ${i}`,d.USAGE)}}async function oo(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",d.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",d.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",d.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",d.USAGE);let n=await Iw(e,t);if(e.edit!==void 0){if(!n)throw new l("--edit requires replacement text from --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function rr(e,t){throw e instanceof l&&e.exitCode===d.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function ef(e){return e==="comments"?"--stdin":"--add -"}function xw(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=ef(t.collectionKey),o=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new l(`--add value "${r}" looks like an option, not annotation text. Use ${s} to read stdin, or use text=${r} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${s} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${o} ${s}`,`${o} --add text=${r}`]})}function Ow(e,t){if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,d.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${ef(e.collectionKey)}`]})}async function Rn(e,t,n,r){Ow(r,t);let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=x(o,I()),a=Vn(t.limit);if(r.input.mode==="list"){let _=await $(s,e,o.id_prefix,o.item_format,i.type_to_folder);if(!_)throw new l(`Item ${e} not found`,d.NOT_FOUND);let h=await K(_,{schema:o.schema}),y=Kt(h.document.metadata,r.collectionKey);return ro(_.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=R(t.author,o.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,h;try{h=await Y({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Kt(g.metadata,r.collectionKey),v=Zp(r.input.index,b.length,r.collectionKey);return Qp(b[v],"deleted"),b.splice(v,1),g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){rr(g,r.conflictGuidance)}let y=Kt(h.item,r.collectionKey);return ro(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";xw(m,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,d.USAGE);if(r.input.mode==="edit"){let _=r.editOp??r.op,h;try{h=await Y({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Kt(g.metadata,r.collectionKey),v=Zp(r.input.index,b.length,r.collectionKey),E=b[v];return Qp(E,"edited"),b[v]={...E,text:u,edited_at:S()},g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){rr(g,r.conflictGuidance)}let y=Kt(h.item,r.collectionKey);return ro(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 Y({pmRoot:s,settings:o,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(_){let h=Kt(_.metadata,r.collectionKey),y={created_at:S(),author:c,text:u};return h.push(r.createEntry(y)),_.metadata[r.collectionKey]=h,{changedFields:[r.collectionKey]}}})}catch(_){rr(_,r.conflictGuidance)}let f=Kt(p.item,r.collectionKey);return ro(p.item.id,r.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:f.length,entry:f.at(-1)},t.fullHistory===!0)}function Zp(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),s=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,o=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${s} index ${e??"(missing)"} out of range (item has ${o})`,d.USAGE)}return e-1}function ro(e,t,n,r,s,o,i=!1){let a=o===void 0||i?xa(n,o!==void 0&&i?void 0:r):o.entry===void 0?[]:[o.entry],c=o!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...[s,o!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...o===void 0?{}:{mutation_receipt:{action:o.action,entry_index:o.entryIndex,changed_count:1,full_history_included:!c},omission_receipt:{has_omissions:c,omitted_field_group_count:c?1:0,omitted_field_groups:c?[{name:`${t}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0579277-f123-5f96-8664-dfe05ade1b24")}catch{}})();async function tf(e,t,n){return[...await bt(ke(e,t),t).catch(()=>[])].reverse().find(o=>o.patch.some(i=>i.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f70f1329-4dfb-5625-ae0a-66c858d88f7b")}catch{}})();var nf="no_available_next_item";function rf(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function io(e,t,n,r={}){let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=j(o.schema),a=R(r.author,o.author_default),c=fn(a),m=null,u=!1,p=[],f=await Y({pmRoot:s,settings:o,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,dm(_.metadata.status,i)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&g!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let v=await tf(s,_.metadata.id,y);throw new l(`Item ${_.metadata.id} is already ${v}. Use --force to take over, or --if-available to skip without failing.`,d.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}p.push(`claim_takeover:${m}->${a}`)}return _.metadata.assignee=a,_.metadata.claim_principal=c,{changedFields:["assignee","claim_principal"],warnings:p}}});return u||await ba({pmRoot:s,settings:o,principal:c,itemId:f.item.id}),{item:f.item,claimed_by:u&&m!==null?m:a,previous_assignee:m,forced:t,...u?{skipped:!0}:{},...p.length>0?{warnings:p}:{}}}async function sf(e,t,n={},r={}){let s=Pw(n.maxAttempts),o=await A(T(process.cwd(),t.path)),i={...n,author:R(n.author,o.author_default)},a=await er({...r,callerAuthor:i.author,limit:String(s)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return Nw(c.slice(0,s),e,t,i)}function Pw(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new l("--max-attempts must be an integer from 1 to 100",d.USAGE);return t}async function Nw(e,t,n,r={},s=io){let o=0;for(let a of e){o+=1;try{let c=await s(a.id,t,n,r),m={...c,recommendation:a,attempts:o,available:!0};if(!c.skipped)return m}catch(c){if(!rf(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:R(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:o,warnings:[nf]};let i=o===0;throw new l(i?"No actionable items matched the selection filters":"No actionable item remained available to claim",i?d.NOT_FOUND:d.CONFLICT,{code:nf,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 ao(e,t,n,r={}){let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=R(r.author,o.author_default),a=fn(i),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await Y({pmRoot:s,settings:o,id:e,op:"release",author:i,message:r.message,force:t,bypassAssigneeConflict:c,mutate(p){return m=p.metadata.assignee??null,!m&&!p.metadata.claim_principal?{changedFields:[]}:(delete p.metadata.assignee,delete p.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(p){rr(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 wa({pmRoot:s,principal:a,itemId:u.item.id}),{item:u.item,released_by:i,previous_assignee:m,forced:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7ae3c89-b50b-5e4f-8273-8318bc976d84")}catch{}})();var Lw=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function of(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 Pa(e,t){return Na(e,t,{operation:"close"})}function Na(e,t,n){let r=of(e);if(!t||r.closeReason!==void 0)return r;let s=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",d.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:s,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function La(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,s=e.dependencies??[],o=s.filter(m=>m.kind==="blocked_by"),i=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),i&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&o.length>0){let m=s.filter(u=>u.kind!=="blocked_by");m.length>0?e.dependencies=m:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...o.map(m=>m.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[t.orderingEdges==="preserve"?`closed_preserved_predecessors:${e.id}:${c.join(",")}`:`closed_removed_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="83affe54-a56c-5d84-b6b0-9634d4238ff5")}catch{}})();var Fw=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function Mw(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new l(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,d.USAGE)}function $w(e){let t=[];for(let n of Fw){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function Dw(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 Uw(e){return typeof e!="string"||e.trim().length===0}async function Gw(e,t,n,r){let s=n?.trim();if(!s)return;if(s===r)throw new l("An item cannot be closed as a duplicate of itself.",d.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let o=x(t,I()),i=new Map,a=async m=>{if(i.has(m))return i.get(m)??null;let u=await $(e,m,t.id_prefix,t.item_format,o.type_to_folder);if(!u)return i.set(m,null),null;let{document:p}=await K(u,{schema:t.schema});return i.set(m,p.metadata),p.metadata},c=await a(s);if(!c)throw new l(`Duplicate target "${s}" was not found. Create or locate the canonical item first.`,d.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${s}" --duplicate-of ${s}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await Dw(a,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${s}" points back to "${r}".`,d.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new l(`Duplicate target "${s}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,d.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function jw(e,t,n){return e.filter(r=>r.parent===t&&!Oe(r.status,n)).map(r=>r.id).sort((r,s)=>r.localeCompare(s))}function qw(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),s=Fp(e),o=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:s.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(o)).filter(({blockerIds:a})=>a.every(c=>{if(c===o)return!0;let m=r.get(c);return m!==void 0&&Oe(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function Kw(e,t,n,r,s,o){let i=qw(n,r,o),a=[];for(let c of i)try{let m=await Y({pmRoot:e,settings:t,id:c.id,op:"update",author:s,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(h=>{let y=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=o.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let u=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${u}`)}return a}function zw(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 Bw(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)Uw(e[s])&&(e[s]=o,n.push(s));return n}function Hw(e,t,n,r){let s=[];if(t!=="off"){let o=$w(e);if(o.length>0){let i=o.map(a=>a.label);if(t==="strict"){let a=o.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(m=>[m,"<value>"])];throw new l(`Cannot close item ${e.id}: missing ${i.join(", ")}. Populate fields or use --validate-close warn.`,d.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:Bs(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}s.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new l(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,d.USAGE);s.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return s}return n.length>0&&s.push(`closed_with_active_children:${e.id}:${n.join(",")}`),s}function Vw(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function Ww(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function Yw(e,t){if(Oe(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use --force to close again.`,d.CONFLICT);let n=zw(e,t.options),r=Bw(e,t.duplicateOf),s=Hw(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"]:[],...Vw(e,t.closeReason),...n];if(Cu(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(...Ww(e));let a=La(e,t.lifecyclePolicy);return i.push(...a.changedFields),s.push(...a.warnings),{changedFields:i,...s.length>0?{warnings:s}:{}}}async function af(e,t,n,r){let s=T(process.cwd(),r.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=j(o.schema),a=R(n.author,o.author_default),c=x(o,I()).type_to_folder,m=await $(s,e,o.id_prefix,o.item_format,c);if(!m)throw await it(s,e,o.id_prefix,c);let u=await Gw(s,o,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Pa({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=Mw(n.validateClose)??o.governance.close_validation_default,h=await re(s,o.item_format,c,void 0,o.schema),y=jw(h,m.id,i),g=new Date().toISOString(),b=n.completedAt===void 0?g:Q(n.completedAt,new Date(g),"completed-at"),v=await Y({pmRoot:s,settings:o,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(E){return Yw(E.metadata,{pmRoot:s,statusRegistry:i,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:g,completedAt:b,lifecyclePolicy:p})}});return{item:v.item,changed_fields:v.changedFields,warnings:[...v.warnings,...await Kw(s,o,h,m.id,a,i)]}}function Tt(e,t,n,r){return af(e,t,n,r)}import Jw from"fast-json-patch";import Fa from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="353be665-9f67-5d0e-99c9-6bbb7e927e0b")}catch{}})();function Xw(e,t){return _u(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Qw(e){let t=ea(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:He(Gt(t))}async function Zw(e,t,n,r){let s=await $(e,t,n.id_prefix,n.item_format,r);if(s){let c=ke(e,s.id),m=await uu({pmRoot:e,settings:n,itemId:s.id,commandLabel:"restore"});return{id:s.id,historyPath:c,located:s,historyPolicyWarnings:m.warnings}}let o=_e(t,n.id_prefix),i=Xi(t),a=o===i?[o]:[o,i];for(let c of a){let m=ke(e,c);if(await k(m))return{id:c,historyPath:m,located:null,historyPolicyWarnings:[]}}throw new l(`Item ${t} not found`,d.NOT_FOUND)}function ev(e,t){let n=jt(e),r=jt(t),s=Jw.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 tv(e){if(await q(e.subject.historyPath)!==e.historyRawBeforeLock)throw new l(`History for ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);let n=await $(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),r=n?await K(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==e.currentItemRawBeforeLock)throw new l(`Item ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);return{loadedItemUnderLock:r,existingItemPath:n?.itemPath??null}}function nv(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Qw(t),originalRaw:null}}function rv(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new l(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,d.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function sv(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await me(e.existingItemPath,e.resolvedOriginalRaw),await Fa.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await me(e.existingItemPath,e.resolvedOriginalRaw);return}await Fa.rm(e.restoredItemPath,{force:!0})}async function ov(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 zt(e,t,n,r){let s=T(process.cwd(),r.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=x(o,I()),a=await Zw(s,e,o,i.type_to_folder),c=a.id,m=await q(a.historyPath),u=await bt(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let p=Xw(t,u),f=hu(ea(u,p.historyIndex),p),_=su(f,{schema:o.schema});if(_.metadata.id!==c)throw new l(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let y=(a.located?await K(a.located,{schema:o.schema}):null)?.raw??null,g=R(n.author,o.author_default),b=await xe(s,c,o.locks.ttl_seconds,g,!!n.force,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let{loadedItemUnderLock:v,existingItemPath:E}=await tv({pmRoot:s,resolvedId:c,subject:a,settings:o,typeToFolder:i.type_to_folder,historyRawBeforeLock:m,currentItemRawBeforeLock:y}),N="toon",P=nv(v,u),M=rv({document:P.document,author:g,force:n.force,enforcement:o.governance.ownership_enforcement,resolvedId:c}),G=ev(P.document,_);await gs({pm_root:s,operation:"restore",before:P.document,after:_,changed_fields:G,sdk:As({pmRoot:s,settings:o,typeToFolder:i.type_to_folder})});let Ie=$e(_,{format:N,schema:o.schema}),ee=$t(s,_.metadata.type,c,N,i.type_to_folder),pe=await gn(s,g),ie=[];try{await me(ee,Ie),E&&ee!==E&&await Fa.rm(E);let Pt=De({nowIso:S(),author:g,op:"restore",before:P.document,after:_,message:n.message});try{await wt(a.historyPath,Pt)}catch(ut){throw await sv({existingItemPath:E,resolvedOriginalRaw:P.originalRaw,restoredItemPath:ee}),ut}ie=await yn({pmRoot:s,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:ee,previousItemPath:E??void 0,document:_})}finally{await pe()}let Xe=await ov({restoredItemPath:ee,historyPath:a.historyPath,before:P.document,after:_});mn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:P.document.metadata.status,status:_.metadata.status,previous:Ut(P.document.metadata,G),current:Ut(_.metadata,G),changed_fields:G});let ze=u[p.historyIndex];return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,entry_ts:ze.ts,entry_op:ze.op},changed_fields:G,warnings:[...a.historyPolicyWarnings,...M,...ie,...Xe]}}finally{await b()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4da07a98-855e-59cf-a6a4-2f59a8b3c0bd")}catch{}})();var df=1,Ma="close-many",iv=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function av(e,t){return Qn(e,t,{includePagination:!1})}function cv(e,t){return Qn(e,t)}function dv(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)}function lv(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 mv(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new l("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",d.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function uv(e,t){let n=j(t.schema),r=x(t,I()),s=await re(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),Oe(a.status,n)))continue;let c=o.get(a.parent);c?c.push(a.id):o.set(a.parent,[a.id])}for(let a of o.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:o,parentByChild:i}}function cf(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let s=0,o=t.get(e),i=[],a=new Set,c=!1;for(;o!==void 0&&!a.has(o);){let m=n?.get(o);if(m!==void 0){s+=m+1;break}a.add(o),i.push(o),s+=1,o=t.get(o)}if(o!==void 0&&a.has(o)&&(c=!0),!c){n?.set(e,s);for(let[m,u]of i.entries())n?.set(u,s-m-1)}return s}async function pv(e){let t=await Ns(e.pmRoot,Ma,e.rollbackId,df),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Ls(t.items,(s,o)=>zt(s,o,{author:e.options.author,message:n,force:!0},e.global));return{...Dt({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 fv(e,t,n,r,s){return e.map(o=>{let i=(t.get(o.id)??[]).filter(c=>!n.has(c)),a=!lf(o,r,s);return{id:o.id,title:typeof o.title=="string"?o.title:"",status:o.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function _v(e){let t=await Ps(e.pmRoot,Ma,e.checkpointId,{schema_version:df,id:e.checkpointId,created_at:e.nowValue,author:R(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function hv(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 Tt(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:cn(s)})}}return{rows:t,closedIds:n}}function gv(e){return typeof e.rollback=="string"?e.rollback:void 0}function yv(e,t){if(t.trim().length===0)throw new l("--rollback requires a checkpoint id",d.USAGE);if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(cv(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function bv(e){if(!av(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${iv}). Refusing to match every item.`,d.USAGE)}function wv(e,t){let n=new Map;return[...e].sort((r,s)=>{let o=cf(s.id,t,n)-cf(r.id,t,n);return o!==0?o:r.id.localeCompare(s.id)})}function lf(e,t,n){return n||!Oe(e.status,t)}function vv(e,t,n){return new Set(e.filter(r=>lf(r,t,n)).map(r=>r.id))}async function kv(e){bv(e.options);let t=j(e.settings.schema),n=mv(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,s=await Et(e.options.status,lv(e.options.list),e.global),{childrenByParent:o,parentByChild:i}=await uv(e.pmRoot,e.settings),a=wv(s.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(p=>p.trim()).filter(p=>p.length>0))],m=new Set(a.map(p=>p.id)),u=vv(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:s,matched:a,unmatchedIds:c.filter(p=>!m.has(p)),planRows:fv(a,o,u,t,r)}}function Sv(e){return{outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds.length>0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function Ev(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 _v({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 mf(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=e.dryRun===!0,o=gv(e);if(dv(e.list),o!==void 0)return yv(e,o),pv({pmRoot:n,rollbackId:o,options:e,global:t});let i=await kv({pmRoot:n,settings:r,options:e,global:t});if(s)return Sv(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=S(),m=Os(Ma,c),u=await Ev({context:i,options:e,closableIds:a,checkpointId:m,nowValue:c}),p={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:i.validateCloseMode,force:i.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await hv({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{...Dt({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 Tv}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 $a(e,t){let n=e.add!==void 0,r=e.stdin===!0,s=typeof e.file=="string",o=Number(n)+Number(r)+Number(s);if(o===0)return;if(o>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",d.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add")??"",emptyFlag:"--add"};if(r)return{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);try{return{value:await Tv(i,"utf8"),emptyFlag:"--file"}}catch(a){if(Oa(a)&&Mt(a))throw new l(`--file path not found: ${i}`,d.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${i}": ${c}`,d.USAGE)}}async function Av(e,t){let n=e.edit,r=e.delete,s=n!==void 0,o=r!==void 0;if(s&&o)throw new l("Specify only one of --edit or --delete",d.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",d.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",d.USAGE);if(o){if(await $a(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(s){let c=await $a(e,t);if(c===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let i=await $a(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 uf(e,t,n){let r=Ne(),s=await Av(t,r),o=s.mode==="add"||s.mode==="edit",i=s.value??"";return Rn(e,t,n,{input:{...s,rawValue:t.add??i,value:o?Cn(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 pf(e,t,n){return Rn(e,t,n,{input:await oo(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Cn(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 Cv(e){if(e===void 0)return;if(e.trim().length===0)throw new l("--add-json must contain a JSON value",d.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new l("--add-json must be valid JSON",d.USAGE,{code:"structured_event_json_invalid"})}return t}function Rv(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 Iv(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new l("--since must be a valid ISO timestamp",d.USAGE,{code:"structured_event_since_invalid"});return t}async function ff(e,t,n){let r=Cv(t.addJson),s=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&s)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let o=r===void 0?void 0:J(r),i=[t.since,t.eventType].some(h=>h!==void 0),a=Iv(t.since),c=Vn(t.limit),m=await Rn(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await oo(o===void 0?t:{add:o},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>Cn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:Rv(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm notes pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}}),u=t.eventType?.trim(),p=m.notes.filter(h=>{let y=[h.format==="json",h.data!==void 0].every(Boolean),g=[a===void 0,Date.parse(h.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),b=[!u,h.event_type===u].includes(!0);return[!i,[y,g,b].every(Boolean)].includes(!0)}),f=i?xa(p,c):p,_=f.filter(h=>h.format==="json").length;return{...m,notes:f,count:f.length,...i?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f9c9b926-c912-548e-a9c7-64c2c69767cd")}catch{}})();function co(e,t){if(!t&&/[:,=]/.test(e))throw new l(`Invalid --dep value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE)}function sr(e,t,n=ra()){for(let r of t??[])try{qd(e,r.id,r.kind,n)}catch(s){throw new l(cn(s),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function _f(e,t){return(await K(e,{schema:t})).document.metadata.created_at}async function xv(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await $(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:_f(n,t.schema)}function Ov(e){let t=e.registry.require(e.dependency.kind);return new l(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,d.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function Pv(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 _f(n.get(s),e.context.schema)])));for(let s of e.holders){let o=await xv(s,e.context);if(o!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(o),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw Ov({holder:s,dependency:i,sourceCreatedAt:o,targetCreatedAt:a,registry:e.registry})}}}async function Bt(e){let t=e.registry??ra(),n=(e.dependencies??[]).filter(i=>!$u(i.source_kind)),r=[...new Set(n.map(i=>i.id))],s=await Promise.all(r.map(async i=>({target:i,located:await $(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),o=s.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(o.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${o.length===1?"":"s"} not found: ${o.join(", ")}`,d.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:o,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${o.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:o,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${o[0]}" --limit 10`}});return await Pv({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 lo(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function mo(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function uo(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Rr.includes(t))return t;let n=se(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new l("Confidence must be an integer 0..100 or one of low|med|medium|high",d.USAGE);return n}function po(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new l("Regression must be one of true|false|1|0",d.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="afc4f3d5-ba5e-5dd7-abc9-531b319cdb4e")}catch{}})();var Nv=new Set(["none","null"]);function fo(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 Ge(e){return e===void 0?!1:Nv.has(e.trim().toLowerCase())}function _o(e,t,n){if(!Ge(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function ge(e,t,n){if(!e||e.length===0||!e.some(o=>Ge(o)))return;let s=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${s}`.trim(),d.USAGE)}function ho(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new l(`${n.valueFlag} entries must be strings.`,d.USAGE);let s=r;if(!s.some(a=>Ge(a)))continue;if(s.filter(a=>!Ge(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2fcfbe50-039b-5031-8b18-a208908a0d87")}catch{}})();function gf(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,d.USAGE)}function Da(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function ye(e,t,n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE);return e}var yf=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Lv(e,t){return t==="defined"?e!==void 0:!!e}function hf(e,t,n){if(!Lv(e,n))return;let r=se(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function Fv(e,t,n){let r=e?Q(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new l("--event recur_until must be at or after start",d.USAGE);return r}function Mv(e){return Array.from(new Set(Da(e).map(t=>ye(t.toLowerCase(),Fd,"event weekday")))).sort((t,n)=>Si(t)-Si(n))}function $v(e){return Array.from(new Set(Da(e).map(t=>{let n=se(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new l("--event recur_by_month_day values must be integers 1..31",d.USAGE);return n}))).sort((t,n)=>t-n)}function Dv(e,t){return Array.from(new Set(Da(e).map(n=>Q(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function bf(e,t,n,r){let s=e.recur_freq?.trim(),o=e.recur_interval?.trim(),i=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![s,o,i,a,c,m,u].some(E=>E!==void 0))return;if(!s)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let f=ye(s.toLowerCase(),Ld,"event recurrence frequency"),_=hf(o,"recur_interval",r),h=hf(i,"recur_count",r),y=Fv(a,t,n),g=Mv(c),b=$v(m),v=Dv(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 wf="--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.",Uv="--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).",Gv=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,jv=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,kf=1e3,Ua=60*kf,qv=60*Ua;function vf(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new l(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,d.USAGE);return n.toISOString()}function Kv(e,t){let n=new Date(e),r=t.trim(),s=Gv.exec(r);if(s){let a=s[1]==="-"?-1:1,c=Number.parseInt(s[2],10)*a;return vf(n.getTime()+c*Ua,r)}let o=jv.exec(r);if(o){let[,a,c,m,u]=o;if(c||m||u){let f=a==="-"?-1:1,_=Number.parseInt(c??"0",10),h=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),g=_*qv+h*Ua+y*kf;return vf(n.getTime()+f*g,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return Q(i,n,"event.duration")}function Sf(e,t,n,r){if(t&&n)throw new l(Uv,d.USAGE);if(n){let o=Kv(e,n);if(o<e)throw new l(wf,d.USAGE);return o===e?void 0:o}if(!t)return;let s=Q(t,r,"event.end");if(s<e)throw new l(wf,d.USAGE);if(s!==e)return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var zv=["at","date","text","title"],Bv=["start","date","end","duration","title","description","location","timezone","all_day",...yf],Hv=["key","value"];function Ef(e,t){return t==="trimmed"?e?.trim():e}function Vv(e,t){return t==="defined"?e!==void 0:!!e}function go(e,t,n){return e.map(r=>{let s=te(r,"--reminder");Ue(s,"--reminder",zv);let o=Ef(s.at??s.date,n.valueMode),i=Ef(s.text??s.title,n.valueMode);if(!o||!i)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let a=i.trim();if(!a)throw new l("--reminder text must not be empty",d.USAGE);return{at:Q(o,t,"reminder.at"),text:a}})}function yo(e,t,n){return e.map(r=>{let s=te(r,"--event");Ue(s,"--event",Bv);let o=(s.start??s.date)?.trim();if(!o)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let i=Q(o,t,"event.start"),a=s.end?.trim(),c=s.duration?.trim(),m=Sf(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[M,G,Ie]of v)if(G!==void 0&&!Ie)throw new l(`--event ${M} must not be empty`,d.USAGE);let E=s.all_day?.trim(),N=bf(s,i,t,n.recurrenceEmptyNumericGuard),P=Vv(E,n.allDayEmptyGuard)?gf(E,"--event all_day"):void 0;return{start_at:i,end_at:m,title:h,description:y,location:g,all_day:P,timezone:b,recurrence:N}})}function bo(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new l("--type-option values must not be empty",d.USAGE);let s,o;if(r.includes(",")||r.includes(`
5
+ `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=te(r,"--type-option");Ue(a,"--type-option",Hv),s=a.key?.trim(),o=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),m=a;if(a<=0&&c>0&&(m=c),m<=0||m===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);s=r.slice(0,m).trim(),o=r.slice(m+1).trim()}if(!s||!o)throw new l("--type-option requires key and value",d.USAGE);t[s]=o}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var Wv=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Tf(e,t,n,r){if(Wv.has(t.trim().toLowerCase())||n!==r.open_status)return;let s=ps("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 Ht=["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"],Yv=new Set(Ht),Jv=Ht.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),Xv=new RegExp(`^(?:[-*+]\\s+)?(?:${Jv})\\s*[:=]`,"i");function wo(e){return e.startsWith("```")||e.includes(`
6
+ `)?!0:Xv.test(e)}function vo(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!Yv.has(i)){r.push(s);continue}if(Object.hasOwn(n,i))throw new l(`${t} provides key "${s}" more than once after case normalization`,d.USAGE);n[i]=o}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(s=>`"${s}"`).join(", ")}. Allowed keys: ${Ht.join(", ")}.`,d.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new l(`${t} command and cmd must match when both are provided`,d.USAGE);let{cmd:s,...o}=n;return{...o,command:o.command??s}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="74163bed-a473-543e-ae6a-0d5091b3b3a9")}catch{}})();var Wt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Hs,Yu,"FORCE_COLOR"]),Eo=/^[A-Za-z_][A-Za-z0-9_]*$/,Vt=["schema","tracker","auto"];function or(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1);if(!Eo.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(Wt.has(i.toUpperCase()))throw new l(`${t} env_set key "${i}" is reserved for sandbox safety`,d.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function ir(e,t){if(!e)return;let n=Sn(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,d.USAGE);for(let r of n){if(!Eo.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(Wt.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function To(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,d.USAGE)}function Ao(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Vt.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${Vt.join(", ")}`,d.USAGE)}function Yt(e){if(!e)return;let t=Sn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function xn(e,t,n){let r=Yt(e);if(!(!r||r.length===0)){for(let s of r)try{new RegExp(s,"m")}catch(o){throw new l(`${t} ${n} includes invalid regex "${s}": ${o instanceof Error?o.message:String(o)}`,d.USAGE)}return r}}function Co(e,t){if(!e)return;let n=se(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,d.USAGE);return n}function Ro(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function Io(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,d.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${i}" must be numeric`,d.USAGE);r[i]=c}return Object.keys(r).length>0?r:void 0}var Qv=new Set(Ht);function xo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zv(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!Qv.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: ${Ht.join(", ")}.`);return n}function In(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 ko(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 Af(e,t,n){let r=ko(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 So(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 ek(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:So(n,"timeout_seconds",t),o=r===void 0?void 0:So(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 tk(e,t){let n=In(e,"scope",t);if(n===void 0)return"project";if(!Ze.includes(n))throw t(`field "scope" must be one of: ${Ze.join(", ")}`);return n}function nk(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!xo(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(!Eo.test(s))throw t(`field "env_set" key "${s}" is invalid`);if(Wt.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 rk(e,t){let n=ko(e,"env_clear",t);if(n){for(let r of n){if(!Eo.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(Wt.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function sk(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 ok(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=So(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 ik(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!xo(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 ak(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!xo(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]=So(o,`assert_json_field_gte.${s}`,t)}return Object.keys(r).length>0?r:void 0}function ck(e,t,n){let r=p=>new l(`${n} ${t} ${p}`,d.USAGE);if(!xo(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Ht.join(", ")}.`);let s=Zv(e,r),o=In(s,"command",r),i=In(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=In(s,"path",r),m=In(s,"pm_context_mode",r);if(m!==void 0&&!Vt.includes(m))throw r(`field "pm_context_mode" must be one of: ${Vt.join(", ")}`);let u=In(s,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:tk(s,r),timeout_seconds:ek(s,r),pm_context_mode:m,env_set:nk(s,r),env_clear:rk(s,r),shared_host_safe:sk(s,"shared_host_safe",r),assert_stdout_contains:ko(s,"assert_stdout_contains",r),assert_stdout_regex:Af(s,"assert_stdout_regex",r),assert_stderr_contains:ko(s,"assert_stderr_contains",r),assert_stderr_regex:Af(s,"assert_stderr_regex",r),assert_stdout_min_lines:ok(s,r),assert_json_field_equals:ik(s,r),assert_json_field_gte:ak(s,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function Cf(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,d.USAGE);let r;try{r=JSON.parse(n)}catch(o){throw new l(`${t} value is not valid JSON: ${o instanceof Error?o.message:String(o)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let s=Array.isArray(r)?r:[r];if(s.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return s.map((o,i)=>ck(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 Ga=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],ja=[{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"}],Rf=[...Ga,...ja],Oo=[{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 Po(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let s=r.trim().toLowerCase();if(!s)throw new l("--unset values must not be empty",d.USAGE);if(Ge(s))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let o=e.resolveDefinition(s);if(!o)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(o.metadataKey),n.add(o.optionKey)}return{metadataKeys:t,optionKeys:n}}function No(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 dk={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 lk(e){return dk[e]}function qa(e){return lk(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7d69bb56-9fab-5059-9357-5b6bea2078b9")}catch{}})();var mk=["strict","progressive"],uk=["lightweight"],Pf=new Set(["Reminder","Meeting","Event"]),pk=new Set(["author","created_at","text"]),za=[...Rf,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...Oo],fk=(()=>{let e=new Map;for(let t of za)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Lo=new Map(za.map(e=>[e.optionKey,e.canonical])),_k=za.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function hk(e,t){let n=ne(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function gk(e,t){let n=e.default_status;if(n!==void 0){let r=ne(n,t);if(r)return r}return t.open_status}function Ka(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}var yk=fo();function Nf(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};Ge(t.template)&&(t.template=void 0);let r=new Set([...Lo.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Ge(o))continue;let i=s==="rank"?"order":Lo.get(s)??s;n(i),t[s]=void 0}return ho(t,yk)}function ce(e){if(e!==void 0)return e}function bk(e,t){return Po({raw:e,supportedFields:_k,resolveDefinition:n=>fk.get(n)??No(n,"create",t)})}var If=["id","kind","type","author","created_at","source_kind"],Fo=["path","scope","note"];function wk(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let i=o.trim(),a=Ba(i,If);co(i,a);let c=a?te(o,"--dep"):{id:i,kind:"related"};a&&Ue(c,"--dep",If);let m=ce(c.id),u=vk(ce(c.kind??c.type));if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",d.USAGE);if(m.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=Wn(ce(c.source_kind)),f=ce(c.author);return{id:Yn(m,n,p),kind:ye(u,Ft,"dependency kind"),created_at:Ka(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function vk(e){return typeof e=="string"?Lr(e)??e.trim():e}function Ba(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:qs(e)}function Xt(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(ge(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(i=>{let a=i.trim(),c=()=>{if(a.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:a}},m;try{m=te(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!pk.has(f)).length>0)return{created_at:Ka(m.created_at,n),author:ce(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:Ka(m.created_at,n),author:ce(m.author)??r,text:p}}),explicitEmpty:!1})}function Ha(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),s=Ba(r,Fo),o=s?te(n,"--file"):{path:r};if(s&&Ue(o,"--file",Fo),!o.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:o.path,scope:ye(o.scope??"project",Ze,"file scope"),note:ce(o.note)}}),explicitEmpty:!1})}function Va(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),s=wo(r)?vo(te(n,"--test"),"--test"):{command:r},o=ce(s.command),i=ce(s.path);if(!o)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let a=ce(s.timeout_seconds),c=ce(s.timeout);if(a&&c&&a!==c)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let m=a??c;return{command:o,path:i,scope:ye(s.scope??"project",Ze,"test scope"),timeout_seconds:m?se(m,"timeout_seconds"):void 0,pm_context_mode:Ao(s.pm_context_mode,"--test"),env_set:or(s.env_set,"--test"),env_clear:ir(s.env_clear,"--test"),shared_host_safe:To(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Yt(s.assert_stdout_contains),assert_stdout_regex:xn(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Yt(s.assert_stderr_contains),assert_stderr_regex:xn(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Co(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:Ro(s.assert_json_field_equals,"--test"),assert_json_field_gte:Io(s.assert_json_field_gte,"--test"),note:ce(s.note)}}),explicitEmpty:!1})}function Wa(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),s=Ba(r,Fo),o=s?te(n,"--doc"):{path:r};if(s&&Ue(o,"--doc",Fo),!o.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:o.path,scope:ye(o.scope??"project",Ze,"doc scope"),note:ce(o.note)}}),explicitEmpty:!1})}function kk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--reminder","Use --clear-reminders to clear reminders."),{values:go(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function Sk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--event","Use --clear-events to clear linked events."),{values:yo(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function Ek(e,t,n,r=[]){let s=[...Ir.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 Tk(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function xf(e,t,n){let r=Dn("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function Ak(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 Lf(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 Ck(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(xf(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(xf(r,e.name,"required_create_repeatables"));return n}function Rk(e,t,n,r){for(let s of e)if(!(!Lf(t,s)&&!n.has(s)))throw new l(`Option ${fe("create",s)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function Ik(e,t,n){if(t!=="strict")return;let r=e.filter(o=>n.has(o)&&!qa(o));if(r.length===0)return;let s=[...new Set(r.map(o=>fe("create",o)))].sort((o,i)=>o.localeCompare(i));throw new l(`Strict create mode requires concrete values for ${s.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function xk(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:bo(e),explicitEmpty:!1})}async function Ok(e){let t=Ne();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 Pk(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${mk.join(", ")}`,d.USAGE)}function Nk(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new l("--schedule-preset must not be empty",d.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new l(`Invalid --schedule-preset value "${e}". Allowed: ${uk.join(", ")}`,d.USAGE)}function Lk(e,t,n){let r=Pk(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",d.USAGE);return"progressive"}function Fk(e,t,n,r){let s=e.name,o=Ak(t),i=Ck(e,n),a=an(e,"create",i);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);Rk(a.disabled,o,r,s),Ik(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&qa(u)?!0:Lf(o,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>fe("create",u)))].sort((u,p)=>u.localeCompare(p))}var Ff=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function Mk(e,t){let n=[];for(let r of e){let s=r.match(Ff);s&&s[2]===t&&n.push(s[1])}return[...new Set(n)].sort((r,s)=>r.localeCompare(s))}function $k(e,t){return e.filter(n=>{let r=n.match(Ff);return!r||r[2]!==t})}function Dk(e,t,n,r){let s=$k(e,t);if(s.length===0)return;let o=Mf(n,[],[],r.open_status);throw new l(s.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[o],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function Uk(e,t){let r=e.options.find(s=>s.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function Gk(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 Mf(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(...Gk(c,e.name,r)),a.add(c));for(let c of n){let m=Uk(e,c);s.push("--type-option",`${c}=${m}`)}return s.join(" ")}function Ya(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new l("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",d.USAGE):new l('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',d.USAGE):new l(`Missing required option ${t}`,d.USAGE);return n}function jk(e){return kn(e)}function qk(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 Kk(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function zk(){let e=I();return e?e.commands.some(t=>t.action==="templates-show"||Kk(t.command)==="templates show"):!1}function Bk(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new l(`Templates package returned invalid payload for template "${t}". Expected an options object.`,d.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Templates package returned invalid options for template "${t}".`,d.GENERIC_FAILURE);let r={};for(let[s,o]of Object.entries(n)){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"){r[s]=o;continue}if(Array.isArray(o)&&o.every(i=>typeof i=="string")){r[s]=[...o];continue}throw new l(`Templates package returned unsupported option value for "${s}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function Hk(e,t,n){if(!zk())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await ys({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let s=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${s}`,d.USAGE)}return Bk(r.result,e)}function Vk(e){return k(C(e)).then(t=>{if(!t)throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)})}function B(e,t,n){return e.has(t)||n===void 0?void 0:ce(n)}function Jt(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var Wk=new Set(["milestone","meeting","reminder","event"]);function $f(e,t,n,r){let s=t!==void 0,o=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return Wk.has(e.toLowerCase())&&!s&&!o&&!i}function Yk(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`),$f(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 Jk(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let s=await bs(r);return s===void 0?{parent:e,parentSource:void 0}:{parent:s,parentSource:"focus"}}async function Xk(e,t,n,r,s,o){let i=$s(s);if(Us(r,i,t.id_prefix),await $(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let c=_e(i,t.id_prefix);return{parent:i,warnings:Ds(c,o).warnings}}async function Qk(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await Xk(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function Zk(e){if(e.explicitId===void 0)return Hn(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||Su(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=_e(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",d.USAGE);return n}function Of(e,t,n,r,s){let o=B(e,t,n);if(o===void 0)return{value:void 0,warnings:[]};let i=Ks(r,o,s);return{value:i.value,warnings:i.warnings}}async function eS(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:s,blockedBy:o,status:i,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(o===void 0)return{dependencyValues:u,status:i};let p=_e(o,n.id_prefix),f=await $(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:i};if((u??[]).some(y=>y.id===f.id&&y.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:i};let h=s.blocked_statuses.has("blocked")?"blocked":[...s.blocked_statuses].sort((y,g)=>y.localeCompare(g))[0]??s.open_status;return{dependencyValues:u,status:h}}function tS(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&&ue(s,n)){e.type=s;return}ue("Task",n)&&(e.type="Task")}function nS(e,t){return e.options.filter(n=>Dn("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function rS(e,t,n,r,s){let o=e,i=[];if(o.template!==void 0){let h=o.template.trim();if(h.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let y=await Hk(h,t,n);o=Nf(qk(y,o))}if(o.type===void 0&&tS(o,r,s),o.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let a=ue(o.type,s);if(!a){let h=Tu(o.type),y=h?ue(h,s):void 0;if(y)i.push(`type_coercion:${o.type.trim()}:${y}`),o.type=y,a=y;else throw new l(gt(o.type,s.types,yt(n,r.schema)),d.USAGE)}let c=Pr(a,s);if(!c)throw new l(`Invalid type value "${o.type}"`,d.USAGE);let m=c.name,u=nS(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=Nk(o.schedulePreset);if(f!==void 0&&!Pf.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=Lk(o.createMode,f,r.governance.create_mode_default);return{resolvedOptions:o,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function sS(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),s=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let o of s)if(o.enabled){if(o.values&&o.values.length>0)throw new l(`Cannot combine ${o.clearFlag} with ${o.valueFlag}`,d.USAGE);n.add(o.metadataKey),r.add(o.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function oS(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=Lo.get(r)??r;throw new l(`Cannot combine --unset ${o} with ${fe("create",r)}`,d.USAGE)}}function iS(e){let t=(n,r)=>{let s=Lo.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;_o(n,fe("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 aS(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,d.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,d.USAGE)}function cS(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:s,openStatus:o,type:i,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(_=>{let h=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${h}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),u=[Mf(n,r,s,o),...m.map(_=>_.example)].join(" "),p=[`Run "pm create --help --type ${i}" for type-aware required option guidance.`];t.includes("--title")&&p.push('Title can also be passed as the first positional argument (example: pm create "Your title" --type '+i+")."),a==="strict"&&(p.push('For staged onboarding, retry with "--create-mode progressive".'),Pf.has(i)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&p.push(`Required custom field formats: ${m.map(_=>_.description).join("; ")}.`);let f=t.length===1?`Missing required option ${t[0]} for type "${i}"`:`Missing required options ${t.join(", ")} for type "${i}"`;throw new l(f,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${i}" in one invocation.`,examples:[u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:["--create-mode progressive",...t]}:void 0})}function dS(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?St(t.tags):[];return wn(n,t.addTags)}function lS(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new l("--order and --rank must match when both are provided",d.USAGE);let n=t.order??t.rank,r=Jt(e,"order",n,s=>se(s,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function mS(e,t,n,r,s,o){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",d.USAGE);let i=e!==t.close_status?void 0:r.completedAt===void 0?o:Q(r.completedAt,new Date(o),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:i,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:s}:{explicit:r.closeReason};return{closeReason:Na(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function uS(e){let{pmRoot:t,type:n,id:r,settings:s,typeRegistry:o,author:i,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=$t(t,n,r,s.item_format,o.type_to_folder),g=ke(t,r),b=await xe(t,r,s.locks.ttl_seconds,i,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),v=[];try{let E=c.metadata.dependencies&&c.metadata.dependencies.length>0?await re(t,s.item_format,o.type_to_folder,void 0,s.schema):void 0;if(await $(t,r,s.id_prefix,s.item_format,o.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);await gs({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:As({pmRoot:t,settings:s,typeToFolder:o.type_to_folder})});let P=await gn(t,i,{required:s.governance.duplicate_detection_mode==="strict"&&h!==!0}),M=[];try{s.governance.duplicate_detection_mode==="strict"&&h!==!0&&await An(_,{pmRoot:t,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1}),await me(y,$e(c,{format:s.item_format,schema:s.schema,extensionFieldNames:a}));try{let G=De({nowIso:f,author:i,op:"create",before:m,after:c,message:u});await wt(g,G)}catch(G){throw await on(y),G}M=await yn({pmRoot:t,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:y,document:c})}finally{await P()}v=[...E?Zs(E,[...E,c.metadata],r):[],...M,...await z({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await z({path:g,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],mn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Ut(c.metadata,p),changed_fields:p})}finally{await b()}return v}async function At(e,t){let n=Nf(await Ok(e)),r=T(process.cwd(),t.path);await Vk(r);let s=await A(r),o=j(s.schema),i=Be(s.schema),a=x(s,I()),c=await rS(n,t,r,s,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=bk(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=sS(n,f);oS(n,f),iS(n);let y=Fk(m,n,p,h),g=S(),b=R(ce(n.author),s.author_default),v=wk(n.dep,g,s.id_prefix,b),E=Xt("--comment",n.comment,g,b),N=Xt("--note",n.note,g,b),P=Xt("--learning",n.learning,g,b),M=Ha(n.file),G=Va(n.test),Ie=Wa(n.doc),ee=kk(n.reminder,g),pe=Sk(n.event,g),ie=xk(n.typeOption),Xe=Un(u,ie.values,a),ze=I(),Pt=ft(ze),ut=xr(n.field,ze),Nt=Vm(n,i,u),pi=new Set(Nt.missing_required_flags),vr=i.definitions.filter(H=>pi.has(`--${H.cli_flag}`));aS(ut,Nt,f);let Qe=Mk(Xe.errors,u),hd=Qe.map(H=>`--type-option ${H}=<value>`),kr=[...new Set([...y,...hd,...Nt.missing_required_flags])].sort((H,vi)=>H.localeCompare(vi));cS({combinedMissingFlags:kr,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:Qe,openStatus:o.open_status,type:u,createMode:p,missingRequiredRuntimeFields:vr}),Dk(Xe.errors,u,m,o);let ae=await Zk({pmRoot:r,settings:s,typeRegistry:a,explicitId:n.id}),ve=n.status!==void 0?hk(n.status,o):gk(m,o),fi=n.priority!==void 0?jk(n.priority):2,O=f.metadataKeys,Sr=dS(O,n),_i=Jt(O,"deadline",n.deadline,H=>Q(H,new Date(g),"deadline")),Zy=Jt(O,"estimated_minutes",n.estimatedMinutes,H=>vn(H,"estimated-minutes")),eb=B(O,"acceptance_criteria",n.acceptanceCriteria),tb=B(O,"definition_of_ready",n.definitionOfReady),nb=lS(O,n),rb=B(O,"goal",n.goal),sb=B(O,"objective",n.objective),ob=B(O,"value",n.value),ib=B(O,"impact",n.impact),ab=B(O,"outcome",n.outcome),cb=B(O,"why_now",n.whyNow),db=B(O,"assignee",n.assignee),lb=O.has("author")?void 0:ce(n.author)??b,mb=B(O,"parent",n.parent),gd=await Jk(mb,n,O,r),hi=gd.parent,ub=gd.parentSource,pb=B(O,"reviewer",n.reviewer),fb=Jt(O,"risk",n.risk,H=>ye(lo(H),rn,"risk")),_b=Jt(O,"confidence",n.confidence,H=>uo(H)),hb=n.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,yd=s.validation.sprint_release_format,Lt=[...c.warnings,...Yk(u,ae,_i,ee.values,pe.values)],bd=await Qk({itemId:ae,parent:hi,pmRoot:r,settings:s,typeRegistry:a,policy:hb});hi=bd.parent,Lt.push(...bd.warnings);let wd=Of(O,"sprint",n.sprint,"sprint",yd),gb=wd.value;Lt.push(...wd.warnings);let vd=Of(O,"release",n.release,"release",yd),yb=vd.value;Lt.push(...vd.warnings);let kd=B(O,"blocked_by",n.blockedBy),Sd=await eS({pmRoot:r,settings:s,typeRegistry:a,statusRegistry:o,blockedBy:kd,dependencyValues:v.values,status:ve,statusExplicit:n.status!==void 0,nowValue:g,author:b}),gi=Sd.dependencyValues;sr(ae,gi),Lt.push(...await Bt({pmRoot:r,dependencies:gi,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:ae,createdAt:g}],schema:s.schema})),ve=Sd.status;let bb=B(O,"blocked_reason",n.blockedReason),wb=B(O,"unblock_note",n.unblockNote),vb=B(O,"reporter",n.reporter),kb=Jt(O,"severity",n.severity,H=>ye(mo(H),sn,"severity")),Sb=B(O,"environment",n.environment),Eb=B(O,"repro_steps",n.reproSteps),Ed=B(O,"resolution",n.resolution),Tb=B(O,"expected_result",n.expectedResult),Ab=B(O,"actual_result",n.actualResult),Cb=B(O,"affected_version",n.affectedVersion),Rb=B(O,"fixed_version",n.fixedVersion),Ib=B(O,"component",n.component),xb=Jt(O,"regression",n.regression,H=>po(H)),Ob=B(O,"customer_impact",n.customerImpact),yi=Ya(n.title,"--title"),bi=n.description??"",Er=n.body??"",Td=await An({title:yi,description:bi,body:Er},{pmRoot:r,mode:s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Lt.push(...eo(Td));let wi=mS(ve,o,s,n,Ed,g),Pb=wi.closeReason,Nb=ve===o.close_status?g:void 0,Lb=wi.completedAt;Lt.push(...wi.warnings);let Tr=Yi({id:ae,title:yi,description:bi,type:u,type_options:Xe.normalized,status:ve,closed_at:Nb,completed_at:Lb,close_reason:Pb,priority:fi,tags:Sr,created_at:g,updated_at:g,deadline:_i,assignee:db,author:lb,estimated_minutes:Zy,acceptance_criteria:eb,definition_of_ready:tb,order:nb,goal:rb,objective:sb,value:ob,impact:ib,outcome:ab,why_now:cb,parent:hi,reviewer:pb,risk:fb,confidence:_b,sprint:gb,release:yb,blocked_by:kd,blocked_reason:bb,unblock_note:wb,reporter:vb,severity:kb,environment:Sb,repro_steps:Eb,resolution:Ed,expected_result:Tb,actual_result:Ab,affected_version:Cb,fixed_version:Rb,component:Ib,regression:xb,customer_impact:Ob,dependencies:gi,comments:E.values,notes:N.values,learnings:P.values,files:M.values,tests:G.values,docs:Ie.values,reminders:ee.values,events:pe.values,...ut,...Nt.values});try{Or(Tr,ze)}catch(H){throw new l(H instanceof Error?H.message:"Invalid extension item field values",d.USAGE)}let Fb=He({metadata:Tr,body:Er},{schema:s.schema,extensionFieldNames:Pt}),Mb={metadata:{},body:""},Ad=[..._].sort((H,vi)=>H.localeCompare(vi)),$b=Tk(n.message,Ad),Cd=Ek(Tr,Er,Ad,[...Object.keys(ut),...Object.keys(Nt.values??{})]),Db=await uS({pmRoot:r,type:u,id:ae,settings:s,typeRegistry:a,author:b,extensionFieldNames:Pt,afterDocument:Fb,beforeDocument:Mb,historyMessage:$b,changedFields:Cd,nowValue:g,similarityCandidate:{title:yi,description:bi,body:Er},allowDuplicate:n.allowDuplicate}),Rd=structuredClone(Tr);p==="strict"&&_.has("dependencies")&&(Rd.dependencies=[]);let Ub=Tf(ae,u,ve,o);return $f(u,_i,ee.values,pe.values)&&nu(`[pm] warning: ${u} '${ae}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${ae} --deadline <ISO>' or 'pm update ${ae} --event "start=<ISO>,end=<ISO>"'.`),{item:Rd,changed_fields:Cd,warnings:[...Lt,...Db],...Object.fromEntries([["parent_source",ub],["next_transition",Ub],["similarity_advisory",Td]].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]="a421c150-13a9-5334-85a4-5b3199a5d2c7")}catch{}})();var Za=[...Ga,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...ja,...Oo],pS=(()=>{let e=new Map;for(let t of Za)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Mo=new Map(Za.map(e=>[e.optionKey,e.canonical])),fS=Za.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),_S=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),hS=fo({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function gS(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([...Mo.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Ge(o))continue;let i=s==="rank"?"order":Mo.get(s)??s;n(i),t[s]=void 0}return ho(t,hS)}function Hf(e,t,n=[]){return Po({raw:e,supportedFields:fS,resolveDefinition:r=>{let s=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return pS.get(r)??No(r,"update",t)??(s?{optionKey:"field",metadataKey:s}:void 0)}})}var Df=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 Uf(e){let t=e.disallowedFlags.flatMap(r=>{let s=Df.get(r);return s?[s(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let s=Df.get(r);return s?[`Replace ${r} with: ${s(e.id)}`]:[]});return new l(e.message,d.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function yS(e,t,n){let r=t.ownershipMetadataBypass===!0,s=t.ownershipDependencyBypass===!0;if(!r&&!s)return;if(r&&s)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let o=(c,m,u)=>{c&&u.push(m)};if(s){let c=[];if(o(t.title!==void 0,"--title",c),o(t.description!==void 0,"--description",c),o(t.body!==void 0,"--body",c),o(t.status!==void 0,"--status",c),o(t.closeReason!==void 0,"--close-reason",c),o(t.priority!==void 0,"--priority",c),o(t.type!==void 0,"--type",c),o(t.tags!==void 0,"--tags",c),o(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),o(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),o(t.deadline!==void 0,"--deadline",c),o(t.estimatedMinutes!==void 0,"--estimate",c),o(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),o(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),o(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),o(t.definitionOfReady!==void 0,"--definition-of-ready",c),o(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),o(t.goal!==void 0,"--goal",c),o(t.objective!==void 0,"--objective",c),o(t.value!==void 0,"--value",c),o(t.impact!==void 0,"--impact",c),o(t.outcome!==void 0,"--outcome",c),o(t.whyNow!==void 0,"--why-now",c),o(t.assignee!==void 0,"--assignee",c),o(t.parent!==void 0,"--parent",c),o(t.reviewer!==void 0,"--reviewer",c),o(t.risk!==void 0,"--risk",c),o(t.confidence!==void 0,"--confidence",c),o(t.sprint!==void 0,"--sprint",c),o(t.release!==void 0,"--release",c),o(t.blockedBy!==void 0,"--blocked-by",c),o(t.blockedReason!==void 0,"--blocked-reason",c),o(t.unblockNote!==void 0,"--unblock-note",c),o(t.reporter!==void 0,"--reporter",c),o(t.severity!==void 0,"--severity",c),o(t.environment!==void 0,"--environment",c),o(t.reproSteps!==void 0,"--repro-steps",c),o(t.resolution!==void 0,"--resolution",c),o(t.expectedResult!==void 0,"--expected-result",c),o(t.actualResult!==void 0,"--actual-result",c),o(t.affectedVersion!==void 0,"--affected-version",c),o(t.fixedVersion!==void 0,"--fixed-version",c),o(t.component!==void 0,"--component",c),o(t.regression!==void 0,"--regression",c),o(t.customerImpact!==void 0,"--customer-impact",c),o(t.depRemove!==void 0,"--dep-remove",c),o(t.replaceDeps===!0,"--replace-deps",c),o(t.replaceTests===!0,"--replace-tests",c),o(t.replaceFiles===!0,"--replace-files",c),o(t.replaceDocs===!0,"--replace-docs",c),o(t.comment!==void 0,"--comment",c),o(t.note!==void 0,"--note",c),o(t.learning!==void 0,"--learning",c),o(t.file!==void 0,"--file",c),o(t.test!==void 0,"--test",c),o(t.doc!==void 0,"--doc",c),o(t.reminder!==void 0,"--reminder",c),o(t.event!==void 0,"--event",c),o(t.typeOption!==void 0,"--type-option",c),o(t.clearDeps===!0,"--clear-deps",c),o(t.clearComments===!0,"--clear-comments",c),o(t.clearNotes===!0,"--clear-notes",c),o(t.clearLearnings===!0,"--clear-learnings",c),o(t.clearFiles===!0,"--clear-files",c),o(t.clearTests===!0,"--clear-tests",c),o(t.clearDocs===!0,"--clear-docs",c),o(t.clearReminders===!0,"--clear-reminders",c),o(t.clearEvents===!0,"--clear-events",c),o(t.clearTypeOptions===!0,"--clear-type-options",c),o(t.force===!0,"--force",c),o(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw Uf({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=>_S.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw Uf({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 bS(e,t){let n=ne(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function wS(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=_m({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=ne(e.fromStatus,e.statusRegistry)??e.fromStatus,r=ne(e.toStatus,e.statusRegistry)??e.toStatus,s=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${hm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(s,d.USAGE);return`workflow_transition_not_allowed: ${s}`}function vS(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}function $o(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var kS=["id","kind","type","author","created_at","source_kind"],SS=["id","kind","type","source_kind"];function ES(e){return e.startsWith("```")||e.includes(`
8
+ `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:qs(e)}function Vf(e){return typeof e=="string"?Lr(e)??e.trim():e}function Do(e,t,n,r){return e?(ge(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=ES(i);co(i,a);let c=a?te(o,"--dep"):{id:i,kind:"related"};a&&Ue(c,"--dep",kS);let m=c.id?.trim(),u=Vf((c.kind??c.type)?.trim());if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",d.USAGE);if(m.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=Wn($o(c.source_kind)),f=$o(c.author);return{id:Yn(m,t,p),kind:ye(u,Ft,"dependency kind"),created_at:vS(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function TS(e,t){return e?(ge(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new l("--dep-remove requires id or key/value selectors",d.USAGE);if(r.includes("=")||/^(?:[-*+]\s+)?(?:id|kind|type|source_kind)\s*[:=]/i.test(r)||r.startsWith("```")){let s=te(r,"--dep-remove");Ue(s,"--dep-remove",SS);let o=s.id?.trim();if(!o)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(o.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${o}"`,d.USAGE);let i=Vf($o(s.kind??s.type)),a=Wn($o(s.source_kind));return{id:Yn(o,t,a),kind:i?ye(i,Ft,"dependency kind"):void 0,source_kind:a}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:_e(r,t)}})):[]}function Gf(e){let t=e.source_kind?.trim().toLowerCase()??"";return`${e.id.trim().toLowerCase()}::${e.kind}::${t}`}function AS(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 CS(e,t,n,r,s,o){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await $(n,_e(i,r),r,s,o);return a?{id:a.id}:{unresolved:i}}function RS(e,t,n,r,s){let o=AS(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 IS(e){return`${e.path}::${e.scope}`}function xS(e){return`${e.path}::${e.scope}`}function OS(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}`}function PS(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 NS(e){return kn(e)}function jf(e,t){let n=Dn("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function LS(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=Hf(e.unset,t,n);for(let i of o.optionKeys)s(i,!0)}return r}function FS(e,t,n,r,s){let o=Pr(e,n);if(!o)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=an(o,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let a=LS(t,r,s);for(let c of i.disabled)if(a.has(jf(c,e)))throw new l(`Option ${fe("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of i.required)if(!a.has(jf(c,e)))throw new l(`Missing required option ${fe("update",c)} for type "${e}"`,d.USAGE)}var MS=new Set(["order","rank"]),$S=xi.filter(e=>!MS.has(e)),Wf=["tags","closeReason",...$S],DS=["title","description","body","status","closeReason","completedAt","priority","type",...xi,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],US=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>Q(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>vn(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"}],GS=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>ye(lo(e),rn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>uo(e)}],jS=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>ye(mo(e),sn,"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=>po(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Qa(e,t,n){for(let r of e){let s=t[r.optionKey],o=n.clearItemMetadataKeys.has(r.metadataKey);if(!(s===void 0&&!o)){if(o){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof s!="string")throw new l(`${fe("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(s,n):s.trim(),n.changedFields.push(r.metadataKey)}}}async function qS(e){let t=Ne();return gS({...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 KS(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 Ja(e){if(e.enabled&&(!e.values||e.values.length===0))throw new l(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,d.USAGE);if(e.enabled&&e.clearEnabled)throw new l(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,d.USAGE)}function ec(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new l("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",d.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new l("--replace-deps requires at least one --dep entry",d.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new l("--replace-deps cannot be combined with --dep-remove",d.USAGE);Ja({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Ja({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Ja({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function zS(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new l(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,d.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function BS(e){let t={};for(let n of Wf)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function HS(e,t){let n=BS(e);for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=Mo.get(r)??r;throw new l(`Cannot combine --unset ${o} with ${fe("update",r)}`,d.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --add-ac",d.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --remove-ac",d.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new l("Cannot combine --unset tags with --remove-tags",d.USAGE)}}function VS(e){let t=(n,r)=>{let s=Mo.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;_o(n,fe("update",r),o)};for(let n of Wf)t(e[n],String(n));t(e.order??e.rank,"order"),ge(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),ge(e.event,"--event","Use --clear-events to clear linked events.")}function WS(e,t){let n={};for(let r of DS)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 YS(e){let t=await $(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 JS(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function XS(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new l("--order and --rank must match when both are provided",d.USAGE)}async function QS(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=$s(e.options.parent);if(Us(e.id,t,e.settings.id_prefix),await $(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=_e(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:Ds(r,e.parentReferencePolicy).warnings}}function ZS(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function eE(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await $(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?ue(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",s=wS({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return s?[s]:[]}async function tE(e){if(!e.fieldFlags.status||ne(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],s=[];if(n.length>0){let a=await at(e.id,{...e.options,status:void 0,closeReason:void 0,message:void 0},e.global);s=a.changed_fields,r.push(...a.warnings)}let o=await Tt(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 nE(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Ya(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")),ne(e.metadata.status,n)??e.metadata.status}function rE(e,t,n,r,s){let o=bS(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}o!==t.statusRegistry.close_status&&r===t.statusRegistry.close_status&&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 sE(e,t,n,r){if(t.options.status!==void 0&&rE(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!Oe(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=Q(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function oE(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let s=t.options.closeReason?.trim()??"";if(s.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=s}r.push("close_reason");return}t.options.status!==void 0&&n===t.statusRegistry.close_status&&e.metadata.status!==t.statusRegistry.canceled_status&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function iE(e,t,n,r){sE(e,t,n,r),oE(e,t,n,r)}function aE(e,t,n){let r=ue(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=NS(t.options.priority),n.push("priority")),t.options.type!==void 0){let s=ue(t.options.type,t.typeRegistry);if(!s)throw new l(gt(t.options.type,t.typeRegistry.types,yt(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=s,r=s,n.push("type")}return FS(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),cE(e,t,r,n),r}function cE(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=bo(t.options.typeOption??[]),i=Un(n,o,t.typeRegistry);if(i.errors.length>0)throw new l(i.errors.join("; "),d.USAGE);e.metadata.type_options=i.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let s=Un(n,e.metadata.type_options,t.typeRegistry);if(s.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${s.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=s.normalized}function dE(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){let s=new Set(r.map(o=>Gf(o)));for(let o of t.dependencyUpdates.additions){let i=Gf(o);s.has(i)||(r.push(o),s.add(i))}}t.dependencyRemovals.length>0&&(r=r.filter(s=>!t.dependencyRemovals.some(o=>PS(s,o)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function lE(e,t,n){Xa(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Xa(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Xa(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Xa(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 mE(e,t,n){qf(e,"files",t.options.file,t.fileUpdates.values,IS,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),uE(e,t,n),qf(e,"docs",t.options.doc,t.docUpdates.values,xS,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function qf(e,t,n,r,s,o,i,a){if(!(n===void 0&&!i.has(t))){if(o)e.metadata[t]=r;else if(i.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(u=>s(u)));for(let u of r){let p=s(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function uE(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Kf(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Kf([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Kf(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let s=OS(r);n.has(s)||(t.push(r),n.add(s))}return t}function pE(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?St(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=js(wn(i,r),s),n.changedFields.push("tags")}Qa(US,t.options,n),_E(e,t,n.changedFields)}function fE(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=Gs(bn(e.metadata.acceptance_criteria),r,s);if(o.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${o.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:o.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let i=o.criteria.join("; ");e.metadata.acceptance_criteria!==i&&(i===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=i,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function _E(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let s=se(r??"","order");if(!Number.isInteger(s))throw new l("Order must be an integer",d.USAGE);e.metadata.order=s}n.push("order")}}function hE(e,t,n,r){gE(e,t,n.changedFields),yE(e,t,n.changedFields),Qa(GS,t.options,n),zf(e,t,"sprint",r,n.changedFields),zf(e,t,"release",r,n.changedFields),bE(e,t,n.changedFields),Qa(jS,t.options,n)}function gE(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new l("--assignee must not be empty. Use --unset assignee to clear it.",d.USAGE);e.metadata.assignee=r}n.push("assignee")}}function yE(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 zf(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=Ks(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=o.value,r.push(...o.warnings)}s.push(n)}}function bE(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)&&RS(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function wE(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=go(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=yo(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function vE(e,t,n){Bf(e,t.runtimeFieldRegistry.definitions.map(s=>s.metadata_key),t.clearItemMetadataKeys,n),Bf(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[s,o]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(s)){let i=s.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===s)?.cli_flag??i;throw new l(`Cannot combine --unset ${i} with --${c}`,d.USAGE)}tt(e[s],o)||(e[s]=o,n.push(s))}let r=xr(t.options.field,t.extensionRegistrations);for(let s of Object.keys(r))if(t.clearItemMetadataKeys.has(s))throw new l(`Cannot combine --unset ${s.replaceAll("_","-")} with --field ${s}=...`,d.USAGE);for(let[s,o]of Object.entries(r))tt(e[s],o)||(e[s]=o,n.push(s))}function Bf(e,t,n,r){for(let s of t)!n.has(s)||e[s]===void 0||(delete e[s],r.push(s))}function kE(e,t){let n=structuredClone(e.metadata),r=e.body,s=[],o=[],i=nE(e,t.options,t.statusRegistry,s),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:s,nowValue:t.nowValue};iE(e,t,i,s),aE(e,t,s),dE(e,t,s),lE(e,t,s),mE(e,t,s),pE(e,t,c),fE(e,t,c),hE(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"))&&sr(e.metadata.id,e.metadata.dependencies),ne(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,s.includes("assignee")||s.push("assignee")),wE(e,t,s),vE(a,t,s);try{Or(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(p){throw new l(p instanceof Error?p.message:"Invalid extension item field values",d.USAGE)}let m=e.metadata,u=[...new Set(s)].filter(p=>p==="body"?e.body!==r:!tt(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&o.push(`acceptance_criteria_replaced:${bn(n.acceptance_criteria).length}:${bn(m.acceptance_criteria).length}`),{changedFields:u,warnings:o}}async function at(e,t,n){t=await qS(t);let r=T(process.cwd(),n.path);await JS(r);let s=await A(r),o=j(s.schema),i=Be(s.schema),a=I(),c=ft(a),m=x(s,a),u=s.governance.workflow_enforcement??"off",p=u==="off"?[]:fm(s.schema),f=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],_=Hf(t.unset,i,c),h=new Set(_.optionKeys),y=new Set(_.metadataKeys);ec(t),zS({definitions:KS(t),options:t,clearOptionKeys:h,clearItemMetadataKeys:y}),yS(e,t,y),HS(t,_),VS(t);let g=R(t.author,s.author_default),b=new Date,v=b.toISOString(),E=Do(t.dep,s.id_prefix,v,g);sr(e,E.additions);let N=await Bt({pmRoot:r,dependencies:E.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:m.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),P=TS(t.depRemove,s.id_prefix),M=Xt("--comment",t.comment,v,g),G=t.ownershipMetadataBypass===!0&&M.values?{...M,values:M.values.map(O=>({...O,author:g}))}:M,Ie=Xt("--note",t.note,v,g),ee=Xt("--learning",t.learning,v,g),pe=Ha(t.file),ie=Va(t.test),Xe=Wa(t.doc),ze=[],Pt=await QS({id:e,options:t,unsetTargets:_,pmRoot:r,settings:s,typeRegistry:m,parentReferencePolicy:f}),ut=await CS(t.blockedBy,y.has("blocked_by"),r,s.id_prefix,s.item_format,m.type_to_folder),Nt=ut.id,pi=[...Pt.warnings,...ZS(ut)],vr=vs(t,i,t.runtimeFieldCommands),Qe=WS(t,vr);if(!Object.values(Qe).some(Boolean))return YS({pmRoot:r,id:e,settings:s,typeRegistry:m});ze.push(...await eE({options:t,fieldFlags:Qe,workflowEnforcement:u,typeWorkflows:p,statusRegistry:o,typeRegistry:m,pmRoot:r,id:e,settings:s}));let kr=await tE({options:t,fieldFlags:Qe,statusRegistry:o,workflowTransitionWarnings:ze,global:n,id:e});if(kr)return kr;XS(t);let ae=Qe.dep||Qe.depRemove||Qe.blockedBy?await re(r,s.item_format,m.type_to_folder,void 0,s.schema):void 0,ve=await Y({pmRoot:r,settings:s,typeToFolder:m.type_to_folder,id:e,op:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0?"update_ownership_bypass":"update",author:g,message:t.message,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:c,skipNoop:!0,mutate(O){return ae=ae?.map(Sr=>Sr.id===O.metadata.id?structuredClone(O.metadata):Sr),kE(O,{options:t,settings:s,typeRegistry:m,statusRegistry:o,runtimeFieldRegistry:i,extensionRegistrations:a,extensionFieldNames:c,clearItemMetadataKeys:y,dependencyUpdates:E,dependencyRemovals:P,commentUpdates:G,noteUpdates:Ie,learningUpdates:ee,fileUpdates:pe,testUpdates:ie,docUpdates:Xe,resolvedParentValue:Pt.resolvedParentValue,resolvedBlockedByDependencyId:Nt,runtimeFieldUpdates:vr,nowValue:b,nowIso:v,author:g,pmRoot:r})}}),fi=ae?Zs(ae,ae.map(O=>O.id===ve.item.id?ve.item:O),ve.item.id):[];return{item:ve.item,changed_fields:ve.changedFields,warnings:[...ze,...pi,...N,...fi,...ve.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]="e797d654-df89-554b-876b-cb2faa350bd0")}catch{}})();var Jf=1,nc="update-many",SE=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),EE=["--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(", "),TE={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"},AE=[{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"}],CE={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"},Xf=e=>{let t={};for(let[n,r]of Object.entries(e))SE.has(n)||r!==void 0&&(t[n]=r);return t},RE=e=>Object.keys(Xf(e)).length>0,Qf=e=>typeof e=="string"?e.trim():e,IE=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},tc=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},xE=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Qf(e)},OE={priority:IE,estimatedMinutes:tc,order:tc,rank:tc,regression:xE},PE=(e,t)=>{if(t!==void 0)return(OE[e]??Qf)(t)},NE=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return CE[t]??t},Uo=(e,t)=>tt(e,t),LE=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],FE=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,ME=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",Yf=(e,t)=>t===void 0?void 0:e[t],On=e=>Array.isArray(e)?e.length:0,$E=(e,t,n)=>{let r=n[e.addKey],s=Yf(n,e.removeKey),o=On(r),i=On(s),a=n[e.clearKey]===!0,c=Yf(n,e.replaceKey)===!0;if(![a,c,o>0,i>0].includes(!0))return;let m=LE(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:ME({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:o,remove_count:i,before_count:FE(e.field,m)}}},DE=(e,t)=>{let n=[];for(let r of AE){let s=$E(r,e,t);s!==void 0&&n.push(s)}return n},UE=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],GE=(e,t)=>{if(![t.tags!==void 0,On(t.addTags)>0,On(t.removeTags)>0].includes(!0))return;let n=UE(e.tags),r=t.tags===void 0?n:St(t.tags),s=wn(r,t.addTags),o=js(s,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!Uo(i,o))return{field:"tags",before:n,after:o}},jE=(e,t)=>{let n=e.acceptance_criteria,r=Gs(bn(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let s=r.criteria.join("; ");if(!Uo(typeof n=="string"?n:"",s))return{field:"acceptance_criteria",before:n,after:s}},qE=(e,t,n)=>{for(let[r,s]of Object.entries(TE)){let o=n[r];if(o===void 0)continue;let i=t[s],a=PE(r,o);Uo(i,a)||e.push({field:s,before:i,after:a})}},KE=(e,t,n,r)=>{let s=vs(n,r,["update_many"]);for(let[o,i]of Object.entries(s)){let a=t[o];Uo(a,i)||e.push({field:o,before:a,after:i})}},zE=(e,t,n)=>{for(let r of n??[]){let s=NE(r),o=t[s];o!==void 0&&e.push({field:s,before:o,after:null})}},BE=(e,t,n={})=>{let r=e,s=[],o=GE(r,n);if(o&&s.push(o),qE(s,r,n),On(n.addAc)>0||On(n.removeAc)>0){let i=jE(r,n);i!==void 0&&s.push(i)}return s.push(...DE(r,n)),KE(s,r,n,t),zE(s,r,n.unset),{id:e.id,changes:s}},HE=(e,t)=>Eu(e,t,{strict:!0,flagLabel:"--filter-status"}),VE=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)},WE=[({update:e})=>{e.priority!==void 0&&kn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,I());if(!ue(e.type,r))throw new l(gt(e.type,r.types,yt(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!ne(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,d.USAGE)}},({update:e})=>{e.deadline!==void 0&&Q(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&vn(e.estimatedMinutes,"estimated-minutes")}],YE=(e,t,n,r)=>{let s={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let o of WE)o(s)},JE=async e=>{let t=await Ns(e.pmRoot,nc,e.rollbackId,Jf),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Ls(t.items,(s,o)=>zt(s,o,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...Dt({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}},XE=async e=>{let t={schema_version:Jf,id:e.checkpointId,created_at:e.nowValue,author:R(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Ps(e.pmRoot,nc,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},QE=(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))},rc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},ZE=async e=>{let t=T(process.cwd(),e.path);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:j(n.schema),runtimeFieldRegistry:Be(n.schema)}},eT=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Qn(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",d.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",d.USAGE);return JE({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},tT=async e=>{HE(e.options.status,e.runtime.statusRegistry);let t=await Et(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=BE(s,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?o:{...o,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await Et(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:QE(e.options.list?.ids,r)}},nT=e=>({outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...rc(e)}),rT=e=>({...Dt({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:[],...rc(e)}),sT=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,s=new Set(e.plans.filter(o=>o.changes.length>0).map(o=>o.id));for(let o of e.items){if(!s.has(o.id)){t.push({id:o.id,status:"skipped"});continue}try{let i=await at(o.id,{...e.options.update,message:r,runtimeFieldCommands:["update_many"]},e.global);t.push({id:o.id,status:"updated",changed_fields:i.changed_fields,warnings:i.warnings}),n.push(o.id)}catch(i){t.push({id:o.id,status:"failed",error:cn(i)})}}return{rows:t,updatedIds:n}},oT=async e=>{if(e.plan.actionable.length===0)return rT(e.plan);let t=S(),n=Os(nc,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 XE({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 sT({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=p=>i.rows.filter(f=>f.status===p).length,c=a("updated"),m=a("skipped"),u=a("failed");return{...Dt({applied:c,skipped:m,failed:u,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...o?{checkpoint:o}:{},updated_count:c,skipped_count:m,failed_count:u,rows:i.rows,ids:i.updatedIds,...rc(e.plan)}},Zf=async(e,t)=>{let n=await ZE(t),r=typeof e.rollback=="string"?e.rollback:void 0,s=Xf(e.update);if(VE(e.list),r!==void 0)return eT({runtime:n,rollbackId:r,options:e,global:t,updateSummary:s});if(!RE(e.update))throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${EE}).`,d.USAGE);YE(e.update,n.settings,n.statusRegistry,n.pmRoot),ec(e.update);let o=await Bt({pmRoot:n.pmRoot,dependencies:Do(e.update.dep,n.settings.id_prefix,S(),R(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await tT({options:e,global:t,runtime:n,updateSummary:s,dependencyWarnings:o});return await Bt({pmRoot:n.pmRoot,dependencies:Do(e.update.dep,n.settings.id_prefix,S(),R(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:i.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:n.settings.schema}),e.dryRun===!0?nT(i):oT({runtime:n,options:e,global:t,plan:i})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d5ea029-26ef-51bc-bacc-b1d4d807a024")}catch{}})();var iT=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],e_=["brief","standard","deep"],r_="plan-step-",dc="draft",cc=["bug-investigation","feature-implementation","refactoring-sprint"],t_={"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 aT(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(t_,t)?t_[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${cc.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${cc[0]}`]});return n.map(r=>({...r}))}function cT(e,t){return t>0?Math.round(e/t*100):0}function s_(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 Fe(e){return Array.isArray(e)?e.flatMap(t=>Sn(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Sn(e,{unique:!1}):[]}function be(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function o_(e,t=dc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ei.find(s=>s===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${Ei.join(", ")}`,d.USAGE);return r}function lc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ti.find(s=>s===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${Ti.join(", ")}`,d.USAGE);return r}function i_(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ci.find(s=>s===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${Ci.join(", ")}`,d.USAGE);return r}function dT(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ai.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${Ai.join(", ")}`,d.USAGE);return n}function lT(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=e_.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${e_.join(", ")}`,d.USAGE);return n}function mT(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new l("Plan --fields requires a comma-separated list of plan field names",d.USAGE);return t}var sc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function uT(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(!sc.has(i)){s.push(o);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(s.length>0)throw new l(`Unknown Plan --fields value(s): ${s.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...sc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:s,suggested_retry:`pm plan show <id> --fields ${[...sc].join(",")}`}});return r}function mc(e,t){let n={};for(let r of e.split(",")){let s=r.trim();if(s.length===0)continue;let o=s.indexOf("=");if(o<=0)throw new l(`Invalid ${t} entry "${s}"; expected key=value`,d.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[s.slice(0,o).trim().toLowerCase()]=s.slice(o+1).trim()}return n}function uc(e){let t=mc(e,"--file");if(!t.path)throw new l("--file requires path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function pc(e){let t=mc(e,"--test");if(!t.command&&!t.path)throw new l("--test requires at least command=<value> or path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function fc(e){let t=mc(e,"--doc");if(!t.path)throw new l("--doc requires path=<value>",d.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function pT(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=cT(t.completed,t.total),t}function fT(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${r_}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new l("Could not allocate step id (limit reached)",d.GENERIC_FAILURE)}function Pn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(s=>s.id===n);if(r)return r;if(/^\d+$/.test(n)){let s=Number.parseInt(n,10),o=e.find(i=>i.order===s);if(o)return o}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function n_(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 _T(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],s=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",d.USAGE);for(let i of e.slice().sort((a,c)=>a.order-c.order)){let a=n_(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=Pn(e,i);if(o.has(a.id))continue;o.add(a.id);let c=n_(a);if(c){s.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:s}}function hT(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 gT(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function yT(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 Te(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=pT(n),s=gT(n),o={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??dc,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:yT(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 Ae(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&&!na(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function a_(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new l(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,d.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function bT(e){let t=T(process.cwd(),e.path);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=await A(t);return{pmRoot:t,settings:n}}async function c_(e,t){let n=x(e.settings,I()),r=await $(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,d.NOT_FOUND);let s=await K(r,{schema:e.settings.schema});return a_(s.document.metadata),{document:s.document,itemId:r.id}}function wT(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of Fe(e.related))t.push(`id=${n},kind=related`);for(let n of Fe(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of Fe(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function vT(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 kT(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||Fe(e.dependsOn).length>0||Fe(e.link).length>0}function ST(e){let t=e.stepTitle?.trim()||void 0,n=s_(e.step),r=e.template?.trim()?aT(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(s=>s.title)],templateSteps:r}}function ET(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",d.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${cc[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",d.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function TT(e,t){let n=lc(e.stepStatus,"pending"),r=_c(e,"depends_on"),s=be(e.file).map(uc),o=be(e.test).map(pc),i=be(e.doc).map(fc),a=S();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:s.length>0?s:void 0,tests:o.length>0?o:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function AT(e){let t=ST(e),n=kT(e);if(ET(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[TT(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=S();return{steps:t.stepTitles.map((s,o)=>({id:`${r_}${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 CT(e,t,n){let r=e.title?.trim();if(!r)throw new l("pm plan create requires --title",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let s=o_(e.mode,dc),o=dT(e.harness),i=e.fromSearch?.trim(),a=vT(e),{steps:c,hasPerStepDetailOptions:m}=AT(e);if(c.length===0&&m)throw new l("pm plan create step options require --step-title (or a single --step)",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?R(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:be(e.file),test:be(e.test),doc:be(e.doc),field:be(e.field),assignee:R(e.author,n.settings.author_default),blockedBy:void 0,dep:wT(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")},_=await At(f,t),h=await Y({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:R(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let b=["plan_mode"];g.metadata.plan_mode=s,o&&(g.metadata.plan_harness=o,b.push("plan_harness"));let v=e.scope?.trim();v&&(g.metadata.plan_scope=v,b.push("plan_scope"));let E=e.resumeContext?.trim();return E&&(g.metadata.plan_resume_context=E,b.push("plan_resume_context")),g.metadata.plan_steps=c,b.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],b.push("plan_validation")),p&&(g.metadata.assignee=p,b.push("assignee")),{changedFields:b}}}),y=Te(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Ae(_.item.id,y),warnings:[..._.warnings],generated_at:S()}}async function RT(e,t,n){let r=lT(t.depth),s=mT(t.fields),{document:o,itemId:i}=await c_(n,e),a=Te(o.metadata,s===null?r:"deep");return{action:"show",plan:s===null?a:uT(a,s),next_actions:Ae(i,a),warnings:[],generated_at:S()}}function IT(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 We(e){let t=R(e.options.author,e.ctx.settings.author_default),n,r=await Y({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){a_(s.metadata);let o=j(e.ctx.settings.schema);if(Oe(s.metadata.status,o)||na(s.metadata.plan_mode))throw new l(`Plan ${s.metadata.id} is terminal (status=${s.metadata.status}, plan_mode=${s.metadata.plan_mode??"unset"}) and cannot be mutated.`,d.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let i=(s.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(s.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,s);n=c.resultStep;let m=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));s.metadata.plan_steps=m;let u=IT(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 xT(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let s=lc(t.stepStatus,"pending"),o=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await We({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;d_(u,void 0,s,o);let f=OT(u,t,{order:p,title:r,status:s});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Te(i.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Ae(c,m),warnings:[],generated_at:S()}}function d_(e,t,n,r){if(n!=="in_progress"||r)return;let s=e.find(o=>o.id!==t&&o.status==="in_progress");if(s)throw new l(`Plan already has step ${s.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function OT(e,t,n){let r=_c(t,"depends_on"),s=be(t.file).map(uc),o=be(t.test).map(pc),i=be(t.doc).map(fc),a=S();return{id:fT(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 _c(e,t){let n=Fe(e.dependsOn).map(u=>({id:u,kind:t})),r=Fe(e.related).map(u=>({id:u,kind:"related"})),s=Fe(e.blocks).map(u=>({id:u,kind:"blocks"})),o=Fe(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=Fe(e.link),a=i_(e.linkKind,t),c=e.linkNote?.trim(),m=i.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...s,...o,...m]}async function oc(e,t,n,r){let{document:s,resultStep:o,itemId:i}=await We({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=Pn(c,r.stepRef),p=S(),f=r.finalStatus??lc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return d_(c,u.status==="in_progress"?u.id:void 0,f,_),PT(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Te(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:Ae(i,a),warnings:[],generated_at:S()}}function PT(e,t,n,r){NT(e,t,n),LT(e,t),e.status=n,e.updated_at=r,FT(e,n,r)}function NT(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new l("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",d.USAGE)}function LT(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=be(t.file).map(uc),s=be(t.test).map(pc),o=be(t.doc).map(fc);r.length>0&&(e.files=ic(e.files,r)),s.length>0&&(e.tests=ic(e.tests,s)),o.length>0&&(e.docs=ic(e.docs,o))}function ic(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 FT(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function MT(e,t,n,r,s){let{document:o,itemId:i}=await We({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${s}`,mutator(c){let m=Pn(c,r),u=c.filter(f=>f.id!==m.id),p=Math.max(1,Math.min(s,u.length+1));return u.splice(p-1,0,m),u.forEach((f,_)=>{f.order=_+1,f.updated_at=S()}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=Te(o.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Ae(i,a),warnings:[],generated_at:S()}}async function $T(e,t,n,r){let{document:s,itemId:o}=await We({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=Pn(a,r),m=a.filter(u=>u.id!==c.id);return m.forEach((u,p)=>{u.order=p+1}),a.length=0,a.push(...m),{changedSteps:[c.id]}}}),i=Te(s.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Ae(o,i),warnings:[],generated_at:S()}}async function DT(e,t,n,r){let s=_c(t,i_(t.linkKind,"related"));if(s.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let o=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await We({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Pn(u,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of s){let b=h(g);y.has(b)||(_.push(g),y.add(b))}if(f.linked_items=_,f.updated_at=S(),o){let g=p.metadata.dependencies??[],b=E=>`${E.kind}:${E.id}`,v=new Set(g.map(b));for(let E of s){let N=E.kind==="depends_on"?"blocked_by":E.kind,P={id:E.id,kind:N,created_at:S(),author:R(t.author,n.settings.author_default)};v.has(b(P))||(g.push(P),v.add(b(P)))}p.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),m=Te(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ae(a,m),warnings:[],generated_at:S()}}async function UT(e,t,n,r){let s=Fe(t.link);if(s.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:o,itemId:i,resultStep:a}=await We({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=Pn(m,r),p=(u.linked_items??[]).filter(f=>!s.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=S(),{changedSteps:[u.id],resultStep:u}}}),c=Te(o.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Ae(i,c),warnings:[],generated_at:S()}}async function ac(e,t,n,r){let s=hT(r,t);if(!s){let m=`--${r}-text`,u=`--${r}`;throw new l(`pm plan ${r} requires ${m}`,d.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${m} "..."`,`pm plan ${r} <plan-id> ${u} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${m} <value>`}})}let o=R(t.author,n.settings.author_default),{document:i,itemId:a}=await We({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,u){let p=S();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:o,decision:s,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:o,text:s}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:s,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Te(i.metadata,"deep");return{action:r,plan:c,next_actions:Ae(a,c),warnings:[],generated_at:S()}}async function GT(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:s,itemId:o}=await We({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Te(s.metadata,"brief");return{action:"resume",plan:i,next_actions:Ae(o,i),warnings:[],generated_at:S()}}async function jT(e,t,n){let r=o_(t.mode??"approved","approved"),{document:s,itemId:o}=await We({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(a,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Te(s.metadata,"brief");return{action:"approve",plan:i,next_actions:Ae(o,i),warnings:[],generated_at:S()}}function l_(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function qT(e,t){let n=Te(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ae(e.itemId,n),warnings:l_(t),generated_at:S()}}function KT(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 zT(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let s of be(e.options.field)){let o=s.indexOf("=");if(o<=0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.USAGE);let c=i.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.USAGE);let[m,...u]=c,p=`${m}${u.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(p))throw new l(`Invalid --field entry "${s}"; "${p}" is reserved by materialize and cannot be overridden`,d.USAGE);n[p]=a}for(let s of e.targets){let o=await At({...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:KT(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 BT(e,t,n){for(let r of t){let s=n.find(a=>a.from_step===r.id);if(!s)continue;let o=e.find(a=>a.id===r.id);if(!o)continue;let i=o.linked_items??[];i.push({id:s.id,kind:"implements",note:`materialized as ${s.type}`}),o.linked_items=i,o.updated_at=S()}}async function HT(e,t,n){let r=Fe(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let s=t.materializeType?.trim()||"Task",o=x(n.settings,I()),i=ue(s,o);if(!i)throw new l(`Invalid --materialize-type "${s}"`,d.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await c_(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=_T(u,r);if(p.length===0){if(f.length>0)return qT(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await zT({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await We({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(b){return BT(b,p,_),{changedSteps:p.map(v=>v.id)}}}),g=Te(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ae(y,g),warnings:l_(f),generated_at:S()}}function VT(e){if(e.subcommand==="create")return e;let t=s_(e.options.step);if(t.length>1)throw new l(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,d.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:{...e.options,stepTitle:t[0]}}:e}function ct(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function Qt(e,t){let n=ct(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function WT(e){let t=Qt(e,"reorder-step");if(e.reorderTo===void 0)throw new l("pm plan reorder-step requires <plan-id> <step> <new-order>",d.USAGE);return{...t,reorderTo:e.reorderTo}}var YT={create:(e,t)=>CT(e.options,e.global,t),show:(e,t)=>RT(ct(e,"show"),e.options,t),"add-step":(e,t)=>xT(ct(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=Qt(e,"update-step");return oc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=Qt(e,"complete-step");return oc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=Qt(e,"block-step");return oc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=WT(e);return MT(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=Qt(e,"remove-step");return $T(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=Qt(e,"link");return DT(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=Qt(e,"unlink");return UT(n.id,e.options,t,n.stepRef)},decision:(e,t)=>ac(ct(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>ac(ct(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>ac(ct(e,"validation"),e.options,t,"validation"),resume:(e,t)=>GT(ct(e,"resume"),e.options,t),approve:(e,t)=>jT(ct(e,"approve"),e.options,t),materialize:(e,t)=>HT(ct(e,"materialize"),e.options,t)};function JT(e){let t=YT[e];if(!t)throw Ee({command_path:"plan",token:e,allowed:iT});return t}async function m_(e){let t=await bT(e.global),n=VT(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]="4eb2056a-4444-514a-a0db-79b8875c3d65")}catch{}})();function XT(e,t){return[...new Set([...Ir.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 QT(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function hc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await $(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,m=S(),u=R(t.author,s.author_default),p=await Hn(r,s.id_prefix,{tokenLength:s.ids.token_length,typeToFolder:o.type_to_folder,probeExisting:!1}),f=j(s.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let h={...c,id:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let y=ft(I()),g=He({metadata:h,body:a.document.body},{schema:s.schema,extensionFieldNames:y}),b=await An({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=XT(g.metadata,g.body),E=$t(r,g.metadata.type,p,s.item_format,o.type_to_folder),N=ke(r,p),P=await xe(r,p,s.locks.ttl_seconds,u,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),M={metadata:{},body:""},G,Ie;try{let ee=await gn(r,u,{required:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await An({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 pe=await $(r,p,s.id_prefix,s.item_format,o.type_to_folder);if(pe)throw new l(`Cannot copy to ${p}: an item with that id already exists at ${pe.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${pe.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await me(E,$e(g,{format:s.item_format,schema:s.schema,extensionFieldNames:y}));try{let ie=De({nowIso:m,author:u,op:"create",before:M,after:g,message:QT(i.id,t.message)});await wt(N,ie)}catch(ie){throw await on(E),ie}Ie=await yn({pmRoot:r,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:E,document:g})}finally{await ee()}G=[...await z({path:E,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:M,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:M,after:g,changed_fields:v})],mn({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Ut(g.metadata,v),changed_fields:v})}finally{await P()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:v,warnings:[...eo(b),...Ie,...G],...b===void 0?{}:{similarity_advisory:b}}}import Go from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="14aa55e1-cb5f-55ea-bf4c-412217d87449")}catch{}})();async function gc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=R(t.author,s.author_default),i=await fu({pmRoot:r,settings:s,id:e,author:o,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?Go.relative(r,i.targetPath).split(Go.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:Go.relative(r,ke(r,i.item.id)).split(Go.sep).join("/"),tombstone_retention:"retain_append_only",warnings:i.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f43df79-0b27-53b3-b8bd-9f2a35561733")}catch{}})();async function ZT(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}async function yc(e,t,n){let r=T(process.cwd(),n.path);if(await ZT(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",d.USAGE);let p=await A(r),f=fn(R(void 0,p.author_default));return await Hm(r),await Qs({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 bs(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 eA(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let o=await A(r),i=x(o,I()),a=await $(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=_e(a.id,o.id_prefix),m=await K(a,{schema:o.schema}),u=u_(m.document.metadata.title);return await Bm(r,c),await Qs({pmRoot:r,settings:o,principal:fn(R(void 0,o.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function eA(e,t){let n=await A(e),r=x(n,I()),s=await $(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 u_(o.document.metadata.title)}function u_(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 p_=new Set(["item_format"]),f_=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"]),tA=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"]),nA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","telemetry_tracking"]),rA={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function sA(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(p_.has(t)||f_.has(t)||tA.has(t)||t==="context")return t}function oA(e){let t=e.trim().toLowerCase();return rA[t]??e}function __(e,t){let n=sA(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."}:p_.has(n)?{routable:!0,flag:"format",value:t}:f_.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:nA.has(n)?oA(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9a8d99c-df4e-55b3-81f5-27124d598c5f")}catch{}})();var h_=["project","global"],dt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],context:["context"]},iA=Object.keys(dt).map(e=>dt[e][0]),aA=Object.fromEntries(Object.keys(dt).flatMap(e=>dt[e].map(t=>[t,e]))),cA={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)."},dA=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],lA=new Set(["metadata_required_fields",...dA]),mA=new Set(["test_result_tracking","telemetry_tracking"]),uA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),pA=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),fA=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),_A=new Set(["governance_preset","governance_create_default_type"]),v_=e=>lA.has(e),hA=e=>pA.has(e),gA=e=>fA.has(e),yA=e=>_A.has(e);function bc(e){return e==="definition_of_done"||v_(e)}function bA(e){if(h_.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${h_.join(", ")}`,d.USAGE)}function wA(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Ee({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function vA(e){let t=aA[e];if(t)return t;let n=Ni.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${iA.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function kA(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,s)=>r.localeCompare(s));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",d.USAGE);return n}function SA(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",d.USAGE):new l("Config set item-format requires --format toon",d.USAGE)}function k_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",d.USAGE)}function S_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set test-result-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function E_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function vc(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",d.USAGE)}function T_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",d.USAGE)}function A_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",d.USAGE)}function C_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",d.USAGE)}function R_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",d.USAGE)}function I_(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-workflow-enforcement requires one of: off, warn, strict",d.USAGE)}function x_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",d.USAGE)}function O_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",d.USAGE)}function g_(e,t){switch(e){case"history_missing_stream_policy":return k_(t);case"sprint_release_format_policy":return ta(t);case"parent_reference_policy":case"governance_parent_reference_policy":return Ms(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return vc(t);case"governance_preset":return T_(t);case"governance_ownership_enforcement":return A_(t);case"governance_create_mode_default":return C_(t);case"governance_close_validation_default":return R_(t);case"governance_require_close_reason":return O_(t);case"governance_workflow_enforcement":return I_(t);case"governance_force_required_for_stale_lock":return x_(t);case"test_result_tracking":return S_(t);case"telemetry_tracking":return E_(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var y_={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"},EA=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function TA(e,t){let n=[...new Set((e??[]).map(o=>o.trim()).filter(o=>o.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",d.USAGE);let r=n.map(o=>o.toLowerCase().replaceAll("-","_")),s=r.filter(o=>y_[o]===void 0);if(s.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${s.join(", ")}. Supported values: ${EA.join(", ")}`,d.USAGE);return[...new Set(r.map(o=>y_[o]))].sort((o,i)=>o.localeCompare(i))}function AA(e,t,n){let r=[...new Set((t??[]).map(s=>s.trim().toLowerCase()).filter(s=>s.length>0))].sort((s,o)=>s.localeCompare(o));if(n){if(r.length>0)throw new l(`Config set ${dt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${dt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function CA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function RA(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,d.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,d.USAGE);return vA(t)}function P_(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var IA={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 kc(e,t){return IA[t](e)}function Me(e,t){return t.length===0?e:{...e,warnings:t}}async function xA(e,t){let n=process.cwd(),r=e==="project"?T(n,t.path):et(n),s=C(r);if(e==="project"&&!await k(s))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);return{pmRoot:r,settingsPath:s}}function OA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,d.USAGE)}function b_(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new l(`Context ${t} must be a positive integer`,d.USAGE)}async function PA(e,t,n,r,s){let o=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!Ri.includes(c))throw new l(`Context --default-depth must be one of ${Ri.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,o=!0)}if(t.activityLimit!==void 0){let c=b_(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,o=!0)}if(t.staleThresholdDays!==void 0){let c=b_(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,o=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of a){let u=OA(m);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,o=!0)}}return o&&await Se(n.pmRoot,e,"config:set:context"),Me({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 NA(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,d.USAGE);return{...n,value:t}}function LA(e,t,n,r,s,o){if(s===void 0)return o;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,d.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',d.USAGE);if(r)return NA(t,s,o);P_(n);let i=__(n,s);if(!i.routable)throw new l(i.reason,d.USAGE);if(i.flag==="criterion"){if(o.criterion!==void 0&&o.criterion.length>0)throw new l(`Config set ${t} received both positional value "${s}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...o,criterion:i.values}}if(i.flag==="format")return{...o,format:i.value};if(o.policy!==void 0&&g_(n,o.policy)!==g_(n,i.value))throw new l(`Config set ${t} received both positional value "${s}" and --policy "${o.policy}". Pass only one.`,d.USAGE);return{...o,policy:i.value}}function FA(e){let t=Object.keys(dt).map(r=>({key:r,aliases:dt[r],value_kind:r==="context"?"object":bc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:bc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:cA[r],value:kc(e.settings,r)})),n=Ni.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Li(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Me({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function MA(e){let t=Object.fromEntries(Object.keys(dt).map(n=>[n,kc(e.settings,n)]));return Me({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function $A(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"?Me({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Me({...r,context_settings:n},e.warnings):Array.isArray(n)?Me({...r,criteria:n},e.warnings):Me({...r,policy:n},e.warnings)}async function DA(e,t,n,r){if(t==="get"){let a=Li(e.settings,n);return Me({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let s=r.value;if(typeof s!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let o=pm(n,s);if(!o.ok)throw new l(o.error.message,d.USAGE);let i=_s(e.settings,n,o.parsed.value);return i&&await Se(e.target.pmRoot,e.settings,`config:set:${n.path}`),Me({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 Se(e.target.pmRoot,e.settings,n)}function w_(e,t,n){return e!==n||t!==n}function oe(e,t,n,r){return Me({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function wc(e,t,n,r){return Me({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function UA(e,t){let n=SA(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,s;if(r){let o=x(e.settings,I()),i=await Au(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 Se(e.target.pmRoot,e.settings,"config:set:item_format")}return Me({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 GA(e,t,n){if(t==="history_missing_stream_policy"){let o=k_(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"),oe(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let o=ta(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"),oe(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let o=Ms(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"),oe(e,t,e.settings.validation.parent_reference,i)}let r=vc(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"),oe(e,t,e.settings.validation.metadata_profile,s)}async function jA(e,t,n){if(t==="metadata_required_fields"){let a=TA(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((m,u)=>m!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await X(e,c,"config:set:metadata_required_fields"),wc(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=AA(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}`),wc(e,t,[...s],i)}async function qA(e,t,n){if(t==="governance_preset"){let c=T_(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await X(e,m,"config:set:governance_preset"),oe(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",s=r?n.policy.trim():"";if(r&&s.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await X(e,c,"config:set:governance_create_default_type"),oe(e,t,e.settings.governance.create_default_type??"",c)}if(s.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let o=x(e.settings,I()),i=ue(s,o);if(!i)throw new l(gt(s,o.types,yt(e.target.pmRoot,e.settings.schema)),d.USAGE);let a=e.settings.governance.create_default_type!==i;return e.settings.governance.create_default_type=i,await X(e,a,"config:set:governance_create_default_type"),oe(e,t,e.settings.governance.create_default_type,a)}async function KA(e,t,n){if(t==="governance_ownership_enforcement"){let o=A_(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"),oe(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let o=C_(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"),oe(e,t,e.settings.governance.create_mode_default,i)}let r=R_(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"),oe(e,t,e.settings.governance.close_validation_default,s)}async function zA(e,t,n){if(t==="governance_parent_reference_policy"){let o=Ms(n.policy),i=e.settings.governance.preset!=="custom"||w_(e.settings.governance.parent_reference,e.settings.validation.parent_reference,o);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=o,e.settings.validation.parent_reference=o,await X(e,i,"config:set:governance_parent_reference_policy"),oe(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let o=vc(n.policy),i=e.settings.governance.preset!=="custom"||w_(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,o);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=o,e.settings.validation.metadata_profile=o,await X(e,i,"config:set:governance_metadata_validation_profile"),oe(e,t,e.settings.governance.metadata_profile,i)}let r=I_(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"),oe(e,t,e.settings.governance.workflow_enforcement,s)}async function BA(e,t,n){if(t==="governance_require_close_reason"){let a=O_(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"),oe(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let s=x_(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"),oe(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function HA(e,t,n){if(t==="test_result_tracking"){let a=S_(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"),oe(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}let s=E_(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"),oe(e,t,e.settings.telemetry.enabled?"enabled":"disabled",o)}async function VA(e,t,n){let r=kA(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"),wc(e,t,[...e.settings.workflow.definition_of_done],s)}async function WA(e,t,n){if(n.clearCriteria===!0&&!bc(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?UA(e,n):t==="context"?PA(e.settings,n,e.target,e.scope,e.warnings):t==="definition_of_done"?VA(e,t,n):v_(t)?jA(e,t,n):mA.has(t)?HA(e,t,n):uA.has(t)?BA(e,t,n):hA(t)?KA(e,t,n):gA(t)?zA(e,t,n):yA(t)?qA(e,t,n):GA(e,t,n)}async function N_(e,t,n,r,s,o){let i=bA(e),a=wA(t),c=a==="get"||a==="set"?fs(n):void 0,m=c?void 0:RA(a,n),u=LA(a,n,m,c,o,r),p=await xA(i,s),{settings:f,metadata:_,warnings:h}=await mu(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:CA(h)};return c?DA(y,a,c,u):a==="list"?FA(y):a==="export"?MA(y):(P_(m),a==="get"?$A(y,m):WA(y,m,u))}import SC from"node:fs/promises";import V from"node:path";import EC from"node:readline/promises";import{stdin as TC,stdout as Ce}from"node:process";import F_ from"node:fs/promises";import je from"node:path";import YA from"node:readline/promises";import{stdin as JA,stdout as jo}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]="b7c97e30-02c8-547c-b3db-c6c59e662b54")}catch{}})();var M_=["ask","add","skip","status"],XA=["AGENTS.md","CLAUDE.md"],QA=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],ZA=8,Ec=1,eC="<!-- pm-cli:agent-guidance:start:",tC=`<!-- pm-cli:agent-guidance:start:v${Ec} -->`,Sc="<!-- pm-cli:agent-guidance:end -->",dr="Add workflow guidance later: pm init --agent-guidance add";var nC=()=>YA.createInterface({input:JA,output:jo});function ar(e,t){let n=je.relative(e,t);return n.length===0?je.basename(t):n.split(je.sep).join("/")}function L_(e){return e.endsWith(`
9
9
  `)?e:`${e}
10
- `}function WA(e){return e.includes(`\r
10
+ `}function rC(e){return e.includes(`\r
11
11
  `)?`\r
12
12
  `:`
13
- `}function I_(e){let t=e.indexOf(BA);if(t===-1)return null;let n=e.indexOf(yc,t);return n===-1?null:{start_index:t,end_index:n+yc.length}}function YA(e){return I_(e)!==null}function JA(e){return[HA,"## pm Workflow (Agent Quickstart)","",'- Orient before mutate: `pm context --limit 10`, `pm search "<keywords>" --limit 10`, `pm list-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="node scripts/run-tests.mjs test -- ..."`.','- 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.","",yc,""].join(e)}function XA(e){let t=WA(e),n=JA(t),r=I_(e);if(r){let i=e.slice(r.end_index),a=i.startsWith(`\r
13
+ `}function $_(e){let t=e.indexOf(eC);if(t===-1)return null;let n=e.indexOf(Sc,t);return n===-1?null:{start_index:t,end_index:n+Sc.length}}function sC(e){return $_(e)!==null}function oC(e){return[tC,"## 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="node scripts/run-tests.mjs test -- ..."`.','- 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.","",Sc,""].join(e)}function iC(e){let t=rC(e),n=oC(t),r=$_(e);if(r){let i=e.slice(r.end_index),a=i.startsWith(`\r
14
14
  `)?i.slice(2):i.startsWith(`
15
- `)?i.slice(1):i,c=A_(`${e.slice(0,r.start_index)}${n}${a}`);return{next_content:c,changed:c!==e}}let s=e.length===0?"":e.endsWith(`
15
+ `)?i.slice(1):i,c=L_(`${e.slice(0,r.start_index)}${n}${a}`);return{next_content:c,changed:c!==e}}let s=e.length===0?"":e.endsWith(`
16
16
  `)?`
17
17
  `:`
18
18
 
19
- `,o=A_(`${e}${s}${n}`);return{next_content:o,changed:o!==e}}function QA(e,t){let n=je.dirname(e);return je.basename(e)==="pm"&&je.basename(n)===".agents"?je.dirname(n):je.resolve(t,e)}function ZA(e,t){let n=e.find(s=>je.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:je.join(t,"AGENTS.md")}function eC(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 tC(e){let t=VA();try{Go.write(`
19
+ `,o=L_(`${e}${s}${n}`);return{next_content:o,changed:o!==e}}function aC(e,t){let n=je.dirname(e);return je.basename(e)==="pm"&&je.basename(n)===".agents"?je.dirname(n):je.resolve(t,e)}function cC(e,t){let n=e.find(s=>je.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:je.join(t,"AGENTS.md")}function dC(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 lC(e){let t=nC();try{jo.write(`
20
20
  Agent guidance check
21
- `),Go.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 Go.write(`
23
- `),eC(n,!0)}finally{t.close()}}function x_(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:bc,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 O_(e){let t=[];for(let n of qA){let r=je.join(e,n),s=await k(r);if(!s){t.push({file_path:r,exists:s,has_guidance:!1,has_marker:!1});continue}let o=await C_.readFile(r,"utf8"),i=o.toLowerCase(),a=KA.filter(m=>i.includes(m)),c=YA(o);t.push({file_path:r,exists:s,has_guidance:c||a.length>=zA,has_marker:c})}return t}function dr(e,t){e.includes(t)||e.push(t)}function nC(e,t){let n=x_(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function rC(e){let n=await k(e)?await C_.readFile(e,"utf8"):"",r=XA(n);return r.changed?(await me(e,r.next_content),{changed:!0,warnings:await z({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function sC(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=>ir(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>ir(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>ir(e.projectRoot,t.file_path))}}async function oC(e,t,n){return e?await O_(n):t}function ar(e,t,n){e.state={...e.state,...n,template_version:bc,last_checked_files:t}}async function P_(e,t){if(t.presentBefore)return;let n=await rC(t.targetPath);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function iC(e,t){t||(e.warnings.push("agent_guidance:missing"),dr(e.nextSteps,cr))}function aC(e,t){e.skipped=!0,ar(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),dr(e.nextSteps,cr)}async function cC(e,t){await P_(e,t),ar(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function dC(e,t){e.state.declined&&ar(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function lC(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),dr(e.nextSteps,cr)}async function mC(e,t){if(e.prompted=!0,await tC(t.targetRelativePath)){await P_(e,t),ar(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,ar(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),dr(e.nextSteps,cr)}function uC(e){e.warnings.push("agent_guidance:missing_non_interactive"),dr(e.nextSteps,cr)}async function pC(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(iC(n,t.presentBefore),n):t.mode==="skip"?(aC(n,t.checkedFiles),n):t.mode==="add"?(await cC(n,t),n):t.presentBefore?(dC(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(lC(n),n):t.interactive?(await mC(n,t),n):(uC(n),n)}async function N_(e){let t=QA(e.pm_root,e.cwd),n=await O_(t),r=ZA(n,t),s=ir(t,r),o=n.map(u=>ir(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await pC(x_(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:s,checkedFiles:o,presentBefore:i}),c=nC(e.settings,a.state);return n=await oC(a.applied,n,t),{summary:sC({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 gC=()=>_C.createInterface({input:hC,output:Ce});function yC(){return structuredClone(pt)}var bC=["minimal","default","strict"];function F_(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--preset must not be empty",d.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new l(`Invalid --preset value "${e}". Allowed: ${bC.join(", ")}`,d.USAGE)}function wC(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return Zl(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${Ql.join(", ")}`,d.USAGE)}}}function vC(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new l("--author must not be empty",d.USAGE);return t}function wc(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 kC(e,t,n,r){let s=r?.trim();if(r!==void 0&&s?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(s!==void 0){if(t.path!==void 0||wc(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=V.resolve(e,s),u=V.join(m,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:m}}}if(t.path===void 0&&wc(n)){let m=V.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let o=T(e,t.path),i=V.join(V.resolve(e),".agents","pm"),a=V.dirname(V.dirname(o)),c=V.resolve(o)===i?"current":"ancestor";return{pmRoot:o,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:o,workspace_root:a,discovery:c,requested_cwd:V.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:o}}}function SC(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new l("--id-prefix must not be empty",d.USAGE);if(wc(t))throw new l(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,d.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&kt(e)!==kt(t))throw new l(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,d.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${kt(e)}`,`pm init --id-prefix ${kt(t)}`]});return t}function EC(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--agent-guidance must not be empty",d.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new l(`Invalid --agent-guidance value "${e}". Allowed: ${R_.join(", ")}`,d.USAGE)}function TC(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function $_(e,t){let n=Od[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function AC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function CC(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(AC).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function RC(e,t,n){let r=ms(t.schema),s=rt(e,r.files.types,nt.types),i=Jl(await q(s)),a=[],c=[];for(let m of em(n)){let u=Xl(i,m);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await vt({pmRoot:e,filePath:s,raw:ds(i),op:"init:type-preset",author:R(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:s}}async function IC(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",V.join(".agents","pm")];for(let n of t)if(await k(V.join(e,n)))return!0;return!1}async function xC(e,t,n){if(!t||n||await k(V.join(e,"settings.json"))||!await IC(e))return;let r=V.join(e,".agents","pm");throw new l(`Refusing to initialize tracker files directly in workspace root "${e}".`,d.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function M_(e,t){let n=[],r=[];for(let s of t){let o=s?V.join(e,s):e,i=await k(o);await fC.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 OC(e,t){let n=gC();try{Ce.write(`pm init setup wizard (agent-optimized)
21
+ `),jo.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 jo.write(`
23
+ `),dC(n,!0)}finally{t.close()}}function D_(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:Ec,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 U_(e){let t=[];for(let n of XA){let r=je.join(e,n),s=await k(r);if(!s){t.push({file_path:r,exists:s,has_guidance:!1,has_marker:!1});continue}let o=await F_.readFile(r,"utf8"),i=o.toLowerCase(),a=QA.filter(m=>i.includes(m)),c=sC(o);t.push({file_path:r,exists:s,has_guidance:c||a.length>=ZA,has_marker:c})}return t}function lr(e,t){e.includes(t)||e.push(t)}function mC(e,t){let n=D_(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function uC(e){let n=await k(e)?await F_.readFile(e,"utf8"):"",r=iC(n);return r.changed?(await me(e,r.next_content),{changed:!0,warnings:await z({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function pC(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=>ar(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>ar(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>ar(e.projectRoot,t.file_path))}}async function fC(e,t,n){return e?await U_(n):t}function cr(e,t,n){e.state={...e.state,...n,template_version:Ec,last_checked_files:t}}async function G_(e,t){if(t.presentBefore)return;let n=await uC(t.targetPath);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function _C(e,t){t||(e.warnings.push("agent_guidance:missing"),lr(e.nextSteps,dr))}function hC(e,t){e.skipped=!0,cr(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),lr(e.nextSteps,dr)}async function gC(e,t){await G_(e,t),cr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function yC(e,t){e.state.declined&&cr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function bC(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),lr(e.nextSteps,dr)}async function wC(e,t){if(e.prompted=!0,await lC(t.targetRelativePath)){await G_(e,t),cr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,cr(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),lr(e.nextSteps,dr)}function vC(e){e.warnings.push("agent_guidance:missing_non_interactive"),lr(e.nextSteps,dr)}async function kC(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(_C(n,t.presentBefore),n):t.mode==="skip"?(hC(n,t.checkedFiles),n):t.mode==="add"?(await gC(n,t),n):t.presentBefore?(yC(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(bC(n),n):t.interactive?(await wC(n,t),n):(vC(n),n)}async function j_(e){let t=aC(e.pm_root,e.cwd),n=await U_(t),r=cC(n,t),s=ar(t,r),o=n.map(u=>ar(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await kC(D_(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:s,checkedFiles:o,presentBefore:i}),c=mC(e.settings,a.state);return n=await fC(a.applied,n,t),{summary:pC({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 AC=()=>EC.createInterface({input:TC,output:Ce});function CC(){return structuredClone(pt)}var RC=["minimal","default","strict"];function K_(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--preset must not be empty",d.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new l(`Invalid --preset value "${e}". Allowed: ${RC.join(", ")}`,d.USAGE)}function IC(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return sm(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${rm.join(", ")}`,d.USAGE)}}}function xC(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new l("--author must not be empty",d.USAGE);return t}function Tc(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 OC(e,t,n,r){let s=r?.trim();if(r!==void 0&&s?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(s!==void 0){if(t.path!==void 0||Tc(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=V.resolve(e,s),u=V.join(m,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:m}}}if(t.path===void 0&&Tc(n)){let m=V.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let o=T(e,t.path),i=V.join(V.resolve(e),".agents","pm"),a=V.dirname(V.dirname(o)),c=V.resolve(o)===i?"current":"ancestor";return{pmRoot:o,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:o,workspace_root:a,discovery:c,requested_cwd:V.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:o}}}function PC(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new l("--id-prefix must not be empty",d.USAGE);if(Tc(t))throw new l(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,d.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&kt(e)!==kt(t))throw new l(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,d.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${kt(e)}`,`pm init --id-prefix ${kt(t)}`]});return t}function NC(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--agent-guidance must not be empty",d.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new l(`Invalid --agent-guidance value "${e}". Allowed: ${M_.join(", ")}`,d.USAGE)}function LC(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function z_(e,t){let n=Md[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function FC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function MC(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(FC).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function $C(e,t,n){let r=us(t.schema),s=rt(e,r.files.types,nt.types),i=tm(await q(s)),a=[],c=[];for(let m of om(n)){let u=nm(i,m);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await vt({pmRoot:e,filePath:s,raw:ls(i),op:"init:type-preset",author:R(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:s}}async function DC(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",V.join(".agents","pm")];for(let n of t)if(await k(V.join(e,n)))return!0;return!1}async function UC(e,t,n){if(!t||n||await k(V.join(e,"settings.json"))||!await DC(e))return;let r=V.join(e,".agents","pm");throw new l(`Refusing to initialize tracker files directly in workspace root "${e}".`,d.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function B_(e,t){let n=[],r=[];for(let s of t){let o=s?V.join(e,s):e,i=await k(o);await SC.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 GC(e,t){let n=AC();try{Ce.write(`pm init setup wizard (agent-optimized)
24
24
  `),Ce.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
25
25
 
26
26
  `),Ce.write(`1/3 Item ID prefix
@@ -30,26 +30,26 @@ Agent guidance check
30
30
  `),Ce.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
31
31
  `),Ce.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
32
32
  `),Ce.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=F_(i)}catch{Ce.write(`Unrecognized governance preset "${i}"; using minimal.
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=K_(i)}catch{Ce.write(`Unrecognized governance preset "${i}"; using minimal.
34
34
  `)}Ce.write(`
35
35
  3/3 Project telemetry
36
36
  `),Ce.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
37
- `);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=TC(m,t);return Ce.write(`
38
- `),{prefix:s,preset:a,telemetry_enabled:u}}finally{n.close()}}function PC(e){return{presetFromOption:F_(e.preset),useDefaults:e.defaults===!0,authorFromOption:vC(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:EC(e.agentGuidance),typePreset:wC(e.typePreset)}}function NC(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 LC(e,t,n,r){if(t.length===0||n)return;let s=r.discovery==="ancestor";throw new l(`${s?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:s?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...s?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...s?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function FC(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&&($_(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 $C(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=NC({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return LC(e.settingsPath,n,e.options.force===!0,e.target),FC({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Se(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function MC(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 OC(t,pt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,s=!0}let o=n??"minimal",i=yC();i.id_prefix=t,$_(i,o);let a=bs()?.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 Se(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:s}}async function L_(e){return e.settingsExists?await $C(e):await MC({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function DC(e){let t=await N_({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 Se(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function UC(e,t){let n=[],r=[],s=await rm(e,t.schema);for(let o of s.created_paths)n.push(o),r.push(...await z({path:o,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function GC(e){if(e.typePreset===void 0)return;let t=await RC(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 jC(e){let n=x(e.settings,I()).folders.filter(s=>!Ri.includes(s)),r=await M_(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function qC(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 KC(e,t,n,r){if(!e)return;let s=await En("all",{install:!0,project:!0},{...t,path:n});r.push(...s.warnings);let o=CC(s),i=o.packages.filter(a=>!a.ok).map(a=>a.alias);if(!o.installed_all||i.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${i.length>0?`: ${i.join(", ")}`:"."}`,d.GENERIC_FAILURE);return o}function zC(e){let t=r=>zs([...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 BC(e,t,n,r=zu){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let s=await r({pmRoot:e,workspaceRoot:t});s.gitattributes.changed&&n.push(`updated:merge_fence:${s.gitattributes.path}`)}catch(s){if(!(s instanceof l))throw s;n.push(`merge_fence_skipped:install_failed:${s.context.code??"pm_error"}:${s.message}:run pm merge install after resolving the Git repository error`)}}async function lr(e,t,n={}){let r=process.cwd(),s=kC(r,t,e,n.workspace),o=s.pmRoot;e=SC(s.prefixArg,n.idPrefix);let i=PC(n);await xC(o,s.target.mode==="tracker-path",n.force===!0);let a=[],c=[],m=V.join(o,"settings.json"),u=await k(m),p;u&&(p=await L_({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:kt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target}));let f=await M_(o,Ri);a.push(...f.createdDirs),c.push(...f.warnings),p??=await L_({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:kt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target});let{settings:_}=p,h=qC(s.target),y=await qu(h??V.dirname(o)),g=h??y,b=await DC({pmRoot:o,cwd:g??r,agentGuidanceMode:i.agentGuidanceMode,settings:_,warnings:c}),v=await UC(o,_);a.push(...v.createdDirs),c.push(...v.warnings);let E=await GC({pmRoot:o,settings:_,typePreset:i.typePreset,warnings:c});if(E&&(_=await A(o)),await jC({pmRoot:o,settings:_,createdDirs:a,warnings:c}),g&&i.agentGuidanceMode!=="status"){let $=await Di(g,{pmRoot:o});$.changed&&c.push(`updated:gitignore:${$.path}`)}!u&&n.mergeFence!==!1&&i.agentGuidanceMode!=="status"&&await BC(o,y,c);let N=await KC(i.installBundledPackages,t,o,c),P=zC({installBundledPackages:i.installBundledPackages,registeredTypePreset:E,agentGuidanceNextSteps:b.next_steps,target:s.target});return{ok:!0,path:o,target:s.target,settings:_,created_dirs:a,warnings:c,governance_preset:_.governance.preset,wizard_used:p.wizardUsed,...E?{registered_type_preset:E}:{},...N?{installed_packages:N}:{},next_steps:P,agent_guidance:b}}import QC from"node:fs/promises";import Sc 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 U_=10,Zt="https://schema.unbrained.dev/pm/eval-query-set/v1";var jo={schema:Zt,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},qe=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},HC=new Set(["keyword","semantic","hybrid"]);function D_(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 VC(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),s=D_(r,n),o=Array.from({length:t.size},()=>1),i=D_(o,n);return i===0?0:s/i}function WC(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 vc(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 YC(e,t,n){return n<=0?0:vc(e,t,n)/n}function JC(e,t,n){return t.size===0?0:vc(e,t,n)/t.size}function G_(e,t,n){return{ndcg:VC(e,t,n),mrr:WC(e,t,n),precision:YC(e,t,n),recall:JC(e,t,n),relevant_total:t.size,retrieved_relevant:vc(e,t,n)}}function j_(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 XC(e,t){if(typeof e!="object"||e===null)throw new qe(`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 qe(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new qe(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(o=>typeof o!="string"))throw new qe(`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 qe(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!HC.has(n.mode)))throw new qe(`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 kc(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==Zt)throw new qe(`Unsupported eval query set schema; expected "${Zt}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new qe('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new qe("Eval query set must contain at least one query");return{schema:Zt,queries:n.map((r,s)=>XC(r,s))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b90a064c-f423-5bf7-9fbf-1fb273c7b5af")}catch{}})();var ZC=Sc.join("search","eval-queries.json"),Ec={schema:Zt,examples:[JSON.stringify(jo)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},eR=new Set(["keyword","semantic","hybrid"]),tR=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!eR.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},nR=e=>{if(e===void 0||e==="")return U_;let t=Ld(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},rR=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new l("Eval --fail-under must be a number in the range [0, 1]",d.USAGE);return n},Ct=e=>Math.round(e*1e4)/1e4,sR=async e=>{try{return await QC.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Ec,examples:[`echo '${JSON.stringify(jo)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},oR=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new l(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,d.USAGE,Ec)}},iR=e=>{try{return kc(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Ec)}},aR=async e=>iR(oR(await sR(e),e)),cR=(e,t)=>t?Sc.resolve(process.cwd(),t):Sc.join(e,ZC),dR=async(e,t,n,r)=>{let s=e.mode??t,i=(await er(e.query,{mode:s,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=G_(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:Ct(a.ndcg),mrr:Ct(a.mrr),precision:Ct(a.precision),recall:Ct(a.recall)}}},lR=(e,t,n,r)=>{let s=j_(n);return{k:e,query_count:t.length,aggregate:{ndcg:Ct(s.ndcg),mrr:Ct(s.mrr),precision:Ct(s.precision),recall:Ct(s.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||s.ndcg>=r}},q_=async(e,t)=>{let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=nR(e.k),s=tR(e.mode),o=rR(e.failUnder),i=cR(n,e.queries),a=await aR(i),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await dR(u,s,r,t);m.push(f),c.push(p)}return lR(r,c,m,o)};import{readFile as vR,writeFile as kR}from"node:fs/promises";import SR 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 Tc(e,t){let n=vs(e);if(n)throw new l(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,d.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(i)try{let a=JSON.parse(i);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new l(`History merge input (${t}) contains invalid JSON at line ${s+1}.`,d.GENERIC_FAILURE)}}return r}function Rt(e){return J({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function mR(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Rt(e[r])===Rt(t[r]);)r+=1;return r}function K_(e,t,n){Tc(e,"base");let r=Tc(t,"ours"),s=Tc(n,"theirs"),o=mR(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(Rt)),c=s.slice(o).filter(p=>!a.has(Rt(p))),m=[...i,...c].sort((p,f)=>{let _=_n(p.ts,f.ts);if(_!==0)return _;let h=a.has(Rt(p)),y=a.has(Rt(f));return h!==y?Number(y)-Number(h):Rt(p).localeCompare(Rt(f))}),u=Ss([...r.slice(0,o),...m]);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 Ac(e,t){let n=vs(e);if(n)throw new l(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,d.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{throw new l(`Relationship merge input (${t}) contains invalid JSON at line ${s+1}.`,d.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new l(`Relationship merge input (${t}) line ${s+1} is not a relationship event (eventId + sequence required).`,d.GENERIC_FAILURE);r.push(a)}return r}function qo(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
37
+ `);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=LC(m,t);return Ce.write(`
38
+ `),{prefix:s,preset:a,telemetry_enabled:u}}finally{n.close()}}function jC(e){return{presetFromOption:K_(e.preset),useDefaults:e.defaults===!0,authorFromOption:xC(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:NC(e.agentGuidance),typePreset:IC(e.typePreset)}}function qC(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 KC(e,t,n,r){if(t.length===0||n)return;let s=r.discovery==="ancestor";throw new l(`${s?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:s?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...s?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...s?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function zC(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&&(z_(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 BC(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=qC({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return KC(e.settingsPath,n,e.options.force===!0,e.target),zC({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Se(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function HC(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 GC(t,pt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,s=!0}let o=n??"minimal",i=CC();i.id_prefix=t,z_(i,o);let a=ws()?.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 Se(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:s}}async function q_(e){return e.settingsExists?await BC(e):await HC({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function VC(e){let t=await j_({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 Se(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function WC(e,t){let n=[],r=[],s=await cm(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 YC(e){if(e.typePreset===void 0)return;let t=await $C(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 JC(e){let n=x(e.settings,I()).folders.filter(s=>!Ii.includes(s)),r=await B_(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function XC(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 QC(e,t,n,r){if(!e)return;let s=await En("all",{install:!0,project:!0},{...t,path:n});r.push(...s.warnings);let o=MC(s),i=o.packages.filter(a=>!a.ok).map(a=>a.alias);if(!o.installed_all||i.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${i.length>0?`: ${i.join(", ")}`:"."}`,d.GENERIC_FAILURE);return o}function ZC(e){let t=r=>Bs([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let s=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(s)||n.push(s)}return n}async function eR(e,t,n,r=Qu){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let s=await r({pmRoot:e,workspaceRoot:t});s.gitattributes.changed&&n.push(`updated:merge_fence:${s.gitattributes.path}`)}catch(s){if(!(s instanceof l))throw s;n.push(`merge_fence_skipped:install_failed:${s.context.code??"pm_error"}:${s.message}:run pm merge install after resolving the Git repository error`)}}async function mr(e,t,n={}){let r=process.cwd(),s=OC(r,t,e,n.workspace),o=s.pmRoot;e=PC(s.prefixArg,n.idPrefix);let i=jC(n);await UC(o,s.target.mode==="tracker-path",n.force===!0);let a=[],c=[],m=V.join(o,"settings.json"),u=await k(m),p;u&&(p=await q_({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:kt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target}));let f=await B_(o,Ii);a.push(...f.createdDirs),c.push(...f.warnings),p??=await q_({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:kt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target});let{settings:_}=p,h=XC(s.target),y=await Ju(h??V.dirname(o)),g=h??y,b=await VC({pmRoot:o,cwd:g??r,agentGuidanceMode:i.agentGuidanceMode,settings:_,warnings:c}),v=await WC(o,_);a.push(...v.createdDirs),c.push(...v.warnings);let E=await YC({pmRoot:o,settings:_,typePreset:i.typePreset,warnings:c});if(E&&(_=await A(o)),await JC({pmRoot:o,settings:_,createdDirs:a,warnings:c}),g&&i.agentGuidanceMode!=="status"){let M=await ji(g,{pmRoot:o});M.changed&&c.push(`updated:gitignore:${M.path}`)}!u&&n.mergeFence!==!1&&i.agentGuidanceMode!=="status"&&await eR(o,y,c);let N=await QC(i.installBundledPackages,t,o,c),P=ZC({installBundledPackages:i.installBundledPackages,registeredTypePreset:E,agentGuidanceNextSteps:b.next_steps,target:s.target});return{ok:!0,path:o,target:s.target,settings:_,created_dirs:a,warnings:c,governance_preset:_.governance.preset,wizard_used:p.wizardUsed,...E?{registered_type_preset:E}:{},...N?{installed_packages:N}:{},next_steps:P,agent_guidance:b}}import aR from"node:fs/promises";import Rc 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 V_=10,Zt="https://schema.unbrained.dev/pm/eval-query-set/v1";var qo={schema:Zt,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},qe=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},tR=new Set(["keyword","semantic","hybrid"]);function H_(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 nR(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),s=H_(r,n),o=Array.from({length:t.size},()=>1),i=H_(o,n);return i===0?0:s/i}function rR(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 Ac(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 sR(e,t,n){return n<=0?0:Ac(e,t,n)/n}function oR(e,t,n){return t.size===0?0:Ac(e,t,n)/t.size}function W_(e,t,n){return{ndcg:nR(e,t,n),mrr:rR(e,t,n),precision:sR(e,t,n),recall:oR(e,t,n),relevant_total:t.size,retrieved_relevant:Ac(e,t,n)}}function Y_(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 iR(e,t){if(typeof e!="object"||e===null)throw new qe(`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 qe(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new qe(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(o=>typeof o!="string"))throw new qe(`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 qe(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!tR.has(n.mode)))throw new qe(`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 Cc(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==Zt)throw new qe(`Unsupported eval query set schema; expected "${Zt}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new qe('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new qe("Eval query set must contain at least one query");return{schema:Zt,queries:n.map((r,s)=>iR(r,s))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b90a064c-f423-5bf7-9fbf-1fb273c7b5af")}catch{}})();var cR=Rc.join("search","eval-queries.json"),Ic={schema:Zt,examples:[JSON.stringify(qo)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},dR=new Set(["keyword","semantic","hybrid"]),lR=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!dR.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},mR=e=>{if(e===void 0||e==="")return V_;let t=Ud(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},uR=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new l("Eval --fail-under must be a number in the range [0, 1]",d.USAGE);return n},Ct=e=>Math.round(e*1e4)/1e4,pR=async e=>{try{return await aR.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Ic,examples:[`echo '${JSON.stringify(qo)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},fR=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new l(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,d.USAGE,Ic)}},_R=e=>{try{return Cc(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Ic)}},hR=async e=>_R(fR(await pR(e),e)),gR=(e,t)=>t?Rc.resolve(process.cwd(),t):Rc.join(e,cR),yR=async(e,t,n,r)=>{let s=e.mode??t,i=(await tr(e.query,{mode:s,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=W_(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:Ct(a.ndcg),mrr:Ct(a.mrr),precision:Ct(a.precision),recall:Ct(a.recall)}}},bR=(e,t,n,r)=>{let s=Y_(n);return{k:e,query_count:t.length,aggregate:{ndcg:Ct(s.ndcg),mrr:Ct(s.mrr),precision:Ct(s.precision),recall:Ct(s.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||s.ndcg>=r}},J_=async(e,t)=>{let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=mR(e.k),s=lR(e.mode),o=uR(e.failUnder),i=gR(n,e.queries),a=await hR(i),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await yR(u,s,r,t);m.push(f),c.push(p)}return bR(r,c,m,o)};import{readFile as xR,writeFile as OR}from"node:fs/promises";import PR 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 xc(e,t){let n=ks(e);if(n)throw new l(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,d.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(i)try{let a=JSON.parse(i);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new l(`History merge input (${t}) contains invalid JSON at line ${s+1}.`,d.GENERIC_FAILURE)}}return r}function Rt(e){return J({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function wR(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Rt(e[r])===Rt(t[r]);)r+=1;return r}function X_(e,t,n){xc(e,"base");let r=xc(t,"ours"),s=xc(n,"theirs"),o=wR(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(Rt)),c=s.slice(o).filter(p=>!a.has(Rt(p))),m=[...i,...c].sort((p,f)=>{let _=_n(p.ts,f.ts);if(_!==0)return _;let h=a.has(Rt(p)),y=a.has(Rt(f));return h!==y?Number(y)-Number(h):Rt(p).localeCompare(Rt(f))}),u=Es([...r.slice(0,o),...m]);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 Oc(e,t){let n=ks(e);if(n)throw new l(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,d.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{throw new l(`Relationship merge input (${t}) contains invalid JSON at line ${s+1}.`,d.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new l(`Relationship merge input (${t}) line ${s+1} is not a relationship event (eventId + sequence required).`,d.GENERIC_FAILURE);r.push(a)}return r}function Ko(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
39
39
  `)}
40
- `}function uR(e){return e.map((t,n)=>({...t,sequence:n+1}))}function z_(e,t,n){Ac(e,"base");let r=Ac(t,"ours"),s=Ac(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:qo(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:qo(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:qo(s),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:s.length-i,entries_total:s.length,reanchored:!1};let a=r.slice(i),c=new Set(a.map(f=>f.eventId)),m=s.slice(i).filter(f=>!c.has(f.eventId)),u=[...a,...m].sort((f,_)=>{if(f.timestamp!==void 0&&_.timestamp!==void 0){let g=_n(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=uR([...r.slice(0,i),...u]);return{merged:qo(p),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:m.length,entries_total:p.length,reanchored:!0}}var pR=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],fR=["updated_at"];function en(e,t){return J(e??null)===J(t??null)}function _R(e,t,n){let r=u=>Array.isArray(u)?u:[],s=new Set(r(e).map(u=>J(u))),o=r(t),i=new Set(o.map(u=>J(u))),a=r(n),c=new Set(a.map(u=>J(u))),m=o.filter(u=>{let p=J(u);return!s.has(p)||c.has(p)});for(let u of a){let p=J(u);!i.has(p)&&!s.has(p)&&m.push(u)}return m}function hR(e,t){return _n(String(e),String(t))>=0?e:t}function B_(e,t,n,r){return en(t,n)?{value:t,from_theirs:!1,conflict:!1}:en(e,t)?{value:n,from_theirs:!0,conflict:!1}:en(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function H_(e,t,n,r,s){let o=B_(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 Cc(e){return{...e.metadata}}function Rc(e,t,n){try{return He(Hm(e,n),n)}catch(r){throw new l(`Item merge input (${t}) is not a readable item document: ${String(r)}`,d.GENERIC_FAILURE)}}function gR(e,t,n,r,s){let o=new Set(pR),i=new Set(fR),a=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((m,u)=>m.localeCompare(u)),c={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let m of a){let u=e[m],p=t[m],f=n[m];if(o.has(m)){let h=_R(u,p,f);c.merged[m]=h,en(h,p)||c.unionFields.push(m);continue}if(i.has(m)){c.merged[m]=hR(p,f);continue}let _=H_(u,p,f,r,s);_.value!==void 0&&(c.merged[m]=_.value),_.conflict?(c.conflictFields.push(m),c.conflictDecisions.push({field:m,base:u,ours:p,theirs:f,retained:_.value,discarded:_.from_theirs?p:f})):_.from_theirs&&c.fieldsFromTheirs.push(m)}return c}function V_(e,t,n,r={}){let s=r.preferred??"ours",o=r.conflictResolution??"preferred_side",i=e.trim().length>0,a=Rc(t,"ours",r),c=Rc(n,"theirs",r),m=i?Rc(e,"base",r):a,u=i?Cc(m):{},p=Cc(a),f=Cc(c),{merged:_,conflictFields:h,fieldsFromTheirs:y,unionFields:g,conflictDecisions:b}=gR(u,p,f,s,o),v=H_(i?m.body:"",a.body,c.body,s,o);return v.conflict?(h.push("body"),b.push({field:"body",base:i?m.body:"",ours:a.body,theirs:c.body,retained:v.value,discarded:v.from_theirs?a.body:c.body})):v.from_theirs&&y.push("body"),{merged:Me({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 Ic(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xc(e,t){let n=vs(e);if(n)throw new l(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,d.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new l(`JSON merge input (${t}) is not valid JSON.`,d.GENERIC_FAILURE)}}function yR(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=m=>{let u=new Map;for(let p of m){let f=J(p);u.set(f,(u.get(f)??0)+1)}return u},s=r(e),o=r(t),i=r(n);for(let[m,u]of s)if((o.get(m)??0)<u||(i.get(m)??0)<u)return null;let a=new Map(o),c=[];for(let m of n){let u=J(m),p=a.get(u)??0;p>0?a.set(u,p-1):c.push(m)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function bR(e,t,n,r,s,o,i){if(!Ic(t)||!Ic(n))return null;let a=Ic(e)?e:{},c={},m=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,p)=>u.localeCompare(p));for(let u of m){let p=s.length>0?`${s}.${u}`:u,f=wR(a,t,n,u,r,p,o,i);f!==void 0&&(c[u]=f)}return c}function W_(e,t,n,r,s,o,i){if(en(t,n))return t;let a=yR(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(s),a.merged;let c=bR(e,t,n,r,s,o,i);if(c!==null)return c;let m=B_(e,t,n,r);return m.conflict?o.push(s):m.from_theirs&&i.push(s),m.value}function wR(e,t,n,r,s,o,i,a){let c=Object.prototype.hasOwnProperty.call(t,r),m=Object.prototype.hasOwnProperty.call(n,r),u=Object.prototype.hasOwnProperty.call(e,r);if(c&&m)return W_(e[r],t[r],n[r],s,o,i,a);if(c){if(u&&en(e[r],t[r])){a.push(o);return}return u?(i.push(o),s==="theirs"?void 0:t[r]):t[r]}if(!(u&&en(e[r],n[r])))return u?(i.push(o),s==="theirs"?n[r]:void 0):(a.push(o),n[r])}function Y_(e,t,n,r={}){let s=r.preferred??"ours",o=xc(e,"base"),i=xc(t,"ours"),a=xc(n,"theirs"),c=[],m=[],u=W_(o,i,a,s,"",c,m);return{merged:`${JSON.stringify(u??null,null,2)}
41
- `,conflict_paths:c,paths_from_theirs:m,preferred:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d79e3a4-6104-5855-837f-69a041b87b27")}catch{}})();var J_=["item","history","relationship","json"];function ER(e){let t=e.trim().toLowerCase();if(J_.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${J_.join(", ")}.`,d.USAGE)}function TR(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new l(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,d.USAGE)}async function Oc(e,t){try{return await vR(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function AR(e){let t=T(process.cwd(),e.path);return await k(C(t))?A(t):null}function CR(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function X_(e,t){let n=ER(e.artifact),r=TR(e.prefer),s=SR.resolve(e.outputPath??e.oursPath),[o,i,a]=await Promise.all([Oc(e.basePath,"base"),Oc(e.oursPath,"ours"),Oc(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=K_(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 _=z_(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 AR(t),h=V_(o,i,a,{format:CR(e.itemPath??s,_),schema:_?.schema,extensionFieldNames:ft(I()),preferred:r,conflictResolution:"stable_value_order"});c=h.merged,u.push(...h.conflict_fields),p.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0&&(m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,decisions:h.conflict_decisions})}else{let _=Y_(o,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await kR(s,c,"utf8"),m!==void 0){let _=await dp(m);_!==null&&(p.receipt=Yn(_))}let f=[];if(u.length>0){let _=p.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${p.receipt.receipt_id} with item ${p.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${u.join(", ")}; the item driver kept the direction-independent stable value. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&p.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:u.length===0,artifact:n,output_path:s,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:S()}}import eh from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de9b7f82-0f51-599d-b1fa-2d54e3acbdbc")}catch{}})();function Q_(e,t){return t==="body"?e.body:e.metadata[t]}function Pc(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)&&Pc(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)&&Pc(s,n[r]))}function Z_(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 Xm(o.patch))i.add(Ls(c.path)),c.from&&i.add(Ls(c.from));let a=[...n].filter(c=>i.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:s+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,m)=>c.localeCompare(m))})}}return r.reverse()}function RR(e,t,n){let r=eh.compare(t,n);if(r.length===0)return;let s=new Set;for(let h of r)s.add(Ls(h.path));let o=new Set([...s].filter(h=>Pc(Q_(t,h),Q_(n,h)))),i=new Set([...s].filter(h=>!o.has(h))),a=Z_(e,i),c=Z_(e,o),m=[...s].sort((h,y)=>h.localeCompare(y)),u=[...i].sort((h,y)=>h.localeCompare(y)),p=[...o].sort((h,y)=>h.localeCompare(y)),f=[...new Set(a.map(h=>h.author))].sort((h,y)=>h.localeCompare(y)),_=[...new Set(c.map(h=>h.author))].sort((h,y)=>h.localeCompare(y));return{reconciled_field_count:s.size,reconciled_fields:m,reverted_field_count:i.size,reverted_fields:u,discarded_events:a,discarded_authors:f,preserved_field_count:o.size,preserved_fields:p,preserved_events:c,preserved_authors:_,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function IR(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=jt(o.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:i,currentItemPath:s,matchedChainBefore:Pe(i,r)===a,currentItemRawBeforeLock:o.raw,loadedItem:o}}function xR(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 OR(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:S(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?eh.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Pe(e.finalReplay,e.itemHashVersion),after_hash:Pe(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 PR(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 NR(e){return Rs({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})=>Cs({historyPath:e.historyPath,nextHistoryRaw:ot(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function mr(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await Is(r,e,s,o.type_to_folder);if(!await k(i.historyPath))throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let a=await q(i.historyPath),c=await bt(i.historyPath,i.id);if(c.length===0)throw new l(`No history entries exist for ${i.id}; nothing to repair.`,d.USAGE);let m=hn(c),u=Qm(c),p=t.normalizeProvenance?ap(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=Zm(p.entries),_=new Set(p.entries.map(ie=>ie.item_hash_version).filter(ie=>ie!==void 0)),h=Ss(p.entries,f),y=await IR(i,s,c,f),g=h.finalDocument,b=y.currentItemReplay!==null&&Pe(g,f)!==Pe(y.currentItemReplay,f),v=b&&y.currentItemReplay?RR(h.entries,g,y.currentItemReplay):void 0,E=[h.entriesRehashed>0,h.entriesPatchRepaired>0,b,t.forceAuditEntry===!0,p.receipt.changed].some(Boolean),N=R(t.author,s.author_default),P=!!t.dryRun,$=xR({message:t.message,entriesRehashed:h.entriesRehashed,entriesPatchRepaired:h.entriesPatchRepaired,reconcileNeeded:b}),{rewrittenEntries:U,auditEntryAdded:Ie}=OR({reanchorEntries:h.entries,changed:E,reconcileNeeded:b,currentItemReplay:y.currentItemReplay,finalReplay:g,author:N,message:$,auditOperation:t.auditOperation??"history_repair",auditContext:p.receipt.changed?{...t.auditContext,provenance_normalization:p.receipt}:t.auditContext,itemHashVersion:f,explicitItemHashVersion:h.explicitItemHashVersion}),ee=hn(U);if(!ee.ok)throw new l(`history-repair produced an invalid rewritten chain (${ee.errors.join(", ")}).`,d.GENERIC_FAILURE);let pe=PR(E,h.skippedOps,v);return E&&!P&&pe.push(...await NR({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:U})),{id:i.id,dry_run:P,changed:E,history:{path:i.historyPath,entries_scanned:c.length,chain_drift_before:!m.ok,entries_rehashed:h.entriesRehashed,entries_patch_repaired:h.entriesPatchRepaired,converted_replace_to_add:h.convertedReplaceToAdd,skipped_ops:h.skippedOps,reconciled_with_item:b,audit_entry_added:Ie,verify_ok:ee.ok,verify_errors:ee.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(pe)].sort((ie,Xe)=>ie.localeCompare(Xe)),generated_at:S()}}function th(e,t){if(t&&e!==void 0)throw new l("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",d.USAGE);if(!t&&e===void 0)throw new l("history-repair: provide an item <id> or pass --all to repair every drifted stream.",d.USAGE)}async function Ko(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=x(r,I()),o=[],i=await Es(n,r.item_format,s.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await Pu(n,i),c=e.normalizeProvenance?await cp(n):[],m=[...new Set([...a.driftedItems,...c])].sort((_,h)=>_.localeCompare(h)),u=[],p=[],f={repaired:0,skipped_clean:0,failed:0};for(let _ of m)try{let h=await mr(_,{...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 Ym(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:i.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:u,totals:f,warnings:[...new Set([...o,...p])].sort((_,h)=>_.localeCompare(h)),generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c5620467-6c8c-5702-b742-57fba9e302c5")}catch{}})();async function nh(e,t){let n=e.dryRun===!0,r=await lp(process.cwd(),{includeLossless:!0}),{pendingDecisions:s}=mp(r);if(!n&&e.force!==!0&&s.length>0)throw new l(`Merge reconciliation would accept ${s.length} receipt(s) containing discarded scalar values. Review pm merge report and rerun with --force only after deciding which values to retain or re-apply.`,d.CONFLICT,{code:"merge_reconcile_discards_require_acceptance",required:"Explicitly review every discarded field before accepting reconciliation.",nextSteps:s.map(g=>`Review receipt ${g.id} for ${g.item_id}: ${g.decisions.map(b=>b.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let o=r.reduce((g,b)=>((g[b.item_id]??=[]).push(b),g),{}),i=Object.fromEntries(Object.entries(o).map(([g,b])=>[g,{merge:{receipts:b.map(Yn)}}])),a=await Ko({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:i},t),c=new Set(a.streams.map(g=>g.id)),m=Object.keys(o).filter(g=>!c.has(g));(await Promise.allSettled(m.map(g=>mr(g,{dryRun:n,author:e.author??t.author,message:e.message??"record field-aware branch merge provenance",force:e.force,auditOperation:"merge_reconcile",auditContext:i[g],forceAuditEntry:!0},t)))).forEach((g,b)=>{let v=m[b];if(g.status==="fulfilled"){let E=g.value.changed?"repaired":"skipped_clean";a.streams.push({id:v,outcome:E,entries_rehashed:g.value.history.entries_rehashed,entries_patch_repaired:g.value.history.entries_patch_repaired,reconciled_with_item:g.value.history.reconciled_with_item,warnings:g.value.warnings}),a.totals[E]+=1}else a.streams.push({id:v,outcome:"failed",error:g.reason instanceof Error?g.reason.message:String(g.reason)}),a.totals.failed+=1});let p=0;!n&&a.totals.failed===0&&(await Promise.all(r.map(g=>up(process.cwd(),g))),p=r.length);let f=await Ys({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(Yn)},validation:f,guidance:y,generated_at:f.generated_at}}import{createHash as LR}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]="3f9853cc-0719-544f-8726-3cfd6063b59e")}catch{}})();var sh=1,oh=/^[A-Za-z0-9_-]+$/,FR=100,rh=1e3;function Ke(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 $R(e){return LR("sha256").update(J({type:Ke(e.type),author:Ke(e.author),item:Ke(e.item),harness:Ke(e.harness),agent_instance:Ke(e.agentInstance),provenance:Ke(e.provenanceFilter)})).digest("hex").slice(0,24)}function MR(e,t){let n={version:sh,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 DR(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===sh,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 UR(e,t){let n=e.trim();if(n.length===0||n.length>4096||!oh.test(n))throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"})}if(!DR(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function GR(e){let t=e??FR;if(!Number.isSafeInteger(t)||t<0||t>rh)throw new l(`Mutation event limit must be an integer from 0 to ${rh}.`,d.USAGE,{code:"invalid_event_limit"});return t}function jR(e,t){let n=e?.trim();if(!n)return{};if(oh.test(n))return{cursor:UR(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new l("Mutation event --since must be an event cursor or ISO timestamp.",d.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function qR(e,t){let n=await Vi(e,t);if(n===null){if(!await Vm(e))throw new l("Mutation events require a runtime with node:sqlite DatabaseSync support.",d.GENERIC_FAILURE,{code:"event_index_unavailable"});n=await Vi(e,t)}if(n===null)throw new l("Mutation event index could not be opened after rebuild.",d.GENERIC_FAILURE,{code:"event_index_unavailable"});return n}async function zo(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=GR(e.limit);if(e.full===!0&&e.provenance===!0)throw new l("Mutation event projections are mutually exclusive. Use --provenance or --full.",d.USAGE);let r=await A(t),s=r.agent_identity.identity_vocabulary,o=vu(r.agent_identity.harness_signals),i=ku({provenance:e.provenanceFilter},o),a=Ke(e.harness),c=$R(e),{cursor:m,sinceTimestamp:u}=jR(e.since,c),p={...m?{after_ts:m.ts,after_stream_id:m.stream_id,after_stream_offset:m.stream_offset}:u?{since_ts:u}:{},ops:Ke(e.type),authors:Ke(e.author),harnesses:a,harness_alias_authors:a?Object.entries(s.aliases).filter(([,h])=>a.includes(h)).map(([h])=>h):void 0,agent_instances:Ke(e.agentInstance),provenance:[...i].map(([h,y])=>({dimension:h,values:[...y]})),stream_ids:Ke(e.item),limit:n},f=await qR(t,p),_=f.events.map(h=>({cursor:MR(h,c),item_id:h.stream_id,version:h.stream_offset+1,ts:h.entry.ts,author:h.entry.author,type:h.entry.op,...h.entry.message===void 0?{}:{message:h.entry.message},patch_count:h.entry.patch.length,...e.full===!0?{entry:h.entry}:{},...e.provenance===!0?{provenance:Su(h.entry,s,{itemId:h.stream_id,version:h.stream_offset+1})}:{}}));return{events:_,count:_.length,has_more:f.has_more,..._.length===0?{}:{next_cursor:_[_.length-1].cursor},source:"derived_index",...e.provenanceSummary===!0?{provenance_summary:Eu(f.events.map(h=>h.entry),s,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]="32223457-5f57-5049-99cf-c5d766413fb6")}catch{}})();var KR="1h",zR="now",BR="+1d";function It(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function ih(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 ah(e,t,n,r){let s=ih(e,t,n),o=[];return It(o,"start",n.start??zR),n.end!==void 0?It(o,"end",n.end):It(o,"duration",n.duration??KR),It(o,"location",n.location),It(o,"timezone",n.timezone),n.allDay===!0&&It(o,"all_day","true"),s.event=[o.join(",")],At(s,r)}function ch(e,t,n){return ah("Meeting",e,t,n)}function dh(e,t,n){return ah("Event",e,t,n)}function lh(e,t,n){let r=ih("Reminder",e,t),s=[];return It(s,"at",t.at??BR),It(s,"text",t.text??e),r.reminder=[s.join(",")],At(r,n)}import pr from"node:crypto";import{cp as uh,lstat as XR,mkdir as tn,readFile as Nn,readdir as Lc,rename as _h,rm as $c,writeFile as Ho}from"node:fs/promises";import L from"node:path";import{constants as xt}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]="679bb2a0-aada-586e-a831-591266be2ee0")}catch{}})();var mh=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"}]]),HR=/^[a-z][a-z0-9_]{0,63}$/u,VR=new Map([[xt.errno.EACCES,"EACCES"],[xt.errno.EDQUOT,"EDQUOT"],[xt.errno.EMFILE,"EMFILE"],[xt.errno.ENFILE,"ENFILE"],[xt.errno.ENOMEM,"ENOMEM"],[xt.errno.ENOSPC,"ENOSPC"],[xt.errno.EPERM,"EPERM"],[xt.errno.EROFS,"EROFS"]]),WR={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function YR(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&mh.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:VR.get(Math.abs(t.errno))??null}function JR(e,t,n={}){let r=YR(e);if(r===null)return null;if(!HR.test(t))throw new l("Host environment operation labels must be bounded identifiers.",d.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let s=mh.get(r);return new l(`Host filesystem operation ${t} ${s.summary}.`,d.GENERIC_FAILURE,{code:n.codes?.[s.category]??WR[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 Bo(e,t,n={}){try{return await t()}catch(r){throw JR(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]="36aacc71-c5f5-56f1-85f4-28b2be5b02e2")}catch{}})();var hh="https://schema.unbrained.dev/pm/workspace-snapshot/v1",gh=L.join("runtime","workspace-snapshots"),QR=new Set(["checkpoints","locks","runtime","search","transactions"]),ZR=/^[a-z0-9][a-z0-9._-]*$/,ur="sdk-workspace-transaction",Nc={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},yh={renameEntry:_h,removeEntry:async e=>{await $c(e,{recursive:!0,force:!0})}},Fc=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 Nn(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!==ur||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await me(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
42
- `)}};async function bh(e,t=""){let n=await Lc(L.join(e,t),{withFileTypes:!0}),r=[];for(let s of n.sort((o,i)=>o.name.localeCompare(i.name))){if(t.length===0&&QR.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 bh(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 bh(e),n=pr.createHash("sha256"),r=[],s=0;for(let i of t){let a=await Nn(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:hh,fingerprint:o,files:t,bytes:s},contents:r}}function ph(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
43
- `).filter(t=>t.trim().length>0).length}async function eI(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 Nn(L.join(e,i))]));for(let[i,a]of o)n.set(i,a)}return n}function Mc(e){if(!ZR.test(e))throw new l("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",d.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function vh(e,t){return Bo(`workspace_snapshot_${e}`,t,{codes:{capacity:Nc.capacity.code,permission:Nc.permission.code,resource:Nc.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 nn(e){return L.join(e,gh)}function kh(e){return new l(`Unknown workspace snapshot: ${e}`,d.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Sh(e,t){try{return JSON.parse(await Nn(e,"utf8"))}catch(n){throw _t(n)?kh(t):n}}async function fh(e,t,n){try{await $c(e,{recursive:n})}catch(r){throw _t(r)?kh(t):r}}async function tI(e,t,n=yh){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 nI(e,t,n,r,s){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await s?.()}catch(o){throw await r.renameEntry(n,t),await r.removeEntry(e),o}await r.removeEntry(n)}async function rI(e,t){return Mc(t),/^[a-f0-9]{64}$/.test(t)?t:(await Sh(L.join(nn(e),"refs",`${t}.json`),t)).fingerprint}async function Dc(e,t={}){if(t.name!==void 0&&(Mc(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new l("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",d.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await wh(e),s=nn(e),o=L.join(s,"objects",n.fingerprint),i=!1;try{i=(await XR(o)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&_t(a)))throw a}if(!i){let a=L.join(s,"objects",`.create-${process.pid}-${pr.randomUUID()}`);await vh("create_object",async()=>{await tn(L.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=L.join(a,"files",m);await tn(L.dirname(u),{recursive:!0}),await Ho(u,r[c])}await Ho(L.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
44
- `,"utf8"),await tn(L.dirname(o),{recursive:!0})}),i=await tI(a,o)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=L.join(s,"refs");await tn(c,{recursive:!0});let m=L.join(c,`.ref-${process.pid}-${pr.randomUUID()}`);await Ho(m,`${JSON.stringify(a,null,2)}
45
- `,"utf8"),await _h(m,L.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function fr(e,t){let n=await rI(e,t),r=await Sh(L.join(nn(e),"objects",n,"manifest.json"),t);if(r.schema!==hh||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,d.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function Uc(e){let t=nn(e),n=await Lc(L.join(t,"objects")).catch(s=>{if(s instanceof Error&&"code"in s&&_t(s))return[];throw s}),r=await Lc(L.join(t,"refs")).catch(s=>{if(s instanceof Error&&"code"in s&&_t(s))return[];throw s});return{objects:await Promise.all(n.filter(s=>/^[a-f0-9]{64}$/.test(s)).sort().map(s=>fr(e,s))),references:await Promise.all(r.filter(s=>s.endsWith(".json")).sort().map(async s=>JSON.parse(await Nn(L.join(t,"refs",s),"utf8"))))}}async function Gc(e,t){let n=await fr(e,t),{manifest:r,contents:s}=await wh(e),o=new Map(r.files.map((p,f)=>[p,s[f]])),i=await eI(L.join(nn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),m=new Set([...a,...c]);for(let p of m){let f=o.get(p),_=i.get(p);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=ph(o.get(p)),_=ph(i.get(p));return{path:p,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(p=>p.removed_entries>0).sort((p,f)=>p.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:m.size,removed_file_count:[...a].filter(p=>!c.has(p)).length,added_file_count:[...c].filter(p=>!a.has(p)).length,removed_item_count:[...a].filter(p=>p.endsWith(".toon")&&!c.has(p)).length,affected_history_stream_count:u.length,removed_history_entry_count:u.reduce((p,f)=>p+f.removed_entries,0),affected_history_streams:u,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function Eh(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",d.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",s=n.lockTtlSeconds??60,o=n.lockWaitMs??5e3,i=await xe(e,ur,s,r,!1,!1,o),a=new Fc(Pr(e,ur),r,s);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await Gc(e,t),f=await fr(e,t),_=await Dc(e),h=f.fingerprint,y=nn(e),g=L.join(y,"objects",h,"files"),b=L.dirname(e),v=L.basename(e);c=L.join(b,`.${v}.restore-${pr.randomUUID()}`);let E=L.join(b,`.${v}.backup-${pr.randomUUID()}`);await vh("restore_stage",async()=>{await tn(c,{recursive:!0}),await uh(g,c,{recursive:!0,force:!1}),await tn(L.join(c,"runtime"),{recursive:!0}),await uh(y,L.join(c,gh),{recursive:!0,force:!1})});let N=await eu({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:p.changed_file_count,removed_file_count:p.removed_file_count,removed_item_count:p.removed_item_count,affected_history_stream_count:p.affected_history_stream_count,removed_history_entry_count:p.removed_history_entry_count},lockTtlSeconds:s,lockWaitMs:o}),P=L.relative(c,N.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let $=Pr(c,ur);return await tn(L.dirname($),{recursive:!0}),await Ho($,await Nn(Pr(e,ur)),{flag:"wx"}),m=!0,await nI(c,e,E,yh,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:P,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([$c(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function Th(e,t){Mc(t);let n=nn(e);if(!/^[a-f0-9]{64}$/.test(t))return await fh(L.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Uc(e);if(r.some(s=>s.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await fh(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]="37ac2a74-f150-5b9d-96d6-d9cc441215be")}catch{}})();function _r(e){return{...e.args,...e.options}}function lt(e,t){let n=w(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Ln(e){return typeof e=="string"?[e]:he(e)}function Ah(e){return q_(_r(e),e.global)}function Ch(e){let t=_r(e);return zo({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Ln(t.type),author:Ln(t.author),item:Ln(t.item),limit:t.limit===void 0?void 0:Le(t.limit,"limit"),full:t.full===!0,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Ln(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Ln(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Ln(t.provenanceFilter)}})}function Rh(e){let t=_r(e),n=lt(t,"subcommand");if(n==="install")return Ku({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return nh({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return pp({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return X_({artifact:lt(t,"artifact"),basePath:lt(t,"basePath"),oursPath:lt(t,"oursPath"),theirsPath:lt(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw Ee({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Ih(e){let t=_r(e),n=lt(t,"subcommand");if(n!=="snapshot")throw Ee({command_path:"workspace",token:n,allowed:["snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??lt(t,"snapshot_action"),s=T(process.cwd(),e.global.path);if(r==="create")return Dc(s,{name:w(t,"name")});if(r==="list")return Uc(s);let o=lt(t,"target");if(r==="inspect")return fr(s,o);if(r==="delete")return Th(s,o);if(r==="restore")return t.dryRun===!0?Gc(s,o):Eh(s,o,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Le(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Le(t.lockWaitMs,"lockWaitMs")});throw Ee({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Vo(e){let t=_r(e),n=lt(t,"title");return e.action==="meet"?ch(n,t,e.global):e.action==="event"?dh(n,t,e.global):lh(n,t,e.global)}import hI from"node:path";import sI from"node:fs/promises";import xh from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f232e106-54f4-572e-8f6e-054f52290267")}catch{}})();var oI="templates",iI=".json",aI=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,cI=_s.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),dI=new Set(cI);function lI(e){let t=e.trim();if(!aI.test(t))throw new l(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,d.USAGE);return t}function Oh(e){return xh.join(e,oI)}function Ph(e,t){return xh.join(Oh(e),`${t}${iI}`)}async function mI(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function Nh(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function uI(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 Nh(t)}function pI(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new l(`Template "${t}" has invalid options payload.`,d.GENERIC_FAILURE);let n=e,r={};for(let[s,o]of Object.entries(n)){let i=s.trim();if(i.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof o=="string"){r[i]=o;continue}if(Array.isArray(o)&&o.every(a=>typeof a=="string")){r[i]=[...o];continue}throw new l(`Template "${t}" contains invalid value for option "${i}".`,d.GENERIC_FAILURE)}return Nh(r)}function fI(e,t){let n;try{n=JSON.parse(e)}catch{throw new l(`Template "${t}" contains invalid JSON.`,d.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Template "${t}" has invalid document shape.`,d.GENERIC_FAILURE);let r=n,s=pI(r.options,t),o=S();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:o,updated_at:typeof r.updated_at=="string"?r.updated_at:o,options:s}}async function _I(e,t){let n=await q(Ph(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return fI(n,t)}async function jc(e,t,n){let r=T(process.cwd(),n.path);await mI(r);let s=lI(e),o=uI(t);if(Object.keys(o).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let i=S(),a=Ph(r,s),c=i;await k(a)&&(c=(await _I(r,s)).created_at);let m={name:s,created_at:c,updated_at:i,options:o},u=await A(r);return await sI.mkdir(Oh(r),{recursive:!0}),await vt({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
46
- `,op:"templates:save",author:R(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:a,options:m.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1e34cfb-3d4e-5b79-8585-3162e71e574c")}catch{}})();var Mh=["list","show","apply","lint"],gI="schema-types",yI="schema-statuses",bI="schema-fields";function Wo(){let e=I();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Dh(){let{profiles:e,warnings:t}=tm(Wo());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:im(n.definition)})),warnings:t,generated_at:S()}}function Uh(e){let t;try{t=ls(e,Wo())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...am(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function Gh(e){let t;try{t=ls(e,Wo())}catch(s){throw new l(s instanceof Error?s.message:String(s),d.USAGE)}let{resolved:n}=t,r=Sm(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:S()}}function wI(e,t){return hI.join(e,"templates",`${t}.json`)}async function vI(e,t){let n=await q(wI(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 Lh(e,t,n,r){let s=new Map;for(let o of r.templates){let i=await vI(e,o.name);i!==void 0&&s.set(o.name,i)}return{typesRaw:await q(rt(e,t.files.types,nt.types)),statusesRaw:await q(rt(e,t.files.statuses,nt.statuses)),fieldsRaw:await q(rt(e,t.files.fields,nt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:s,installedPackages:new Set}}function Fn(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 Fh(e,t,n,r,s){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Fn(t.types.changes),statuses:Fn(t.statuses.changes),fields:Fn(t.fields.changes),workflows:Fn(t.workflows.changes.map(o=>({key:o.type,status:o.status}))),config:Fn(t.config.changes),templates:Fn(t.templates.changes.map(o=>({key:o.name,status:o.status}))),packages:t.packages,warnings:[...new Set(s)].sort((o,i)=>o.localeCompare(i)),generated_at:S()}}async function kI(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function SI(e){try{let t=ls(e,Wo());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function jh(e,t,n){let r=T(process.cwd(),n.path);await kI(r);let s=SI(e),o=s.profile,i=s.warnings,a=t.dryRun===!0,c=await A(r),m=ms(c.schema);if(a){let b=await Lh(r,m,c,o),v=$h(o,b);return Fh(o,v,!1,!0,[...i])}let u=R(t.author,c.author_default),p=nu(c),f=!!t.force,_=[...i],h=[],y=async b=>{h.push(await xe(r,b,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(gI),await y(yI),await y(bI);let b=await Lh(r,m,c,o);if(g=$h(o,b),g.types.changed){let v=rt(r,m.files.types,nt.types);await vt({pmRoot:r,filePath:v,raw:ds(g.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let E=new Set(o.types.map(P=>Yl(P).name)),N=g.types.file.definitions.filter(P=>E.has(P.name));await Yu(r,N,_,"profile:apply-type-folder"),_.push(...await z({path:v,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let v=rt(r,m.files.statuses,nt.statuses);await vt({pmRoot:r,filePath:v,raw:om(g.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let v=rt(r,m.files.fields,nt.fields);await vt({pmRoot:r,filePath:v,raw:nm(g.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let v of g.config.changes){if(v.status==="unchanged")continue;let E=ps(v.key);E!==void 0&&fs(c,E,v.value)}c.schema.type_workflows=g.workflows.result,await Se(r,c,"profile:apply-config")}for(let v of g.templates.changes)v.status!=="unchanged"&&await jc(v.name,{...v.options},n)}finally{for(let b of h.reverse())try{await b()}catch{}}return Fh(o,g,g.changed,!1,_)}function $h(e,t){try{return Em(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import Kh from"node:fs/promises";import zh 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 EI(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 TI(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 qh(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return EI(t.ids,n,t.minEntries)}return TI(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6609492-75a9-5111-b9b3-1b81908f3084")}catch{}})();function AI(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(n)){let o=Number.parseInt(n,10);if(!Number.isSafeInteger(o)||o<1||o>t.length+1)throw new l(`history-compact --before version must be between 1 and ${t.length+1}.`,d.USAGE);let i=Math.max(0,Math.min(t.length,o-1));return{kind:"version",raw:n,compactCount:i,retainedCount:t.length-i}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let s=0;for(let[o,i]of t.entries()){let a=Date.parse(i.ts);if(!Number.isFinite(a))throw new l(`History for this item contains invalid timestamp at entry ${o+1}.`,d.GENERIC_FAILURE);if(a>=r)break;s+=1}return{kind:"timestamp",raw:n,compactCount:s,retainedCount:t.length-s}}function CI(e,t){let n=ks(),r=ks();for(let s=0;s<e.length;s+=1){let o=e[s];if(Pe(n)!==o.before_hash)throw new l(`history-compact detected before-hash drift at entry ${s+1}; run pm history-repair first.`,d.CONFLICT);if(n=As(n,o.patch,s+1,o.op),Pe(n)!==o.after_hash)throw new l(`history-compact detected after-hash drift at entry ${s+1}; run pm history-repair first.`,d.CONFLICT);s+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function RI(e,t,n){let r=structuredClone(t),s=[];for(let[o,i]of e.entries()){let a=Pe(r);r=As(r,i.patch,n+o+1,i.op),s.push({...i,before_hash:a,after_hash:Pe(r)})}return{entries:s,finalReplay:r}}async function II(e,t,n){let r=e.located?await K(e.located,{schema:t.schema}):null;return r?{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:Pe(jt(r.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function xI(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 OI(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 PI(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=CI(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),s=RI(r,t,e.boundary.compactCount),i=[De({nowIso:S(),author:e.author,op:"history_compact_baseline",before:Gt(ks()),after:Gt(t),message:OI(e.boundary)}),...s.entries];return e.dryRun||i.push(De({nowIso:S(),author:e.author,op:"history_compact",before:Gt(n),after:Gt(n),message:xI(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function NI(e){return Rs({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})=>Cs({historyPath:e.historyPath,nextHistoryRaw:ot(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function qc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await Is(r,e,s,o.type_to_folder),a=i.historyPath,c=await q(a);if(c===null)throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let m=await bt(a,i.id);if(m.length===0)throw new l(`No history entries exist for ${i.id}; nothing to compact.`,d.USAGE);let u=hn(m);if(!u.ok)throw new l(`history-compact requires a valid history chain (${u.errors.join(", ")}). Run pm history-repair ${i.id} first.`,d.CONFLICT);let p=AI(t.before,m),f=p.compactCount>0,_=!!t.dryRun,h=R(t.author,s.author_default),y=[];f||y.push("history_compact_noop_before_boundary");let g=await II(i,s,m);g.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:E}=PI({historyEntries:m,boundary:p,changed:f,dryRun:_,author:h,options:t}),N=hn(b);if(!N.ok)throw new l(`history-compact produced an invalid rewritten chain (${N.errors.join(", ")}).`,d.GENERIC_FAILURE);f&&!_&&y.push(...await NI({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 P=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:P},history:{path:a,entries_scanned:m.length,entries_after:b.length,baseline_entry_added:v,audit_entry_added:E,verify_ok:N.ok,verify_errors:N.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:g.matchedChainBefore},warnings:[...new Set(y)].sort(($,U)=>$.localeCompare(U)),generated_at:S()}}var LI=3;function Bh(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function FI(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function $I(e){let t=G(e.settings.schema),n=Js(t),r=await re(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),s=new Map(r.map(m=>[m.id,n.classify(m.status)])),o=zh.join(e.pmRoot,"history"),i=[],a=[];if(!await k(o))return{candidates:i,preselectionErrors:a};let c=(await Kh.readdir(o)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=zh.join(o,m),p=m.slice(0,-6);try{let f=await Kh.readFile(u,"utf8");await un({path:u,scope:"project"}),i.push({id:p,entries:FI(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 MI(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 qc(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 Hh(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=x(r,I()),{candidates:o,preselectionErrors:i}=await $I({pmRoot:n,settings:r,typeToFolder:s.type_to_folder}),a=e.ids!==void 0&&e.ids.length>0?"ids":"scan",c=e.minEntries??LI,m=r.history.compact_policy,u=a==="scan"&&e.allOver===void 0&&m.enabled,p=e.allOver??(u?m.max_entries:void 0),f=qh(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 MI({row:g,options:e,dryRun:_,global:t});if(h.push(b.result),!b.selected){y.items_skipped+=1;continue}y.selected+=1,b.compacted&&(y.items_compacted+=1),b.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:_,mode:a,scope:e.scope??null,criteria:{min_entries:c,all_over:p??null,policy_threshold_applied:u},totals:y,results:h,generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f762b5e6-8224-531f-9dd1-f71dc18c3ddf")}catch{}})();function Vh(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return th(n,t),t?Ko(e.options,e.global):mr(n,e.options,e.global)}function Wh(e){let t=e.options.ids,n=Array.isArray(t)?t.map(String).filter(m=>m.trim().length>0):typeof t=="string"?t.split(",").map(m=>m.trim()).filter(Boolean):void 0,r=Le(e.options.allOver??e.options.all_over,"history-compact allOver"),s=Le(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),o=w(e.options,"scope"),i=[];e.options.closed===!0&&i.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&i.push("all-streams"),(o==="closed"||o==="all-streams")&&i.push(o);let a=[...new Set(i)];if(a.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let c=a[0];return Bh(e.id,{ids:n,allOver:r,scope:c}),e.id!==void 0?qc(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):Hh({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]="c2ef0de1-bc44-5550-862c-f3929334fbef")}catch{}})();function Yh(e,t,n){let r;if(typeof e.lines=="string")r=Hs(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=Hs(`${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]="d440a41a-ae54-55fd-b939-5404a1edcdd7")}catch{}})();var DI=Mi("list").properties.outputSession,UI={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:{...DI},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Jh={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},Z={type:"string",description:"pm item id, for example pm-abc1."},GI=`Operation name (one of): ${dn.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,jI={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."}},qI={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 D(e,t=[]){return{...Jh,properties:{...Jh.properties,...e},required:t}}var KI=[{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:D({action:{type:"string",enum:[...dn],description:GI},id:Z,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."},...UI},["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:D({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:D({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:D({query:{type:"string"},options:{type:"object"},...qI},["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:D({options:{type:"object"},...jI})},{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:D({id:Z,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.",inputSchema:D({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"}})},{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:D({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:D({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:Z,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:D({id:Z,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:D({id:Z,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:D({id:Z,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:D({id:Z,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:D({id:Z,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:D({id:Z,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:D({id:Z,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:D({id:Z,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:D({id:Z,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:D({id:Z,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:D({id:Z,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:D({id:Z,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:D({id:Z,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:D({subcommand:{type:"string",enum:[...ym]},id:Z,target:Z,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:D({id:Z,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:D({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:D({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:D({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:D({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:[...vi]},description:`Lifecycle roles for add-status: ${vi.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:D({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:D({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:D({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."}})}],zI={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"},BI=KI.map(e=>{let t=zI[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Mi(t,{properties:n,required:r})}});function Xh(){return BI.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]="6fc2cd04-2fe4-5a0e-944d-fab0f86509e2")}catch{}})();var HI=new Set(["claim","close","context","create","get","help","list","next","plan","release","search","update","validate"]),VI=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),Zh=Object.freeze([...Kn.map(e=>({command:e,tier:HI.has(e)?"core":VI.has(e)?"standard":"full"})),{command:"completion-statuses",tier:"internal"},{command:"completion-tags",tier:"internal"},{command:"completion-types",tier:"internal"},{command:"test-runs-worker",tier:"internal"}]),Qh={core:0,standard:1,full:2,internal:3},WI=new Map(Zh.map(({command:e,tier:t})=>[e,t]));function eg(e,t="standard"){return WI.get(e.trim().toLowerCase())??t}function tg(e){let t=Qh[e];return Zh.filter(n=>n.tier!=="internal"&&Qh[n.tier]<=t).map(n=>n.command)}var _q=Object.freeze({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:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});var hq=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),gq=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8cdd82c3-979e-5f7f-bc72-592c7e55f11c")}catch{}})();var ng=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"]]]),YI=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],ug=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Jo=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"]),hr=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"]),pg=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"]]),fg=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"]]),_g=new Map([...fg.entries()].flatMap(([e,t])=>mt(t).map(n=>[n,e]))),hg=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],gg=new Map(hg.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),JI=10,XI=20,rg=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."]]),yg=[["init",ll],["install",ul],["uninstall",pl],["explore",fl],["manage",wl],["describe",_l],["reload",vl],["doctor",kl],["catalog",Sl],["adopt",El],["adopt-all",hl],["activate",gl],["deactivate",yl],["migrate",bl]],QI=yg.map(([e,t])=>e==="init"?[e,ml]:[e,t]),ZI=[...yg.map(([e,t])=>[`extension ${e}`,t]),...QI.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",qr],["config",dl],["extension",Kr],["package",Gn],["packages",Gn],["install",Tl],["create",Yr],["item mutate",Bl],["item complete",Hl],["copy",Jr],["focus",Xr],["update",Qr],["update-many",Zr],["upgrade",Al],["calendar",jn],["cal",jn],["context",qn],["ctx",qn],["get",ts],["search",is],["eval",Wl],["workspace",ht],["workspace snapshot",ht],["workspace snapshot create",ht],["workspace snapshot list",ht],["workspace snapshot inspect",ht],["workspace snapshot restore",ht],["workspace snapshot delete",ht],["next",os],["aggregate",Dr],["deps",rs],["graph",ss],["guide",ns],["reindex",Cl],["history",Ur],["history-compact",il],["history-redact",sl],["history-repair",ol],["history-author-acknowledge",Gr],["merge",rl],["schema",al],["profile",cl],["plan",jr],["restore",xl],["delete",Ol],["close",Rl],["close-many",zr],["append",Br],["claim",Il],["release",Pl],["start-task",Nl],["pause-task",Ll],["close-task",Fl],["comments",Qd],["notes",Zd],["learnings",el],["files",tl],["docs",nl],["test",Dl],["test-all",Ul],["telemetry",Gl],["test-runs",jl],["gc",ql],["stats",Hr],["duplicates",Vr],["validate",Kl],["health",Wr],["assurance",zl],["contracts",as],["completion",cs],["activity",es],...[...ug].map(e=>[e,Mr])],Hc=new Map(ZI);function ex(e){let t=_g.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function sg(e){return Kn.includes(e)?we(e):e.startsWith("extension-")?we(`extension ${e.slice(10)}`):e.startsWith("package-")?we(`package ${e.slice(8)}`):e.startsWith("test-runs-")?we(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?we(`templates ${e.slice(10)}`):Jo.has(e)?fg.get(e)??we(e):null}function tx(e,t){return e.command_path===null?!1:mt(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `))}function mt(e){return e.split("|").map(t=>we(t)).filter(t=>t.length>0)}function nx(e,t){let n=new Set(t),r=new Set;for(let s of e)if(s.command_path)for(let o of mt(s.command_path)){let i=o.split(" ").filter(a=>a.length>0);if(i.length!==0)for(let a=i.length;a>0;a-=1){let c=i.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((s,o)=>s.localeCompare(o))}function Yo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function gr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function rx(e,t){if(!t)return{...e};let r=gr(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 Kc(e,t){let r=gr(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 we(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function bg(e){return e.replace(/\s+/g,"-")}function Ye(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function og(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=Ye(r);!s||n.has(s)||(n.add(s),t.push(s))}return t}function zc(e,t,n){n&&(e[t]=!0)}function ig(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 sx(e){let t=ig(e.long,"long"),n=ig(e.short,"short"),r=t??n;if(!r)return null;let s={flag:r};n&&t&&(s.short=n),zc(s,"required",e.required===!0),zc(s,"repeatable",e.repeatable===!0),zc(s,"list",e.list===!0);let o=Ye(e.description);o&&(s.description=o);let i=Ye(e.value_name);i&&(s.value_name=i);let a=[Ye(e.value_type),Ye(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=we(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=sx(a);if(!c)continue;let m=`${c.flag}|${c.short??""}`;o.dedupe.has(m)||(o.dedupe.add(m),o.flags.push(c))}t.set(s,o)}let n=new Map;for(let[r,s]of t.entries())n.set(r,{flags:s.flags,sources:s.sources.sort((o,i)=>{let a=o.layer.localeCompare(i.layer);return a!==0?a:(o.name??"").localeCompare(i.name??"")})});return n}function ox(e){let t=wg(e.flagRegistrations),n=new Map;for(let o of e.commandDefinitions){let i=we(o.command);if(i.length===0)continue;let a=Ye(o.action)??bg(i),c=Array.isArray(o.arguments)?o.arguments.map(m=>{let u=Ye(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:Ye(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{command:i,action:a,source:{layer:o.layer,name:o.name},description:Ye(o.description),intent:Ye(o.intent),arguments:c,flags:t.get(i)?.flags??[],examples:og(o.examples),failure_hints:og(o.failure_hints)})}let r=new Set;for(let o of e.handlers)r.add(we(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(ix(o,i,t.get(o)?.flags??[]))}return s}function ix(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:bg(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function ax(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 cx(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 dx(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 lx(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]=cx(s,e.action),s.required&&r.push(s.name);for(let s of e.flags){let o=ax(s);!o||n[o]!==void 0||(n[o]=dx(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 mx(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 ux(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&&mx(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 px(e,t=A){let n={mode:pt.extensions.policy.mode,trust_mode:pt.extensions.policy.trust_mode,default_sandbox_profile:pt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=T(process.cwd(),e.path);if(!await k(C(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let s=await t(r),o=await Lr({pmRoot:r,settings:s,cwd:process.cwd(),noExtensions:!1}),i=await Fr({...o,loaded:o.loaded});return{handlers:new Set(i.commands.handlers.map(c=>we(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 fx(e,t={}){let n=new Map;for(let r of dn){let s=Jo.has(r);if(s&&!t.includePackageOwnedActions)continue;let o=sg(r);n.set(r,{action:r,provider:s?"extension":"core",requires_extension:s,command_path:o})}if(t.includePackageOwnedActions)for(let r of Jo)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:sg(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:we(r.command)});return[...n.values()].sort((r,s)=>(r.action??"").localeCompare(s.action??""))}function _x(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null};let n=e.command_path?mt(e.command_path):[],r=n.some(i=>t.handlers.has(i)),s=n.map(i=>pg.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 vg(e){return Hc.get(e)??$r}function hx(e){return hr.has(e)?!1:Hc.has(e)}function gx(e){return ug.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function ag(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function yx(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=ag(r.cli_flag);if(!s)continue;let o=r.cli_aliases.map(a=>yx(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>ag(a)).filter(a=>a!==null&&a!==s);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=o?{flag:s,short:o}:{flag:s},u=`${m.flag}|${m.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(m));for(let p of i){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,s]of t.entries())n.set(r,Oi(s.flags));return n}function cg(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 Oi(n)}function wx(e,t,n,r){return e.map(s=>{let o=hx(s),i=o?vg(s):[],a=n.get(gx(s))??[],c=t.get(s),m=cg(i,a),u=cg(m,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":o?"core":"extension";return{command:s,flags:u,...r?{canonical_command:Bc(s),visibility:eg(Bc(s)),flag_invocations:Lm(s,u)}:{},provider:p,extension_sources:c?.sources}}).sort((s,o)=>s.command.localeCompare(o.command))}function vx(e){let t=new Set(e);return hg.map(n=>({canonical:n.canonical,aliases:n.aliases.filter(r=>t.has(r))})).filter(n=>t.has(n.canonical)&&n.aliases.length>0)}function kx(){return{create_string_options:Tm,create_repeatable_options:_s,update_string_options:Am,update_repeatable_options:Cm,list_string_options:Vd,search_string_options:Wd,calendar_string_options:Yd,context_string_options:Jd,activity_string_options:Xd}}function dg(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=an(e,"create",n),s=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),o=[...new Set(s.map(a=>fe("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 Sx(e){let t={},n={};for(let r of[...e.types].sort((s,o)=>s.localeCompare(o))){let s=e.by_type[r];t[r]=dg(s,"strict"),n[r]=dg(s,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Ex(e,t){let n=gr(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 Tx(e){let t=Yo(e.action)!==void 0||Yo(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,s=e.schemaOnly===!0,o=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=Yo(e.action),u=Yo(e.command),p=!r&&!c&&!s&&!o&&!i&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:s,flagsOnly:o,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function Ax(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",d.USAGE)}async function Cx(e,t=A){try{return await t(e)}catch{return structuredClone(pt)}}async function Rx(e,t){let n=await Cx(t),r=await px(e),s=x(n,r.registrations??I()),o=Be(n.schema),i=ox(r);return{settings:n,runtimeProbe:r,typeRegistry:s,statusRegistry:G(n.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:bx(o),createRequiredOptionContracts:Sx(s),extensionContracts:i,mergedExtensionContracts:ux(i),extensionFlagMap:wg(r.flagRegistrations)}}function lg(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Jo.has(e.selectedAction)||e.selectedCommand!==void 0&&hr.has(e.selectedCommand))}function Ix(e,t){let n=fx(t,{includePackageOwnedActions:lg(e)});return lg(e)&&e.selectedCommand!==void 0&&hr.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:ex(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function xx(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new l(`Unknown action: "${e.selectedAction}".`,d.USAGE)}function Ox(e,t){return[...new Set([...Kn.filter(n=>!hr.has(n)),...[...Hc.keys()].filter(n=>!hr.has(n)),...e.flatMap(n=>n.command_path?mt(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>we(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function Px(e,t){let n=t.slice(0,JI),r=t.length-n.length,s=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),o=t.slice(0,XI),i=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new l(`Command "${e}" is a command namespace. Choose a concrete child command: ${s}.`,d.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:i,nextSteps:[`Retry with a child command, for example: ${i[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:o.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function Nx(e,t){return new l(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,d.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function Lx(e){return new l(`Unknown command: "${e}".`,d.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function Fx(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 Px(e.selectedCommand,r);let s=pg.get(e.selectedCommand);throw s?Nx(e.selectedCommand,s):Lx(e.selectedCommand)}function $x(e,t){let n=Ix(e,t.mergedExtensionContracts);xx(e,n);let r=Ox(n,t.mergedExtensionContracts);Fx(e,r);let s=e.selectedCommand?_g.get(e.selectedCommand):void 0,o=e.selectedCommand?n.filter(m=>s?m.action===s:tx(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!o.some(m=>m.action===e.selectedAction))throw new l(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,d.USAGE);let i=e.selectedAction?o.filter(m=>m.action===e.selectedAction):o,a=[...new Map(i.map(m=>_x(m,t.runtimeProbe)).map(m=>[s?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(m=>m.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:o,scopedActionDescriptors:i,selectedPackageOwnedAction:s,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function Mx(e){return new Set(gr(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 Dx(e){let t=km,n=gr(t),r=Mx(t),s=e.filter(o=>!r.has(o.action)).map(o=>lx(o));return s.length>0?{...t,oneOf:[...n,...s]}:t}function mg(e,t,n){let r=new Set(t.actionDescriptors.map(o=>o.action)),s=e.selectedAction?rx(n,e.selectedAction):e.selectedCommand?Kc(n,new Set(t.scopedActionDescriptors.map(o=>o.action))):Kc(n,r);return e.runtimeOnly&&!e.selectedAction?Kc(s,new Set(t.actions)):s}function Ux(e,t,n){let r=Dx(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?Ex(mg(e,n,r),t.createRequiredOptionContracts):mg(e,n,r);return{mergedSchema:r,filteredSchema:o}}function Gx(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?nx(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function jx(e,t){return t}function Bc(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":gg.get(t)??t}var qx=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"]]),Kx=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function zx(e,t){let n=rg.get(e)??(e.includes(" ")?void 0:rg.get(Bc(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>mt(m.command).includes(e));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let s=e.split(" "),o=s.at(-1),i=s.slice(0,-1).join(" "),a=qx.get(o),c=Kx.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function Bx(e,t=[]){return[...new Set(e.map(we))].filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r)).map(n=>{let r=Li(n,{generateFallback:!0}),s=n.split(" ")[0],o=gg.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),i=new Set([...vg(n).map(m=>m.flag),...t.filter(m=>mt(m.command).includes(n)).flatMap(m=>m.flags.map(u=>u.flag))]),a=(ng.get(n)??ng.get(o)??YI).filter(m=>i.has(m)),c=zx(n,t);return{command:n,...c,...a.length>0?{flags:a}:{},default_max_estimated_tokens:r.default_max_estimated_tokens,default_max_estimated_tokens_by_format:{...r.default_max_estimated_tokens_by_format}}})}function Hx(e){return e.map(t=>({budget:Li(t,{generateFallback:!0}),envelope:Fm(t)}))}function Vx(e){let t=new Map;for(let n of e){let r=Im(n),s=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,o=s.join(","),i=t.get(o)??{commands:[],exit_codes:s};i.commands.push(n),t.set(o,i)}return[...t.values()]}function Wx(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>mt(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(s=>mt(s.command).some(o=>r.has(o)))}return t.extensionContracts}function Yx(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 Jx(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:[...um],services:[...pm],policy_modes:[...fm],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...gm],trust_modes:[..._m],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...hm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Td],create_modes:[...Ad],close_validation_modes:[...Cd],workflow_enforcement_modes:[...Rd]},e.relationship_kind_contracts=[...Fd,...(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 Xx(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 Qx(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=wx(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let o=new Set(r);e.list_projections=Object.entries(Pp).filter(([i])=>o.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...Op],compact_fields:[...xp]}))}s.length>0&&(e.command_aliases=s)}}function Zx(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=kx();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function eO(e,t,n){e.command_summaries=Bx(t,n),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...wm],allows_unbounded_opt_out:!0}}async function kg(e,t){let n=Tx(e);Ax(n);let r=T(process.cwd(),t.path),s=await Rx(t,r),o=$x(n,s),i=Ux(n,s,o),a=Gx(n,o),c=jx(n,a),m=Yx(n,i,o,c),u=Wx(n,s,c);if((n.summary||n.fullOutput)&&eO(m,c,u),n.summary)return m;let p=vx(a);return n.flagsOnly&&!n.fullOutput||Jx(m,s,n),Xx(m,n,i,u),Qx(m,n,s,c,p),Zx(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...Ru],gate_triggers:[...Cu]}),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=Xh(),m.context_intents=xm(),m.read_output_dimensions=Fi,m.error_codes=Nm,m.command_output_contracts=Hx(c),m.command_exit_contracts={vocabulary:Rm,command_sets:Vx(c)}),m}import MO from"node:fs/promises";import Gg 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 Xo(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 tO(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,s=null,o=null,i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let u;try{u=JSON.parse(m)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(Xo(f,i,p,s,"min")&&(i=f,s=p),Xo(f,a,p,o,"max","max")&&(a=f,o=p))}return{id:e,bytes:n,lines:r,oldest_ts:s,newest_ts:o}}function Sg(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),s=e.map(({id:_,raw:h})=>tO(_,h)),o=0,i=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of s){if(o+=_.lines,i+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);Xo(h,m,_.id,a?.id??null,"min")&&(m=h,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);Xo(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 rO}from"node:crypto";import{execFile as sO}from"node:child_process";import Ag 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 Eg=1;function nO(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 Vc(e){if(e===null)return{format_version:Eg,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Eg||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!nO(r))throw new l("Improvement ledger contains an invalid observation.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aaa927b3-4bc4-561f-aff1-85dc95c12ea1")}catch{}})();var iO=oO(sO),aO=50,Tg=1e3,cO=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Cg(e){let t=e.trim().toLowerCase();if(!cO.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function dO(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function yr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return n}}function lO(e){let t=e??aO;if(!Number.isSafeInteger(t)||t<0||t>Tg)throw new l(`Improvement observation limit must be an integer from 0 to ${Tg}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Rg(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function mO(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});let r=Cg(n.metric),s=dO(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||s==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let o=await pO(e,n.revision),i=yr(n.source,"source"),a=yr(n.itemId,"itemId"),c=yr(n.unit,"unit"),m=yr(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:Rg(n.observedAt??S(),"observedAt"),...o,author:R(n.author,t.author_default),...a===void 0?{}:{item_id:a},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:rO("sha256").update(J(u)).digest("hex").slice(0,24),...u}}function uO(e,t){let n=t.idempotency_key?e.observations.find(s=>s.idempotency_key===t.idempotency_key):e.observations.find(s=>s.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(s=>s.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function pO(e,t){let n=yr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await iO("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Nd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function fO(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 Ig(e,t={}){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await mO(n,r,e),o=Ag.join(n,"improvement-ledger.json"),i=await tu({pmRoot:n,filePath:o,op:"improvement_observe",author:s.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${s.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Vc(a),m=uO(c,s);return m?{raw:a,result:m}:(c.observations.push(s),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${J(c)}
47
- `,result:s})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function xg(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=e.metric===void 0?void 0:Cg(e.metric),r=e.since===void 0?void 0:Rg(e.since,"since"),s=lO(e.limit),i=Vc(await q(Ag.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of i){let m=a.get(c.metric)??[];m.push(c),a.set(c.metric,m)}return{observations:[...i].reverse().slice(0,s),total:i.length,truncated:i.length>s,trends:[...a].map(([,c])=>fO(c)).sort((c,m)=>c.metric.localeCompare(m.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6162845d-f4b4-5d1f-a210-ddef1a5c38f6")}catch{}})();function Og(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 _O(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 hO(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 Wc(e=zn,t=pn){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 gO(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 Yc(e,t=pn,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 yO(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let s=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let u=`${c.agent_harness}\0${m}`,p=s.get(u)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),s.set(u,p)}let o=[...s.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[u])=>m.localeCompare(u)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),i=o.filter(c=>c.entries>=r),a=i.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:i.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:o,failures:a}}function 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=Og(o),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(o);continue}let u={id:a.id,...i?.label===void 0?{}:{label:i.label},...i?.parent_id===void 0?{}:{parent_id:i.parent_id},source:a.source,entries:[o],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let s=[];for(let o of n.values()){let i=o.parent_id?r.get(o.parent_id):void 0;i&&_O(o,i,r)?i.children.push(o):s.push(o)}return hO(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 wO=1e4,Pg=1e5,vO=1e3,kO=30,SO=["append","comment","docs","file","learning","note","test_run"];function EO(e){let t=e??wO;if(!Number.isSafeInteger(t)||t<1||t>Pg)throw new l(`History analytics event limit must be an integer from 1 to ${Pg}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function Ng(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",d.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function TO(e){let t=e?.trim();if(!t)return new Date(Date.now()-kO*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let s=Number(n[1]),o=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(s)||s<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-s*o).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function Lg(e,t){let n=EO(t.eventLimit),r=TO(t.since),s=[],o=r,i=!1;for(;s.length<n;){let a=await zo({pmRoot:e,since:o,limit:Math.min(vO,n-s.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(s.push(...c),i=a.has_more,o=a.next_cursor,!a.has_more)break}return{events:s,receipt:{since:r,events:s.length,truncated:i,...i?{next_cursor:o}:{},source:"history_event_index"}}}function AO(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function CO(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 RO(e){return SO.some(t=>e.startsWith(t))}function Fg(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 IO(e,t,n){let r=new Map,s=new Map,o=new Map;for(let i of t){let a=AO(i.entry,e),c=CO(i.entry),m=s.get(i.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&s.set(i.item_id,u),!a)continue;let p=Fg(r,a);p.events+=1,RO(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,o.set(i.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:o}}function xO(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&&(Fg(e,i).defectEscapes+=1)}}}function OO(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 PO(e,t,n,r,s,o){let{buckets:i,lastCloseValue:a}=IO(e,t,r);return xO(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>OO(c,m,s,o)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function NO(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 LO(e,t,n){let r=Wc(t),s=Yc(e,pn,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 $g(e,t=zn,n={}){let r=Ng(n.minimumSample);return{...LO(e.events.map(s=>s.entry),t,r),window:e.receipt}}function Mg(e,t,n,r={}){let s=Ng(r.minimumSample),o=NO(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>PO(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 FO=32;function $O(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 br(e,t){let n=$O(e).map(s=>{let[o,...i]=s.split(","),a=o.indexOf("="),c=o.slice(0,a).trim(),m=o.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${s}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,f;for(let _ of i){let h=_.indexOf("="),y=_.slice(0,h).trim(),g=_.slice(h+1).trim();if(y==="unit"&&g.length>0)p=g;else if(y==="threshold"&&g.length>0&&Number.isFinite(Number(g)))f=Number(g);else throw new l(`Invalid --measure attribute "${_}"`,d.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(s=>[s.name,s])).values()].sort((s,o)=>s.name.localeCompare(o.name)).slice(0,FO)}function Dg(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 Ug(e,t){let n=e.flatMap(o=>o.measurements??[]).filter(o=>o.name===t).sort((o,i)=>i.recorded_at.localeCompare(o.recorded_at)),r=n[0],s=n[1];return{name:t,latest:r?.value??null,previous:s?.value??null,delta:r!==void 0&&s!==void 0?r.value-s.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d28c7ac7-9801-5b0c-84c9-51deede398be")}catch{}})();function DO(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function UO(e,t,n,r,s){let o=Qn(e,"type",r),i=new Set(o.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),m=(s?[...o.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:o.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=DO([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>s||f>0));return{byType:m,byStatus:p,omitted:s?0:a.length+Object.values(u).filter(f=>f===0).length}}function GO(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function jO(e){let t=Gg.join(e,"history");if(!await k(t))return[];await un({path:t,scope:"project"});let n=(await MO.readdir(t)).filter(s=>s.endsWith(".jsonl")).sort((s,o)=>s.localeCompare(o)),r=[];for(let s of n){let o=Gg.join(t,s),i=await q(o);i!==null&&(await un({path:o,scope:"project"}),r.push({id:s.slice(0,-6),raw:i}))}return r}async function qO(e,t){let n=[],r=S();for(let s of br(t.observe,r))n.push(await Ig({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 KO(e,t,n){let r={};return t.byAssignee&&(r.assignee=Qn(e,"assignee",n)),t.byTag&&(r.tag=Qn(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=Qn(e,"priority",n)),r}async function zO(e,t,n,r,s){let o={since:s.since,eventLimit:s.eventLimit,minimumSample:s.minimumSample},i=s.provenanceCoverage||s.fleetAttribution?await Lg(e,o):void 0;return{provenanceCoverage:s.provenanceCoverage&&i?$g(i,n.agent_identity?.harness_signals,o):void 0,fleetAttribution:s.fleetAttribution&&i?Mg(i,t,r,o):void 0}}function BO(e,t,n,r,s){let o=Object.keys(s.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...s.metadataCoverage?{metadata_coverage:s.metadataCoverage}:{},...o?{breakdowns:s.breakdowns}:{},...s.storage?{storage:s.storage}:{},...s.fieldUtilization?{field_utilization:s.fieldUtilization}:{},...s.improvementLedger?{improvement_ledger:s.improvementLedger}:{},...s.recordedObservations.length>0?{recorded_observations:s.recordedObservations}:{},...s.provenanceCoverage?{provenance_coverage:s.provenanceCoverage}:{},...s.fleetAttribution?{fleet_attribution:s.fleetAttribution}:{},generated_at:S()}}async function Jc(e,t={}){let n=T(process.cwd(),e.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await qO(e,t),o=x(r,I()),i=G(r.schema),a=t.fieldUtilization?await Es(n,r.item_format,o.type_to_folder,void 0,r.schema):await re(n,r.item_format,o.type_to_folder,void 0,r.schema);await ou({pmRoot:n,settings:r,itemIds:a.map(E=>E.id),commandLabel:"stats"});let c=Js(i),m=UO(a,o.types,i.definitions.map(E=>E.id),c,t.includeEmpty===!0),u=await jO(n),p=0;for(let E of u)p+=GO(E.raw);let f=t.storage?Sg(u):void 0,_=t.metadataCoverage?Rp(a,c):void 0,h=KO(a,t,c),y=t.fieldUtilization?Ip(a):void 0,g=t.measurements===!0||s.length>0?await xg({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:b,fleetAttribution:v}=await zO(n,a,r,i.terminal_statuses,t);return BO({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:y,improvementLedger:g,recordedObservations:s,provenanceCoverage:b,fleetAttribution:v})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0e63298a-d2d7-5217-af50-a206348b4cd4")}catch{}})();function jg(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:he(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 HO from"node:fs/promises";import Ot 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 Hg=Ot.join("runtime","telemetry","events.jsonl"),Vg=Ot.join("runtime","telemetry","state.json"),VO=Ot.join("runtime","telemetry"),WO=20,qg=["status","flush","stats","clear"],Kg=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Xc=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,zg=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},YO=e=>({command:Xc(e.event.command,"<unknown>"),eventType:Xc(e.event.event_type,"unknown"),eventSchemaVersion:zg(e.event.schema_version),clientSchemaVersion:zg(e.client_schema_version)}),JO=()=>({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:{}}),XO=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},QO=e=>{let t=e?.command_resolution;return Xc(t,"")||void 0},Wg=(e,t)=>{e[t]=(e[t]??0)+1},ZO=(e,t)=>{let n=XO(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=QO(t);r!==void 0&&Wg(e.resolution_counts,r)},eP=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Bg=(e,t)=>{t!==void 0&&e.add(t)},tP=(e,t)=>{let n=YO(t),r=e.get(n.command)??JO();r.count+=1,r.max_attempts=Math.max(r.max_attempts,eP(t.attempts)),Wg(r.event_type_counts,n.eventType),Bg(r.event_schema_versions,n.eventSchemaVersion),Bg(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&ZO(r,t.event.payload),e.set(n.command,r)},nP=(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:Kg(r,.5),duration_p95_ms:Kg(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)}:{}}},rP=e=>{let t=(e??"status").trim().toLowerCase();if(qg.includes(t))return t;throw Ee({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:qg,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Qc=()=>{throw new l("--limit must be a positive integer",d.USAGE)},Yg=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Qc():e,sP=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Qc():Yg(Number.parseInt(t,10))},oP=e=>e===void 0?WO:typeof e=="number"?Yg(e):typeof e=="string"?sP(e):Qc(),iP=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},aP=e=>{try{let t=JSON.parse(e);return iP(t)?t:void 0}catch{return}},cP=e=>e===null?[]:e.split(`
48
- `).map(t=>t.trim()).filter(t=>t.length>0),Jg=e=>{let t=cP(e),n=[],r=0;for(let s of t){let o=aP(s);o===void 0?r+=1:n.push(o)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},dP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lP=e=>{try{let t=JSON.parse(e);return dP(t)?t:{}}catch{return{}}},mP=async e=>{let t=await q(e);return t===null||t.trim().length===0?{}:lP(t)},Qo=e=>e??null,Zo=async e=>{let t=await A(e),n=Ot.join(e,Hg),r=Ot.join(e,Vg),s=await q(n),o=Jg(s),i=await mP(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:Qo(i.last_attempted_flush_at),last_successful_flush_at:Qo(i.last_successful_flush_at),last_failed_flush_at:Qo(i.last_failed_flush_at),last_failed_flush_error:Qo(i.last_failed_flush_error)}},uP=e=>{let t=new Map;for(let n of e)tP(t,n);return[...t.entries()].map(([n,r])=>nP(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},pP=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Zo(t.globalPmRoot),generated_at:S()}),fP=async(e,t)=>{let n=await Zo(t.globalPmRoot);await wu(t.globalPmRoot);let r=await Zo(t.globalPmRoot),s=Math.max(0,n.queue_entries-r.queue_entries),o=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:s,queue_progressed:s>0,queue_empty:o,queue_drained:o,status:r,generated_at:S()}},_P=async(e,t)=>{let n=oP(e.limit),r=await q(t.queuePath),s=Jg(r),o=uP(s.entries),i=o.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:o.length,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_rows_total:s.rows_total,truncated:o.length>i.length,stats:i,generated_at:S()}},hP=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 Se(t.globalPmRoot,n,"telemetry:clear");let s=Ot.join(t.globalPmRoot,VO),o=await k(s);return await HO.rm(s,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:o&&!await k(s),queue_exists_after:await k(t.queuePath),state_exists_after:await k(t.statePath),status:await Zo(t.globalPmRoot),generated_at:S()}},gP={status:pP,flush:fP,stats:_P,clear:hP};async function Xg(e,t){let n=rP(e.subcommand),r=et(process.cwd());return gP[n](e,{globalPmRoot:r,queuePath:Ot.join(r,Hg),statePath:Ot.join(r,Vg)})}import{spawn as hy}from"node:child_process";import{cp as ny,mkdir as kP,mkdtemp as gy,open as nd,readdir as rd,rm as yy}from"node:fs/promises";import{tmpdir as by}from"node:os";import le 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 Qg=20;function yP(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return Qg;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?Qg:t}function Zc(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=_n(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=yP();return t.length>n?t.slice(t.length-n):t}async function ei(e){await Y({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=Zc([...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 Zg=100;function ed(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,d.USAGE);return n}function bP(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Zg?n:`${n.slice(0,Zg-3)}...`}function ey(e){return e.map((t,n)=>`${n+1}. ${bP(t)}`).join("; ")}function wP(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 ty(e,t){let n=wP(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((s,o)=>o+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(s=>`--${s}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,d.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,d.USAGE);if(r==="match"){let s=t.match.trim().toLowerCase();if(s.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let o=[],i=[];for(let a=0;a<e.length;a+=1)vP(e[a],s)&&(i.push(e[a]),o.push(a+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${ey(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:o,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let s=ed(t.onlyIndex);if(s>e.length)throw new l(`--only-index ${s} is out of range: this item has ${e.length} linked test(s). Available entries: ${ey(e)}`,d.USAGE);return{selector:"only-index",requested:String(s),selected:[e[s-1]],selected_indexes:[s],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4322c352-6b95-5796-94eb-5a68745d53bc")}catch{}})();var ni=20*1024*1024,SP=3e3,EP=1e4,TP=5e3,ry=120,AP=new Set(["locks","extensions","runtime"]),CP=new Set(["history","index","search","extensions","locks","runtime"]),RP=[/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],IP=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,xP=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,OP=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 id(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 PP(){return id("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",SP)}function NP(){return id("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",EP)}function LP(){return id("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",TP)}function FP(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 $P(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 ad(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 MP(e){let t=e??"project";if(!Ze.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function ri(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Vt.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${Vt.join(", ")}`,d.USAGE)}function wy(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:ri(e.pm_context_mode)}function vy(e,t){return e==="auto"?t?"tracker":"schema":e}function DP(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 UP(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 GP(e,t){let n={};if(!e)return n;for(let r of e){let s=sr(r,t);if(s)for(let[o,i]of Object.entries(s))n[o]=i}return n}function jP(e,t){if(!e)return[];let n=[];for(let r of e){let s=or(r,t);s&&n.push(...s)}return[...new Set(n)]}function qP(e){let t=si(e);return Jn(t).some(n=>aa(n)!==null)}function ky(e){let t=si(e);return Jn(t).some(n=>{let r=aa(n);if(!r)return!1;let s=Tp(r);return s?OP.has(s.subcommand):!1})}function ti(e){if(e)return kp.has(e.subcommand)?Tn(e.args,Sp)?.subcommand:e.subcommand}function sy(e,t){if(e==="npx"||e==="bunx")return Ws(t)?.command;if(e==="pnpm")return ti(Tn(t,yp));if(e==="npm")return ti(Tn(t,bp));if(e==="yarn")return ti(Tn(t,wp));if(e==="bun")return ti(Tn(t,vp))}function oy(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function td(e){return!e||!da(e.command)&&!Ep(e.command)?!1:Vs(e.args)==="test-all"}var KP=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])]),zP=new Set(["npx","bunx"]);function Sy(e){let t=e.split(" ").filter(i=>i.length>0),n=ca(t);if(n.length===0)return!1;let[r,...s]=n,o=KP.get(r);if(o){let i=s.findIndex(a=>o.test(a));return i>=0?Sy(s.slice(i+1).join(" ")):!1}return da(r)||la(r)?Vs(s)==="test-all":r==="node"&&s.length>0&&la(s[0])?Vs(s.slice(1))==="test-all":zP.has(r)?td(Ws(s)):r==="pnpm"?td(ma(s)):r==="npm"?td(ua(s)):!1}function Ey(e){let t=si(e);return Jn(t).some(n=>Sy(n))}function Ty(e){if(Ey(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function si(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function BP(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 HP(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 VP(e){let t=e.split(" ").filter(o=>o.length>0),n=ca(t);if(n.length===0)return!1;let[r,...s]=n;return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?WP(s):YP(r,s)}function WP(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function YP(e,t){return e==="npx"||e==="bunx"?oy(Ws(t)?.command):e==="pnpm"||e==="npm"?oy((e==="pnpm"?ma(t):ua(t))?.command)||sy(e,t)==="vitest":(e==="yarn"||e==="bun")&&sy(e,t)==="vitest"}function Ay(e){let t=si(e);if(Jn(t).some(s=>!BP(s)&&VP(s)&&!HP(s)))throw new l('Linked test runner commands must be sandbox-safe: use "node scripts/run-tests.mjs <test|coverage>", use a package-manager script such as "pnpm test", or include PM_PATH=... PM_GLOBAL_PATH=... INLINE in the command string (exporting them in your shell environment is not checked). Example: "PM_PATH=/tmp/pm-x PM_GLOBAL_PATH=/tmp/pm-x-g vitest run".',d.USAGE)}function JP(e){if(Ey(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function XP(e){return e?e.map(QP):[]}function QP(e){let t=e.trim(),n=bo(t)?wo(te(e,"--add"),"--add"):{command:t},r=de(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return Ty(r),Ay(r),{command:r,path:de(n.path),scope:MP(n.scope),timeout_seconds:ZP(de(n.timeout_seconds),de(n.timeout)),pm_context_mode:To(de(n.pm_context_mode),"--add"),env_set:sr(de(n.env_set),"--add"),env_clear:or(de(n.env_clear),"--add"),shared_host_safe:Eo(de(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Yt(de(n.assert_stdout_contains)),assert_stdout_regex:xn(de(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Yt(de(n.assert_stderr_contains)),assert_stderr_regex:xn(de(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Ao(de(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Co(de(n.assert_json_field_equals),"--add"),assert_json_field_gte:Ro(de(n.assert_json_field_gte),"--add"),note:de(n.note)}}function de(e){let t=e?.trim();return t&&t.length>0?t:void 0}function ZP(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",d.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(se(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function eN(e){return e?e.flatMap(t=>{let n=bf(t,"--add-json");for(let r of n){let s=r.command;if(!s)throw new l("--add-json requires a non-empty command string",d.USAGE);Ty(s),Ay(s)}return n}):[]}function tN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",d.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let s=n.slice(r[0].length).trim();if(!s)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:s}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let s=te(n,"--remove"),o=s.path!==void 0?"path":"command",i=s.path??s.command;if(!i?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:o,value:i.trim()}}return{kind:"either",value:n}}):[]}function nN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function rN(e){try{e.stdin?.end()}catch{}}function Cy(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=ry?t:`${t.slice(0,ry-3)}...`}function Ry(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function sd(e){try{process.stderr.write(`${e}
49
- `)}catch{}}function sN(e,t){if(!Ry(t))return null;let n=Cy(e.command),r=Date.now();sd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let s=setInterval(()=>{let o=Date.now()-r;sd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${o} command="${n}"`)},NP());return s.unref?.(),s}function oN(e,t,n,r){if(!Ry(r))return;let s=Cy(e.command),o=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let m=t.exitCode===null?"null":String(t.exitCode),u=c.length>0?` ${c.join(" ")}`:"";sd(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${o}${u} command="${s}"`)}async function iy(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=hy("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 iN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function aN(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 iy(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{iy(r)},PP()),t.forceKillTimer.unref?.()}}function cN(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)},LP()),r.unref?.())}),e.on("close",(o,i)=>{s({code:o,signal:i})})})}function dN(e,t,n,r){return hy(e,{cwd:process.cwd(),env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function ay(e){let t=await nd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,ni),s=Buffer.alloc(r);return r>0&&await t.read(s,0,r,0),{text:s.toString("utf8"),truncated:n>ni}}finally{await t.close()}}async function lN(e,t,n,r,s){let o=Date.now(),i=await gy(le.join(by(),"pm-linked-test-output-"));try{let a=le.join(i,"stdout.log"),c=le.join(i,"stderr.log"),[m,u]=await Promise.all([nd(a,"w"),nd(c,"w")]),p;try{p=dN(e,n,m.fd,u.fd)}finally{await Promise.all([m.close(),u.close()])}rN(p);let f={heartbeat:sN(r,s),forceKillTimer:null,timedOutTimer:null},_=aN(p,f),h=!1,y;p.on("error",U=>{y=U.message}),f.timedOutTimer=setTimeout(()=>{h=!0,_()},t),f.timedOutTimer.unref?.();let{code:g,signal:b}=await cN(p);iN(f);let[v,E]=await Promise.all([ay(a),ay(c)]),N=v.truncated||E.truncated,P=N?`
50
- [pm linked-test output truncated at ${ni} bytes per stream; the child process continued to completion]
51
- `:"",$={stdout:`${v.text}${P}`,stderr:E.text,exitCode:g,signal:b,timedOut:h,maxBufferExceeded:!1,outputTruncated:N,spawnError:y};return oN(r,$,o,s),$}finally{await yy(i,{recursive:!0,force:!0})}}function mN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${ni} 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 uN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
52
- `);return RP.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>IP.test(n)&&xP.test(n))}function pN(e){return uN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function fN(){return{infra_collision:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function oi(e){let t=fN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function cy(e,t){for(let[n,r]of Object.entries(t.env_set))Wt.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)Wt.has(n.toUpperCase())||delete e[n]}function _N(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 hN(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 gN(e,t,n){return{env_set:GP(e,"--env-set"),env_clear:jP(t,"--env-clear"),shared_host_safe:n===!0}}async function Mn(e,t,n=!1,r=kP){if(await k(e))try{await Bo("seed_linked_test",async()=>{if(await r(le.dirname(t),{recursive:!0}),n){await ny(e,t,{recursive:!0,force:!0});return}await ny(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&&_t(s))return;throw s}}async function dy(e,t,n){await Mn(C(n.projectPmRoot),C(e)),await Mn(le.join(n.projectPmRoot,"extensions"),le.join(e,"extensions"),!0),await Mn(C(n.globalPmRoot),C(t)),await Mn(le.join(n.globalPmRoot,"extensions"),le.join(t,"extensions"),!0)}async function ly(e,t){if(!await k(e))return;let n=await rd(e,{withFileTypes:!0});for(let r of n){if(AP.has(r.name))continue;let s=le.join(e,r.name),o=le.join(t,r.name);if(r.isDirectory()){await Mn(s,o,!0);continue}r.isFile()&&await Mn(s,o)}}async function $n(e){if(!await k(e))return 0;let t=0,n=await rd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||CP.has(r.name))continue;let s=le.join(e,r.name),o;try{o=await rd(s,{withFileTypes:!0})}catch{continue}for(let i of o)i.isFile()&&Pd.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function yN(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 my(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 wN(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?tt(e,t):Object.is(e,t)}function kN(e,t,n){let r=[];r.push(...uy("stdout",t,e.assert_stdout_contains)),r.push(...py("stdout",t,e.assert_stdout_regex)),r.push(...uy("stderr",n,e.assert_stderr_contains)),r.push(...py("stderr",n,e.assert_stderr_regex)),r.push(...SN(t,e.assert_stdout_min_lines));let s=e.assert_json_field_equals??{},o=e.assert_json_field_gte??{};if(!(Object.keys(s).length>0||Object.keys(o).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,m]of Object.entries(s)){let u=my(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=wN(m);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,m]of Object.entries(o)){let u=my(a,c);if(!u.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof u.value!="number"||!Number.isFinite(u.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}u.value<m&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${m}, actual ${u.value})`)}return r}function uy(e,t,n){let r=[];for(let s of n??[])t.includes(s)||r.push(`${e} missing required text: "${s}"`);return r}function py(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 SN(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 EN=[{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 TN(e,t){let n=`${e}
53
- ${t}`;for(let r of EN)if(r.regex.test(n))return r.code;return null}function AN(e){return{root:e,schemaProjectPmPath:le.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:le.join(e,"schema","global"),trackerProjectPmPath:le.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:le.join(e,"tracker","global")}}async function CN(e,t=lr,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 RN(e,t,n){t&&(await dy(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await dy(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await ly(t.projectPmRoot,e.trackerProjectPmPath),await ly(t.globalPmRoot,e.trackerGlobalPmPath)))}function IN(e,t,n){return e.some(r=>{let s=r.command??"",o=s.length>0&&ky(s),i=n?.autoPmContext===!0&&o?"auto":wy(r,t,n?.overrideLinkedPmContext===!0);return vy(i,o)==="tracker"})}async function xN(e,t){return{sourceProjectItemCount:t?await $n(t.projectPmRoot):0,sourceGlobalItemCount:t?await $n(t.globalPmRoot):0,schemaProjectItemCount:await $n(e.schemaProjectPmPath),schemaGlobalItemCount:await $n(e.schemaGlobalPmPath),trackerProjectItemCount:await $n(e.trackerProjectPmPath),trackerGlobalItemCount:await $n(e.trackerGlobalPmPath)}}function ON(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 PN(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?ri(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?qP(n):!1,s=r&&n?ky(n):!1,o=e.options?.autoPmContext===!0&&s,i=o?"auto":wy(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=vy(i,s);return{linkedOverridePmContextMode:t,executionContext:ON({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:s,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:o})}}function fy(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function od(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 NN(e){if(!e.linkedTest.command)return fy(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=JP(e.linkedTest.command);if(t)return fy(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=UP({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 od(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&&!DP(e.linkedTest)?od(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function LN(e){let t=hN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return cy(n,e.runtimeDirectives),cy(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&_N(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[Bs]="read_only",n}function FN(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 $N(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 MN(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:yN(e.execution),failure_category:pN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:mN(e.execution,e.timeoutMs)}}function DN(e){if(e.options?.failOnEmptyTestRun===!0){let n=TN(e.execution.stdout,e.execution.stderr);if(n)return $N({...e,emptyRunSignal:n})}let t=kN(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?od(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):FN(e.linkedTest,e.executionContext,e.execution)}async function UN(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await lN(t,n,LN(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?DN({...e,execution:r}):MN({...e,execution:r,timeoutMs:n})}async function cd(e,t,n){let r=[],s=await gy(le.join(by(),"pm-linked-test-")),o=AN(s),i=ri(n?.pmContext),a=n?.progress===!0?"always":"auto",c=gN(n?.envSet,n?.envClear,n?.sharedHostSafe),m=n?.sourceRoots,u=IN(e,i,n);try{await CN(o,lr,u),await RN(o,m,u);let p=await xN(o,m);for(let f=0;f<e.length;f+=1){let _=e[f],h=PN({linkedTest:_,layout:o,counts:p,sourceRoots:m,runLevelPmContextMode:i,options:n}),y=NN({linkedTest:_,executionContext:h.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:h.linkedOverridePmContextMode,options:n});if(y){r.push(y);continue}r.push(await UN({linkedTest:_,index:f,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:c,progressMode:a,executionContext:h.executionContext,options:n}))}}finally{await yy(o.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function GN(e){let{id:t,pmRoot:n,settings:r,typeToFolder:s}=e,o=await M(n,t,r.id_prefix,r.item_format,s);if(!o)throw new l(`Item ${t} not found`,d.NOT_FOUND);let i=await K(o,{schema:r.schema});return{itemId:o.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function jN(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode}function qN(e,t){let n=[...e];for(let r of t)n.some(s=>jN(s,r))||n.push(r);return n}function KN(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 zN(e,t,n,r){return KN(qN(e,t),n,r)}function BN(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 HN(e){if(BN(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",d.USAGE)}async function VN(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 GN({id:t,pmRoot:r,settings:s,typeToFolder:o});let m=0,u=await Y({pmRoot:r,settings:s,id:t,op:i.length>0?"tests_add":"tests_remove",author:R(n.author,s.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=zN(f,i,a,c);if(m=_.removed,(a.length>0||c.length>0)&&m===0)throw new l("No linked tests matched the requested removal selector",d.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return p.metadata.tests=_.tests,{changedFields:tt(f,_.tests)?[]:["tests"]}}});return{itemId:u.item.id,tests:u.item.tests??[],testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:m}}function WN(e,t){HN(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:ed(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?ty(t,n):void 0,s=e.timeout===void 0?void 0:se(e.timeout,"timeout");if(s!==void 0&&s<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:s,pmContextMode:ri(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function YN(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await cd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,sourceRoots:{projectPmRoot:r,globalPmRoot:et(process.cwd())}})}function JN(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=ad(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 XN(e){let t=$P(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),s=S(),o=br(e.options.measure,s);return{run_id:FP("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 QN(e){let{options:t,pmRoot:n,settings:r,itemId:s,runStartedAt:o,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!o)return;let m=XN({options:t,runStartedAt:o,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return m;try{return await ei({pmRoot:n,settings:r,itemId:s,author:R(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),m}catch(u){return c.push(`test_result_tracking_failed:${s}:${u instanceof Error?u.message:String(u)}`),m}}function _y(e,t,n){let r;if(e.metricBelow!==void 0){let s=e.metricBelow.indexOf("="),o=e.metricBelow.slice(0,s).trim(),i=e.metricBelow.slice(s+1).trim(),a=Number(i);if(s<=0||o.length===0||i.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",d.USAGE);r=Dg(t,o,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Ug(t,e.metricDiff)}}async function ii(e,t,n){let r=Ne(),s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);br(t.measure,"validation"),_y(t,[],void 0);let i=x(o,I()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...XP(a),...eN(c)],p=tN(m),f=nN(t.removeIndex),_=await VN({id:e,options:t,pmRoot:s,settings:o,typeToFolder:i.type_to_folder,adds:u,removes:p,removeIndexes:f}),h=WN(t,_.tests),y=t.run===!0?S():void 0,g=await YN({options:t,runOptions:h,pmRoot:s}),b=oi(g),v=t.run===!0&&t.failOnSkipped===!0&&g.some(U=>U.status==="skipped"),E=JN(t,h.runSelection,g),N=await QN({options:t,pmRoot:s,settings:o,itemId:_.itemId,runStartedAt:y,runResults:g,failOnSkippedTriggered:v,warnings:E}),P=N?Zc([..._.testRuns,N]):_.testRuns,$=_y(t,P,N);return{ok:g.every(U=>U.status!=="failed")&&v!==!0,id:_.itemId,tests:_.tests,run_results:g,failure_categories:b,selection:h.runSelection?{selector:h.runSelection.selector,requested:h.runSelection.requested,selected_indexes:h.runSelection.selected_indexes,selected_count:h.runSelection.selected_count,skipped_count:h.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:v?!0:void 0,warnings:E.length>0?E:void 0,changed:_.changed,count:_.tests.length,..._.removed>0?{removed:_.removed}:{},...$}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7fea0ecb-35e2-5d40-931f-ffdd1a465fdc")}catch{}})();var ZN=(e,t)=>{if(e===void 0)return;let n=ne(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},eL=e=>{if(e===void 0)return;let t=se(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},Iy=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,d.USAGE);return n},tL=e=>e instanceof Error?e.message:String(e),nL=()=>{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)}`},rL=e=>e.trim().replaceAll(/\s+/g," "),sL=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))),iL=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},ai=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),xy=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),aL=e=>typeof e=="number"?e:void 0,cL=e=>{let t={assert_stdout_contains:ai(e.assert_stdout_contains),assert_stdout_regex:ai(e.assert_stdout_regex),assert_stderr_contains:ai(e.assert_stderr_contains),assert_stderr_regex:ai(e.assert_stderr_regex),assert_stdout_min_lines:aL(e.assert_stdout_min_lines),assert_json_field_equals:xy(e.assert_json_field_equals),assert_json_field_gte:xy(e.assert_json_field_gte)};return JSON.stringify(t)},dL=e=>{let t=dd(e.command);return t!==void 0?`command:${e.scope}:${rL(t)}`:`path:${e.scope}:${dd(e.path)??""}`},Oy=e=>{let t=sL(e.env_set),n=oL(e.env_clear),r=iL(e.pm_context_mode),s=e.shared_host_safe===!0?"true":"false",o=cL(e);return`${dL(e)}:${t}:${n}:${r}:${s}:${o}`},lL=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,mL=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}},uL=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},ci=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
54
- `)}catch{}},pL=async(e,t,n)=>{let r=[],s=0;for(let o of e){let i=await ii(o.id,{run:!1},{...t,path:n});s+=i.tests.length,r.push({item:o,tests:i.tests})}return{itemTests:r,linkedTests:s}},fL=async e=>{let t=G(e.settings.schema),n=x(e.settings,I()),r=ZN(e.options.status,t),s=Iy(e.options.limit,"--limit"),o=Iy(e.options.offset,"--offset")??0,a=(await re(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(m=>r?m.status===r:!0).sort((m,u)=>m.id.localeCompare(u.id));return{filteredItems:s===void 0?a.slice(o):a.slice(o,o+s),statusFilter:r,limitFilter:s,offsetFilter:o}},_L=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let s=Oy(r);if(!t.has(s)){t.set(s,r.timeout_seconds);continue}t.set(s,lL(t.get(s),r.timeout_seconds))}return t},hL=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=Oy(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 cd(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=mL(i),c=oi(i),m=await bL(e,a,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:m,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:i,failure_categories:c}}},gL=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),yL=e=>e?!0:void 0,bL=async(e,t,n)=>{if(!n.trackingEnabled)return[];try{let r=gL(t,n.options);await ei({pmRoot:n.pmRoot,settings:n.settings,itemId:e.item.id,author:n.trackingAuthor,message:`Track test-all run summary (${n.trackingRunId})`,entry:{run_id:n.trackingRunId,kind:"test-all",status:r?"failed":"passed",started_at:n.runStartedAt,finished_at:S(),recorded_at:S(),attempt:n.trackingAttempt,resumed_from:n.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:yL(n.options.failOnSkipped===!0&&t.skipped>0)}})}catch(r){return[`test_result_tracking_failed:${e.item.id}:${tL(r)}`]}return[]},wL=()=>{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},dd=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:et(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:_L(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:R(e.options.author,e.settings.author_default),trackingRunId:nL(),trackingAttempt:wL(),trackingResumedFrom:dd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),kL=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:oi([]),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}},SL=async(e,t,n)=>{for(let[r,s]of e.entries()){ci(t.options,`item ${r+1}/${e.length} start id=${s.item.id} linked_tests=${s.tests.length}`);let o=await hL(s,t);uL(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),ci(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}`)}},EL=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(s=>s.run_results),r=ad(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}`)},TL=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}),AL=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(" "),CL=async(e,t)=>{let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await fL({pmRoot:n,settings:r,options:e}),o=eL(e.timeout),i=S(),a=await pL(s.filteredItems,t,n);return ci(e,AL({...s,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:s.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:o,runStartedAt:i}},RL=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}},Py=async(e,t)=>{let n=await CL(e,t),{accumulation:r,failOnEmptyTestRunTriggered:s}=kL(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 SL(n.itemTests,o,r),EL(e,r);let i=RL({options:e,accumulation:r,failOnEmptyTestRunTriggered:s});return ci(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),TL({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]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function Ny(e){return us("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]="2643d11d-befc-5a87-8bec-760951eec4d0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2567f6a-cd1c-56b5-a93d-41e92ed574bf")}catch{}})();function Ly(){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]="e791d84f-7d4c-59fa-9644-527109dbb596")}catch{}})();var $y=[{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-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-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-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"]}],Fy=new Map;for(let e of $y){Fy.set(e.id,e);for(let t of e.aliases)Fy.set(t,e)}function ld(){return $y.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]="c337a436-ac3e-5447-9c76-de9aeebb2a1c")}catch{}})();var hz=[...Tr],gz=[...Ar],yz=tg("full"),bz=F(Mr),wz=F(Dr),vz=F(Br),kz=F(Jr),Sz=F(Xr),Ez=F($l),Tz=F(Ml),Az=F(Yr),Cz=F(ts),Rz=F(Qr),Iz=F(Zr),xz=F(zr),Oz=F(es),Pz=F(Ur),Nz=F(Gr,!1),Lz=F(Vl),Fz=F(jn),$z=F(qn),Mz=F(os),Dz=F(rs),Uz=F(Vr),Gz=F(ss),jz=F(ns),qz=F(is),Kz=F(Hr),zz=F(Wr),Bz=F(qr),Hz=F(as),Vz=F(jr);var IL=F(cs),Wz=`${IL} bash zsh fish`,Yz=xL(ld());var Jz=F(Kr),Xz=F(Gn);var Qz=$r.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function xL(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0224a672-e326-5555-a4b4-1fa3550d9e61")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8f02f498-5cee-59fa-9f4e-fd882c58d401")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bedbe090-60c3-5935-a656-da4997cd80f7")}catch{}})();var Gy=Symbol("pm.active-extension-host-context");function Re(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[Gy]=!0,n}run(t,n={}){return jy({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Mp(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options: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,...Re({...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",Re(t))}update(t,n={}){return this.runTyped("update",{id:t,...Re(n)})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Re(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Re(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Re(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Re(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Re(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Re(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},...Re(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Re(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Re(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Re(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 PL(e={},t={}){return new j(t).context(e)}function NL(e={},t={}){return new j(t).list(e)}function LL(e,t={},n={}){return new j(n).search(e,t)}function FL(e,t={},n={}){return new j(n).get(e,t)}function $L(e={},t={}){return new j(t).next(e)}function ML(e={},t={}){return new j(t).aggregate(e)}function DL(e,t={},n={}){return new j(n).comments(e,t)}function UL(e,t={},n={}){return new j(n).notes(e,t)}function GL(e,t={},n={}){return new j(n).learnings(e,t)}function jL(e,t={},n={}){return new j(n).files(e,t)}function qL(e,t={},n={}){return new j(n).filesDiscover(e,t)}function KL(e,t={},n={}){return new j(n).docs(e,t)}function zL(e,t={},n={}){return new j(n).deps(e,t)}function BL(e,t={},n={},r={}){return new j(r).graph(e,t,n)}function HL(e,t,n={},r={}){return new j(r).append(e,t,n)}function VL(e={},t={}){return new j(t).create(e)}function WL(e,t={},n={}){return new j(n).update(e,t)}function YL(e,t,n={},r={}){return new j(r).close(e,t,n)}function JL(e,t={},n={}){return new j(n).claim(e,t)}function XL(e={},t={}){return new j(t).claimNext(e)}function QL(e,t={},n={}){return new j(n).release(e,t)}function ZL(e,t={},n={}){return new j(n).copy(e,t)}function eF(e,t={},n={}){return new j(n).delete(e,t)}function tF(e,t,n={},r={}){return new j(r).restore(e,t,n)}function nF(e,t={},n={}){return new j(n).focus(e,t)}function Je(e,t){let n=w(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}var My=$m(),rF=new OL;function di(){Ui(Ud()),Gi(Gd()),ji(jd()),qi(qd()),Ki(Kd()),zi(zd()),Bi(Bd())}async function sF(e,t,n,r){return Mm(()=>t===void 0?My.read(()=>Dy(e,n,r)):My.write(()=>iF(t,()=>Dy(e,n,r))))}async function Dy(e,t,n){let r=T(t,e.path);if(e.noExtensions)return di(),Ea({pmRoot:r},()=>n(null));if(!await k(C(r)))return di(),n(null);let s=null,o;try{let i=await A(r),a=await Lr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Fr({...a,loaded:a.loaded});o={loadResult:a,activationResult:c},Ui(c.hooks),Gi(c.commands),ji(c.parsers),qi(c.preflight),Ki(c.services),zi(c.renderers),Bi(c.registrations),s={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){di(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Ea({pmRoot:r,packages:s?.packages},()=>n(s))}finally{di(),o&&await Hd(o.loadResult,o.activationResult).catch(()=>{})}}async function oF(e,t,n,r,s){if(!s)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let o=qt(e),a=s.registrations.commands.find(m=>qt(m.action)===o)?.command??s.commands.handlers.find(m=>qt(m.command)===o)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=await gs({command:na(a),args:he(n.args??t.args),options:ra(t,n),global:r,pm_root:s.pmRoot,sdk:jp(s.pmRoot,j.forActiveExtensionHost({pmRoot:s.pmRoot,author:typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension"}))});if(!c.handled){let m=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${m}`,d.USAGE)}return c.result}async function iF(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var aF=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function cF(e){let t=Je(e,"action"),n=qt(t),r=mi(Up,n),s=r?.action??n,o={...e,action:s};return r?.options!==void 0&&(o.options={...r.options,...xi(e.options)}),s==="package"&&(o.options={...xi(o.options),vocabulary:"package"}),{action:s,args:o}}function dF(e){return!aF.has(qt(e))}async function jy(e){let t=cF(e),n=Zi(t.args),r=dF(t.action),s=w(t.args,"cwd"),o=s??process.cwd();try{return e[Gy]===!0||rF.getStore()===!0?await Uy(t.action,t.args,n,null):await sF(n,s,o,i=>Uy(t.action,t.args,n,i))}finally{r&&wa()}}function mi(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function li(e){return w(e.args,"target")??w(e.options,"target")}function W(e,t=e.options){return e.id??Je(t,"id")}async function lF(e){let t=ln("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),ba(await Et(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function mF(e){let t=ln("search",e.options);return t.compact===void 0&&t.full===void 0&&t.fields===void 0&&(t.compact=!0),ba(await er(Je(e.args,"query"),t,e.global),t)}async function uF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options);return st(await At(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function pF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(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 st(await mc(W(e,s),s,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function fF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options);return st(await at(W(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function _F(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options),s=w(e.args,"reason")??w(e.args,"text")??w(r,"reason")??w(r,"text");return st(await Tt(W(e,r),s,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function hF(e){let t=ro(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")),rf(W(e),t,e.global)}function qy(e,t){return gp(Yh(e.options,t,Le),e.global)}function gF(e){let t=he(e.options.lookupPath);if(t&&t.length>0)return qy(e,t);let n=W(e);return e.options.discover===!0?ia(n,ta(e.options),e.global):hp(n,Ks(e.options),e.global)}function yF(e){return Xg({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:Fu(e.args,e.options)},e.global)}function bF(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),fp(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 l("Missing required argument: configAction",64);return T_(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 vF(e){let t=e.options;return Au(Tu(t),e.global)}function kF(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}function SF(e){let t=w(e.args,"subcommand")??Je(e.options,"subcommand"),n=e.options;return r_({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:EF(e),reorderTo:kF(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function EF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function TF(e){let t=w(e.args,"subcommand")??Je(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:he(n)}}function AF(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,a=mi({list:()=>Qu(t.global),show:()=>Zu(r,t.global),"show-status":()=>ep(r,t.global),"list-fields":()=>rp(t.global),"show-field":()=>sp(r,t.global),"remove-type":()=>Wu(r,{author:s,force:o},t.global),"remove-field":()=>np(r,{author:s,force:o},t.global),"remove-status":()=>Xu(r,{author:s,force:o},t.global),"apply-preset":()=>op(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:s,force:o},t.global)},n);return a?a():null}function CF(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 tp(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:he(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:he(a),author:r,force:s},t.global)}function RF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e,i=t.args.role??t.options.role;return Ju(n,{role:i===void 0?void 0:he(i),alias:o,description:w(t.args,"description")??w(t.options,"description"),order:Le(t.args.order??t.options.order,"schema add-status order"),author:r,force:s},t.global)}function IF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e;return Vu(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 xF(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,i=w(t.args,"to")??Je(t.options,"to"),a=w(t.args,"migrationId")??w(t.args,"migration_id")??w(t.options,"migrationId")??w(t.options,"migration_id"),c=w(t.args,"fieldTypeScope")??w(t.options,"fieldTypeScope")??w(t.args,"type")??w(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:i}:n==="rename-field"?{kind:"rename-field",from:r??"",to:i,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:i};return Bu(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:s,force:o},t.global)}function OF(e){let t=TF(e),n=AF(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return xF(t);if(t.subcommand==="add-field")return CF(t);if(t.subcommand==="add-status")return RF(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?ip({minCount:Le(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):IF(t);throw Ee({command_path:"schema",token:t.subcommand,allowed:Hu,exit_code:64})}function PF(e){let t=w(e.args,"subcommand")??Je(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),o=mi({list:()=>Dh(),show:()=>Uh(r),lint:()=>Gh(r),apply:()=>jh(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 Ee({command_path:"profile",token:t,allowed:Mh,exit_code:64});return o()}async function NF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options);return st(await Kp(W(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function LF(e){let{changedFields:t,runnerOptions:n}=Ve(e.args,e.options);return st(await Bf(oa(n),e.global),{changedFields:t})}async function FF(e){let{changedFields:t,runnerOptions:n}=Ve(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),st(await nf(sa(s),e.global),{changedFields:t})}async function $F(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options),s=w(r,"target")??Je(e.args,"target");return st(await zt(W(e,r),s,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Ky(e){let t={...e};return delete t.assignee,t}async function MF(e){let t=T(process.cwd(),e.global.path),n=await A(t),r=Ny(G(n.schema)),s=W(e),o=await oo(s,e.force,e.global,e.options),i=await at(s,{...Ky(e.options),status:r,force:e.force},e.global);return{id:s,action:"start_task",claim:o,update:i}}async function DF(e){let t=T(process.cwd(),e.global.path),n=await A(t),r=W(e),s=G(n.schema).open_status,o=await at(r,{...Ky(e.options),status:s,force:e.force},e.global),i=await io(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:o,release:i}}async function UF(e){let t=W(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await Tt(t,n,{...e.options,force:e.force},e.global),s=await io(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:s}}function GF(e){let t={...e.args,...e.options};return Ou(Je(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),Du(t),e.global)}function jF(e){return Gu(T(process.cwd(),e.global.path),{...e.args,...e.options})}var qF={init:e=>lr(w(e.args,"prefix"),e.global,e.options),context:e=>ha(ln("context",e.options),e.global),next:e=>Zn(ln("next",e.options),e.global),eval:Ah,events:Ch,merge:Rh,workspace:Ih,meet:Vo,event:Vo,remind:Vo,list:lF,get:e=>ga(W(e),e.global,ln("get",e.options)),search:mF,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:he(e.options.status);return ya(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:Le(e.options.limit,"limit")})},create:uF,copy:pF,focus:e=>pc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:fF,restore:$F,claim:e=>e.options.next===!0||e.args.next===!0?Jp(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):oo(W(e),e.force,e.global,e.options),release:e=>io(W(e),e.force,e.global,e.options),"start-task":MF,"pause-task":DF,"close-task":UF,close:_F,comments:hF,notes:e=>of(W(e),ro(e.options),e.global),learnings:e=>sf(W(e),ro(e.options),e.global),files:gF,docs:e=>_p(W(e),Ks(e.options),e.global),test:e=>ii(W(e),e.options,e.global),"test-all":e=>Py(e.options,e.global),telemetry:yF,validate:e=>Ys(e.options,e.global,{runUpdate:(t,n,r)=>at(t,n,r)}),health:bF,assurance:e=>Ap(e.args,e.options,e.global),contracts:e=>kg(e.options,e.global),config:wF,activity:vF,aggregate:e=>pa(e.options,e.global),extension:e=>En(li(e),e.options,e.global),package:e=>En(li(e),e.options,e.global),install:e=>En(li(e),{...e.options,install:!0},e.global),upgrade:e=>Lp(li(e),e.options,e.global),delete:e=>uc(W(e),e.options,e.global),deps:e=>xu(W(e),e.options,e.global),graph:GF,"files-discover":e=>ia(W(e),e.options,e.global),"files-lookup":e=>qy(e,he(e.options.paths)),history:e=>Np(W(e),e.options,e.global),"history-redact":e=>du(W(e),e.options,e.global),"history-repair":Vh,"history-compact":Wh,"history-author-acknowledge":jF,plan:SF,schema:OF,profile:PF,stats:e=>Jc(e.global,jg(e.options)),append:NF,"update-many":LF,"close-many":FF,gc:e=>Fp(e.global,e.options)};async function Uy(e,t,n,r){let s=ea(t,e);$i(e,s),vm(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=mi(qF,e),a=i?await i(o):await oF(e,t,s,n,r);return s.resolvedOutputFormat="json",Pm(e,s,a)}var KF={closeManyOptionsFromFlat:sa,extensionOptionsFromArgs:ra,globalOptions:Zi,mutationListOptions:Mu,normalizeActionName:qt,normalizeCommandPath:na,normalizeMcpUpdateOptions:Uu,normalizeMcpOptionsArrays:$u,optionsWithAuthor:ea,readRequiredString:Je,readScalarString:Nu,readScalarStringAllowBlank:Lu,readStringArray:he,updateManyOptionsFromFlat:oa,withAddNoteOption:Ks,withFilesDiscoveryOptions:ta,withMutationCompaction:Ve};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=KF);(function(){try{var e=typeof window<"u"?window:typeof 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]="dfc95179-77dd-5762-9bcc-c6bb461ff553")}catch{}})();export{pn as AGENT_PROVENANCE_DIMENSIONS,jm as BASELINE_ITEM_FORMAT_VERSION,zn as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,Tr as BUILTIN_ITEM_TYPE_VALUES,Cr as CONFIDENCE_TEXT_VALUES,qm as CURRENT_ITEM_FORMAT_VERSION,Ft as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,sn as ISSUE_SEVERITY_VALUES,Ed as ITEM_TYPE_VALUES,va as PM_CLI_EXPECTED_ERROR_NAME,Ub as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,Mb as PM_READ_OUTPUT_DIMENSIONS,Db as PM_READ_OUTPUT_OPTION_FLAGS,Fi as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,j as PmClient,rn as RISK_VALUES,iw as SEMANTIC_ATTRIBUTION_LIMITS,Ar as STATUS_VALUES,Yb as agentSessionEnvironment,ML as aggregate,Wc as analyzeAgentProvenanceDescriptorCoverage,Bb as analyzeSdkCliParameterCompleteness,HL as append,qb as applyReadOutputDimensions,Pb as applyReadOutputSessionReferences,Nb as attachReadOutputSessionReceipt,Hb as boundAgentEpisodeIdentity,He as canonicalDocument,JL as claim,XL as claimNext,Bm as classifyItemFormatVersion,YL as close,DL as comments,PL as context,ZL as copy,VL as create,Gp as createPmCliExpectedError,$b as decodeReadOutputContinuationCursor,eF as deleteItem,zL as deps,Zb as detectAgentIdentity,nw as detectHarnessIdentity,ew as diagnoseAgentIdentity,KL as docs,Km as effectiveItemFormatVersion,Ly as emptyImportedDocument,Fb as encodeReadOutputContinuationCursor,yO as evaluateSemanticAttributionCoverage,sw as explainSourceTraceability,jL as files,qL as filesDiscover,nF as focus,FL as get,BL as graph,bO as groupHistoryByEpisode,Yp as isAlreadyClaimedError,eo as isPmCliExpectedError,Kb as isReadOutputBudgetExceeded,GL as learnings,NL as list,$L as next,zm as normalizeItemFormatVersion,_e as normalizeItemId,ne as normalizeStatusInput,UL as notes,S as nowIso,Ob as parseReadOutputSession,Hs as parseSourceLineRange,bs as readAuthorEnvironment,Lb as readOutputSessionRemainingTokens,fa as recordClaimSemanticAttribution,Xs as recordFocusSemanticAttribution,_a as recordReleaseSemanticAttribution,Jb as registerHarnessSignalDescriptors,QL as release,Vb as resolveAgentSessionContextFromSignals,rw as resolveAuthorIdentity,Og as resolveHistoryEpisodeGroupIdentity,jb as resolveReadOutputDimensions,zb as resolveReadOutputEncoding,Gb as resolveReadOutputSurface,ow as resolveSemanticLineageIds,tF as restore,jy as runAction,Wb as runWithAgentSessionContext,Xb as runWithHarnessDetectionSignals,Qb as runWithWorkspaceHarnessSignalDescriptors,LL as search,aw as semanticAttributionAffinity,Me as serializeItemDocument,gO as summarizeAgentModelProvenance,Yc as summarizeAgentProvenance,WL as update,$i as validateReadOutputOptions,tw as writeAuthorEnvironment};
40
+ `}function vR(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Q_(e,t,n){Oc(e,"base");let r=Oc(t,"ours"),s=Oc(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:Ko(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:Ko(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:Ko(s),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:s.length-i,entries_total:s.length,reanchored:!1};let a=r.slice(i),c=new Set(a.map(f=>f.eventId)),m=s.slice(i).filter(f=>!c.has(f.eventId)),u=[...a,...m].sort((f,_)=>{if(f.timestamp!==void 0&&_.timestamp!==void 0){let g=_n(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=vR([...r.slice(0,i),...u]);return{merged:Ko(p),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:m.length,entries_total:p.length,reanchored:!0}}var kR=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],SR=["updated_at"];function en(e,t){return J(e??null)===J(t??null)}function ER(e,t,n){let r=u=>Array.isArray(u)?u:[],s=new Set(r(e).map(u=>J(u))),o=r(t),i=new Set(o.map(u=>J(u))),a=r(n),c=new Set(a.map(u=>J(u))),m=o.filter(u=>{let p=J(u);return!s.has(p)||c.has(p)});for(let u of a){let p=J(u);!i.has(p)&&!s.has(p)&&m.push(u)}return m}function TR(e,t){return _n(String(e),String(t))>=0?e:t}function Z_(e,t,n,r){return en(t,n)?{value:t,from_theirs:!1,conflict:!1}:en(e,t)?{value:n,from_theirs:!0,conflict:!1}:en(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function eh(e,t,n,r,s){let o=Z_(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 Pc(e){return{...e.metadata}}function Nc(e,t,n){try{return He(Zm(e,n),n)}catch(r){throw new l(`Item merge input (${t}) is not a readable item document: ${String(r)}`,d.GENERIC_FAILURE)}}function AR(e,t,n,r,s){let o=new Set(kR),i=new Set(SR),a=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((m,u)=>m.localeCompare(u)),c={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let m of a){let u=e[m],p=t[m],f=n[m];if(o.has(m)){let h=ER(u,p,f);c.merged[m]=h,en(h,p)||c.unionFields.push(m);continue}if(i.has(m)){c.merged[m]=TR(p,f);continue}let _=eh(u,p,f,r,s);_.value!==void 0&&(c.merged[m]=_.value),_.conflict?(c.conflictFields.push(m),c.conflictDecisions.push({field:m,base:u,ours:p,theirs:f,retained:_.value,discarded:_.from_theirs?p:f})):_.from_theirs&&c.fieldsFromTheirs.push(m)}return c}function th(e,t,n,r={}){let s=r.preferred??"ours",o=r.conflictResolution??"preferred_side",i=e.trim().length>0,a=Nc(t,"ours",r),c=Nc(n,"theirs",r),m=i?Nc(e,"base",r):a,u=i?Pc(m):{},p=Pc(a),f=Pc(c),{merged:_,conflictFields:h,fieldsFromTheirs:y,unionFields:g,conflictDecisions:b}=AR(u,p,f,s,o),v=eh(i?m.body:"",a.body,c.body,s,o);return v.conflict?(h.push("body"),b.push({field:"body",base:i?m.body:"",ours:a.body,theirs:c.body,retained:v.value,discarded:v.from_theirs?a.body:c.body})):v.from_theirs&&y.push("body"),{merged:$e({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 Lc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fc(e,t){let n=ks(e);if(n)throw new l(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,d.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new l(`JSON merge input (${t}) is not valid JSON.`,d.GENERIC_FAILURE)}}function CR(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=m=>{let u=new Map;for(let p of m){let f=J(p);u.set(f,(u.get(f)??0)+1)}return u},s=r(e),o=r(t),i=r(n);for(let[m,u]of s)if((o.get(m)??0)<u||(i.get(m)??0)<u)return null;let a=new Map(o),c=[];for(let m of n){let u=J(m),p=a.get(u)??0;p>0?a.set(u,p-1):c.push(m)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function RR(e,t,n,r,s,o,i){if(!Lc(t)||!Lc(n))return null;let a=Lc(e)?e:{},c={},m=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,p)=>u.localeCompare(p));for(let u of m){let p=s.length>0?`${s}.${u}`:u,f=IR(a,t,n,u,r,p,o,i);f!==void 0&&(c[u]=f)}return c}function nh(e,t,n,r,s,o,i){if(en(t,n))return t;let a=CR(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(s),a.merged;let c=RR(e,t,n,r,s,o,i);if(c!==null)return c;let m=Z_(e,t,n,r);return m.conflict?o.push(s):m.from_theirs&&i.push(s),m.value}function IR(e,t,n,r,s,o,i,a){let c=Object.prototype.hasOwnProperty.call(t,r),m=Object.prototype.hasOwnProperty.call(n,r),u=Object.prototype.hasOwnProperty.call(e,r);if(c&&m)return nh(e[r],t[r],n[r],s,o,i,a);if(c){if(u&&en(e[r],t[r])){a.push(o);return}return u?(i.push(o),s==="theirs"?void 0:t[r]):t[r]}if(!(u&&en(e[r],n[r])))return u?(i.push(o),s==="theirs"?n[r]:void 0):(a.push(o),n[r])}function rh(e,t,n,r={}){let s=r.preferred??"ours",o=Fc(e,"base"),i=Fc(t,"ours"),a=Fc(n,"theirs"),c=[],m=[],u=nh(o,i,a,s,"",c,m);return{merged:`${JSON.stringify(u??null,null,2)}
41
+ `,conflict_paths:c,paths_from_theirs:m,preferred:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d79e3a4-6104-5855-837f-69a041b87b27")}catch{}})();var sh=["item","history","relationship","json"];function NR(e){let t=e.trim().toLowerCase();if(sh.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${sh.join(", ")}.`,d.USAGE)}function LR(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new l(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,d.USAGE)}async function Mc(e,t){try{return await xR(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function FR(e){let t=T(process.cwd(),e.path);return await k(C(t))?A(t):null}function MR(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function oh(e,t){let n=NR(e.artifact),r=LR(e.prefer),s=PR.resolve(e.outputPath??e.oursPath),[o,i,a]=await Promise.all([Mc(e.basePath,"base"),Mc(e.oursPath,"ours"),Mc(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=X_(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 _=Q_(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 FR(t),h=th(o,i,a,{format:MR(e.itemPath??s,_),schema:_?.schema,extensionFieldNames:ft(I()),preferred:r,conflictResolution:"stable_value_order"});c=h.merged,u.push(...h.conflict_fields),p.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0&&(m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,decisions:h.conflict_decisions})}else{let _=rh(o,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await OR(s,c,"utf8"),m!==void 0){let _=await gp(m);_!==null&&(p.receipt=Jn(_))}let f=[];if(u.length>0){let _=p.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${p.receipt.receipt_id} with item ${p.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${u.join(", ")}; the item driver kept the direction-independent stable value. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&p.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:u.length===0,artifact:n,output_path:s,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:S()}}import 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]="de9b7f82-0f51-599d-b1fa-2d54e3acbdbc")}catch{}})();function ih(e,t){return t==="body"?e.body:e.metadata[t]}function $c(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)&&$c(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)&&$c(s,n[r]))}function ah(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 ou(o.patch))i.add(Fs(c.path)),c.from&&i.add(Fs(c.from));let a=[...n].filter(c=>i.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:s+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,m)=>c.localeCompare(m))})}}return r.reverse()}function $R(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(Fs(h.path));let o=new Set([...s].filter(h=>$c(ih(t,h),ih(n,h)))),i=new Set([...s].filter(h=>!o.has(h))),a=ah(e,i),c=ah(e,o),m=[...s].sort((h,y)=>h.localeCompare(y)),u=[...i].sort((h,y)=>h.localeCompare(y)),p=[...o].sort((h,y)=>h.localeCompare(y)),f=[...new Set(a.map(h=>h.author))].sort((h,y)=>h.localeCompare(y)),_=[...new Set(c.map(h=>h.author))].sort((h,y)=>h.localeCompare(y));return{reconciled_field_count:s.size,reconciled_fields:m,reverted_field_count:i.size,reverted_fields:u,discarded_events:a,discarded_authors:f,preserved_field_count:o.size,preserved_fields:p,preserved_events:c,preserved_authors:_,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function DR(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=jt(o.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:i,currentItemPath:s,matchedChainBefore:Pe(i,r)===a,currentItemRawBeforeLock:o.raw,loadedItem:o}}function UR(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 GR(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:S(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?ch.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Pe(e.finalReplay,e.itemHashVersion),after_hash:Pe(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 jR(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 qR(e){return Is({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})=>Rs({historyPath:e.historyPath,nextHistoryRaw:ot(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function ur(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await xs(r,e,s,o.type_to_folder);if(!await k(i.historyPath))throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let a=await q(i.historyPath),c=await bt(i.historyPath,i.id);if(c.length===0)throw new l(`No history entries exist for ${i.id}; nothing to repair.`,d.USAGE);let m=hn(c),u=iu(c),p=t.normalizeProvenance?_p(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=au(p.entries),_=new Set(p.entries.map(ie=>ie.item_hash_version).filter(ie=>ie!==void 0)),h=Es(p.entries,f),y=await DR(i,s,c,f),g=h.finalDocument,b=y.currentItemReplay!==null&&Pe(g,f)!==Pe(y.currentItemReplay,f),v=b&&y.currentItemReplay?$R(h.entries,g,y.currentItemReplay):void 0,E=[h.entriesRehashed>0,h.entriesPatchRepaired>0,b,t.forceAuditEntry===!0,p.receipt.changed].some(Boolean),N=R(t.author,s.author_default),P=!!t.dryRun,M=UR({message:t.message,entriesRehashed:h.entriesRehashed,entriesPatchRepaired:h.entriesPatchRepaired,reconcileNeeded:b}),{rewrittenEntries:G,auditEntryAdded:Ie}=GR({reanchorEntries:h.entries,changed:E,reconcileNeeded:b,currentItemReplay:y.currentItemReplay,finalReplay:g,author:N,message:M,auditOperation:t.auditOperation??"history_repair",auditContext:p.receipt.changed?{...t.auditContext,provenance_normalization:p.receipt}:t.auditContext,itemHashVersion:f,explicitItemHashVersion:h.explicitItemHashVersion}),ee=hn(G);if(!ee.ok)throw new l(`history-repair produced an invalid rewritten chain (${ee.errors.join(", ")}).`,d.GENERIC_FAILURE);let pe=jR(E,h.skippedOps,v);return E&&!P&&pe.push(...await qR({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:G})),{id:i.id,dry_run:P,changed:E,history:{path:i.historyPath,entries_scanned:c.length,chain_drift_before:!m.ok,entries_rehashed:h.entriesRehashed,entries_patch_repaired:h.entriesPatchRepaired,converted_replace_to_add:h.convertedReplaceToAdd,skipped_ops:h.skippedOps,reconciled_with_item:b,audit_entry_added:Ie,verify_ok:ee.ok,verify_errors:ee.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(pe)].sort((ie,Xe)=>ie.localeCompare(Xe)),generated_at:S()}}function dh(e,t){if(t&&e!==void 0)throw new l("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",d.USAGE);if(!t&&e===void 0)throw new l("history-repair: provide an item <id> or pass --all to repair every drifted stream.",d.USAGE)}async function zo(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=x(r,I()),o=[],i=await Ts(n,r.item_format,s.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await Gu(n,i),c=e.normalizeProvenance?await hp(n):[],m=[...new Set([...a.driftedItems,...c])].sort((_,h)=>_.localeCompare(h)),u=[],p=[],f={repaired:0,skipped_clean:0,failed:0};for(let _ of m)try{let h=await ur(_,{...e,auditContext:e.auditContextById?.[_],auditContextById:void 0},t),y=h.changed?"repaired":"skipped_clean";f[y]+=1,p.push(...h.warnings.map(g=>`${_}:${g}`)),u.push({id:_,outcome:y,entries_rehashed:h.history.entries_rehashed,entries_patch_repaired:h.history.entries_patch_repaired,reconciled_with_item:h.history.reconciled_with_item,...h.reconciliation?{reconciliation:h.reconciliation}:{},warnings:h.warnings})}catch(h){f.failed+=1,u.push({id:_,outcome:"failed",error:h instanceof Error?h.message:String(h)})}return e.dryRun||await ru(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:i.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:u,totals:f,warnings:[...new Set([...o,...p])].sort((_,h)=>_.localeCompare(h)),generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c5620467-6c8c-5702-b742-57fba9e302c5")}catch{}})();async function lh(e,t){let n=e.dryRun===!0,r=await yp(process.cwd(),{includeLossless:!0}),{pendingDecisions:s}=bp(r);if(!n&&e.force!==!0&&s.length>0)throw new l(`Merge reconciliation would accept ${s.length} receipt(s) containing discarded scalar values. Review pm merge report and rerun with --force only after deciding which values to retain or re-apply.`,d.CONFLICT,{code:"merge_reconcile_discards_require_acceptance",required:"Explicitly review every discarded field before accepting reconciliation.",nextSteps:s.map(g=>`Review receipt ${g.id} for ${g.item_id}: ${g.decisions.map(b=>b.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let o=r.reduce((g,b)=>((g[b.item_id]??=[]).push(b),g),{}),i=Object.fromEntries(Object.entries(o).map(([g,b])=>[g,{merge:{receipts:b.map(Jn)}}])),a=await zo({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:i},t),c=new Set(a.streams.map(g=>g.id)),m=Object.keys(o).filter(g=>!c.has(g));(await Promise.allSettled(m.map(g=>ur(g,{dryRun:n,author:e.author??t.author,message:e.message??"record field-aware branch merge provenance",force:e.force,auditOperation:"merge_reconcile",auditContext:i[g],forceAuditEntry:!0},t)))).forEach((g,b)=>{let v=m[b];if(g.status==="fulfilled"){let E=g.value.changed?"repaired":"skipped_clean";a.streams.push({id:v,outcome:E,entries_rehashed:g.value.history.entries_rehashed,entries_patch_repaired:g.value.history.entries_patch_repaired,reconciled_with_item:g.value.history.reconciled_with_item,warnings:g.value.warnings}),a.totals[E]+=1}else a.streams.push({id:v,outcome:"failed",error:g.reason instanceof Error?g.reason.message:String(g.reason)}),a.totals.failed+=1});let p=0;!n&&a.totals.failed===0&&(await Promise.all(r.map(g=>wp(process.cwd(),g))),p=r.length);let f=await Js({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(Jn)},validation:f,guidance:y,generated_at:f.generated_at}}import{createHash as KR}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e8cd5790-eacf-5ef7-bc0a-11ea3fe17d2d")}catch{}})();var ph=1,fh=/^[A-Za-z0-9_-]+$/,zR=100,mh=1e3;var xG=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function Ke(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 BR(e){return KR("sha256").update(J({type:Ke(e.type),author:Ke(e.author),item:Ke(e.item),harness:Ke(e.harness),agent_instance:Ke(e.agentInstance),provenance:Ke(e.provenanceFilter)})).digest("hex").slice(0,24)}function uh(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 HR(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 VR(e,t){let n=e.trim();if(n.length===0||n.length>4096||!fh.test(n))throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"})}if(!HR(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function WR(e){let t=e??zR;if(!Number.isSafeInteger(t)||t<0||t>mh)throw new l(`Mutation event limit must be an integer from 0 to ${mh}.`,d.USAGE,{code:"invalid_event_limit"});return t}function YR(e,t){let n=e?.trim();if(!n)return{};if(fh.test(n))return{cursor:VR(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new l("Mutation event --since must be an event cursor or ISO timestamp.",d.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function JR(e,t){let n=await Ji(e,t);if(n===null){if(!await eu(e))return{...await tu(e,t),source:"authoritative_history"};n=await Ji(e,t)}if(n===null)throw new l("Mutation event index could not be opened after rebuild.",d.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function XR(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Bo(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=WR(e.limit),r=XR(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new l("Mutation event projections are mutually exclusive. Use --provenance or --full.",d.USAGE);let s=await A(t),o=s.agent_identity.identity_vocabulary,i=Iu(s.agent_identity.harness_signals),a=xu({provenance:e.provenanceFilter},i),c=Ke(e.harness),m=BR(e),{cursor:u,sinceTimestamp:p}=YR(e.since,m),f={...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:Ke(e.type),authors:Ke(e.author),harnesses:c,harness_alias_authors:c?Object.entries(o.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:Ke(e.agentInstance),provenance:[...a].map(([y,g])=>({dimension:y,values:[...g]})),stream_ids:Ke(e.item),limit:n},_=await JR(t,f),h=_.events.map(y=>({...r==="row"?{cursor:uh(y,m)}:{},item_id:y.stream_id,version:y.stream_offset+1,ts:y.entry.ts,author:y.entry.author,type:y.entry.op,...y.entry.message===void 0?{}:{message:y.entry.message},patch_count:y.entry.patch.length,...e.full===!0?{entry:y.entry}:{},...e.provenance===!0?{provenance:Ou(y.entry,o,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:uh(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Pu(_.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 QR="1h",ZR="now",eI="+1d";function It(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function _h(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 hh(e,t,n,r){let s=_h(e,t,n),o=[];return It(o,"start",n.start??ZR),n.end!==void 0?It(o,"end",n.end):It(o,"duration",n.duration??QR),It(o,"location",n.location),It(o,"timezone",n.timezone),n.allDay===!0&&It(o,"all_day","true"),s.event=[o.join(",")],At(s,r)}function gh(e,t,n){return hh("Meeting",e,t,n)}function yh(e,t,n){return hh("Event",e,t,n)}function bh(e,t,n){let r=_h("Reminder",e,t),s=[];return It(s,"at",t.at??eI),It(s,"text",t.text??e),r.reminder=[s.join(",")],At(r,n)}import fr from"node:crypto";import{cp as vh,lstat as iI,mkdir as tn,readFile as Nn,readdir as Uc,rename as Eh,rm as jc,writeFile as Vo}from"node:fs/promises";import L from"node:path";import{constants as xt}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 wh=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"}]]),tI=/^[a-z][a-z0-9_]{0,63}$/u,nI=new Map([[xt.errno.EACCES,"EACCES"],[xt.errno.EDQUOT,"EDQUOT"],[xt.errno.EMFILE,"EMFILE"],[xt.errno.ENFILE,"ENFILE"],[xt.errno.ENOMEM,"ENOMEM"],[xt.errno.ENOSPC,"ENOSPC"],[xt.errno.EPERM,"EPERM"],[xt.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),rI={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function sI(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&wh.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:nI.get(Math.abs(t.errno))??null}function oI(e,t,n={}){let r=sI(e);if(r===null)return null;if(!tI.test(t))throw new l("Host environment operation labels must be bounded identifiers.",d.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let s=wh.get(r);return new l(`Host filesystem operation ${t} ${s.summary}.`,d.GENERIC_FAILURE,{code:n.codes?.[s.category]??rI[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 Ho(e,t,n={}){try{return await t()}catch(r){throw oI(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]="36aacc71-c5f5-56f1-85f4-28b2be5b02e2")}catch{}})();var Th="https://schema.unbrained.dev/pm/workspace-snapshot/v1",Ah=L.join("runtime","workspace-snapshots"),aI=new Set(["checkpoints","locks","runtime","search","transactions"]),cI=/^[a-z0-9][a-z0-9._-]*$/,pr="sdk-workspace-transaction",Dc={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Ch={renameEntry:Eh,removeEntry:async e=>{await jc(e,{recursive:!0,force:!0})}},Gc=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 Nn(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!==pr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await me(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
42
+ `)}};async function Rh(e,t=""){let n=await Uc(L.join(e,t),{withFileTypes:!0}),r=[];for(let s of n.sort((o,i)=>o.name.localeCompare(i.name))){if(t.length===0&&aI.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 Rh(e,o));else if(s.isFile())r.push(o);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${o}`)}return r}async function Ih(e){let t=await Rh(e),n=fr.createHash("sha256"),r=[],s=0;for(let i of t){let a=await Nn(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:Th,fingerprint:o,files:t,bytes:s},contents:r}}function kh(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
43
+ `).filter(t=>t.trim().length>0).length}async function dI(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 Nn(L.join(e,i))]));for(let[i,a]of o)n.set(i,a)}return n}function qc(e){if(!cI.test(e))throw new l("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",d.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function xh(e,t){return Ho(`workspace_snapshot_${e}`,t,{codes:{capacity:Dc.capacity.code,permission:Dc.permission.code,resource:Dc.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 nn(e){return L.join(e,Ah)}function Oh(e){return new l(`Unknown workspace snapshot: ${e}`,d.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Ph(e,t){try{return JSON.parse(await Nn(e,"utf8"))}catch(n){throw _t(n)?Oh(t):n}}async function Sh(e,t,n){try{await jc(e,{recursive:n})}catch(r){throw _t(r)?Oh(t):r}}async function lI(e,t,n=Ch){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 mI(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 uI(e,t){return qc(t),/^[a-f0-9]{64}$/.test(t)?t:(await Ph(L.join(nn(e),"refs",`${t}.json`),t)).fingerprint}async function Kc(e,t={}){if(t.name!==void 0&&(qc(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new l("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",d.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await Ih(e),s=nn(e),o=L.join(s,"objects",n.fingerprint),i=!1;try{i=(await iI(o)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&_t(a)))throw a}if(!i){let a=L.join(s,"objects",`.create-${process.pid}-${fr.randomUUID()}`);await xh("create_object",async()=>{await tn(L.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=L.join(a,"files",m);await tn(L.dirname(u),{recursive:!0}),await Vo(u,r[c])}await Vo(L.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
44
+ `,"utf8"),await tn(L.dirname(o),{recursive:!0})}),i=await lI(a,o)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=L.join(s,"refs");await tn(c,{recursive:!0});let m=L.join(c,`.ref-${process.pid}-${fr.randomUUID()}`);await Vo(m,`${JSON.stringify(a,null,2)}
45
+ `,"utf8"),await Eh(m,L.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function _r(e,t){let n=await uI(e,t),r=await Ph(L.join(nn(e),"objects",n,"manifest.json"),t);if(r.schema!==Th||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,d.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function zc(e){let t=nn(e),n=await Uc(L.join(t,"objects")).catch(s=>{if(s instanceof Error&&"code"in s&&_t(s))return[];throw s}),r=await Uc(L.join(t,"refs")).catch(s=>{if(s instanceof Error&&"code"in s&&_t(s))return[];throw s});return{objects:await Promise.all(n.filter(s=>/^[a-f0-9]{64}$/.test(s)).sort().map(s=>_r(e,s))),references:await Promise.all(r.filter(s=>s.endsWith(".json")).sort().map(async s=>JSON.parse(await Nn(L.join(t,"refs",s),"utf8"))))}}async function Bc(e,t){let n=await _r(e,t),{manifest:r,contents:s}=await Ih(e),o=new Map(r.files.map((p,f)=>[p,s[f]])),i=await dI(L.join(nn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),m=new Set([...a,...c]);for(let p of m){let f=o.get(p),_=i.get(p);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=kh(o.get(p)),_=kh(i.get(p));return{path:p,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(p=>p.removed_entries>0).sort((p,f)=>p.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:m.size,removed_file_count:[...a].filter(p=>!c.has(p)).length,added_file_count:[...c].filter(p=>!a.has(p)).length,removed_item_count:[...a].filter(p=>p.endsWith(".toon")&&!c.has(p)).length,affected_history_stream_count:u.length,removed_history_entry_count:u.reduce((p,f)=>p+f.removed_entries,0),affected_history_streams:u,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function Nh(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",d.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",s=n.lockTtlSeconds??60,o=n.lockWaitMs??5e3,i=await xe(e,pr,s,r,!1,!1,o),a=new Gc(Nr(e,pr),r,s);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await Bc(e,t),f=await _r(e,t),_=await Kc(e),h=f.fingerprint,y=nn(e),g=L.join(y,"objects",h,"files"),b=L.dirname(e),v=L.basename(e);c=L.join(b,`.${v}.restore-${fr.randomUUID()}`);let E=L.join(b,`.${v}.backup-${fr.randomUUID()}`);await xh("restore_stage",async()=>{await tn(c,{recursive:!0}),await vh(g,c,{recursive:!0,force:!1}),await tn(L.join(c,"runtime"),{recursive:!0}),await vh(y,L.join(c,Ah),{recursive:!0,force:!1})});let N=await cu({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}),P=L.relative(c,N.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let M=Nr(c,pr);return await tn(L.dirname(M),{recursive:!0}),await Vo(M,await Nn(Nr(e,pr)),{flag:"wx"}),m=!0,await mI(c,e,E,Ch,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:P,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([jc(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function Lh(e,t){qc(t);let n=nn(e);if(!/^[a-f0-9]{64}$/.test(t))return await Sh(L.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await zc(e);if(r.some(s=>s.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Sh(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 hr(e){return{...e.args,...e.options}}function lt(e,t){let n=w(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Ln(e){return typeof e=="string"?[e]:he(e)}function Fh(e){return J_(hr(e),e.global)}function Mh(e){let t=hr(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Bo({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Ln(t.type),author:Ln(t.author),item:Ln(t.item),limit:t.limit===void 0?void 0:Le(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:Ln(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Ln(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Ln(t.provenanceFilter)}})}function $h(e){let t=hr(e),n=lt(t,"subcommand");if(n==="install")return Xu({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return lh({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return vp({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return oh({artifact:lt(t,"artifact"),basePath:lt(t,"basePath"),oursPath:lt(t,"oursPath"),theirsPath:lt(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw Ee({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Dh(e){let t=hr(e),n=lt(t,"subcommand");if(n!=="snapshot")throw Ee({command_path:"workspace",token:n,allowed:["snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??lt(t,"snapshot_action"),s=T(process.cwd(),e.global.path);if(r==="create")return Kc(s,{name:w(t,"name")});if(r==="list")return zc(s);let o=lt(t,"target");if(r==="inspect")return _r(s,o);if(r==="delete")return Lh(s,o);if(r==="restore")return t.dryRun===!0?Bc(s,o):Nh(s,o,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Le(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Le(t.lockWaitMs,"lockWaitMs")});throw Ee({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Wo(e){let t=hr(e),n=lt(t,"title");return e.action==="meet"?gh(n,t,e.global):e.action==="event"?yh(n,t,e.global):bh(n,t,e.global)}import TI from"node:path";import pI from"node:fs/promises";import Uh from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f232e106-54f4-572e-8f6e-054f52290267")}catch{}})();var fI="templates",_I=".json",hI=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,gI=hs.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),yI=new Set(gI);function bI(e){let t=e.trim();if(!hI.test(t))throw new l(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,d.USAGE);return t}function Gh(e){return Uh.join(e,fI)}function jh(e,t){return Uh.join(Gh(e),`${t}${_I}`)}async function wI(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function qh(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function vI(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(yI.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 qh(t)}function kI(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new l(`Template "${t}" has invalid options payload.`,d.GENERIC_FAILURE);let n=e,r={};for(let[s,o]of Object.entries(n)){let i=s.trim();if(i.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof o=="string"){r[i]=o;continue}if(Array.isArray(o)&&o.every(a=>typeof a=="string")){r[i]=[...o];continue}throw new l(`Template "${t}" contains invalid value for option "${i}".`,d.GENERIC_FAILURE)}return qh(r)}function SI(e,t){let n;try{n=JSON.parse(e)}catch{throw new l(`Template "${t}" contains invalid JSON.`,d.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Template "${t}" has invalid document shape.`,d.GENERIC_FAILURE);let r=n,s=kI(r.options,t),o=S();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:o,updated_at:typeof r.updated_at=="string"?r.updated_at:o,options:s}}async function EI(e,t){let n=await q(jh(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return SI(n,t)}async function Hc(e,t,n){let r=T(process.cwd(),n.path);await wI(r);let s=bI(e),o=vI(t);if(Object.keys(o).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let i=S(),a=jh(r,s),c=i;await k(a)&&(c=(await EI(r,s)).created_at);let m={name:s,created_at:c,updated_at:i,options:o},u=await A(r);return await pI.mkdir(Gh(r),{recursive:!0}),await vt({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
46
+ `,op:"templates:save",author:R(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:a,options:m.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1e34cfb-3d4e-5b79-8585-3162e71e574c")}catch{}})();var Hh=["list","show","apply","lint"],AI="schema-types",CI="schema-statuses",RI="schema-fields";function Yo(){let e=I();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Vh(){let{profiles:e,warnings:t}=im(Yo());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:mm(n.definition)})),warnings:t,generated_at:S()}}function Wh(e){let t;try{t=ms(e,Yo())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...um(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function Yh(e){let t;try{t=ms(e,Yo())}catch(s){throw new l(s instanceof Error?s.message:String(s),d.USAGE)}let{resolved:n}=t,r=Im(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:S()}}function II(e,t){return TI.join(e,"templates",`${t}.json`)}async function xI(e,t){let n=await q(II(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 Kh(e,t,n,r){let s=new Map;for(let o of r.templates){let i=await xI(e,o.name);i!==void 0&&s.set(o.name,i)}return{typesRaw:await q(rt(e,t.files.types,nt.types)),statusesRaw:await q(rt(e,t.files.statuses,nt.statuses)),fieldsRaw:await q(rt(e,t.files.fields,nt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:s,installedPackages:new Set}}function Fn(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 zh(e,t,n,r,s){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Fn(t.types.changes),statuses:Fn(t.statuses.changes),fields:Fn(t.fields.changes),workflows:Fn(t.workflows.changes.map(o=>({key:o.type,status:o.status}))),config:Fn(t.config.changes),templates:Fn(t.templates.changes.map(o=>({key:o.name,status:o.status}))),packages:t.packages,warnings:[...new Set(s)].sort((o,i)=>o.localeCompare(i)),generated_at:S()}}async function OI(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function PI(e){try{let t=ms(e,Yo());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function Jh(e,t,n){let r=T(process.cwd(),n.path);await OI(r);let s=PI(e),o=s.profile,i=s.warnings,a=t.dryRun===!0,c=await A(r),m=us(c.schema);if(a){let b=await Kh(r,m,c,o),v=Bh(o,b);return zh(o,v,!1,!0,[...i])}let u=R(t.author,c.author_default),p=lu(c),f=!!t.force,_=[...i],h=[],y=async b=>{h.push(await xe(r,b,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(AI),await y(CI),await y(RI);let b=await Kh(r,m,c,o);if(g=Bh(o,b),g.types.changed){let v=rt(r,m.files.types,nt.types);await vt({pmRoot:r,filePath:v,raw:ls(g.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let E=new Set(o.types.map(P=>em(P).name)),N=g.types.file.definitions.filter(P=>E.has(P.name));await rp(r,N,_,"profile:apply-type-folder"),_.push(...await z({path:v,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let v=rt(r,m.files.statuses,nt.statuses);await vt({pmRoot:r,filePath:v,raw:lm(g.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let v=rt(r,m.files.fields,nt.fields);await vt({pmRoot:r,filePath:v,raw:am(g.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let v of g.config.changes){if(v.status==="unchanged")continue;let E=fs(v.key);E!==void 0&&_s(c,E,v.value)}c.schema.type_workflows=g.workflows.result,await Se(r,c,"profile:apply-config")}for(let v of g.templates.changes)v.status!=="unchanged"&&await Hc(v.name,{...v.options},n)}finally{for(let b of h.reverse())try{await b()}catch{}}return zh(o,g,g.changed,!1,_)}function Bh(e,t){try{return xm(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import Qh from"node:fs/promises";import Zh 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 NI(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 LI(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 Xh(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return NI(t.ids,n,t.minEntries)}return LI(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6609492-75a9-5111-b9b3-1b81908f3084")}catch{}})();function FI(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(n)){let o=Number.parseInt(n,10);if(!Number.isSafeInteger(o)||o<1||o>t.length+1)throw new l(`history-compact --before version must be between 1 and ${t.length+1}.`,d.USAGE);let i=Math.max(0,Math.min(t.length,o-1));return{kind:"version",raw:n,compactCount:i,retainedCount:t.length-i}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let s=0;for(let[o,i]of t.entries()){let a=Date.parse(i.ts);if(!Number.isFinite(a))throw new l(`History for this item contains invalid timestamp at entry ${o+1}.`,d.GENERIC_FAILURE);if(a>=r)break;s+=1}return{kind:"timestamp",raw:n,compactCount:s,retainedCount:t.length-s}}function MI(e,t){let n=Ss(),r=Ss();for(let s=0;s<e.length;s+=1){let o=e[s];if(Pe(n)!==o.before_hash)throw new l(`history-compact detected before-hash drift at entry ${s+1}; run pm history-repair first.`,d.CONFLICT);if(n=Cs(n,o.patch,s+1,o.op),Pe(n)!==o.after_hash)throw new l(`history-compact detected after-hash drift at entry ${s+1}; run pm history-repair first.`,d.CONFLICT);s+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function $I(e,t,n){let r=structuredClone(t),s=[];for(let[o,i]of e.entries()){let a=Pe(r);r=Cs(r,i.patch,n+o+1,i.op),s.push({...i,before_hash:a,after_hash:Pe(r)})}return{entries:s,finalReplay:r}}async function DI(e,t,n){let r=e.located?await K(e.located,{schema:t.schema}):null;return r?{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:Pe(jt(r.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function UI(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 GI(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 jI(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=MI(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),s=$I(r,t,e.boundary.compactCount),i=[De({nowIso:S(),author:e.author,op:"history_compact_baseline",before:Gt(Ss()),after:Gt(t),message:GI(e.boundary)}),...s.entries];return e.dryRun||i.push(De({nowIso:S(),author:e.author,op:"history_compact",before:Gt(n),after:Gt(n),message:UI(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function qI(e){return Is({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})=>Rs({historyPath:e.historyPath,nextHistoryRaw:ot(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function Vc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await xs(r,e,s,o.type_to_folder),a=i.historyPath,c=await q(a);if(c===null)throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let m=await bt(a,i.id);if(m.length===0)throw new l(`No history entries exist for ${i.id}; nothing to compact.`,d.USAGE);let u=hn(m);if(!u.ok)throw new l(`history-compact requires a valid history chain (${u.errors.join(", ")}). Run pm history-repair ${i.id} first.`,d.CONFLICT);let p=FI(t.before,m),f=p.compactCount>0,_=!!t.dryRun,h=R(t.author,s.author_default),y=[];f||y.push("history_compact_noop_before_boundary");let g=await DI(i,s,m);g.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:E}=jI({historyEntries:m,boundary:p,changed:f,dryRun:_,author:h,options:t}),N=hn(b);if(!N.ok)throw new l(`history-compact produced an invalid rewritten chain (${N.errors.join(", ")}).`,d.GENERIC_FAILURE);f&&!_&&y.push(...await qI({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 P=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:P},history:{path:a,entries_scanned:m.length,entries_after:b.length,baseline_entry_added:v,audit_entry_added:E,verify_ok:N.ok,verify_errors:N.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:g.matchedChainBefore},warnings:[...new Set(y)].sort((M,G)=>M.localeCompare(G)),generated_at:S()}}var KI=3;function eg(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function zI(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function BI(e){let t=j(e.settings.schema),n=Xs(t),r=await re(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),s=new Map(r.map(m=>[m.id,n.classify(m.status)])),o=Zh.join(e.pmRoot,"history"),i=[],a=[];if(!await k(o))return{candidates:i,preselectionErrors:a};let c=(await Qh.readdir(o)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=Zh.join(o,m),p=m.slice(0,-6);try{let f=await Qh.readFile(u,"utf8");await un({path:u,scope:"project"}),i.push({id:p,entries:zI(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 HI(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 Vc(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 tg(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=x(r,I()),{candidates:o,preselectionErrors:i}=await BI({pmRoot:n,settings:r,typeToFolder:s.type_to_folder}),a=e.ids!==void 0&&e.ids.length>0?"ids":"scan",c=e.minEntries??KI,m=r.history.compact_policy,u=a==="scan"&&e.allOver===void 0&&m.enabled,p=e.allOver??(u?m.max_entries:void 0),f=Xh(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 HI({row:g,options:e,dryRun:_,global:t});if(h.push(b.result),!b.selected){y.items_skipped+=1;continue}y.selected+=1,b.compacted&&(y.items_compacted+=1),b.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:_,mode:a,scope:e.scope??null,criteria:{min_entries:c,all_over:p??null,policy_threshold_applied:u},totals:y,results:h,generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f762b5e6-8224-531f-9dd1-f71dc18c3ddf")}catch{}})();function ng(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return dh(n,t),t?zo(e.options,e.global):ur(n,e.options,e.global)}function rg(e){let t=e.options.ids,n=Array.isArray(t)?t.map(String).filter(m=>m.trim().length>0):typeof t=="string"?t.split(",").map(m=>m.trim()).filter(Boolean):void 0,r=Le(e.options.allOver??e.options.all_over,"history-compact allOver"),s=Le(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),o=w(e.options,"scope"),i=[];e.options.closed===!0&&i.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&i.push("all-streams"),(o==="closed"||o==="all-streams")&&i.push(o);let a=[...new Set(i)];if(a.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let c=a[0];return eg(e.id,{ids:n,allOver:r,scope:c}),e.id!==void 0?Vc(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):tg({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]="c2ef0de1-bc44-5550-862c-f3929334fbef")}catch{}})();function sg(e,t,n){let r;if(typeof e.lines=="string")r=Vs(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=Vs(`${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 VI=Gi("list").properties.outputSession,WI={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:{...VI},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},og={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},Z={type:"string",description:"pm item id, for example pm-abc1."},YI=`Operation name (one of): ${Mi.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,JI={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."}},XI={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 D(e,t=[]){return{...og,properties:{...og.properties,...e},required:t}}var QI=[{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:D({action:{type:"string",enum:[...Mi],description:YI},id:Z,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."},...WI},["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:D({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:D({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:D({query:{type:"string"},options:{type:"object"},...XI},["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:D({options:{type:"object"},...JI})},{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:D({id:Z,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:D({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:D({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:D({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:Z,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:D({id:Z,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:D({id:Z,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:D({id:Z,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:D({id:Z,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:D({id:Z,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:D({id:Z,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:D({id:Z,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:D({id:Z,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:D({id:Z,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:D({id:Z,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:D({id:Z,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:D({id:Z,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:D({id:Z,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:D({subcommand:{type:"string",enum:[...Sm]},id:Z,target:Z,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:D({id:Z,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:D({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:D({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:D({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:D({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:[...ki]},description:`Lifecycle roles for add-status: ${ki.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:D({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:D({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:D({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."}})}],ZI={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"},ex=QI.map(e=>{let t=ZI[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Gi(t,{properties:n,required:r})}});function ig(){return ex.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]="6fc2cd04-2fe4-5a0e-944d-fab0f86509e2")}catch{}})();var tx=new Set(["claim","close","context","create","get","help","list","next","plan","release","search","update","validate"]),nx=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),cg=Object.freeze([...zn.map(e=>({command:e,tier:tx.has(e)?"core":nx.has(e)?"standard":"full"})),{command:"completion-statuses",tier:"internal"},{command:"completion-tags",tier:"internal"},{command:"completion-types",tier:"internal"},{command:"test-runs-worker",tier:"internal"}]),ag={core:0,standard:1,full:2,internal:3},rx=new Map(cg.map(({command:e,tier:t})=>[e,t]));function dg(e,t="standard"){return rx.get(e.trim().toLowerCase())??t}function lg(e){let t=ag[e];return cg.filter(n=>n.tier!=="internal"&&ag[n.tier]<=t).map(n=>n.command)}var Cq=Object.freeze({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:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});var Rq=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),Iq=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9a66a2a0-94be-595b-983d-347ec95af85e")}catch{}})();var mg=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"]]]),sx=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],vg=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Xo=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"]),gr=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"]),kg=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"]]),Sg=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"]]),Eg=new Map([...Sg.entries()].flatMap(([e,t])=>mt(t).map(n=>[n,e]))),Tg=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],Ag=new Map(Tg.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),ox=10,ix=20,ug=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate work through typed operations."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage portable workspace primitives."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),Cg=[["init",_l],["install",gl],["uninstall",yl],["explore",bl],["manage",Tl],["describe",wl],["reload",Al],["doctor",Cl],["catalog",Rl],["adopt",Il],["adopt-all",vl],["activate",kl],["deactivate",Sl],["migrate",El]],ax=Cg.map(([e,t])=>e==="init"?[e,hl]:[e,t]),cx=[...Cg.map(([e,t])=>[`extension ${e}`,t]),...ax.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Kr],["config",fl],["extension",zr],["package",Gn],["packages",Gn],["install",xl],["create",Jr],["item mutate",Jl],["item complete",Xl],["copy",Xr],["focus",Qr],["update",Zr],["update-many",es],["upgrade",Ol],["calendar",jn],["cal",jn],["context",qn],["ctx",qn],["get",ns],["search",as],["eval",Zl],["workspace",ht],["workspace snapshot",ht],["workspace snapshot create",ht],["workspace snapshot list",ht],["workspace snapshot inspect",ht],["workspace snapshot restore",ht],["workspace snapshot delete",ht],["next",is],["aggregate",Ur],["deps",ss],["graph",os],["guide",rs],["reindex",Pl],["history",Gr],["history-compact",ml],["history-redact",dl],["history-repair",ll],["history-author-acknowledge",jr],["merge",cl],["schema",ul],["profile",pl],["plan",qr],["restore",Fl],["delete",Ml],["close",Nl],["close-many",Br],["append",Hr],["claim",Ll],["release",$l],["start-task",Dl],["pause-task",Ul],["close-task",Gl],["comments",rl],["notes",sl],["learnings",ol],["files",il],["docs",al],["test",Kl],["test-all",zl],["telemetry",Bl],["test-runs",Hl],["gc",Vl],["stats",Vr],["duplicates",Wr],["validate",Wl],["health",Yr],["assurance",Yl],["contracts",cs],["completion",ds],["activity",ts],...[...vg].map(e=>[e,Dr])],Xc=new Map(cx);function dx(e){let t=Eg.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 zn.includes(e)?we(e):e.startsWith("extension-")?we(`extension ${e.slice(10)}`):e.startsWith("package-")?we(`package ${e.slice(8)}`):e.startsWith("test-runs-")?we(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?we(`templates ${e.slice(10)}`):Xo.has(e)?Sg.get(e)??we(e):null}function lx(e,t){return e.command_path===null?!1:mt(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `))}function mt(e){return e.split("|").map(t=>we(t)).filter(t=>t.length>0)}function mx(e,t){let n=new Set(t),r=new Set;for(let s of e)if(s.command_path)for(let o of mt(s.command_path)){let i=o.split(" ").filter(a=>a.length>0);if(i.length!==0)for(let a=i.length;a>0;a-=1){let c=i.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((s,o)=>s.localeCompare(o))}function Jo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function yr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function ux(e,t){if(!t)return{...e};let r=yr(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 Wc(e,t){let r=yr(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 we(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Rg(e){return e.replace(/\s+/g,"-")}function Ye(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function fg(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=Ye(r);!s||n.has(s)||(n.add(s),t.push(s))}return t}function Yc(e,t,n){n&&(e[t]=!0)}function _g(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 px(e){let t=_g(e.long,"long"),n=_g(e.short,"short"),r=t??n;if(!r)return null;let s={flag:r};n&&t&&(s.short=n),Yc(s,"required",e.required===!0),Yc(s,"repeatable",e.repeatable===!0),Yc(s,"list",e.list===!0);let o=Ye(e.description);o&&(s.description=o);let i=Ye(e.value_name);i&&(s.value_name=i);let a=[Ye(e.value_type),Ye(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(s.value_type=a),s}function Ig(e){let t=new Map;for(let r of e){let s=we(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=px(a);if(!c)continue;let m=`${c.flag}|${c.short??""}`;o.dedupe.has(m)||(o.dedupe.add(m),o.flags.push(c))}t.set(s,o)}let n=new Map;for(let[r,s]of t.entries())n.set(r,{flags:s.flags,sources:s.sources.sort((o,i)=>{let a=o.layer.localeCompare(i.layer);return a!==0?a:(o.name??"").localeCompare(i.name??"")})});return n}function fx(e){let t=Ig(e.flagRegistrations),n=new Map;for(let o of e.commandDefinitions){let i=we(o.command);if(i.length===0)continue;let a=Ye(o.action)??Rg(i),c=Array.isArray(o.arguments)?o.arguments.map(m=>{let u=Ye(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:Ye(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{command:i,action:a,source:{layer:o.layer,name:o.name},description:Ye(o.description),intent:Ye(o.intent),arguments:c,flags:t.get(i)?.flags??[],examples:fg(o.examples),failure_hints:fg(o.failure_hints)})}let r=new Set;for(let o of e.handlers)r.add(we(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(_x(o,i,t.get(o)?.flags??[]))}return s}function _x(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Rg(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function hx(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 gx(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 yx(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 bx(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]=gx(s,e.action),s.required&&r.push(s.name);for(let s of e.flags){let o=hx(s);!o||n[o]!==void 0||(n[o]=yx(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 wx(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 vx(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&&wx(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 kx(e,t=A){let n={mode:pt.extensions.policy.mode,trust_mode:pt.extensions.policy.trust_mode,default_sandbox_profile:pt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=T(process.cwd(),e.path);if(!await k(C(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let s=await t(r),o=await Fr({pmRoot:r,settings:s,cwd:process.cwd(),noExtensions:!1}),i=await Mr({...o,loaded:o.loaded});return{handlers:new Set(i.commands.handlers.map(c=>we(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 Sx(e,t={}){let n=new Map;for(let r of Fi){let s=Xo.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 Xo)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:we(r.command)});return[...n.values()].sort((r,s)=>(r.action??"").localeCompare(s.action??""))}function Ex(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null};let n=e.command_path?mt(e.command_path):[],r=n.some(i=>t.handlers.has(i)),s=n.map(i=>kg.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 xg(e){return Xc.get(e)??$r}function Tx(e){return gr.has(e)?!1:Xc.has(e)}function Ax(e){return vg.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function hg(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function Cx(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function Rx(e){let t=new Map;for(let r of e.definitions){let s=hg(r.cli_flag);if(!s)continue;let o=r.cli_aliases.map(a=>Cx(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>hg(a)).filter(a=>a!==null&&a!==s);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=o?{flag:s,short:o}:{flag:s},u=`${m.flag}|${m.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(m));for(let p of i){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,s]of t.entries())n.set(r,Pi(s.flags));return n}function gg(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 Pi(n)}function Ix(e,t,n,r){return e.map(s=>{let o=Tx(s),i=o?xg(s):[],a=n.get(Ax(s))??[],c=t.get(s),m=gg(i,a),u=gg(m,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":o?"core":"extension";return{command:s,flags:u,...r?{canonical_command:Jc(s),visibility:dg(Jc(s)),flag_invocations:jm(s,u)}:{},provider:p,extension_sources:c?.sources}}).sort((s,o)=>s.command.localeCompare(o.command))}function xx(e,t=Kn){let n=new Set(e),r=new Map;for(let s of Tg){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 Ox(){return{create_string_options:Om,create_repeatable_options:hs,update_string_options:Pm,update_repeatable_options:Nm,list_string_options:Qd,search_string_options:Zd,calendar_string_options:el,context_string_options:tl,activity_string_options:nl}}function yg(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=an(e,"create",n),s=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),o=[...new Set(s.map(a=>fe("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 Px(e){let t={},n={};for(let r of[...e.types].sort((s,o)=>s.localeCompare(o))){let s=e.by_type[r];t[r]=yg(s,"strict"),n[r]=yg(s,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Nx(e,t){let n=yr(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 Lx(e){let t=Jo(e.action)!==void 0||Jo(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,s=e.schemaOnly===!0,o=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=Jo(e.action),u=Jo(e.command),p=!r&&!c&&!s&&!o&&!i&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:s,flagsOnly:o,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function Fx(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",d.USAGE)}async function Mx(e,t=A){try{return await t(e)}catch{return structuredClone(pt)}}async function $x(e,t){let n=await Mx(t),r=await kx(e),s=x(n,r.registrations??I()),o=Be(n.schema),i=fx(r);return{settings:n,runtimeProbe:r,typeRegistry:s,statusRegistry:j(n.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:Rx(o),createRequiredOptionContracts:Px(s),extensionContracts:i,mergedExtensionContracts:vx(i),extensionFlagMap:Ig(r.flagRegistrations)}}function bg(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Xo.has(e.selectedAction)||e.selectedCommand!==void 0&&gr.has(e.selectedCommand))}function Dx(e,t){let n=Sx(t,{includePackageOwnedActions:bg(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Tm);return n.filter(s=>!r.has(s.action))}return bg(e)&&e.selectedCommand!==void 0&&gr.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:dx(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function Ux(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new l(`Unknown action: "${e.selectedAction}".`,d.USAGE)}function Gx(e,t){return[...new Set([...zn.filter(n=>!gr.has(n)),...[...Xc.keys()].filter(n=>!gr.has(n)),...e.flatMap(n=>n.command_path?mt(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>we(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function jx(e,t){let n=t.slice(0,ox),r=t.length-n.length,s=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),o=t.slice(0,ix),i=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new l(`Command "${e}" is a command namespace. Choose a concrete child command: ${s}.`,d.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:i,nextSteps:[`Retry with a child command, for example: ${i[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:o.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function qx(e,t){return new l(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,d.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function Kx(e){return new l(`Unknown command: "${e}".`,d.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function zx(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 jx(e.selectedCommand,r);let s=kg.get(e.selectedCommand);throw s?qx(e.selectedCommand,s):Kx(e.selectedCommand)}function Bx(e,t){let n=Dx(e,t.mergedExtensionContracts);Ux(e,n);let r=Gx(n,t.mergedExtensionContracts);zx(e,r);let s=e.selectedCommand?Eg.get(e.selectedCommand):void 0,o=e.selectedCommand?n.filter(m=>s?m.action===s:lx(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!o.some(m=>m.action===e.selectedAction))throw new l(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,d.USAGE);let i=e.selectedAction?o.filter(m=>m.action===e.selectedAction):o,a=[...new Map(i.map(m=>Ex(m,t.runtimeProbe)).map(m=>[s?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(m=>m.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:o,scopedActionDescriptors:i,selectedPackageOwnedAction:s,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function Hx(e){return new Set(yr(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 Vx(e){let t=Rm,n=yr(t),r=Hx(t),s=e.filter(o=>!r.has(o.action)).map(o=>bx(o));return s.length>0?{...t,oneOf:[...n,...s]}:t}function wg(e,t,n){let r=new Set(t.actionDescriptors.map(o=>o.action)),s=e.selectedAction?ux(n,e.selectedAction):e.selectedCommand?Wc(n,new Set(t.scopedActionDescriptors.map(o=>o.action))):Wc(n,r);return e.runtimeOnly&&!e.selectedAction?Wc(s,new Set(t.actions)):s}function Wx(e,t,n){let r=Vx(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?Nx(wg(e,n,r),t.createRequiredOptionContracts):wg(e,n,r);return{mergedSchema:r,filteredSchema:o}}function Yx(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?mx(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Jx(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Kn.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function Jc(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":Ag.get(t)??t}var Xx=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"]]),Qx=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function Zx(e,t){let n=ug.get(e)??(e.includes(" ")?void 0:ug.get(Jc(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>mt(m.command).includes(e));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let s=e.split(" "),o=s.at(-1),i=s.slice(0,-1).join(" "),a=Xx.get(o),c=Qx.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function eO(e,t=[]){return[...new Set(e.map(we))].filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r)).map(n=>{let r=$i(n,{generateFallback:!0}),s=n.split(" ")[0],o=Ag.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),i=new Set([...xg(n).map(m=>m.flag),...t.filter(m=>mt(m.command).includes(n)).flatMap(m=>m.flags.map(u=>u.flag))]),a=(mg.get(n)??mg.get(o)??sx).filter(m=>i.has(m)),c=Zx(n,t);return{command:n,...c,...a.length>0?{flags:a}:{},default_max_estimated_tokens:r.default_max_estimated_tokens,default_max_estimated_tokens_by_format:{...r.default_max_estimated_tokens_by_format}}})}function tO(e){return e.map(t=>({budget:$i(t,{generateFallback:!0}),envelope:qm(t)}))}function nO(e){let t=new Map;for(let n of e){let r=Mm(n),s=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,o=s.join(","),i=t.get(o)??{commands:[],exit_codes:s};i.commands.push(n),t.set(o,i)}return[...t.values()]}function rO(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>mt(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(s=>mt(s.command).some(o=>r.has(o)))}return t.extensionContracts}function sO(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 oO(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:[...gm],services:[...ym],policy_modes:[...bm],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...km],trust_modes:[...wm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...vm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...xd],create_modes:[...Od],close_validation_modes:[...Pd],workflow_enforcement_modes:[...Nd]},e.relationship_kind_contracts=[...Gd,...(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 iO(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 aO(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=Ix(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let o=new Set(r);e.list_projections=Object.entries(Gp).filter(([i])=>o.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...Up],compact_fields:[...Dp]}))}e.command_aliases=s}}function cO(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=Ox();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function dO(e,t,n){e.command_summaries=eO(t,n),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Am],allows_unbounded_opt_out:!0},e.grammar_contracts={nouns:dn.nouns,shared_verbs:dn.shared_verbs,scope_before_verb:dn.scope_before_verb,visible_top_level_ceiling:dn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:dn.ceiling_raise_requires_pm_item}}async function Og(e,t){let n=Lx(e);Fx(n);let r=T(process.cwd(),t.path),s=await $x(t,r),o=Bx(n,s),i=Wx(n,s,o),a=Yx(n,o),c=Jx(n,a),m=sO(n,i,o,c),u=rO(n,s,c);if((n.summary||n.fullOutput)&&dO(m,c,u),n.summary)return m;let p=xx(o.commandCatalog);return n.flagsOnly&&!n.fullOutput||oO(m,s,n),iO(m,n,i,u),aO(m,n,s,c,p),cO(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...Mu],gate_triggers:[...Fu]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=Lm),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=ig(),m.context_intents=$m(),m.read_output_dimensions=Di,m.error_codes=Gm,m.command_output_contracts=tO(c),m.command_exit_contracts={vocabulary:Fm,command_sets:nO(c)}),m}import HO 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]="ed44fc89-8b6e-5c83-a4f4-ced4e9031dac")}catch{}})();function Qo(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 lO(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,s=null,o=null,i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let u;try{u=JSON.parse(m)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(Qo(f,i,p,s,"min")&&(i=f,s=p),Qo(f,a,p,o,"max","max")&&(a=f,o=p))}return{id:e,bytes:n,lines:r,oldest_ts:s,newest_ts:o}}function Pg(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),s=e.map(({id:_,raw:h})=>lO(_,h)),o=0,i=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of s){if(o+=_.lines,i+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);Qo(h,m,_.id,a?.id??null,"min")&&(m=h,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);Qo(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 uO}from"node:crypto";import{execFile as pO}from"node:child_process";import Fg from"node:path";import{promisify as fO}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 Ng=1;function mO(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Qc(e){if(e===null)return{format_version:Ng,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Ng||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!mO(r))throw new l("Improvement ledger contains an invalid observation.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aaa927b3-4bc4-561f-aff1-85dc95c12ea1")}catch{}})();var _O=fO(pO),hO=50,Lg=1e3,gO=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Mg(e){let t=e.trim().toLowerCase();if(!gO.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function yO(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function br(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return n}}function bO(e){let t=e??hO;if(!Number.isSafeInteger(t)||t<0||t>Lg)throw new l(`Improvement observation limit must be an integer from 0 to ${Lg}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function $g(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function wO(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});let r=Mg(n.metric),s=yO(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||s==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let o=await kO(e,n.revision),i=br(n.source,"source"),a=br(n.itemId,"itemId"),c=br(n.unit,"unit"),m=br(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:$g(n.observedAt??S(),"observedAt"),...o,author:R(n.author,t.author_default),...a===void 0?{}:{item_id:a},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:uO("sha256").update(J(u)).digest("hex").slice(0,24),...u}}function vO(e,t){let n=t.idempotency_key?e.observations.find(s=>s.idempotency_key===t.idempotency_key):e.observations.find(s=>s.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(s=>s.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function kO(e,t){let n=br(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await _O("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Dd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function SO(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 Dg(e,t={}){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await wO(n,r,e),o=Fg.join(n,"improvement-ledger.json"),i=await du({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=Qc(a),m=vO(c,s);return m?{raw:a,result:m}:(c.observations.push(s),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${J(c)}
47
+ `,result:s})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function Ug(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=e.metric===void 0?void 0:Mg(e.metric),r=e.since===void 0?void 0:$g(e.since,"since"),s=bO(e.limit),i=Qc(await q(Fg.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of i){let m=a.get(c.metric)??[];m.push(c),a.set(c.metric,m)}return{observations:[...i].reverse().slice(0,s),total:i.length,truncated:i.length>s,trends:[...a].map(([,c])=>SO(c)).sort((c,m)=>c.metric.localeCompare(m.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6162845d-f4b4-5d1f-a210-ddef1a5c38f6")}catch{}})();function Gg(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 EO(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 TO(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 Zc(e=Bn,t=pn){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 AO(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 ed(e,t=pn,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 CO(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let s=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let u=`${c.agent_harness}\0${m}`,p=s.get(u)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),s.set(u,p)}let o=[...s.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[u])=>m.localeCompare(u)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),i=o.filter(c=>c.entries>=r),a=i.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:i.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:o,failures:a}}function RO(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=Gg(o),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(o);continue}let u={id:a.id,...i?.label===void 0?{}:{label:i.label},...i?.parent_id===void 0?{}:{parent_id:i.parent_id},source:a.source,entries:[o],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let s=[];for(let o of n.values()){let i=o.parent_id?r.get(o.parent_id):void 0;i&&EO(o,i,r)?i.children.push(o):s.push(o)}return TO(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 IO=1e4,jg=1e5,xO=1e3,OO=30,PO=["append","comment","docs","file","learning","note","test_run"];function NO(e){let t=e??IO;if(!Number.isSafeInteger(t)||t<1||t>jg)throw new l(`History analytics event limit must be an integer from 1 to ${jg}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function qg(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",d.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function LO(e){let t=e?.trim();if(!t)return new Date(Date.now()-OO*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let s=Number(n[1]),o=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(s)||s<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-s*o).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function Kg(e,t){let n=NO(t.eventLimit),r=LO(t.since),s=[],o=r,i=!1;for(;s.length<n;){let a=await Bo({pmRoot:e,since:o,limit:Math.min(xO,n-s.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(s.push(...c),i=a.has_more,o=a.next_cursor,!a.has_more)break}return{events:s,receipt:{since:r,events:s.length,truncated:i,...i?{next_cursor:o}:{},source:"history_event_index"}}}function FO(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function MO(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 $O(e){return PO.some(t=>e.startsWith(t))}function zg(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 DO(e,t,n){let r=new Map,s=new Map,o=new Map;for(let i of t){let a=FO(i.entry,e),c=MO(i.entry),m=s.get(i.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&s.set(i.item_id,u),!a)continue;let p=zg(r,a);p.events+=1,$O(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,o.set(i.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:o}}function UO(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&&(zg(e,i).defectEscapes+=1)}}}function GO(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 jO(e,t,n,r,s,o){let{buckets:i,lastCloseValue:a}=DO(e,t,r);return UO(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>GO(c,m,s,o)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function qO(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 KO(e,t,n){let r=Zc(t),s=ed(e,pn,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 Bg(e,t=Bn,n={}){let r=qg(n.minimumSample);return{...KO(e.events.map(s=>s.entry),t,r),window:e.receipt}}function Hg(e,t,n,r={}){let s=qg(r.minimumSample),o=qO(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>jO(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 zO=32;function BO(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 wr(e,t){let n=BO(e).map(s=>{let[o,...i]=s.split(","),a=o.indexOf("="),c=o.slice(0,a).trim(),m=o.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${s}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,f;for(let _ of i){let h=_.indexOf("="),y=_.slice(0,h).trim(),g=_.slice(h+1).trim();if(y==="unit"&&g.length>0)p=g;else if(y==="threshold"&&g.length>0&&Number.isFinite(Number(g)))f=Number(g);else throw new l(`Invalid --measure attribute "${_}"`,d.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(s=>[s.name,s])).values()].sort((s,o)=>s.name.localeCompare(o.name)).slice(0,zO)}function Vg(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 Wg(e,t){let n=e.flatMap(o=>o.measurements??[]).filter(o=>o.name===t).sort((o,i)=>i.recorded_at.localeCompare(o.recorded_at)),r=n[0],s=n[1];return{name:t,latest:r?.value??null,previous:s?.value??null,delta:r!==void 0&&s!==void 0?r.value-s.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d28c7ac7-9801-5b0c-84c9-51deede398be")}catch{}})();function VO(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function WO(e,t,n,r,s){let o=Zn(e,"type",r),i=new Set(o.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),m=(s?[...o.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:o.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=VO([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>s||f>0));return{byType:m,byStatus:p,omitted:s?0:a.length+Object.values(u).filter(f=>f===0).length}}function YO(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function JO(e){let t=Yg.join(e,"history");if(!await k(t))return[];await un({path:t,scope:"project"});let n=(await HO.readdir(t)).filter(s=>s.endsWith(".jsonl")).sort((s,o)=>s.localeCompare(o)),r=[];for(let s of n){let o=Yg.join(t,s),i=await q(o);i!==null&&(await un({path:o,scope:"project"}),r.push({id:s.slice(0,-6),raw:i}))}return r}async function XO(e,t){let n=[],r=S();for(let s of wr(t.observe,r))n.push(await Dg({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 QO(e,t,n){let r={};return t.byAssignee&&(r.assignee=Zn(e,"assignee",n)),t.byTag&&(r.tag=Zn(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=Zn(e,"priority",n)),r}async function ZO(e,t,n,r,s){let o={since:s.since,eventLimit:s.eventLimit,minimumSample:s.minimumSample},i=s.provenanceCoverage||s.fleetAttribution?await Kg(e,o):void 0;return{provenanceCoverage:s.provenanceCoverage&&i?Bg(i,n.agent_identity?.harness_signals,o):void 0,fleetAttribution:s.fleetAttribution&&i?Hg(i,t,r,o):void 0}}function eP(e,t,n,r,s){let o=Object.keys(s.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...s.metadataCoverage?{metadata_coverage:s.metadataCoverage}:{},...o?{breakdowns:s.breakdowns}:{},...s.storage?{storage:s.storage}:{},...s.fieldUtilization?{field_utilization:s.fieldUtilization}:{},...s.improvementLedger?{improvement_ledger:s.improvementLedger}:{},...s.recordedObservations.length>0?{recorded_observations:s.recordedObservations}:{},...s.provenanceCoverage?{provenance_coverage:s.provenanceCoverage}:{},...s.fleetAttribution?{fleet_attribution:s.fleetAttribution}:{},generated_at:S()}}async function td(e,t={}){let n=T(process.cwd(),e.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await XO(e,t),o=x(r,I()),i=j(r.schema),a=t.fieldUtilization?await Ts(n,r.item_format,o.type_to_folder,void 0,r.schema):await re(n,r.item_format,o.type_to_folder,void 0,r.schema);await pu({pmRoot:n,settings:r,itemIds:a.map(E=>E.id),commandLabel:"stats"});let c=Xs(i),m=WO(a,o.types,i.definitions.map(E=>E.id),c,t.includeEmpty===!0),u=await JO(n),p=0;for(let E of u)p+=YO(E.raw);let f=t.storage?Pg(u):void 0,_=t.metadataCoverage?Mp(a,c):void 0,h=QO(a,t,c),y=t.fieldUtilization?$p(a):void 0,g=t.measurements===!0||s.length>0?await Ug({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:b,fleetAttribution:v}=await ZO(n,a,r,i.terminal_statuses,t);return eP({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:y,improvementLedger:g,recordedObservations:s,provenanceCoverage:b,fleetAttribution:v})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0e63298a-d2d7-5217-af50-a206348b4cd4")}catch{}})();function Jg(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:he(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:w(e,"measurementSource"),measurementItem:w(e,"measurementItem"),measurementRevision:w(e,"measurementRevision"),author:w(e,"author"),message:w(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:w(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import tP from"node:fs/promises";import Ot 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 ty=Ot.join("runtime","telemetry","events.jsonl"),ny=Ot.join("runtime","telemetry","state.json"),nP=Ot.join("runtime","telemetry"),rP=20,Xg=["status","flush","stats","clear"],Qg=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},nd=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Zg=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},sP=e=>({command:nd(e.event.command,"<unknown>"),eventType:nd(e.event.event_type,"unknown"),eventSchemaVersion:Zg(e.event.schema_version),clientSchemaVersion:Zg(e.client_schema_version)}),oP=()=>({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:{}}),iP=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},aP=e=>{let t=e?.command_resolution;return nd(t,"")||void 0},ry=(e,t)=>{e[t]=(e[t]??0)+1},cP=(e,t)=>{let n=iP(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=aP(t);r!==void 0&&ry(e.resolution_counts,r)},dP=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,ey=(e,t)=>{t!==void 0&&e.add(t)},lP=(e,t)=>{let n=sP(t),r=e.get(n.command)??oP();r.count+=1,r.max_attempts=Math.max(r.max_attempts,dP(t.attempts)),ry(r.event_type_counts,n.eventType),ey(r.event_schema_versions,n.eventSchemaVersion),ey(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&cP(r,t.event.payload),e.set(n.command,r)},mP=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((o,i)=>o-i),s=Object.entries(t.resolution_counts).sort((o,i)=>o[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((o,i)=>o[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((o,i)=>o-i),client_schema_versions:[...t.client_schema_versions].sort((o,i)=>o-i),...r.length>0?{duration_p50_ms:Qg(r,.5),duration_p95_ms:Qg(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)}:{}}},uP=e=>{let t=(e??"status").trim().toLowerCase();if(Xg.includes(t))return t;throw Ee({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Xg,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},rd=()=>{throw new l("--limit must be a positive integer",d.USAGE)},sy=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?rd():e,pP=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?rd():sy(Number.parseInt(t,10))},fP=e=>e===void 0?rP:typeof e=="number"?sy(e):typeof e=="string"?pP(e):rd(),_P=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},hP=e=>{try{let t=JSON.parse(e);return _P(t)?t:void 0}catch{return}},gP=e=>e===null?[]:e.split(`
48
+ `).map(t=>t.trim()).filter(t=>t.length>0),oy=e=>{let t=gP(e),n=[],r=0;for(let s of t){let o=hP(s);o===void 0?r+=1:n.push(o)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},yP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bP=e=>{try{let t=JSON.parse(e);return yP(t)?t:{}}catch{return{}}},wP=async e=>{let t=await q(e);return t===null||t.trim().length===0?{}:bP(t)},Zo=e=>e??null,ei=async e=>{let t=await A(e),n=Ot.join(e,ty),r=Ot.join(e,ny),s=await q(n),o=oy(s),i=await wP(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:Zo(i.last_attempted_flush_at),last_successful_flush_at:Zo(i.last_successful_flush_at),last_failed_flush_at:Zo(i.last_failed_flush_at),last_failed_flush_error:Zo(i.last_failed_flush_error)}},vP=e=>{let t=new Map;for(let n of e)lP(t,n);return[...t.entries()].map(([n,r])=>mP(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},kP=async(e,t)=>({action:"telemetry",subcommand:"status",status:await ei(t.globalPmRoot),generated_at:S()}),SP=async(e,t)=>{let n=await ei(t.globalPmRoot);await Ru(t.globalPmRoot);let r=await ei(t.globalPmRoot),s=Math.max(0,n.queue_entries-r.queue_entries),o=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:s,queue_progressed:s>0,queue_empty:o,queue_drained:o,status:r,generated_at:S()}},EP=async(e,t)=>{let n=fP(e.limit),r=await q(t.queuePath),s=oy(r),o=vP(s.entries),i=o.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:o.length,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_rows_total:s.rows_total,truncated:o.length>i.length,stats:i,generated_at:S()}},TP=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 Se(t.globalPmRoot,n,"telemetry:clear");let s=Ot.join(t.globalPmRoot,nP),o=await k(s);return await tP.rm(s,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:o&&!await k(s),queue_exists_after:await k(t.queuePath),state_exists_after:await k(t.statePath),status:await ei(t.globalPmRoot),generated_at:S()}},AP={status:kP,flush:SP,stats:EP,clear:TP};async function iy(e,t){let n=uP(e.subcommand),r=et(process.cwd());return AP[n](e,{globalPmRoot:r,queuePath:Ot.join(r,ty),statePath:Ot.join(r,ny)})}import{spawn as Ty}from"node:child_process";import{cp as my,mkdir as OP,mkdtemp as Ay,open as ad,readdir as cd,rm as Cy}from"node:fs/promises";import{tmpdir as Ry}from"node:os";import le 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 ay=20;function CP(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return ay;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?ay:t}function sd(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=_n(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=CP();return t.length>n?t.slice(t.length-n):t}async function ti(e){await Y({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=sd([...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 od(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,d.USAGE);return n}function RP(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 dy(e){return e.map((t,n)=>`${n+1}. ${RP(t)}`).join("; ")}function IP(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 xP(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function ly(e,t){let n=IP(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((s,o)=>o+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(s=>`--${s}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,d.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,d.USAGE);if(r==="match"){let s=t.match.trim().toLowerCase();if(s.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let o=[],i=[];for(let a=0;a<e.length;a+=1)xP(e[a],s)&&(i.push(e[a]),o.push(a+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${dy(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:o,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let s=od(t.onlyIndex);if(s>e.length)throw new l(`--only-index ${s} is out of range: this item has ${e.length} linked test(s). Available entries: ${dy(e)}`,d.USAGE);return{selector:"only-index",requested:String(s),selected:[e[s-1]],selected_indexes:[s],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4322c352-6b95-5796-94eb-5a68745d53bc")}catch{}})();var ri=20*1024*1024,PP=3e3,NP=1e4,LP=5e3,uy=120,FP=new Set(["locks","extensions","runtime"]),MP=new Set(["history","index","search","extensions","locks","runtime"]),$P=[/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],DP=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,UP=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,GP=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 jP(){return md("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",PP)}function qP(){return md("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",NP)}function KP(){return md("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",LP)}function zP(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 BP(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 ud(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 HP(e){let t=e??"project";if(!Ze.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function si(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Vt.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${Vt.join(", ")}`,d.USAGE)}function Iy(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:si(e.pm_context_mode)}function xy(e,t){return e==="auto"?t?"tracker":"schema":e}function VP(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 WP(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 YP(e,t){let n={};if(!e)return n;for(let r of e){let s=or(r,t);if(s)for(let[o,i]of Object.entries(s))n[o]=i}return n}function JP(e,t){if(!e)return[];let n=[];for(let r of e){let s=ir(r,t);s&&n.push(...s)}return[...new Set(n)]}function XP(e){let t=oi(e);return Xn(t).some(n=>ua(n)!==null)}function Oy(e){let t=oi(e);return Xn(t).some(n=>{let r=ua(n);if(!r)return!1;let s=Np(r);return s?GP.has(s.subcommand):!1})}function ni(e){if(e)return xp.has(e.subcommand)?Tn(e.args,Op)?.subcommand:e.subcommand}function py(e,t){if(e==="npx"||e==="bunx")return Ys(t)?.command;if(e==="pnpm")return ni(Tn(t,Ap));if(e==="npm")return ni(Tn(t,Cp));if(e==="yarn")return ni(Tn(t,Rp));if(e==="bun")return ni(Tn(t,Ip))}function fy(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function id(e){return!e||!fa(e.command)&&!Pp(e.command)?!1:Ws(e.args)==="test-all"}var QP=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])]),ZP=new Set(["npx","bunx"]);function Py(e){let t=e.split(" ").filter(i=>i.length>0),n=pa(t);if(n.length===0)return!1;let[r,...s]=n,o=QP.get(r);if(o){let i=s.findIndex(a=>o.test(a));return i>=0?Py(s.slice(i+1).join(" ")):!1}return fa(r)||_a(r)?Ws(s)==="test-all":r==="node"&&s.length>0&&_a(s[0])?Ws(s.slice(1))==="test-all":ZP.has(r)?id(Ys(s)):r==="pnpm"?id(ha(s)):r==="npm"?id(ga(s)):!1}function Ny(e){let t=oi(e);return Xn(t).some(n=>Py(n))}function Ly(e){if(Ny(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function oi(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function eN(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function tN(e){let t=/\bpm_path\s*=/.test(e)||/\$env:pm_path\s*=/.test(e),n=/\bpm_global_path\s*=/.test(e)||/\$env:pm_global_path\s*=/.test(e);return t&&n}function nN(e){let t=e.split(" ").filter(o=>o.length>0),n=pa(t);if(n.length===0)return!1;let[r,...s]=n;return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?rN(s):sN(r,s)}function rN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function sN(e,t){return e==="npx"||e==="bunx"?fy(Ys(t)?.command):e==="pnpm"||e==="npm"?fy((e==="pnpm"?ha(t):ga(t))?.command)||py(e,t)==="vitest":(e==="yarn"||e==="bun")&&py(e,t)==="vitest"}function Fy(e){let t=oi(e);if(Xn(t).some(s=>!eN(s)&&nN(s)&&!tN(s)))throw new l('Linked test runner commands must be sandbox-safe: use "node scripts/run-tests.mjs <test|coverage>", use a package-manager script such as "pnpm test", or include PM_PATH=... PM_GLOBAL_PATH=... INLINE in the command string (exporting them in your shell environment is not checked). Example: "PM_PATH=/tmp/pm-x PM_GLOBAL_PATH=/tmp/pm-x-g vitest run".',d.USAGE)}function oN(e){if(Ny(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function iN(e){return e?e.map(aN):[]}function aN(e){let t=e.trim(),n=wo(t)?vo(te(e,"--add"),"--add"):{command:t},r=de(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return Ly(r),Fy(r),{command:r,path:de(n.path),scope:HP(n.scope),timeout_seconds:cN(de(n.timeout_seconds),de(n.timeout)),pm_context_mode:Ao(de(n.pm_context_mode),"--add"),env_set:or(de(n.env_set),"--add"),env_clear:ir(de(n.env_clear),"--add"),shared_host_safe:To(de(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Yt(de(n.assert_stdout_contains)),assert_stdout_regex:xn(de(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Yt(de(n.assert_stderr_contains)),assert_stderr_regex:xn(de(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Co(de(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Ro(de(n.assert_json_field_equals),"--add"),assert_json_field_gte:Io(de(n.assert_json_field_gte),"--add"),note:de(n.note)}}function de(e){let t=e?.trim();return t&&t.length>0?t:void 0}function cN(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",d.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(se(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function dN(e){return e?e.flatMap(t=>{let n=Cf(t,"--add-json");for(let r of n){let s=r.command;if(!s)throw new l("--add-json requires a non-empty command string",d.USAGE);Ly(s),Fy(s)}return n}):[]}function lN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",d.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let s=n.slice(r[0].length).trim();if(!s)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:s}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let s=te(n,"--remove"),o=s.path!==void 0?"path":"command",i=s.path??s.command;if(!i?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:o,value:i.trim()}}return{kind:"either",value:n}}):[]}function mN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function uN(e){try{e.stdin?.end()}catch{}}function My(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=uy?t:`${t.slice(0,uy-3)}...`}function $y(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function dd(e){try{process.stderr.write(`${e}
49
+ `)}catch{}}function pN(e,t){if(!$y(t))return null;let n=My(e.command),r=Date.now();dd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let s=setInterval(()=>{let o=Date.now()-r;dd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${o} command="${n}"`)},qP());return s.unref?.(),s}function fN(e,t,n,r){if(!$y(r))return;let s=My(e.command),o=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let m=t.exitCode===null?"null":String(t.exitCode),u=c.length>0?` ${c.join(" ")}`:"";dd(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${o}${u} command="${s}"`)}async function _y(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Ty("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 _N(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function hN(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 _y(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{_y(r)},jP()),t.forceKillTimer.unref?.()}}function gN(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)},KP()),r.unref?.())}),e.on("close",(o,i)=>{s({code:o,signal:i})})})}function yN(e,t,n,r){return Ty(e,{cwd:process.cwd(),env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function hy(e){let t=await ad(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,ri),s=Buffer.alloc(r);return r>0&&await t.read(s,0,r,0),{text:s.toString("utf8"),truncated:n>ri}}finally{await t.close()}}async function bN(e,t,n,r,s){let o=Date.now(),i=await Ay(le.join(Ry(),"pm-linked-test-output-"));try{let a=le.join(i,"stdout.log"),c=le.join(i,"stderr.log"),[m,u]=await Promise.all([ad(a,"w"),ad(c,"w")]),p;try{p=yN(e,n,m.fd,u.fd)}finally{await Promise.all([m.close(),u.close()])}uN(p);let f={heartbeat:pN(r,s),forceKillTimer:null,timedOutTimer:null},_=hN(p,f),h=!1,y;p.on("error",G=>{y=G.message}),f.timedOutTimer=setTimeout(()=>{h=!0,_()},t),f.timedOutTimer.unref?.();let{code:g,signal:b}=await gN(p);_N(f);let[v,E]=await Promise.all([hy(a),hy(c)]),N=v.truncated||E.truncated,P=N?`
50
+ [pm linked-test output truncated at ${ri} bytes per stream; the child process continued to completion]
51
+ `:"",M={stdout:`${v.text}${P}`,stderr:E.text,exitCode:g,signal:b,timedOut:h,maxBufferExceeded:!1,outputTruncated:N,spawnError:y};return fN(r,M,o,s),M}finally{await Cy(i,{recursive:!0,force:!0})}}function wN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${ri} 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 vN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
52
+ `);return $P.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>DP.test(n)&&UP.test(n))}function kN(e){return vN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function SN(){return{infra_collision:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function ii(e){let t=SN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function gy(e,t){for(let[n,r]of Object.entries(t.env_set))Wt.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)Wt.has(n.toUpperCase())||delete e[n]}function EN(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 TN(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 AN(e,t,n){return{env_set:YP(e,"--env-set"),env_clear:JP(t,"--env-clear"),shared_host_safe:n===!0}}async function $n(e,t,n=!1,r=OP){if(await k(e))try{await Ho("seed_linked_test",async()=>{if(await r(le.dirname(t),{recursive:!0}),n){await my(e,t,{recursive:!0,force:!0});return}await my(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&&_t(s))return;throw s}}async function yy(e,t,n){await $n(C(n.projectPmRoot),C(e)),await $n(le.join(n.projectPmRoot,"extensions"),le.join(e,"extensions"),!0),await $n(C(n.globalPmRoot),C(t)),await $n(le.join(n.globalPmRoot,"extensions"),le.join(t,"extensions"),!0)}async function by(e,t){if(!await k(e))return;let n=await cd(e,{withFileTypes:!0});for(let r of n){if(FP.has(r.name))continue;let s=le.join(e,r.name),o=le.join(t,r.name);if(r.isDirectory()){await $n(s,o,!0);continue}r.isFile()&&await $n(s,o)}}async function Mn(e){if(!await k(e))return 0;let t=0,n=await cd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||MP.has(r.name))continue;let s=le.join(e,r.name),o;try{o=await cd(s,{withFileTypes:!0})}catch{continue}for(let i of o)i.isFile()&&$d.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function CN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function RN(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 wy(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=RN(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 IN(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 xN(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?tt(e,t):Object.is(e,t)}function ON(e,t,n){let r=[];r.push(...vy("stdout",t,e.assert_stdout_contains)),r.push(...ky("stdout",t,e.assert_stdout_regex)),r.push(...vy("stderr",n,e.assert_stderr_contains)),r.push(...ky("stderr",n,e.assert_stderr_regex)),r.push(...PN(t,e.assert_stdout_min_lines));let s=e.assert_json_field_equals??{},o=e.assert_json_field_gte??{};if(!(Object.keys(s).length>0||Object.keys(o).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,m]of Object.entries(s)){let u=wy(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=IN(m);xN(u.value,p)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(u.value)})`)}for(let[c,m]of Object.entries(o)){let u=wy(a,c);if(!u.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof u.value!="number"||!Number.isFinite(u.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}u.value<m&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${m}, actual ${u.value})`)}return r}function vy(e,t,n){let r=[];for(let s of n??[])t.includes(s)||r.push(`${e} missing required text: "${s}"`);return r}function ky(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 PN(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 NN=[{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 LN(e,t){let n=`${e}
53
+ ${t}`;for(let r of NN)if(r.regex.test(n))return r.code;return null}function FN(e){return{root:e,schemaProjectPmPath:le.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:le.join(e,"schema","global"),trackerProjectPmPath:le.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:le.join(e,"tracker","global")}}async function MN(e,t=mr,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 $N(e,t,n){t&&(await yy(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await yy(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await by(t.projectPmRoot,e.trackerProjectPmPath),await by(t.globalPmRoot,e.trackerGlobalPmPath)))}function DN(e,t,n){return e.some(r=>{let s=r.command??"",o=s.length>0&&Oy(s),i=n?.autoPmContext===!0&&o?"auto":Iy(r,t,n?.overrideLinkedPmContext===!0);return xy(i,o)==="tracker"})}async function UN(e,t){return{sourceProjectItemCount:t?await Mn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Mn(t.globalPmRoot):0,schemaProjectItemCount:await Mn(e.schemaProjectPmPath),schemaGlobalItemCount:await Mn(e.schemaGlobalPmPath),trackerProjectItemCount:await Mn(e.trackerProjectPmPath),trackerGlobalItemCount:await Mn(e.trackerGlobalPmPath)}}function GN(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 jN(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?si(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?XP(n):!1,s=r&&n?Oy(n):!1,o=e.options?.autoPmContext===!0&&s,i=o?"auto":Iy(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=xy(i,s);return{linkedOverridePmContextMode:t,executionContext:GN({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:s,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:o})}}function Sy(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function ld(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 qN(e){if(!e.linkedTest.command)return Sy(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=oN(e.linkedTest.command);if(t)return Sy(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=WP({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 ld(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&&!VP(e.linkedTest)?ld(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function KN(e){let t=TN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return gy(n,e.runtimeDirectives),gy(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&EN(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[Hs]="read_only",n}function zN(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 BN(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 HN(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:CN(e.execution),failure_category:kN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:wN(e.execution,e.timeoutMs)}}function VN(e){if(e.options?.failOnEmptyTestRun===!0){let n=LN(e.execution.stdout,e.execution.stderr);if(n)return BN({...e,emptyRunSignal:n})}let t=ON(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?ld(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):zN(e.linkedTest,e.executionContext,e.execution)}async function WN(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await bN(t,n,KN(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?VN({...e,execution:r}):HN({...e,execution:r,timeoutMs:n})}async function pd(e,t,n){let r=[],s=await Ay(le.join(Ry(),"pm-linked-test-")),o=FN(s),i=si(n?.pmContext),a=n?.progress===!0?"always":"auto",c=AN(n?.envSet,n?.envClear,n?.sharedHostSafe),m=n?.sourceRoots,u=DN(e,i,n);try{await MN(o,mr,u),await $N(o,m,u);let p=await UN(o,m);for(let f=0;f<e.length;f+=1){let _=e[f],h=jN({linkedTest:_,layout:o,counts:p,sourceRoots:m,runLevelPmContextMode:i,options:n}),y=qN({linkedTest:_,executionContext:h.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:h.linkedOverridePmContextMode,options:n});if(y){r.push(y);continue}r.push(await WN({linkedTest:_,index:f,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:c,progressMode:a,executionContext:h.executionContext,options:n}))}}finally{await Cy(o.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function YN(e){let{id:t,pmRoot:n,settings:r,typeToFolder:s}=e,o=await $(n,t,r.id_prefix,r.item_format,s);if(!o)throw new l(`Item ${t} not found`,d.NOT_FOUND);let i=await K(o,{schema:r.schema});return{itemId:o.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function JN(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode}function XN(e,t){let n=[...e];for(let r of t)n.some(s=>JN(s,r))||n.push(r);return n}function QN(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 ZN(e,t,n,r){return QN(XN(e,t),n,r)}function eL(e){return(e.envSet?.length??0)>0||(e.envClear?.length??0)>0||e.sharedHostSafe===!0||e.pmContext!==void 0||e.overrideLinkedPmContext===!0||e.failOnContextMismatch===!0||e.failOnSkipped===!0||e.failOnEmptyTestRun===!0||e.requireAssertionsForPm===!0||e.checkContext===!0||e.autoPmContext===!0}function tL(e){if(eL(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",d.USAGE)}async function nL(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 YN({id:t,pmRoot:r,settings:s,typeToFolder:o});let m=0,u=await Y({pmRoot:r,settings:s,id:t,op:i.length>0?"tests_add":"tests_remove",author:R(n.author,s.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=ZN(f,i,a,c);if(m=_.removed,(a.length>0||c.length>0)&&m===0)throw new l("No linked tests matched the requested removal selector",d.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return p.metadata.tests=_.tests,{changedFields:tt(f,_.tests)?[]:["tests"]}}});return{itemId:u.item.id,tests:u.item.tests??[],testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:m}}function rL(e,t){tL(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:od(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?ly(t,n):void 0,s=e.timeout===void 0?void 0:se(e.timeout,"timeout");if(s!==void 0&&s<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:s,pmContextMode:si(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function sL(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await pd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,sourceRoots:{projectPmRoot:r,globalPmRoot:et(process.cwd())}})}function oL(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=ud(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 iL(e){let t=BP(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),s=S(),o=wr(e.options.measure,s);return{run_id:zP("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 aL(e){let{options:t,pmRoot:n,settings:r,itemId:s,runStartedAt:o,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!o)return;let m=iL({options:t,runStartedAt:o,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return m;try{return await ti({pmRoot:n,settings:r,itemId:s,author:R(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),m}catch(u){return c.push(`test_result_tracking_failed:${s}:${u instanceof Error?u.message:String(u)}`),m}}function Ey(e,t,n){let r;if(e.metricBelow!==void 0){let s=e.metricBelow.indexOf("="),o=e.metricBelow.slice(0,s).trim(),i=e.metricBelow.slice(s+1).trim(),a=Number(i);if(s<=0||o.length===0||i.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",d.USAGE);r=Vg(t,o,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Wg(t,e.metricDiff)}}async function ai(e,t,n){let r=Ne(),s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);wr(t.measure,"validation"),Ey(t,[],void 0);let i=x(o,I()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...iN(a),...dN(c)],p=lN(m),f=mN(t.removeIndex),_=await nL({id:e,options:t,pmRoot:s,settings:o,typeToFolder:i.type_to_folder,adds:u,removes:p,removeIndexes:f}),h=rL(t,_.tests),y=t.run===!0?S():void 0,g=await sL({options:t,runOptions:h,pmRoot:s}),b=ii(g),v=t.run===!0&&t.failOnSkipped===!0&&g.some(G=>G.status==="skipped"),E=oL(t,h.runSelection,g),N=await aL({options:t,pmRoot:s,settings:o,itemId:_.itemId,runStartedAt:y,runResults:g,failOnSkippedTriggered:v,warnings:E}),P=N?sd([..._.testRuns,N]):_.testRuns,M=Ey(t,P,N);return{ok:g.every(G=>G.status!=="failed")&&v!==!0,id:_.itemId,tests:_.tests,run_results:g,failure_categories:b,selection:h.runSelection?{selector:h.runSelection.selector,requested:h.runSelection.requested,selected_indexes:h.runSelection.selected_indexes,selected_count:h.runSelection.selected_count,skipped_count:h.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:v?!0:void 0,warnings:E.length>0?E:void 0,changed:_.changed,count:_.tests.length,..._.removed>0?{removed:_.removed}:{},...M}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7fea0ecb-35e2-5d40-931f-ffdd1a465fdc")}catch{}})();var cL=(e,t)=>{if(e===void 0)return;let n=ne(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},dL=e=>{if(e===void 0)return;let t=se(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},Dy=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,d.USAGE);return n},lL=e=>e instanceof Error?e.message:String(e),mL=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},uL=e=>e.trim().replaceAll(/\s+/g," "),pL=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),fL=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),_L=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},ci=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Uy=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),hL=e=>typeof e=="number"?e:void 0,gL=e=>{let t={assert_stdout_contains:ci(e.assert_stdout_contains),assert_stdout_regex:ci(e.assert_stdout_regex),assert_stderr_contains:ci(e.assert_stderr_contains),assert_stderr_regex:ci(e.assert_stderr_regex),assert_stdout_min_lines:hL(e.assert_stdout_min_lines),assert_json_field_equals:Uy(e.assert_json_field_equals),assert_json_field_gte:Uy(e.assert_json_field_gte)};return JSON.stringify(t)},yL=e=>{let t=fd(e.command);return t!==void 0?`command:${e.scope}:${uL(t)}`:`path:${e.scope}:${fd(e.path)??""}`},Gy=e=>{let t=pL(e.env_set),n=fL(e.env_clear),r=_L(e.pm_context_mode),s=e.shared_host_safe===!0?"true":"false",o=gL(e);return`${yL(e)}:${t}:${n}:${r}:${s}:${o}`},bL=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,wL=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}},vL=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},di=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
54
+ `)}catch{}},kL=async(e,t,n)=>{let r=[],s=0;for(let o of e){let i=await ai(o.id,{run:!1},{...t,path:n});s+=i.tests.length,r.push({item:o,tests:i.tests})}return{itemTests:r,linkedTests:s}},SL=async e=>{let t=j(e.settings.schema),n=x(e.settings,I()),r=cL(e.options.status,t),s=Dy(e.options.limit,"--limit"),o=Dy(e.options.offset,"--offset")??0,a=(await re(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(m=>r?m.status===r:!0).sort((m,u)=>m.id.localeCompare(u.id));return{filteredItems:s===void 0?a.slice(o):a.slice(o,o+s),statusFilter:r,limitFilter:s,offsetFilter:o}},EL=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let s=Gy(r);if(!t.has(s)){t.set(s,r.timeout_seconds);continue}t.set(s,bL(t.get(s),r.timeout_seconds))}return t},TL=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=Gy(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 pd(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=wL(i),c=ii(i),m=await RL(e,a,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:m,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:i,failure_categories:c}}},AL=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),CL=e=>e?!0:void 0,RL=async(e,t,n)=>{if(!n.trackingEnabled)return[];try{let r=AL(t,n.options);await ti({pmRoot:n.pmRoot,settings:n.settings,itemId:e.item.id,author:n.trackingAuthor,message:`Track test-all run summary (${n.trackingRunId})`,entry:{run_id:n.trackingRunId,kind:"test-all",status:r?"failed":"passed",started_at:n.runStartedAt,finished_at:S(),recorded_at:S(),attempt:n.trackingAttempt,resumed_from:n.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:CL(n.options.failOnSkipped===!0&&t.skipped>0)}})}catch(r){return[`test_result_tracking_failed:${e.item.id}:${lL(r)}`]}return[]},IL=()=>{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},fd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},xL=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:et(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:EL(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:R(e.options.author,e.settings.author_default),trackingRunId:mL(),trackingAttempt:IL(),trackingResumedFrom:fd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),OL=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:ii([]),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}},PL=async(e,t,n)=>{for(let[r,s]of e.entries()){di(t.options,`item ${r+1}/${e.length} start id=${s.item.id} linked_tests=${s.tests.length}`);let o=await TL(s,t);vL(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),di(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}`)}},NL=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(s=>s.run_results),r=ud(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}`)},LL=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}),FL=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(" "),ML=async(e,t)=>{let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await SL({pmRoot:n,settings:r,options:e}),o=dL(e.timeout),i=S(),a=await kL(s.filteredItems,t,n);return di(e,FL({...s,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:s.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:o,runStartedAt:i}},$L=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}},jy=async(e,t)=>{let n=await ML(e,t),{accumulation:r,failOnEmptyTestRunTriggered:s}=OL(e,n.linkedTests,n.filteredItems),o=xL({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await PL(n.itemTests,o,r),NL(e,r);let i=$L({options:e,accumulation:r,failOnEmptyTestRunTriggered:s});return di(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),LL({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]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function qy(e){return ps("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]="2643d11d-befc-5a87-8bec-760951eec4d0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2567f6a-cd1c-56b5-a93d-41e92ed574bf")}catch{}})();function Ky(){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 By=[{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"]}],zy=new Map;for(let e of By){zy.set(e.id,e);for(let t of e.aliases)zy.set(t,e)}function _d(){return By.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 Iz=[...Ar],xz=[...Cr],DL=new Set(Kn.filter(e=>e.hidden).map(e=>e.alias)),Oz=lg("full").filter(e=>!DL.has(e)),Pz=F(Dr),Nz=F(Ur),Lz=F(Hr),Fz=F(Xr),Mz=F(Qr),$z=F(jl),Dz=F(ql),Uz=F(Jr),Gz=F(ns),jz=F(Zr),qz=F(es),Kz=F(Br),zz=F(ts),Bz=F(Gr),Hz=F(jr,!1),Vz=F(Ql),Wz=F(jn),Yz=F(qn),Jz=F(is),Xz=F(ss),Qz=F(Wr),Zz=F(os),eB=F(rs),tB=F(as),nB=F(Vr),rB=F(Yr),sB=F(Kr),oB=F(cs),iB=F(qr);var UL=F(ds),aB=`${UL} bash zsh fish`,cB=GL(_d());var dB=F(zr),lB=F(Gn);var mB=$r.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function GL(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0224a672-e326-5555-a4b4-1fa3550d9e61")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8f02f498-5cee-59fa-9f4e-fd882c58d401")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48d9b905-70a1-52c3-9b9c-33624661e6eb")}catch{}})();var Yy=Symbol("pm.active-extension-host-context");function Re(e){return{fullChangedFields:!0,options:e}}var U=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[Yy]=!0,n}run(t,n={}){return Jy({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Bp(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Zi(await this.list(Qi(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,...Re({...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",Re(t))}update(t,n={}){return this.runTyped("update",{id:t,...Re(n)})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Re(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Re(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Re(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Re(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Re(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Re(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},...Re(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Re(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Re(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Re(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 qL(e={},t={}){return new U(t).context(e)}function KL(e={},t={}){return new U(t).list(e)}function zL(e={},t={}){return new U(t).listAllComplete(e)}function BL(e,t={},n={}){return new U(n).search(e,t)}function HL(e,t={},n={}){return new U(n).get(e,t)}function VL(e={},t={}){return new U(t).next(e)}function WL(e={},t={}){return new U(t).aggregate(e)}function YL(e,t={},n={}){return new U(n).comments(e,t)}function JL(e,t={},n={}){return new U(n).notes(e,t)}function XL(e,t={},n={}){return new U(n).learnings(e,t)}function QL(e,t={},n={}){return new U(n).files(e,t)}function ZL(e,t={},n={}){return new U(n).filesDiscover(e,t)}function eF(e,t={},n={}){return new U(n).docs(e,t)}function tF(e,t={},n={}){return new U(n).deps(e,t)}function nF(e,t={},n={},r={}){return new U(r).graph(e,t,n)}function rF(e,t,n={},r={}){return new U(r).append(e,t,n)}function sF(e={},t={}){return new U(t).create(e)}function oF(e,t={},n={}){return new U(n).update(e,t)}function iF(e,t,n={},r={}){return new U(r).close(e,t,n)}function aF(e,t={},n={}){return new U(n).claim(e,t)}function cF(e={},t={}){return new U(t).claimNext(e)}function dF(e,t={},n={}){return new U(n).release(e,t)}function lF(e,t={},n={}){return new U(n).copy(e,t)}function mF(e,t={},n={}){return new U(n).delete(e,t)}function uF(e,t,n={},r={}){return new U(r).restore(e,t,n)}function pF(e,t={},n={}){return new U(n).focus(e,t)}function Je(e,t){let n=w(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}var Hy=Km(),fF=new jL;function li(){qi(zd()),Ki(Bd()),zi(Hd()),Bi(Vd()),Hi(Wd()),Vi(Yd()),Wi(Jd())}async function _F(e,t,n,r){return zm(()=>t===void 0?Hy.read(()=>Vy(e,n,r)):Hy.write(()=>gF(t,()=>Vy(e,n,r))))}async function Vy(e,t,n){let r=T(t,e.path);if(e.noExtensions)return li(),Ia({pmRoot:r},()=>n(null));if(!await k(C(r)))return li(),n(null);let s=null,o;try{let i=await A(r),a=await Fr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Mr({...a,loaded:a.loaded});o={loadResult:a,activationResult:c},qi(c.hooks),Ki(c.commands),zi(c.parsers),Bi(c.preflight),Hi(c.services),Vi(c.renderers),Wi(c.registrations),s={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){li(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Ia({pmRoot:r,packages:s?.packages},()=>n(s))}finally{li(),o&&await Xd(o.loadResult,o.activationResult).catch(()=>{})}}async function hF(e,t,n,r,s){if(!s)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let o=qt(e),a=s.registrations.commands.find(m=>qt(m.action)===o)?.command??s.commands.handlers.find(m=>qt(m.command)===o)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=await ys({command:aa(a),args:he(n.args??t.args),options:ca(t,n),global:r,pm_root:s.pmRoot,sdk:Yp(s.pmRoot,U.forActiveExtensionHost({pmRoot:s.pmRoot,author:typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension"}))});if(!c.handled){let m=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${m}`,d.USAGE)}return c.result}async function gF(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var yF=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function bF(e){let t=Je(e,"action"),n=qt(t),r=ui(Vp,n),s=r?.action??n,o={...e,action:s};return r?.options!==void 0&&(o.options={...r.options,...Oi(e.options)}),s==="package"&&(o.options={...Oi(o.options),vocabulary:"package"}),{action:s,args:o}}function wF(e){return!yF.has(qt(e))}async function Jy(e){let t=bF(e),n=sa(t.args),r=wF(t.action),s=w(t.args,"cwd"),o=s??process.cwd();try{return e[Yy]===!0||fF.getStore()===!0?await Wy(t.action,t.args,n,null):await _F(n,s,o,i=>Wy(t.action,t.args,n,i))}finally{r&&Ta()}}function ui(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function mi(e){return w(e.args,"target")??w(e.options,"target")}function W(e,t=e.options){return e.id??Je(t,"id")}async function vF(e){let t=ln("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),Ea(await Et(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function kF(e){let t=ln("search",e.options);return t.compact===void 0&&t.full===void 0&&t.fields===void 0&&(t.compact=!0),Ea(await tr(Je(e.args,"query"),t,e.global),t)}async function SF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options);return st(await At(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function EF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(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 st(await hc(W(e,s),s,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function TF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options);return st(await at(W(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function AF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options),s=w(e.args,"reason")??w(e.args,"text")??w(r,"reason")??w(r,"text");return st(await Tt(W(e,r),s,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function CF(e){let t=so(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")),uf(W(e),t,e.global)}function Xy(e,t){return Tp(sg(e.options,t,Le),e.global)}function RF(e){let t=he(e.options.lookupPath);if(t&&t.length>0)return Xy(e,t);let n=W(e);return e.options.discover===!0?ma(n,ia(e.options),e.global):Ep(n,zs(e.options),e.global)}function IF(e){return iy({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:Ku(e.args,e.options)},e.global)}function xF(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),kp(e.global,t)}function OF(e){let t=w(e.args,"configAction")??w(e.options,"configAction")??w(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);return N_(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 PF(e){let t=e.options;return Lu(Nu(t),e.global)}function NF(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}function LF(e){let t=w(e.args,"subcommand")??Je(e.options,"subcommand"),n=e.options;return m_({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:FF(e),reorderTo:NF(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function FF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function MF(e){let t=w(e.args,"subcommand")??Je(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:he(n)}}function $F(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,a=ui({list:()=>ip(t.global),show:()=>ap(r,t.global),"show-status":()=>cp(r,t.global),"list-fields":()=>mp(t.global),"show-field":()=>up(r,t.global),"remove-type":()=>np(r,{author:s,force:o},t.global),"remove-field":()=>lp(r,{author:s,force:o},t.global),"remove-status":()=>op(r,{author:s,force:o},t.global),"apply-preset":()=>pp(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:s,force:o},t.global)},n);return a?a():null}function DF(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 dp(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:he(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:he(a),author:r,force:s},t.global)}function UF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e,i=t.args.role??t.options.role;return sp(n,{role:i===void 0?void 0:he(i),alias:o,description:w(t.args,"description")??w(t.options,"description"),order:Le(t.args.order??t.options.order,"schema add-status order"),author:r,force:s},t.global)}function GF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e;return tp(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 jF(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,i=w(t.args,"to")??Je(t.options,"to"),a=w(t.args,"migrationId")??w(t.args,"migration_id")??w(t.options,"migrationId")??w(t.options,"migration_id"),c=w(t.args,"fieldTypeScope")??w(t.options,"fieldTypeScope")??w(t.args,"type")??w(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:i}:n==="rename-field"?{kind:"rename-field",from:r??"",to:i,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:i};return Zu(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:s,force:o},t.global)}function qF(e){let t=MF(e),n=$F(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return jF(t);if(t.subcommand==="add-field")return DF(t);if(t.subcommand==="add-status")return UF(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?fp({minCount:Le(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):GF(t);throw Ee({command_path:"schema",token:t.subcommand,allowed:ep,exit_code:64})}function KF(e){let t=w(e.args,"subcommand")??Je(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),o=ui({list:()=>Vh(),show:()=>Wh(r),lint:()=>Yh(r),apply:()=>Jh(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 Ee({command_path:"profile",token:t,allowed:Hh,exit_code:64});return o()}async function zF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options);return st(await Xp(W(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function BF(e){let{changedFields:t,runnerOptions:n}=Ve(e.args,e.options);return st(await Zf(la(n),e.global),{changedFields:t})}async function HF(e){let{changedFields:t,runnerOptions:n}=Ve(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),st(await mf(da(s),e.global),{changedFields:t})}async function VF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options),s=w(r,"target")??Je(e.args,"target");return st(await zt(W(e,r),s,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Qy(e){let t={...e};return delete t.assignee,t}async function WF(e){let t=T(process.cwd(),e.global.path),n=await A(t),r=qy(j(n.schema)),s=W(e),o=await io(s,e.force,e.global,e.options),i=await at(s,{...Qy(e.options),status:r,force:e.force},e.global);return{id:s,action:"start_task",claim:o,update:i}}async function YF(e){let t=T(process.cwd(),e.global.path),n=await A(t),r=W(e),s=j(n.schema).open_status,o=await at(r,{...Qy(e.options),status:s,force:e.force},e.global),i=await ao(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:o,release:i}}async function JF(e){let t=W(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await Tt(t,n,{...e.options,force:e.force},e.global),s=await ao(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:s}}function XF(e){let t={...e.args,...e.options};return Uu(Je(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),Hu(t),e.global)}function QF(e){return Wu(T(process.cwd(),e.global.path),{...e.args,...e.options})}var ZF={init:e=>mr(w(e.args,"prefix"),e.global,e.options),context:e=>va(ln("context",e.options),e.global),next:e=>er(ln("next",e.options),e.global),eval:Fh,events:Mh,merge:$h,workspace:Dh,meet:Wo,event:Wo,remind:Wo,list:vF,get:e=>ka(W(e),e.global,ln("get",e.options)),search:kF,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:he(e.options.status);return Sa(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:Le(e.options.limit,"limit")})},create:SF,copy:EF,focus:e=>yc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:TF,restore:VF,claim:e=>e.options.next===!0||e.args.next===!0?sf(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):io(W(e),e.force,e.global,e.options),release:e=>ao(W(e),e.force,e.global,e.options),"start-task":WF,"pause-task":YF,"close-task":JF,close:AF,comments:CF,notes:e=>ff(W(e),so(e.options),e.global),learnings:e=>pf(W(e),so(e.options),e.global),files:RF,docs:e=>Sp(W(e),zs(e.options),e.global),test:e=>ai(W(e),e.options,e.global),"test-all":e=>jy(e.options,e.global),telemetry:IF,validate:e=>Js(e.options,e.global,{runUpdate:(t,n,r)=>at(t,n,r)}),health:xF,assurance:e=>Lp(e.args,e.options,e.global),contracts:e=>Og(e.options,e.global),config:OF,activity:PF,aggregate:e=>ya(e.options,e.global),extension:e=>En(mi(e),e.options,e.global),package:e=>En(mi(e),e.options,e.global),install:e=>En(mi(e),{...e.options,install:!0},e.global),upgrade:e=>qp(mi(e),e.options,e.global),delete:e=>gc(W(e),e.options,e.global),deps:e=>Du(W(e),e.options,e.global),graph:XF,"files-discover":e=>ma(W(e),e.options,e.global),"files-lookup":e=>Xy(e,he(e.options.paths)),history:e=>jp(W(e),e.options,e.global),"history-redact":e=>gu(W(e),e.options,e.global),"history-repair":ng,"history-compact":rg,"history-author-acknowledge":QF,plan:LF,schema:qF,profile:KF,stats:e=>td(e.global,Jg(e.options)),append:zF,"update-many":BF,"close-many":HF,gc:e=>Kp(e.global,e.options)};async function Wy(e,t,n,r){let s=oa(t,e);Ui(e,s),Cm(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=ui(ZF,e),a=i?await i(o):await hF(e,t,s,n,r);return s.resolvedOutputFormat="json",Um(e,s,a)}var eM={closeManyOptionsFromFlat:da,extensionOptionsFromArgs:ca,globalOptions:sa,mutationListOptions:Bu,normalizeActionName:qt,normalizeCommandPath:aa,normalizeMcpUpdateOptions:Vu,normalizeMcpOptionsArrays:zu,optionsWithAuthor:oa,readRequiredString:Je,readScalarString:ju,readScalarStringAllowBlank:qu,readStringArray:he,updateManyOptionsFromFlat:la,withAddNoteOption:zs,withFilesDiscoveryOptions:ia,withMutationCompaction:Ve};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=eM);(function(){try{var e=typeof window<"u"?window:typeof 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]="3b27abec-8da3-531a-9bbc-71e97b8b65c5")}catch{}})();export{pn as AGENT_PROVENANCE_DIMENSIONS,Wm as BASELINE_ITEM_FORMAT_VERSION,Bn as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,Ar as BUILTIN_ITEM_TYPE_VALUES,Rr as CONFIDENCE_TEXT_VALUES,Ym as CURRENT_ITEM_FORMAT_VERSION,Ft as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,sn as ISSUE_SEVERITY_VALUES,Id as ITEM_TYPE_VALUES,Aa as PM_CLI_EXPECTED_ERROR_NAME,Wb as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,Hb as PM_READ_OUTPUT_DIMENSIONS,Vb as PM_READ_OUTPUT_OPTION_FLAGS,Di as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,U as PmClient,rn as RISK_VALUES,_w as SEMANTIC_ATTRIBUTION_LIMITS,Cr as STATUS_VALUES,sw as agentSessionEnvironment,WL as aggregate,Zc as analyzeAgentProvenanceDescriptorCoverage,ew as analyzeSdkCliParameterCompleteness,rF as append,Xb as applyReadOutputDimensions,jb as applyReadOutputSessionReferences,qb as attachReadOutputSessionReceipt,tw as boundAgentEpisodeIdentity,He as canonicalDocument,aF as claim,cF as claimNext,Qm as classifyItemFormatVersion,iF as close,YL as comments,qL as context,lF as copy,sF as create,Wp as createPmCliExpectedError,Bb as decodeReadOutputContinuationCursor,mF as deleteItem,tF as deps,cw as detectAgentIdentity,mw as detectHarnessIdentity,dw as diagnoseAgentIdentity,eF as docs,Jm as effectiveItemFormatVersion,Ky as emptyImportedDocument,zb as encodeReadOutputContinuationCursor,CO as evaluateSemanticAttributionCoverage,pw as explainSourceTraceability,QL as files,ZL as filesDiscover,pF as focus,HL as get,nF as graph,RO as groupHistoryByEpisode,rf as isAlreadyClaimedError,to as isPmCliExpectedError,Qb as isReadOutputBudgetExceeded,XL as learnings,KL as list,zL as listAllComplete,VL as next,Xm as normalizeItemFormatVersion,_e as normalizeItemId,ne as normalizeStatusInput,JL as notes,S as nowIso,Gb as parseReadOutputSession,Vs as parseSourceLineRange,ws as readAuthorEnvironment,Kb as readOutputSessionRemainingTokens,ba as recordClaimSemanticAttribution,Qs as recordFocusSemanticAttribution,wa as recordReleaseSemanticAttribution,ow as registerHarnessSignalDescriptors,dF as release,nw as resolveAgentSessionContextFromSignals,uw as resolveAuthorIdentity,Gg as resolveHistoryEpisodeGroupIdentity,Jb as resolveReadOutputDimensions,Zb as resolveReadOutputEncoding,Yb as resolveReadOutputSurface,fw as resolveSemanticLineageIds,uF as restore,Jy as runAction,rw as runWithAgentSessionContext,iw as runWithHarnessDetectionSignals,aw as runWithWorkspaceHarnessSignalDescriptors,BL as search,hw as semanticAttributionAffinity,$e as serializeItemDocument,AO as summarizeAgentModelProvenance,ed as summarizeAgentProvenance,oF as update,Ui as validateReadOutputOptions,lw as writeAuthorEnvironment};
55
55
  //# sourceMappingURL=sdk-core.js.map