@unbrained/pm-cli 2026.9.5 → 2026.9.6

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 (185) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +32 -2
  3. package/dist/cli/main.js +10 -8
  4. package/dist/cli/register-operations.js +13 -8
  5. package/dist/cli-bundle/bundle-manifest.json +150 -158
  6. package/dist/cli-bundle/chunks/chunk-AZDFJGH6.js +9 -0
  7. package/dist/cli-bundle/chunks/{chunk-WWAEGW4V.js → chunk-BAX2BYUW.js} +66 -66
  8. package/dist/cli-bundle/chunks/{chunk-IBYREGSP.js → chunk-CKOL5U7J.js} +51 -51
  9. package/dist/cli-bundle/chunks/{chunk-ZRAQS3UA.js → chunk-JT6XF6GE.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-HUAQITVW.js → chunk-JX4DH4WC.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-QPZHQY2O.js → chunk-NPN5I67J.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-66VPKFP2.js → chunk-OF76PSDQ.js} +2 -2
  13. package/dist/cli-bundle/chunks/chunk-QUWFABDM.js +232 -0
  14. package/dist/cli-bundle/chunks/{chunk-3HBDTJRK.js → chunk-RWWBOWJ5.js} +2 -2
  15. package/dist/cli-bundle/chunks/chunk-WGAOYSYH.js +40 -0
  16. package/dist/cli-bundle/chunks/{chunk-SF6SM6U5.js → chunk-WI2AYPA7.js} +2 -2
  17. package/dist/cli-bundle/chunks/{register-list-query-AYKGODWT.js → register-list-query-5JL52D33.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-mutation-YZYG53SQ.js → register-mutation-ZPG7KMVP.js} +2 -2
  19. package/dist/cli-bundle/chunks/register-operations-I5W3KMGB.js +2 -0
  20. package/dist/cli-bundle/chunks/{register-setup-UJCRVGBG.js → register-setup-H4SVAVX7.js} +2 -2
  21. package/dist/cli-bundle/focused-chunks/{chunk-QL66QNWG.js → chunk-3BZEOXLT.js} +2 -2
  22. package/dist/cli-bundle/focused-chunks/chunk-AL5ON6K6.js +2 -0
  23. package/dist/cli-bundle/focused-chunks/chunk-CHC2IDXA.js +6 -0
  24. package/dist/cli-bundle/focused-chunks/chunk-CK6QFAPZ.js +20 -0
  25. package/dist/cli-bundle/focused-chunks/{chunk-WOCIPMW7.js → chunk-EZR3GHFE.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/chunk-H2WJWK7L.js +56 -0
  27. package/dist/cli-bundle/focused-chunks/{chunk-3ASU6WGI.js → chunk-LIJIA4TY.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-H5FOGAVD.js → chunk-M6PBRFSH.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-B2TTQGFG.js → chunk-NTPY5GSO.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/chunk-P5O7MP5Y.js +2 -0
  31. package/dist/cli-bundle/focused-chunks/chunk-PDMW2E36.js +177 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-YEF5PQQ2.js → chunk-PEFABF7E.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-KWWCBWFO.js → chunk-QTVCLMSZ.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-4OSHLNUE.js → chunk-QTZRBUYA.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/chunk-SGQST3PQ.js +12 -0
  36. package/dist/cli-bundle/focused-chunks/chunk-UKHASMMP.js +10 -0
  37. package/dist/cli-bundle/focused-chunks/chunk-ZPEKQHOC.js +2 -0
  38. package/dist/cli-bundle/main.js +20 -20
  39. package/dist/cli-bundle/sdk-authoring.js +1 -1
  40. package/dist/cli-bundle/sdk-contracts.js +2 -2
  41. package/dist/cli-bundle/sdk-core.js +37 -37
  42. package/dist/cli-bundle/sdk-governance.js +1 -1
  43. package/dist/cli-bundle/sdk-graph.js +1 -1
  44. package/dist/cli-bundle/sdk-merge.js +42 -42
  45. package/dist/cli-bundle/sdk-query.js +1 -1
  46. package/dist/cli-bundle/sdk-runtime.js +1 -1
  47. package/dist/cli-bundle/sdk-testing.js +1 -1
  48. package/dist/cli-bundle/sdk.js +9 -9
  49. package/dist/core/extensions/module-graph-snapshot.js +5 -4
  50. package/dist/core/fs/host-environment-errors.d.ts +27 -0
  51. package/dist/core/fs/host-environment-errors.js +142 -0
  52. package/dist/core/output/mutation-projection.js +12 -5
  53. package/dist/core/store/item-metadata-query-index.js +13 -10
  54. package/dist/core/store/item-metadata-read-work.d.ts +19 -0
  55. package/dist/core/store/item-metadata-read-work.js +44 -0
  56. package/dist/core/store/item-store.js +6 -2
  57. package/dist/core/validate/fix-planning.d.ts +1 -1
  58. package/dist/core/validate/fix-planning.js +2 -2
  59. package/dist/core/validate/missing-link-owners.d.ts +1 -1
  60. package/dist/core/validate/missing-link-owners.js +5 -3
  61. package/dist/core/validate/stale-file-classification.d.ts +6 -4
  62. package/dist/core/validate/stale-file-classification.js +20 -5
  63. package/dist/mcp/server.js +12 -5
  64. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  65. package/dist/sdk/cli-contracts/flag-contracts.js +7 -5
  66. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +4 -3
  67. package/dist/sdk/cli-contracts/grammar-contracts.js +11 -2
  68. package/dist/sdk/cli-contracts/runtime-contracts.js +5 -2
  69. package/dist/sdk/cli-contracts/schemas/assurance-definition.d.ts +254 -5
  70. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +52 -2
  71. package/dist/sdk/cli-contracts/tool-parameter-tables.js +18 -6
  72. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  73. package/dist/sdk/cli-contracts/tool-schema.js +17 -5
  74. package/dist/sdk/context/usage-ledger.d.ts +41 -0
  75. package/dist/sdk/context/usage-ledger.js +186 -0
  76. package/dist/sdk/context-usage.d.ts +18 -9
  77. package/dist/sdk/context-usage.js +37 -112
  78. package/dist/sdk/dependency-provenance.d.ts +7 -0
  79. package/dist/sdk/dependency-provenance.js +14 -4
  80. package/dist/sdk/duplicates.d.ts +2 -0
  81. package/dist/sdk/duplicates.js +3 -2
  82. package/dist/sdk/environment/host-environment-errors.d.ts +5 -27
  83. package/dist/sdk/environment/host-environment-errors.js +4 -137
  84. package/dist/sdk/extension/install-runtime.js +9 -6
  85. package/dist/sdk/extension/install-snapshot.js +7 -6
  86. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +8 -8
  87. package/dist/sdk/governance/assurance-action.d.ts +3 -2
  88. package/dist/sdk/governance/assurance-action.js +23 -11
  89. package/dist/sdk/governance/assurance-runtime.d.ts +2 -0
  90. package/dist/sdk/governance/assurance-runtime.js +6 -3
  91. package/dist/sdk/governance/defect-recurrence-coverage.d.ts +93 -0
  92. package/dist/sdk/governance/defect-recurrence-coverage.js +189 -0
  93. package/dist/sdk/governance/defect-recurrence-graph.d.ts +33 -0
  94. package/dist/sdk/governance/defect-recurrence-graph.js +121 -0
  95. package/dist/sdk/governance/defect-recurrence.d.ts +8 -0
  96. package/dist/sdk/governance/defect-recurrence.js +118 -17
  97. package/dist/sdk/governance/health.d.ts +17 -2
  98. package/dist/sdk/governance/health.js +31 -10
  99. package/dist/sdk/governance/linked-file-report.d.ts +41 -0
  100. package/dist/sdk/governance/linked-file-report.js +72 -0
  101. package/dist/sdk/governance/validate.d.ts +5 -2
  102. package/dist/sdk/governance/validate.js +21 -37
  103. package/dist/sdk/governance.d.ts +2 -0
  104. package/dist/sdk/governance.js +4 -2
  105. package/dist/sdk/history-repair.d.ts +7 -0
  106. package/dist/sdk/history-repair.js +48 -13
  107. package/dist/sdk/lifecycle/close.d.ts +8 -0
  108. package/dist/sdk/lifecycle/close.js +16 -8
  109. package/dist/sdk/lifecycle/create.js +9 -12
  110. package/dist/sdk/lifecycle/update.js +12 -12
  111. package/dist/sdk/lifecycle-policy.d.ts +3 -0
  112. package/dist/sdk/lifecycle-policy.js +2 -2
  113. package/dist/sdk/merge/abandoned-receipts.d.ts +15 -0
  114. package/dist/sdk/merge/abandoned-receipts.js +47 -0
  115. package/dist/sdk/merge/driver.js +4 -2
  116. package/dist/sdk/merge/index.d.ts +1 -0
  117. package/dist/sdk/merge/index.js +2 -2
  118. package/dist/sdk/merge/receipt-operation.d.ts +15 -0
  119. package/dist/sdk/merge/receipt-operation.js +97 -0
  120. package/dist/sdk/merge/receipt-schema.d.ts +20 -0
  121. package/dist/sdk/merge/receipt-schema.js +398 -0
  122. package/dist/sdk/merge/receipts.d.ts +16 -7
  123. package/dist/sdk/merge/receipts.js +54 -340
  124. package/dist/sdk/merge/reconcile.d.ts +2 -0
  125. package/dist/sdk/merge/reconcile.js +11 -4
  126. package/dist/sdk/public-surface.json +1 -1
  127. package/dist/sdk/query/duplicate-candidates.d.ts +7 -0
  128. package/dist/sdk/query/duplicate-candidates.js +71 -0
  129. package/dist/sdk/query/get.js +7 -7
  130. package/dist/sdk/query.d.ts +2 -0
  131. package/dist/sdk/query.js +4 -2
  132. package/dist/sdk/read-output-session.js +5 -3
  133. package/dist/sdk/runtime.js +4 -2
  134. package/dist/sdk/similarity.d.ts +24 -3
  135. package/dist/sdk/similarity.js +50 -55
  136. package/docs/AGENT_GUIDE.md +23 -2
  137. package/docs/BOUNDED_CONTEXT_READS.md +185 -0
  138. package/docs/CLOSE_EVIDENCE_RECOVERY.md +35 -0
  139. package/docs/COMMANDS.md +30 -8
  140. package/docs/CONTEXT_RELEVANCE.md +16 -4
  141. package/docs/DEFECT_RECURRENCE.md +80 -6
  142. package/docs/EXTENSIONS.md +18 -19
  143. package/docs/MERGE_SAFETY.md +50 -0
  144. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +66 -0
  145. package/docs/PR_REVIEW_LOOP.md +18 -3
  146. package/docs/README.md +18 -1
  147. package/docs/RELEASING.md +6 -2
  148. package/docs/SDK_LIFECYCLE.md +27 -0
  149. package/docs/SDK_RUNTIME_BOUNDARIES.md +11 -0
  150. package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -1
  151. package/marketplace.json +2 -2
  152. package/package.json +6 -3
  153. package/packages/pm-beads/package.json +1 -1
  154. package/packages/pm-calendar/package.json +1 -1
  155. package/packages/pm-command-kit/package.json +1 -1
  156. package/packages/pm-digital-twin/package.json +1 -1
  157. package/packages/pm-governance-audit/README.md +10 -1
  158. package/packages/pm-governance-audit/extensions/governance-audit/dedupe-audit.ts +50 -65
  159. package/packages/pm-governance-audit/extensions/governance-audit/index.ts +2 -2
  160. package/packages/pm-governance-audit/extensions/governance-audit/sdk.ts +1 -0
  161. package/packages/pm-governance-audit/package.json +1 -1
  162. package/packages/pm-guide-shell/package.json +1 -1
  163. package/packages/pm-kanban/package.json +1 -1
  164. package/packages/pm-lifecycle-hooks/package.json +1 -1
  165. package/packages/pm-linked-test-adapters/package.json +1 -1
  166. package/packages/pm-search-advanced/package.json +1 -1
  167. package/packages/pm-templates/package.json +1 -1
  168. package/packages/pm-todos/package.json +1 -1
  169. package/packages/pm-vcs/package.json +1 -1
  170. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  171. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  172. package/dist/cli-bundle/chunks/chunk-LUI4E32I.js +0 -231
  173. package/dist/cli-bundle/chunks/chunk-SVK5Y64D.js +0 -40
  174. package/dist/cli-bundle/chunks/chunk-V5GBD5KV.js +0 -9
  175. package/dist/cli-bundle/chunks/register-operations-KFSCC7QV.js +0 -2
  176. package/dist/cli-bundle/focused-chunks/chunk-24IG6ONG.js +0 -2
  177. package/dist/cli-bundle/focused-chunks/chunk-3ITLIBKS.js +0 -56
  178. package/dist/cli-bundle/focused-chunks/chunk-3NQD5YDG.js +0 -2
  179. package/dist/cli-bundle/focused-chunks/chunk-65N6JHAN.js +0 -2
  180. package/dist/cli-bundle/focused-chunks/chunk-GUBM3RGY.js +0 -20
  181. package/dist/cli-bundle/focused-chunks/chunk-JX3RCVCX.js +0 -2
  182. package/dist/cli-bundle/focused-chunks/chunk-MV752SUC.js +0 -12
  183. package/dist/cli-bundle/focused-chunks/chunk-PKIPMCFS.js +0 -6
  184. package/dist/cli-bundle/focused-chunks/chunk-RJMR2JIF.js +0 -9
  185. package/dist/cli-bundle/focused-chunks/chunk-WIUPWIZR.js +0 -177
@@ -1,51 +1,51 @@
1
- import{n as Nm,o as Eo,p as Um,q as Gm,r as Yi,s as Co,t as jm,u as Ji,v as Io,y as iu,z as au}from"./focused-chunks/chunk-YEF5PQQ2.js";import{a as mu,f as uu,h as zt,m as bu,o as wu,r as vu,s as ku,t as Su,x as Eu}from"./focused-chunks/chunk-65N6JHAN.js";import{$ as Gp,Aa as nf,Ab as Pf,Ba as rf,Bb as Lf,Ca as of,Cb as Nf,Da as sf,Db as xn,Ea as af,Eb as ja,Fa as cf,Fb as Ff,Ga as In,H as rr,I as w,Ib as cs,J as Lp,K as Np,Ka as df,L as Me,La as lf,M as Fp,Ma as mf,N as Ca,Na as uf,O as Mp,Oa as pf,P as Ia,Pa as sr,Q as ns,Qa as ff,R as Ra,Ra as _f,S as Cn,Sa as hf,T as Dp,Ta as gf,U as xa,Ua as yf,Ub as Mf,V as ke,Va as bf,Vb as jf,W as Oa,Wa as wf,Wb as qf,X as De,Xa as ir,Xb as Kf,Y as $p,Ya as vf,Z as Up,Za as os,_ as Pa,a as ua,aa as La,ab as ar,b as pp,db as kf,eb as ss,fb as mv,gb as Sf,hb as Ef,i as Ip,ia as jp,ib as Na,j as Rp,jb as Af,ka as or,kb as Tf,la as qp,lb as Cf,ma as rs,mb as If,na as Kp,nb as Rf,oa as zp,ob as xf,pa as Bp,pb as cr,qa as Hp,qb as Fa,ra as Vp,rb as Ma,sa as Wp,sb as is,ta as Yp,tb as Da,ua as Jp,ub as Of,va as Xp,vb as $a,wa as Qp,wb as as,xa as Zp,xb as Rn,ya as ef,yb as Ua,za as tf,zb as Ga}from"./focused-chunks/chunk-3ITLIBKS.js";import{e as Om,g as Pm,h as Lm,k as Fm,q as $m}from"./focused-chunks/chunk-KWWCBWFO.js";import{b as cu,c as Ro,e as du,f as lu,g as Ww}from"./focused-chunks/chunk-QL66QNWG.js";import{H as oa,L as su,a as kl,b as Sl,c as El,d as Al,f as Tl}from"./focused-chunks/chunk-JX3RCVCX.js";import{a as lp,b as mp,c as ms}from"./focused-chunks/chunk-4OSHLNUE.js";import{P as Pp,b as up,j as Op}from"./focused-chunks/chunk-WOCIPMW7.js";import{G as ct,I as qa,La as Ba,Qa as mr,Sa as Gf,Wa as Ha,c as ba,e as wa,g as dp,jb as ur,k as kp,kb as Va,l as Sp,m as Ep,n as Ap,o as Tp,oa as uv,p as Cp,pa as Ka,q as dr,qa as za,ra as ls,sa as pv,ta as fv,v as ds,w as $f,x as lr,y as Uf}from"./focused-chunks/chunk-MV752SUC.js";import{a as Au,b as Tu,c as Cu}from"./focused-chunks/chunk-H5FOGAVD.js";import{A as je,B as Ea,C as fp,D as ve,F as at,G as _p,H as Vo,I as xt,J as me,K as En,L as Wo,M as Yo,P as Jo,Q as Xo,Qa as Tn,R as hp,Ra as bp,S as Qo,Sa as Ta,T as Zo,Ta as wp,U as An,V as Aa,W as es,Xa as vp,Y as gp,Z as yp,Za as us,_ as er,a as vn,b as rp,bb as On,c as va,d as ka,e as op,g as sp,h as ip,i as ap,j as cp,k as Uo,l as Go,m as jo,n as qo,r as Ko,s as Rt,t as kn,u as zo,v as Sn,w as Bo,x as ie,y as Ho,z as Sa}from"./focused-chunks/chunk-GUBM3RGY.js";import{c as Im,f as Rm,g as xm,i as So,j as Et,k as qm,l as Km,m as zm}from"./focused-chunks/chunk-3ASU6WGI.js";import{$ as tm,A as Qr,Aa as vm,B as Fl,Ba as co,C as Ml,Ca as km,D as Dl,Da as Sm,E as Zr,Ea as Em,F as $l,Fa as lo,G as Ul,Ga as mo,H as Gl,Ha as uo,I as eo,Ia as po,J as to,Ja as Yn,K as jl,Ka as fo,L as no,La as Am,Ma as Jn,N as ql,Na as _o,O as Vn,Oa as ho,P as Kl,Pa as go,Q as zl,Qa as yo,R as Bl,Ra as Tm,S as Hl,Sa as St,T as Vl,Ta as bo,U as Wl,Ua as wo,V as Yl,Va as vo,W as Jl,Wa as ko,X as Xl,Y as Ql,Z as Zl,Za as Cm,_ as em,aa as nm,ab as M,ba as rm,ca as Wn,d as Hi,da as om,e as Cl,ea as sm,fa as ro,ga as oo,h as Il,ha as im,i as Vi,ia as am,j as Kt,ja as cm,ka as dm,l as Rl,la as lm,ma as mm,na as um,oa as pm,q as Wi,qa as fm,ra as _m,s as Yr,sa as hm,t as Jr,ta as gm,u as Xr,ua as ym,v as xl,va as bm,w as Ol,wa as so,x as Pl,xa as io,y as Ll,ya as ao,z as Nl,za as wm}from"./focused-chunks/chunk-24IG6ONG.js";import{d as Df}from"./focused-chunks/chunk-3NQD5YDG.js";import{$a as bn,A as dv,Aa as ha,Ab as ts,B as lv,C as gn,D as C,Da as Bu,Fa as ga,G as xu,H as Mo,I as Ou,Ia as Hu,J as Pu,Ja as Vu,K as Lu,Ka as We,L as Nu,M as Fu,Ma as Wu,Na as Yu,O as Q,Oa as A,P as pa,Pa as Re,Q as te,Qa as Ju,Ra as Xu,S as fa,Sa as It,T as Mu,Ta as ya,U as st,Ua as we,V as Tt,Va as Zn,W as yn,Y as Du,Z as $u,_ as _a,a as Ue,b as Yw,ba as Uu,bb as wn,c as Jw,d as Xw,db as Qu,e as Qw,eb as I,fa as Gu,fb as j,ga as ju,gb as Z,ha as qu,hb as Zu,jb as le,k as No,kb as ep,l as Iu,lb as $o,m as Ru,mb as it,n as hn,na as Ge,nb as tp,o as Xn,oa as Ct,ob as re,p as Zw,pb as np,q as ev,qb as xe,r as tv,ra as Do,s as nv,sb as xp,t as rv,ta as Ku,tb as tr,u as ov,ua as Ht,ub as nr,v as sv,va as zu,vb as Ot,w as iv,wa as Qn,x as av,y as Fo,z as cv}from"./focused-chunks/chunk-WIUPWIZR.js";import{b as vt,c as qr,d as Kr,f as rt,h as Ao,i as ot,j as At,k as Mm,m as $,n as To,o as Ve,q as Dm}from"./focused-chunks/chunk-B2TTQGFG.js";import{D as k,H as Lo,J as ne,M as be,Q as _u,Y as hu,Z as gu,aa as _n,b as xo,ea as yu,g as pu,i as fu,k as sa,l as ia,m as aa,n as ca,o as da,p as la,q as ma,r as R,s as pn,t as Bt,u as W,v as Oo,w as fn,z as Po}from"./focused-chunks/chunk-RJMR2JIF.js";import{$ as d,$b as Zi,$c as Vw,Aa as O,B as el,Ba as ge,C as tl,Ca as zr,Cc as Uw,D as nl,Da as mn,Dc as Gw,E as rl,Ea as Bn,Eb as Vr,F as ol,Fa as al,Fb as vl,G as sl,Ga as E,Gb as Wr,H as Di,Ha as cl,Hb as Hn,I as $i,Ia as tt,J as Ui,Ja as de,K as Gi,Ka as jt,L as ji,M as qi,Ma as Ie,Mb as Bm,Na as Br,Nb as Hm,Nc as jw,Ob as Vm,P as jr,Pb as Wm,Pc as qw,Qb as Ym,Qc as Kw,Rb as Jm,Rc as ta,Sb as Xi,Sc as na,Ta as un,Tb as Xm,Tc as ra,U as Ki,Uc as ru,Va as dl,Vb as Qm,W as il,Wb as Zm,Wc as ou,Xa as Bi,Xc as zw,Ya as ll,Z as wt,Zb as Qi,Zc as Bw,_a as ml,_b as eu,_c as Hw,aa as l,ab as Hr,cb as ul,db as pl,fb as fl,gb as _l,hb as hl,hc as Fw,ib as gl,ic as Mw,ja as P,jb as yl,jc as Dw,ka as Gt,kb as bl,kc as $w,la as kt,lb as wl,ma as z,mc as tu,na as he,o as $r,ob as qt,p as Zd,pa as ln,pb as nt,q as Ur,qc as nu,r as Mi,v as Ut,va as zi,vc as ea,w as et,wa as zn,x as cn,xa as ye,y as dn,z as Gr}from"./focused-chunks/chunk-PKIPMCFS.js";import{AsyncLocalStorage as rM}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 zf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _v(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 Wa(e,t){let n=_v(t),r=n==="brief"?n:zf(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:zf(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 Bf(e,t){let n=E(t??process.cwd(),e),r=await A(n);return le(n,r.item_format,O(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]="10052b6f-216f-5b50-81ec-ee373cc13d17")}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 hv=new Map;function Ya(){hv.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]="1ff4005f-be23-5dcf-9834-dbd7d083b76d")}catch{}})();var gv={"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 Hf(e){return Object.fromEntries(Qm.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Vf={ctx:{action:"context"},...gv,...Hf("extension"),...Hf("package"),...Object.fromEntries(Zm.map(e=>[`package-${e}`,{action: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]="41012e87-ed61-56b2-8505-8f786b3952b2")}catch{}})();var Ja="PmCliError";function yv(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 Wf(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,yv(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 ps(e){if(!(e instanceof Error)||e.name!==Ja)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 Xa(e){let t=ml();for(let n of e)t.register(n);return t}function Yf(e,t){return{client:t,isItemNotFoundError:n=>ps(n)&&n.exitCode===d.NOT_FOUND,getItemAt:(n,r)=>dp(n,r,{pmRoot:e}),openRelationshipEventStore:n=>mp.open({pmRoot:e,nodes:n.nodes,registry:Xa(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new pl(n.nodes,n.edges,Xa(n.definitions)),analyzeRelationshipImpact:(n,r,o)=>up(n,r,o),validateRelationshipEvents:n=>{let r=new lp(n.nodes,{registry:Xa(n.definitions)});return n.events.map(o=>r.append({...o,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>pp({...n,pmRoot: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]="c5a14f99-ce5b-5da7-8b17-6b6a56f0644a")}catch{}})();async function Jf(e,t,n=_u){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=t,o=Array.isArray(r.warnings)?r.warnings.filter(s=>typeof s=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{readFile as bv}from"node:fs/promises";import wv from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a7548f2-93a0-5dfc-9d9a-c5aef4656c7c")}catch{}})();var Qa="context-intents.json";function fs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vv(e,t,n){if(!fs(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function Xf(e,t){let n=Array.isArray(e)?e:fs(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,o)=>vv(r,t,o))}async function kv(e){let t=wv.join(e,Qa),n;try{n=await bv(t,"utf8")}catch(o){if(Gt(o))return[];throw await Qu(e),o}let r;try{r=JSON.parse(n)}catch(o){let s=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Qa}: ${s}`,{cause:o})}return Xf(r,Qa)}function Sv(e){if(!fs(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return fs(n)?n.contextIntents??n.context_intents:void 0}function Ev(e){return e.flatMap(t=>{let n=Sv(t.module);return n===void 0?[]:Xf(n,`package ${t.name}`)})}async function Av(e){let t=await kv(e.pmRoot),n=Ev(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Za(e,t){let n=await Av(e);return await gu(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]="b4b1f63b-12f9-574c-8e92-a5cc9c6178c1")}catch{}})();async function Qf(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=xt(),o=E(process.cwd(),n.path);await I(o);let s=await A(o),i=C(t.author,s.author_default),c=(await r.resolveValue(t.body,"--body",_p(t,"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 re({pmRoot:o,settings:s,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
1
+ import{n as Mm,o as Ao,p as jm,q as qm,r as Xi,s as Ro,t as Km,u as Qi,v as Io,y as du,z as lu}from"./focused-chunks/chunk-PEFABF7E.js";import{a as fu,f as _u,h as zt,m as ku,o as Su,r as Eu,s as Au,t as Tu,x as Cu}from"./focused-chunks/chunk-P5O7MP5Y.js";import{$ as qp,$a as as,Aa as of,Ab as xn,Ba as sf,Bb as ja,Ca as af,Cb as qa,Da as cf,Db as Ff,Ea as df,Eb as Mf,Fa as lf,Fb as Df,Ga as In,Gb as On,H as ir,Hb as Ka,I as w,Ib as $f,J as Fp,K as Mp,Ka as mf,L as $e,La as uf,Lb as ms,M as Dp,Ma as pf,N as Ia,Na as ff,O as $p,Oa as _f,P as xa,Pa as hf,Q as os,Qa as gf,R as Oa,Ra as Vt,S as Rn,Sa as yf,Sb as qf,T as Up,Ta as bf,Tb as zf,U as Pa,Ua as is,Ub as Bf,V as Se,Va as wf,Vb as Hf,W as La,Wa as vf,X as Ue,Xa as kf,Y as Gp,Ya as Sf,Z as jp,Za as Pt,_ as Na,_a as Ef,a as fa,aa as Fa,b as hp,cb as cr,gb as Af,hb as cs,i as Op,ia as Kp,ib as hv,j as Pp,jb as Tf,ka as ar,kb as Cf,la as zp,lb as Ma,ma as ss,mb as Rf,na as Bp,nb as If,oa as Hp,ob as xf,pa as Vp,pb as Of,qa as Wp,qb as Pf,ra as Yp,rb as Lf,sa as Jp,sb as dr,ta as Xp,tb as Da,ua as Qp,ub as $a,va as Zp,vb as ds,wa as ef,wb as Ua,xa as tf,xb as Nf,ya as nf,yb as Ga,za as rf,zb as ls}from"./focused-chunks/chunk-H2WJWK7L.js";import{e as Lm,g as Nm,h as Fm,k as Dm,q as Gm}from"./focused-chunks/chunk-QTVCLMSZ.js";import{b as mu,c as Oo,e as uu,f as pu,g as Zw}from"./focused-chunks/chunk-3BZEOXLT.js";import{R as ia,V as cu,a as El,b as Al,c as Tl,d as Cl,f as Rl}from"./focused-chunks/chunk-AL5ON6K6.js";import{a as pp,b as fp,c as fs}from"./focused-chunks/chunk-QTZRBUYA.js";import{P as Np,b as _p,j as Lp}from"./focused-chunks/chunk-EZR3GHFE.js";import{$ as bv,Ca as Wa,Ra as pr,Sa as Ya,W as gv,X as Ba,Y as Ha,Z as ps,_ as yv,c as va,e as ka,g as up,h as Ap,i as Tp,j as Cp,k as Rp,l as Ip,m as xp,n as mr,o as za,ra as Va,wa as ur,ya as Kf}from"./focused-chunks/chunk-SGQST3PQ.js";import{A as Ke,B as Ta,C as gp,D as ke,F as ct,G as yp,H as Wo,I as xt,J as pe,K as An,L as Yo,M as Jo,P as Xo,Pa as Cn,Q as Qo,Qa as kp,R as bp,Ra,S as Zo,Sa as Sp,T as es,U as Tn,V as Ca,W as ts,Wa as Ep,X as wp,Y as vp,Z as rr,a as kn,b as ip,c as Sa,d as Ea,db as us,e as ap,g as cp,gb as Gf,h as dp,hb as lr,i as lp,j as mp,k as Go,kb as jf,l as jo,m as qo,n as Ko,r as zo,s as It,sb as dt,t as Sn,u as Bo,ub as _s,v as En,w as Ho,x as ae,y as Vo,z as Aa,zb as Pn}from"./focused-chunks/chunk-CK6QFAPZ.js";import{c as xm,f as Om,g as Pm,i as Eo,j as Et,k as zm,l as Bm,m as Hm}from"./focused-chunks/chunk-LIJIA4TY.js";import{a as Ru,b as Iu,c as xu}from"./focused-chunks/chunk-M6PBRFSH.js";import{$ as rm,A as Zr,Aa as Sm,B as Dl,Ba as lo,C as $l,Ca as Em,D as Ul,Da as Am,E as eo,Ea as Tm,F as Gl,Fa as mo,G as jl,Ga as uo,H as ql,Ha as po,I as to,Ia as fo,J as no,Ja as Xn,K as Kl,Ka as _o,L as ro,La as Cm,Ma as Qn,N as zl,Na as ho,O as Yn,Oa as go,P as Bl,Pa as yo,Q as Hl,Qa as bo,R as Vl,Ra as Rm,S as Wl,Sa as St,T as Yl,Ta as wo,U as Jl,Ua as vo,V as Xl,Va as ko,W as Ql,Wa as So,X as Zl,Y as em,Z as tm,Za as Im,_ as nm,aa as om,ab as F,ba as sm,ca as Jn,d as Wi,da as im,e as Il,ea as am,fa as oo,ga as so,h as xl,ha as cm,i as Yi,ia as dm,j as Kt,ja as lm,ka as mm,l as Ol,la as um,ma as pm,na as fm,oa as _m,q as Ji,qa as hm,ra as gm,s as Jr,sa as ym,t as Xr,ta as bm,u as Qr,ua as wm,v as Pl,va as vm,w as Ll,wa as io,x as Nl,xa as ao,y as Fl,ya as co,z as Ml,za as km}from"./focused-chunks/chunk-ZPEKQHOC.js";import{A as fv,Aa as ya,Ab as rs,B as _v,C as yn,D as C,Da as Wu,Fa as ba,G as Lu,H as Do,I as Nu,Ia as Yu,J as Fu,Ja as Ju,K as Mu,Ka as Je,L as Du,Lb as Uf,M as $u,Ma as Xu,Na as Qu,O as X,Oa as A,P as _a,Pa as Oe,Q as te,Ra as Zu,S as ha,Sa as ep,T as Uu,Ta as Rt,U as it,Ua as wa,V as Tt,Va as ve,W as bn,Wa as nr,Y as Gu,Z as ju,_ as ga,a as je,ab as wn,b as ev,ba as qu,c as tv,cb as vn,d as nv,e as rv,eb as tp,fa as Ku,fb as R,ga as zu,gb as G,ha as Bu,hb as Q,ib as np,k as Fo,kb as ue,l as Ou,lb as rp,m as Pu,mb as Uo,n as gn,na as qe,nb as at,o as er,oa as Ct,ob as op,p as ov,pb as oe,q as sv,qb as sp,r as iv,ra as $o,rb as Pe,s as av,sb as or,t as cv,ta as Hu,tb as sr,u as dv,ua as Ht,ub as ns,v as lv,va as Vu,vb as Ot,w as mv,wa as tr,x as uv,y as Mo,z as pv}from"./focused-chunks/chunk-PDMW2E36.js";import{b as vt,c as Kr,d as zr,f as ot,h as To,i as st,j as At,k as $m,m as D,n as Co,o as Ye,q as Um}from"./focused-chunks/chunk-NTPY5GSO.js";import{D as k,H as No,J as re,M as we,S as yu,Z as bu,_ as wu,b as Zn,ba as hn,fa as vu,g as hu,i as gu,k as aa,l as ca,m as da,n as la,o as ma,p as ua,q as pa,r as I,s as fn,t as Bt,u as W,v as Po,w as _n,z as Lo}from"./focused-chunks/chunk-UKHASMMP.js";import{$ as d,$a as pl,$b as nu,Aa as O,B as nl,Ba as ye,C as rl,Ca as Br,D as ol,Da as un,E as sl,Ea as Hn,F as il,Fa as dl,Fb as Wr,Fc as zw,G as al,Ga as E,Gb as Sl,Gc as Bw,H as Ui,Ha as ll,Hb as Yr,I as Gi,Ia as nt,Ib as Wn,J as ji,Ja as me,K as qi,Ka as jt,L as Ki,M as zi,Ma as xe,Na as Hr,Nb as Vm,Ob as Wm,P as qr,Pb as Ym,Qb as Jm,Qc as Hw,Rb as Xm,Sb as Qm,Sc as Vw,Ta as pn,Tb as Zi,Tc as Ww,U as Bi,Ub as Zm,Uc as ra,Va as ml,Vc as oa,W as cl,Wb as eu,Wc as sa,Xa as Vi,Xb as tu,Xc as iu,Ya as Vn,Z as wt,Za as ul,Zc as au,_b as ea,_c as Yw,aa as l,ac as ta,ad as Jw,bb as Vr,bd as Xw,cd as Qw,db as fl,eb as _l,gb as hl,hb as gl,ib as yl,ic as Gw,ja as P,jb as bl,jc as jw,ka as Gt,kb as wl,kc as qw,la as kt,lb as vl,lc as Kw,ma as K,mb as kl,mc as xo,na as ge,nc as ru,o as Ur,p as tl,pa as mn,pb as qt,pc as ou,q as Gr,qb as rt,r as $i,tc as su,v as Ut,va as Hi,w as tt,wa as Bn,x as dn,xa as be,y as ln,yc as na,z as jr}from"./focused-chunks/chunk-CHC2IDXA.js";import{AsyncLocalStorage as QF}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 Vf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function wv(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 Ja(e,t){let n=wv(t),r=n==="brief"?n:Vf(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:Vf(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 Wf(e,t){let n=E(t??process.cwd(),e),r=await A(n);return ue(n,r.item_format,O(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]="10052b6f-216f-5b50-81ec-ee373cc13d17")}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 vv=new Map;function Xa(){vv.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]="1ff4005f-be23-5dcf-9834-dbd7d083b76d")}catch{}})();var kv={"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 Yf(e){return Object.fromEntries(eu.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Jf={ctx:{action:"context"},...kv,...Yf("extension"),...Yf("package"),...Object.fromEntries(tu.map(e=>[`package-${e}`,{action: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]="41012e87-ed61-56b2-8505-8f786b3952b2")}catch{}})();var Qa="PmCliError";function Sv(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=d.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function Xf(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,Sv(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 hs(e){if(!(e instanceof Error)||e.name!==Qa)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 Za(e){let t=pl();for(let n of e)t.register(n);return t}function Qf(e,t){return{client:t,isItemNotFoundError:n=>hs(n)&&n.exitCode===d.NOT_FOUND,getItemAt:(n,r)=>up(n,r,{pmRoot:e}),openRelationshipEventStore:n=>fp.open({pmRoot:e,nodes:n.nodes,registry:Za(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new _l(n.nodes,n.edges,Za(n.definitions)),analyzeRelationshipImpact:(n,r,o)=>_p(n,r,o),validateRelationshipEvents:n=>{let r=new pp(n.nodes,{registry:Za(n.definitions)});return n.events.map(o=>r.append({...o,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>hp({...n,pmRoot: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]="c5a14f99-ce5b-5da7-8b17-6b6a56f0644a")}catch{}})();async function Zf(e,t,n=yu){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=t,o=Array.isArray(r.warnings)?r.warnings.filter(s=>typeof s=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{readFile as Ev}from"node:fs/promises";import Av from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a7548f2-93a0-5dfc-9d9a-c5aef4656c7c")}catch{}})();var ec="context-intents.json";function gs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tv(e,t,n){if(!gs(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function e_(e,t){let n=Array.isArray(e)?e:gs(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,o)=>Tv(r,t,o))}async function Cv(e){let t=Av.join(e,ec),n;try{n=await Ev(t,"utf8")}catch(o){if(Gt(o))return[];throw await tp(e),o}let r;try{r=JSON.parse(n)}catch(o){let s=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${ec}: ${s}`,{cause:o})}return e_(r,ec)}function Rv(e){if(!gs(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return gs(n)?n.contextIntents??n.context_intents:void 0}function Iv(e){return e.flatMap(t=>{let n=Rv(t.module);return n===void 0?[]:e_(n,`package ${t.name}`)})}async function xv(e){let t=await Cv(e.pmRoot),n=Iv(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function tc(e,t){let n=await xv(e);return await wu(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]="b4b1f63b-12f9-574c-8e92-a5cc9c6178c1")}catch{}})();async function t_(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=xt(),o=E(process.cwd(),n.path);await R(o);let s=await A(o),i=C(t.author,s.author_default),c=(await r.resolveValue(t.body,"--body",yp(t,"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 oe({pmRoot:o,settings:s,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
2
2
 
3
3
  `:"";return u.body=`${u.body.trimEnd()}${p}${c}
4
- `,{changedFields:["body"]}}});return{item:m.item,appended:c,changed_fields:m.changedFields}}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]="6d20a21c-ac67-5712-9f63-b10ffc0e2c64")}catch{}})();function hs(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,ve(e,t)}function Zf(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 ec(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Vt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Pn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let s=ie(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function tc(e){return typeof e=="object"&&e!==null&&"code"in e}function _r(e,t){if(!at(e))throw new l(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,d.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function Cv(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=xt(),o=at(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",o)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return _r(e,"--stdin"),{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);if(s==="-")return _r(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await Tv(s,"utf8"),emptyFlag:"--file"}}catch(i){if(tc(i)&&Gt(i))throw new l(`--file path not found: ${s}. Use --file - to read stdin.`,d.USAGE);let a=i instanceof Error?i.message:String(i);throw new l(`Failed to read --file path "${s}": ${a}. Use --file - to read stdin.`,d.USAGE)}}async function gs(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 Cv(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 fr(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 t_(e){return e==="comments"?"--stdin":"--add -"}function Iv(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let o=t_(t.collectionKey),s=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 ${o} to read stdin, or use text=${r} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${s} ${o}`,`${s} --add text=${r}`]})}function Rv(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new l(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,d.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});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> ${t_(e.collectionKey)}`]})}function xv(e,t,n,r,o,s){let i=Vt(e.metadata,t),a=o?i.findIndex(c=>c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],entryIndex:a+1}:(i.push(s({created_at:k(),author:n,text:r})),e.metadata[t]=i,{changedFields:[t],entryIndex:i.length})}async function Ln(e,t,n,r){Rv(r,t);let o=E(process.cwd(),n.path);await I(o);let s=await A(o),i=O(s,R()),a=er(t.limit);if(r.input.mode==="list"){let h=await j(o,e,s.id_prefix,s.item_format,i.type_to_folder);if(!h)throw new l(`Item ${e} not found`,d.NOT_FOUND);let y=await Z(h,{schema:s.schema}),g=Vt(y.document.metadata,r.collectionKey);return _s(h.id,r.collectionKey,g,a,t.includeMeta===!0)}let c=C(t.author,s.author_default);if(r.input.mode==="delete"){let h=r.deleteOp??r.op,y;try{y=await re({pmRoot:o,settings:s,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(b){let v=Vt(b.metadata,r.collectionKey),S=e_(r.input.index,v.length,r.collectionKey);return Zf(v[S],"deleted"),v.splice(S,1),b.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(b){fr(b,r.conflictGuidance)}let g=Vt(y.item,r.collectionKey);return _s(y.item.id,r.collectionKey,g,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";Iv(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 h=r.editOp??r.op,y;try{y=await re({pmRoot:o,settings:s,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(b){let v=Vt(b.metadata,r.collectionKey),S=e_(r.input.index,v.length,r.collectionKey),T=v[S];return Zf(T,"edited"),v[S]={...T,text:u,edited_at:k()},b.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(b){fr(b,r.conflictGuidance)}let g=Vt(y.item,r.collectionKey);return _s(y.item.id,r.collectionKey,g,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:g[r.input.index-1]},t.fullHistory===!0)}let p,f=0;try{p=await re({pmRoot:o,settings:s,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(h){let y=xv(h,r.collectionKey,c,u,t.ifAbsent===!0,r.createEntry);return f=y.entryIndex,{changedFields:y.changedFields}}})}catch(h){fr(h,r.conflictGuidance)}let _=Vt(p.item,r.collectionKey);return _s(p.item.id,r.collectionKey,_,a,t.includeMeta===!0,{action:"add",entryIndex:f,entry:_[f-1],changedCount:t.ifAbsent===!0?Math.min(p.changedFields.length,1):void 0},t.fullHistory===!0)}function e_(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,s=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${o} index ${e??"(missing)"} out of range (item has ${s})`,d.USAGE)}return e-1}function Ov(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function _s(e,t,n,r,o,s,i=!1){let a=s===void 0||i?ec(n,s!==void 0&&i?void 0:r):s.entry===void 0?[]:[s.entry],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...s?.changedCount===void 0?{}:{changed:s.changedCount===1},...[o,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...Ov(t,s,c)}}(function(){try{var e=typeof window<"u"?window:typeof 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 n_(e,t,n){return[...await yn(Ie(e,t),t).catch(()=>[])].reverse().find(s=>s.patch.some(i=>i.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a4d95016-05b9-5272-8044-2649da644e98")}catch{}})();var r_="no_available_next_item";function o_(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function ys(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let s=await A(o),i=$(s.schema),a=C(r.author,s.author_default),c=gn(a),m=null,u=!1,p=[],f=await re({pmRoot:o,settings:s,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||y;if(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 n_(o,_.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 Ka({pmRoot:o,settings:s,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 s_(e,t,n={},r={}){let o=Pv(n.maxAttempts),s=await A(E(process.cwd(),t.path)),i={...n,author:C(n.author,s.author_default)},a=await mr({...r,callerAuthor:i.author,limit:String(o)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return Lv(c.slice(0,o),e,t,i)}function Pv(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 Lv(e,t,n,r={},o=ys){let s=0;for(let a of e){s+=1;try{let c=await o(a.id,t,n,r),m={...c,recommendation:a,attempts:s,available:!0};if(!c.skipped)return m}catch(c){if(!o_(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:C(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[r_]};let i=s===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:r_,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 bs(e,t,n,r={}){let o=E(process.cwd(),n.path);await I(o);let s=await A(o),i=C(r.author,s.author_default),a=gn(i),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await re({pmRoot:o,settings:s,id:e,op:"release",author:i,message:r.message,force:t,bypassAssigneeConflict:c,mutate(_){return m=_.metadata.assignee??null,!m&&!_.metadata.claim_principal?{changedFields:[]}:(delete _.metadata.assignee,delete _.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(_){fr(_,{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."]})}await za({pmRoot:o,principal:a,itemId:u.item.id});let p=$(s.schema),f=pa(u.item.status,p)===pa(p.in_progress_status,p);return{item:u.item,released_by:i,previous_assignee:m,forced:t,...f?{warnings:["released_unclaimed_in_progress"],suggestions:[`${u.item.id} remains ${u.item.status} and unclaimed. If work is paused, run pm pause-task ${u.item.id} to move it to ${p.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]="a7ae3c89-b50b-5e4f-8273-8318bc976d84")}catch{}})();var Nv=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function i_(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 nc(e,t){return rc(e,t,{operation:"close"})}function rc(e,t,n){let r=i_(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new 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:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function oc(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],s=o.filter(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"&&s.length>0){let m=o.filter(u=>u.kind!=="blocked_by");m.length>0?e.dependencies=m:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...s.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]="9f28f7d8-993b-5201-b606-d1eab0c3ff5c")}catch{}})();var Fv=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function Mv(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 Dv(e){let t=[];for(let n of Fv){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function $v(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let s=o.trim();if(s===n)return!0;if(r.has(s))return!1;r.add(s),o=(await e(s))?.duplicate_of}return!1}function Uv(e){return typeof e!="string"||e.trim().length===0}async function Gv(e,t,n,r){let o=n?.trim();if(!o)return;if(o===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 s=O(t,R()),i=new Map,a=async m=>{if(i.has(m))return i.get(m)??null;let u=await j(e,m,t.id_prefix,t.item_format,s.type_to_folder);if(!u)return i.set(m,null),null;let{document:p}=await Z(u,{schema:t.schema});return i.set(m,p.metadata),p.metadata},c=await a(o);if(!c)throw new l(`Duplicate target "${o}" 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 ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await $v(a,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${o}" 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 "${o}" 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 jv(e,t,n){return e.filter(r=>r.parent===t&&!te(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function qv(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),o=Df(e),s=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:o.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let m=r.get(c);return m!==void 0&&te(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function Kv(e,t,n,r,o,s){let i=qv(n,r,s),a=[];for(let c of i)try{let m=await re({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(h=>{let y=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=s.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${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 zv(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:s}of r){if(typeof o!="string")continue;let i=o.trim();i.length!==0&&(e[s]=i,n.push(s))}return n}function Bv(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:s}of r)Uv(e[o])&&(e[o]=s,n.push(o));return n}function Hv(e,t,n,r){let o=[];if(t!=="off"){let s=Dv(e);if(s.length>0){let i=s.map(a=>a.label);if(t==="strict"){let a=s.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:xo(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}o.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new 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);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function Vv(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function Wv(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function Yv(e,t){if(te(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use --force to close again.`,d.CONFLICT);let n=zv(e,t.options),r=Bv(e,t.duplicateOf),o=Hv(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let i=["status","closed_at",...s?["completed_at"]:[],...Vv(e,t.closeReason),...n];if(wp(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(...Wv(e));let a=oc(e,t.lifecyclePolicy);return i.push(...a.changedFields),o.push(...a.warnings),{changedFields:i,...o.length>0?{warnings:o}:{}}}async function a_(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let s=await A(o),i=$(s.schema),a=C(n.author,s.author_default),c=O(s,R()).type_to_folder,m=await j(o,e,s.id_prefix,s.item_format,c);if(!m)throw await it(o,e,s.id_prefix,c);let u=await Gv(o,s,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=nc({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=Mv(n.validateClose)??s.governance.close_validation_default,h=await le(o,s.item_format,c,void 0,s.schema),y=jv(h,m.id,i),g=k(),b=n.completedAt===void 0?g:ne(n.completedAt,new Date(g),"completed-at"),v=await re({pmRoot:o,settings:s,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(S){return Yv(S.metadata,{pmRoot:o,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 Kv(o,s,h,m.id,a,i)]}}function dt(e,t,n,r){return a_(e,t,n,r)}import Jv from"fast-json-patch";import sc 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]="7a3effef-6ba8-51ba-ae99-436d4ef69813")}catch{}})();async function c_(e,t,n){let r=await Zu(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:d_(n),recovered:!0}}function Xv(e,t){return rp(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function d_(e){let t=ka(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Tt(Ht(t))}async function Qv(e,t,n,r){let o=await j(e,t,n.id_prefix,n.item_format,r);if(o){let c=Ie(e,o.id),m=await Ju({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"});return{id:o.id,historyPath:c,located:o,historyPolicyWarnings:m.warnings}}let s=we(t,n.id_prefix),i=ya(t),a=s===i?[s]:[s,i];for(let c of a){let m=Ie(e,c);if(await P(m))return{id:c,historyPath:m,located:null,historyPolicyWarnings:[]}}throw new l(`Item ${t} not found`,d.NOT_FOUND)}function Zv(e,t){let n=Qn(e),r=Qn(t),o=Jv.compare(n,r),s=new Set;for(let i of o){if(i.path==="/body"||i.path.startsWith("/body/")){s.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];s.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(s).sort((i,a)=>i.localeCompare(a))}async function ek(e){if(await z(e.subject.historyPath)!==e.historyRawBeforeLock)throw new l(`History for ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);let n=await j(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),r=n?await c_(n,e.settings,e.history):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 tk(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:d_(t),originalRaw:null}}function nk(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 rk(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await he(e.existingItemPath,e.resolvedOriginalRaw),await sc.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await he(e.existingItemPath,e.resolvedOriginalRaw);return}await sc.rm(e.restoredItemPath,{force:!0})}async function ok(e){return[...await W({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 W({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function Wt(e,t,n,r){let o=E(process.cwd(),r.path);await I(o);let s=await A(o),i=O(s,R()),a=await Qv(o,e,s,i.type_to_folder),c=a.id,m=await z(a.historyPath),u=await yn(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let p=Xv(t,u),f=op(ka(u,p.historyIndex),p),_=zu(f,{schema:s.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 c_(a.located,s,u):null)?.raw??null,g=C(n.author,s.author_default),b=await be(o,c,s.locks.ttl_seconds,g,!!n.force,s.governance.force_required_for_stale_lock,s.locks.wait_ms);try{let{loadedItemUnderLock:v,existingItemPath:S}=await ek({pmRoot:o,resolvedId:c,subject:a,settings:s,typeToFolder:i.type_to_folder,historyRawBeforeLock:m,currentItemRawBeforeLock:y,history:u}),T="toon",x=tk(v,u),G=nk({document:x.document,author:g,force:n.force,enforcement:s.governance.ownership_enforcement,resolvedId:c}),F=Zv(x.document,_);await Oo({pm_root:o,operation:"restore",before:x.document,after:_,changed_fields:F,sdk:$o({pmRoot:o,settings:s,typeToFolder:i.type_to_folder})});let X=st(_,{format:T,schema:s.schema}),K=jt(o,_.metadata.type,c,T,i.type_to_folder),pe=await bn(o,g),N=[];try{await he(K,X),S&&K!==S&&await sc.rm(S);let gt=Ge({nowIso:k(),author:g,op:"restore",before:x.document,after:_,message:n.message});try{await Ct(a.historyPath,gt)}catch(Be){throw await rk({existingItemPath:S,resolvedOriginalRaw:x.originalRaw,restoredItemPath:K}),Be}N=await wn({pmRoot:o,preferredFormat:s.item_format,typeToFolder:i.type_to_folder,schema:s.schema,itemPath:K,previousItemPath:S??void 0,document:_})}finally{await pe()}let se=await ok({restoredItemPath:K,historyPath:a.historyPath,before:x.document,after:_});pn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:x.document.metadata.status,status:_.metadata.status,previous:Bt(x.document.metadata,F),current:Bt(_.metadata,F),changed_fields:F});let ht=u[p.historyIndex],Qe=vn(u,!0);return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,version:Qe===null?null:Qe+p.historyIndex+1,entry_ts:ht.ts,entry_op:ht.op},changed_fields:F,warnings:[...v?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...G,...N,...se]}}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]="a97a3cf0-beef-5967-8f5b-2372a6c9f2f7")}catch{}})();var m_=1,ic="close-many",sk=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function ik(e,t){return dr(e,t,{includePagination:!1})}function ak(e,t){return dr(e,t)}function ck(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 dk(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function lk(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 mk(e,t){let n=$(t.schema),r=O(t,R()),o=await le(e,t.item_format,r.type_to_folder,void 0,t.schema),s=new Map,i=new Map;for(let a of o){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),te(a.status,n)))continue;let c=s.get(a.parent);c?c.push(a.id):s.set(a.parent,[a.id])}for(let a of s.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:s,parentByChild:i}}function l_(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,s=t.get(e),i=[],a=new Set,c=!1;for(;s!==void 0&&!a.has(s);){let m=n?.get(s);if(m!==void 0){o+=m+1;break}a.add(s),i.push(s),o+=1,s=t.get(s)}if(s!==void 0&&a.has(s)&&(c=!0),!c){n?.set(e,o);for(let[m,u]of i.entries())n?.set(u,o-m-1)}return o}async function uk(e){let t=await jo(e.pmRoot,ic,e.rollbackId,m_),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await qo(t.items,(o,s)=>Wt(o,s,{author:e.options.author,message:n,force:!0},e.global));return{...zt({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 pk(e,t,n,r,o){return e.map(s=>{let i=(t.get(s.id)??[]).filter(c=>!n.has(c)),a=!u_(s,r,o);return{id:s.id,title:typeof s.title=="string"?s.title:"",status:s.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function fk(e){let t=await Go(e.pmRoot,ic,e.checkpointId,{schema_version:m_,id:e.checkpointId,created_at:e.nowValue,author:C(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 _k(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await dt(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){t.push({id:r.id,status:"failed",error:un(o)})}}return{rows:t,closedIds:n}}function hk(e){return typeof e.rollback=="string"?e.rollback:void 0}function gk(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(ak(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function yk(e){if(!ik(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${sk}). Refusing to match every item.`,d.USAGE)}function bk(e,t){let n=new Map;return[...e].sort((r,o)=>{let s=l_(o.id,t,n)-l_(r.id,t,n);return s!==0?s:r.id.localeCompare(o.id)})}function u_(e,t,n){return n||!te(e.status,t)}function wk(e,t,n){return new Set(e.filter(r=>u_(r,t,n)).map(r=>r.id))}async function vk(e){yk(e.options);let t=$(e.settings.schema),n=lk(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await ct(e.options.status,dk(e.options.list),e.global),{childrenByParent:s,parentByChild:i}=await mk(e.pmRoot,e.settings),a=bk(o.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],m=c.length===0?[]:(await ct(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,u=new Set(m.map(f=>f.id)),p=wk(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!u.has(f)),planRows:pk(a,s,p,t,r)}}function kk(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!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function Sk(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 fk({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 p_(e,t){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=e.dryRun===!0,s=hk(e);if(ck(e.list),s!==void 0)return gk(e,s),uk({pmRoot:n,rollbackId:s,options:e,global:t});let i=await vk({pmRoot:n,settings:r,options:e,global:t});if(o)return kk(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=k(),m=Uo(ic,c),u=await Sk({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 _k({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{...zt({applied:h,skipped:y,failed:g,unmatched:i.unmatchedIds?.length??0}),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!==void 0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}import{readFile as Ek}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]="f761d37b-28df-5176-9e25-762f57aa0abf")}catch{}})();async function ac(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",s=Number(n)+Number(r)+Number(o);if(s===0)return;if(s>1)throw new 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",at(e))??"",emptyFlag:"--add"};if(r)return _r(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);if(i==="-")return _r(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await Ek(i,"utf8"),emptyFlag:"--file"}}catch(a){if(tc(a)&&Gt(a))throw new l(`--file path not found: ${i}. Use --file - to read stdin.`,d.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${i}": ${c}. Use --file - to read stdin.`,d.USAGE)}}async function Ak(e,t){let n=e.edit,r=e.delete,o=n!==void 0,s=r!==void 0;if(o&&s)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(s){if(await ac(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(o){let c=await ac(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 ac(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 f_(e,t,n){let r=xt(),o=await Ak(t,r),s=o.mode==="add"||o.mode==="edit",i=o.value??"";return Ln(e,t,n,{input:{...o,rawValue:t.add??i,value:s?Pn(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm comments pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="972816c9-b407-5b89-a744-249c9771451f")}catch{}})();async function __(e,t,n){return Ln(e,t,n,{input:await gs(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Pn(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]="216389a2-fb85-56a0-8ef2-9f41f1321c16")}catch{}})();function Tk(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 Ck(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 Ik(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 h_(e,t,n){let r=Tk(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let s=r===void 0?void 0:qt(r),i=[t.since,t.eventType].some(h=>h!==void 0),a=Ik(t.since),c=er(t.limit),m=await Ln(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await gs(s===void 0?t:{add:s},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>Pn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:Ck(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?ec(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]="d6f359cb-2bc9-5f96-8789-db91512d0bd5")}catch{}})();function hr(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function gr(e,t,n=Ot()){for(let r of t??[])try{ul(e,r.id,r.kind,n)}catch(o){throw new l(un(o),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function g_(e,t){return(await Z(e,{schema:t})).document.metadata.created_at}async function Rk(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await j(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:g_(n,t.schema)}function xk(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 Ok(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:s})=>s===null?[]:[[o,s]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await g_(n.get(o),e.context.schema)])));for(let o of e.holders){let s=await Rk(o,e.context);if(s!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(s),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw xk({holder:o,dependency:i,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function Yt(e){let t=e.registry??Ot(),n=(e.dependencies??[]).filter(i=>!xp(i.source_kind)),r=[...new Set(n.map(i=>i.id))],o=await Promise.all(r.map(async i=>({target:i,located:await j(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=o.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${s.length===1?"":"s"} not found: ${s.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:s,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${s.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await Ok({dependencies:n,missingTargets:s,resolutions:o,holders:e.holders??[],registry:t,context:e}),s.map(i=>`dependency_target_unresolved:${i}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcbb6070-7457-5454-abf1-fa8153c8efd6")}catch{}})();function ws(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function vs(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function ks(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Gr.includes(t))return t;let n=me(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 Ss(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 Pk=new Set(["none","null"]);function Es(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function qe(e){return e===void 0?!1:Pk.has(e.trim().toLowerCase())}function As(e,t,n){if(!qe(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Se(e,t,n){if(!e||e.length===0||!e.some(s=>qe(s)))return;let o=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${o}`.trim(),d.USAGE)}function Ts(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new l(`${n.valueFlag} entries must be strings.`,d.USAGE);let o=r;if(!o.some(a=>qe(a)))continue;if(o.filter(a=>!qe(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 b_(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 cc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Ee(e,t,n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE);return e}var w_=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Lk(e,t){return t==="defined"?e!==void 0:!!e}function y_(e,t,n){if(!Lk(e,n))return;let r=me(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function Nk(e,t,n){let r=e?ne(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 Fk(e){return Array.from(new Set(cc(e).map(t=>Ee(t.toLowerCase(),sl,"event weekday")))).sort((t,n)=>Di(t)-Di(n))}function Mk(e){return Array.from(new Set(cc(e).map(t=>{let n=me(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 Dk(e,t){return Array.from(new Set(cc(e).map(n=>ne(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function v_(e,t,n,r){let o=e.recur_freq?.trim(),s=e.recur_interval?.trim(),i=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![o,s,i,a,c,m,u].some(S=>S!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let f=Ee(o.toLowerCase(),ol,"event recurrence frequency"),_=y_(s,"recur_interval",r),h=y_(i,"recur_count",r),y=Nk(a,t,n),g=Fk(c),b=Mk(m),v=Dk(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 k_="--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.",$k="--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).",Uk=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,Gk=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,E_=1e3,dc=60*E_,jk=60*dc;function S_(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 qk(e,t){let n=new Date(e),r=t.trim(),o=Uk.exec(r);if(o){let a=o[1]==="-"?-1:1,c=Number.parseInt(o[2],10)*a;return S_(n.getTime()+c*dc,r)}let s=Gk.exec(r);if(s){let[,a,c,m,u]=s;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=_*jk+h*dc+y*E_;return S_(n.getTime()+f*g,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return ne(i,n,"event.duration")}function A_(e,t,n,r){if(t&&n)throw new l($k,d.USAGE);if(n){let s=qk(e,n);if(s<e)throw new l(k_,d.USAGE);return s===e?void 0:s}if(!t)return;let o=ne(t,r,"event.end");if(o<e)throw new l(k_,d.USAGE);if(o!==e)return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var Kk=["at","date","text","title"],zk=["start","date","end","duration","title","description","location","timezone","all_day",...w_],Bk=["key","value"];function T_(e,t){return t==="trimmed"?e?.trim():e}function Hk(e,t){return t==="defined"?e!==void 0:!!e}function Cs(e,t,n){return e.map(r=>{let o=ie(r,"--reminder");je(o,"--reminder",Kk);let s=T_(o.at??o.date,n.valueMode),i=T_(o.text??o.title,n.valueMode);if(!s||!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:ne(s,t,"reminder.at"),text:a}})}function Is(e,t,n){return e.map(r=>{let o=ie(r,"--event");je(o,"--event",zk);let s=(o.start??o.date)?.trim();if(!s)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let i=ne(s,t,"event.start"),a=o.end?.trim(),c=o.duration?.trim(),m=A_(i,a,c,t),u=o.title,p=o.description,f=o.location,_=o.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[G,F,X]of v)if(F!==void 0&&!X)throw new l(`--event ${G} must not be empty`,d.USAGE);let S=o.all_day?.trim(),T=v_(o,i,t,n.recurrenceEmptyNumericGuard),x=Hk(S,n.allDayEmptyGuard)?b_(S,"--event all_day"):void 0;return{start_at:i,end_at:m,title:h,description:y,location:g,all_day:x,timezone:b,recurrence:T}})}function Rs(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 o,s;if(r.includes(",")||r.includes(`
5
- `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=ie(r,"--type-option");je(a,"--type-option",Bk),o=a.key?.trim(),s=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);o=r.slice(0,m).trim(),s=r.slice(m+1).trim()}if(!o||!s)throw new l("--type-option requires key and value",d.USAGE);t[o]=s}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39a36d42-29b1-5f0f-a8b2-f3bfc0ef78c2")}catch{}})();var Vk="hierarchy-integrity";async function xs(e){let t=e.required?await be(e.pmRoot,Vk,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var Wk=new Set(["event","meeting","reminder","milestone","decision","adr"]);function C_(e,t,n,r){if(Wk.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=To("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm start-task ${e}`,to_status:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b29e4416-82ab-585c-9456-718e4699566d")}catch{}})();var lt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],Yk=new Set(lt);function I_(e){return Ko(e,lt)}function Os(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!Yk.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw new l(`${t} provides key "${o}" more than once after case normalization`,d.USAGE);n[i]=s}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${lt.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:o,...s}=n;return{...s,command:s.command??o}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64adcc3c-3646-5990-9442-4c4374a2dc7d")}catch{}})();var Qt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",or,qp,"FORCE_COLOR"]),Ns=/^[A-Za-z_][A-Za-z0-9_]*$/,Xt=["schema","tracker","auto"],R_=["source","isolated","snapshot"];function yr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=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=o.slice(0,s).trim(),a=o.slice(s+1);if(!Ns.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(Qt.has(i.toUpperCase()))throw new l(`${t} env_set key "${i}" is reserved for sandbox safety`,d.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function br(e,t){if(!e)return;let n=Tn(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(!Ns.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(Qt.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function Fs(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 Ms(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Xt.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${Xt.join(", ")}`,d.USAGE)}function Zt(e,t){if(!e)return;let n=e.trim().toLowerCase();if(R_.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${R_.join(", ")}`,d.USAGE)}function en(e){if(!e)return;let t=Tn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Nn(e,t,n){let r=en(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(s){throw new l(`${t} ${n} includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`,d.USAGE)}return r}}function Ds(e,t){if(!e)return;let n=me(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,d.USAGE);return n}function $s(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+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 Us(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+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 Jk=new Set(lt);function Gs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xk(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!Jk.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw t(`provides key "${o}" more than once after case normalization`);n[i]=s}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${lt.join(", ")}.`);return n}function Jt(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 Ps(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=o.filter(i=>i.length>0);return s.length>0?s:void 0}function x_(e,t,n){let r=Ps(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`)}return r}}function Ls(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 Qk(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:Ls(n,"timeout_seconds",t),s=r===void 0?void 0:Ls(r,"timeout",t);if(o!==void 0&&s!==void 0&&o!==s)throw t("timeout and timeout_seconds must match when both are provided");let i=o??s;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function Zk(e,t){let n=Jt(e,"scope",t);if(n===void 0)return"project";if(!et.includes(n))throw t(`field "scope" must be one of: ${et.join(", ")}`);return n}function eS(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Gs(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Ns.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(Qt.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=s}return Object.keys(r).length>0?r:void 0}function tS(e,t){let n=Ps(e,"env_clear",t);if(n){for(let r of n){if(!Ns.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(Qt.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function nS(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 rS(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=Ls(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 oS(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Gs(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(s)}return Object.keys(r).length>0?r:void 0}function sS(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Gs(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=Ls(s,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function iS(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!Gs(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${lt.join(", ")}.`);let o=Xk(e,r),s=Jt(o,"command",r),i=Jt(o,"cmd",r);if(s!==void 0&&i!==void 0&&s!==i)throw r("command and cmd must match when both are provided");let a=s??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=Jt(o,"path",r),m=Jt(o,"pm_context_mode",r);if(m!==void 0&&!Xt.includes(m))throw r(`field "pm_context_mode" must be one of: ${Xt.join(", ")}`);let u=Zt(Jt(o,"workspace_context_mode",r),`${n} ${t}`),p=Jt(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:Zk(o,r),timeout_seconds:Qk(o,r),pm_context_mode:m,workspace_context_mode:u,env_set:eS(o,r),env_clear:tS(o,r),shared_host_safe:nS(o,"shared_host_safe",r),assert_stdout_contains:Ps(o,"assert_stdout_contains",r),assert_stdout_regex:x_(o,"assert_stdout_regex",r),assert_stderr_contains:Ps(o,"assert_stderr_contains",r),assert_stderr_regex:x_(o,"assert_stderr_regex",r),assert_stdout_min_lines:rS(o,r),assert_json_field_equals:oS(o,r),assert_json_field_gte:sS(o,r),note:p!==void 0&&p.trim().length>0?p.trim():void 0}}function O_(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(s){throw new l(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return o.map((s,i)=>iS(s,o.length>1?`entry ${i+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0062e981-158a-5e6a-b028-6c7cef0f59ba")}catch{}})();var lc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],mc=[{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"}],P_=[...lc,...mc],js=[{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 qs(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let o=r.trim().toLowerCase();if(!o)throw new l("--unset values must not be empty",d.USAGE);if(qe(o))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let s=e.resolveDefinition(o);if(!s)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function Ks(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let s of o){if(s.allow_unset===!1)continue;let i=new Set;if(typeof s.key=="string"&&s.key.length>0&&i.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&i.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(i.add(s.cli_flag.replaceAll("-","_").toLowerCase()),i.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let a of s.cli_aliases)typeof a!="string"||a.length===0||(i.add(a.replaceAll("-","_").toLowerCase()),i.add(a.toLowerCase()));if(i.has(r))return{optionKey:s.key,metadataKey:s.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="002f45a2-edc3-5aa0-9af8-d9b1dfecc097")}catch{}})();var aS={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 cS(e){return aS[e]}function uc(e){return cS(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]="c9bfbfd4-3d34-5fa7-b264-6bf9ed5f7f81")}catch{}})();var dS=["strict","progressive"],lS=["lightweight"],M_=new Set(["Reminder","Meeting","Event"]),mS=new Set(["author","created_at","text"]),fc=[...P_,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...js],uS=(()=>{let e=new Map;for(let t of fc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),zs=new Map(fc.map(e=>[e.optionKey,e.canonical])),pS=fc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function fS(e,t){let n=Q(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function _S(e,t){let n=e.default_status;if(n!==void 0){let r=Q(n,t);if(r)return r}return t.open_status}function pc(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 hS=Es();function D_(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s};qe(t.template)&&(t.template=void 0);let r=new Set([...zs.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!qe(s))continue;let i=o==="rank"?"order":zs.get(o)??o;n(i),t[o]=void 0}return ve(e,Ts(t,hS))}function fe(e){if(e!==void 0)return e}function gS(e,t){return qs({raw:e,supportedFields:pS,resolveDefinition:n=>uS.get(n)??Ks(n,"create",t)})}var L_=["id","kind","type","author","created_at","source_kind"],Bs=["path","scope","note"];function yS(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let i=s.trim(),a=Hs(i,L_);hr(i,a);let c=a?ie(s,"--dep"):{id:i,kind:"related"};a&&je(c,"--dep",L_);let m=fe(c.id),u=bS(fe(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=tr(fe(c.source_kind)),f=fe(c.author);return{id:nr(m,n,p),kind:Ee(u,Ut,"dependency kind"),created_at:pc(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function bS(e){return typeof e=="string"?Hr(e)??e.trim():e}function Hs(e,t){return Ko(e,t)?!0:Ho(e)}function nn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Se(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=ie(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!mS.has(f)).length>0)return{created_at:pc(m.created_at,n),author:fe(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:pc(m.created_at,n),author:fe(m.author)??r,text:p}}),explicitEmpty:!1})}function _c(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),o=Hs(r,Bs);Sa(r,"--file","file path",o);let s=o?ie(n,"--file"):{path:r};if(o&&je(s,"--file",Bs),!s.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:s.path,scope:Ee(s.scope??"project",et,"file scope"),note:fe(s.note)}}),explicitEmpty:!1})}function hc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),o=Hs(r,lt);Sa(r,"--test","test command",o);let s=o?Os(ie(n,"--test"),"--test"):{command:r},i=fe(s.command),a=fe(s.path);if(!i)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let c=fe(s.timeout_seconds),m=fe(s.timeout);if(c&&m&&c!==m)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let u=c??m;return{command:i,path:a,scope:Ee(s.scope??"project",et,"test scope"),timeout_seconds:u?me(u,"timeout_seconds"):void 0,pm_context_mode:Ms(s.pm_context_mode,"--test"),workspace_context_mode:Zt(s.workspace_context_mode,"--test"),env_set:yr(s.env_set,"--test"),env_clear:br(s.env_clear,"--test"),shared_host_safe:Fs(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:en(s.assert_stdout_contains),assert_stdout_regex:Nn(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:en(s.assert_stderr_contains),assert_stderr_regex:Nn(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Ds(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:$s(s.assert_json_field_equals,"--test"),assert_json_field_gte:Us(s.assert_json_field_gte,"--test"),note:fe(s.note)}}),explicitEmpty:!1})}function gc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),o=Hs(r,Bs),s=o?ie(n,"--doc"):{path:r};if(o&&je(s,"--doc",Bs),!s.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:s.path,scope:Ee(s.scope??"project",et,"doc scope"),note:fe(s.note)}}),explicitEmpty:!1})}function wS(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Cs(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function vS(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--event","Use --clear-events to clear linked events."),{values:Is(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function kS(e,t,n,r=[]){let o=[...jr.filter(s=>e[s]!==void 0),...r.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(o))}function SS(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function N_(e,t,n){let r=zn("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function ES(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 $_(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 AS(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(N_(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(N_(r,e.name,"required_create_repeatables"));return n}function TS(e,t,n,r){for(let o of e)if(!(!$_(t,o)&&!n.has(o)))throw new l(`Option ${ye("create",o)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function CS(e,t,n){if(t!=="strict")return;let r=e.filter(s=>n.has(s)&&!uc(s));if(r.length===0)return;let o=[...new Set(r.map(s=>ye("create",s)))].sort((s,i)=>s.localeCompare(i));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function IS(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Rs(e),explicitEmpty:!1})}async function RS(e){return await Vo(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function xS(e){return at(e)?await RS(e):e}function OS(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: ${dS.join(", ")}`,d.USAGE)}function PS(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: ${lS.join(", ")}`,d.USAGE)}function LS(e,t,n){let r=OS(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 NS(e,t,n,r){let o=e.name,s=ES(t),i=AS(e,n),a=mn(e,"create",i);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);TS(a.disabled,s,r,o),CS(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&uc(u)?!0:$_(s,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>ye("create",u)))].sort((u,p)=>u.localeCompare(p))}var U_=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function FS(e,t){let n=[];for(let r of e){let o=r.match(U_);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function MS(e,t){return e.filter(n=>{let r=n.match(U_);return!r||r[2]!==t})}function DS(e,t,n,r){let o=MS(e,t);if(o.length===0)return;let s=G_(n,[],[],r.open_status);throw new l(o.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function $S(e,t){let r=e.options.find(o=>o.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function US(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 G_(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],i=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of i)a.has(c)||(o.push(...US(c,e.name,r)),a.add(c));for(let c of n){let m=$S(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function yc(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 GS(e){return An(e)}function jS(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=Array.isArray(o)?[...o]:o;for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=Array.isArray(o)?[...o]:o);return n}function qS(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function KS(){let e=R();return e?e.commands.some(t=>t.action==="templates-show"||qS(t.command)==="templates show"):!1}function zS(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[o,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[o]=s;continue}if(Array.isArray(s)&&s.every(i=>typeof i=="string")){r[o]=[...s];continue}throw new l(`Templates package returned unsupported option value for "${o}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function BS(e,t,n){if(!KS())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await Po({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let o=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${o}`,d.USAGE)}return zS(r.result,e)}function HS(e){return I(e)}function B(e,t,n){return e.has(t)||n===void 0?void 0:fe(n)}function tn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var VS=new Set(["milestone","meeting","reminder","event"]);function j_(e,t,n,r){let o=t!==void 0,s=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return VS.has(e.toLowerCase())&&!o&&!s&&!i}function WS(e,t,n,r,o){let s=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),j_(e,n,r,o)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function YS(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await No(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function JS(e,t,n,r,o,s){let i=Xo(o);if(Zo(r,i,t.id_prefix),await j(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let c=we(i,t.id_prefix);return{parent:i,warnings:Qo(c,s).warnings}}async function XS(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await JS(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function QS(e){if(e.explicitId===void 0)return Zn(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||hp(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=we(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 F_(e,t,n,r,o){let s=B(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let i=es(r,s,o);return{value:i.value,warnings:i.warnings}}async function ZS(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:s,status:i,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(s===void 0)return{dependencyValues:u,status:i};let p=we(s,n.id_prefix),f=await j(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=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((y,g)=>y.localeCompare(g))[0]??o.open_status;return{dependencyValues:u,status:h}}function eE(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let o=t.governance.create_default_type?.trim();if(o&&o.length>0&&ge(o,n)){e.type=o;return}ge("Task",n)&&(e.type="Task")}function tE(e,t){return e.options.filter(n=>zn("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function nE(e,t,n,r,o){let s=e,i=[];if(s.template!==void 0){let h=s.template.trim();if(h.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let y=await BS(h,t,n);s=D_(jS(y,s))}if(s.type===void 0&&eE(s,r,o),s.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let a=ge(s.type,o);if(!a){let h=yp(s.type),y=h?ge(h,o):void 0;if(y)i.push(`type_coercion:${s.type.trim()}:${y}`),s.type=y,a=y;else throw new l(Et(s.type,o.types,At(n,r.schema)),d.USAGE)}let c=zr(a,o);if(!c)throw new l(`Invalid type value "${s.type}"`,d.USAGE);let m=c.name,u=tE(c,s),p=u.map(h=>`${h.key}=${String(s[h.key])}`);if(p.length>0){s.typeOption=[...p,...s.typeOption??[]];for(let h of u)delete s[h.key]}let f=PS(s.schedulePreset);if(f!==void 0&&!M_.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=LS(s.createMode,f,r.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function rE(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of o)if(s.enabled){if(s.values&&s.values.length>0)throw new l(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,d.USAGE);n.add(s.metadataKey),r.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function oE(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=zs.get(r)??r;throw new l(`Cannot combine --unset ${s} with ${ye("create",r)}`,d.USAGE)}}function sE(e){let t=(n,r)=>{let o=zs.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;As(n,ye("create",r),s)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function iE(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)}var aE={"--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","--type-option":"--clear-type-options"};function cE(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:s,type:i,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(h=>{let y=h.type==="boolean"?"<true|false>":h.type==="array"?"<json-array>":h.type==="object"?"<json-object>":h.type==="number"?"<number>":h.type==="string_array"||h.repeatable?"<value>":"<string>";return{example:`--${h.cli_flag} ${y}`,description:`--${h.cli_flag} maps to ${h.metadata_key} (${h.type}${h.repeatable?", repeatable":""})`}}),u=[G_(n,r,o,s),...m.map(h=>h.example)].join(" "),p=[`Run "pm create --help --type ${i}" for type-aware required option guidance.`,...t.filter(h=>h==="--title").map(()=>'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".'),M_.has(i)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&p.push(`Required custom field formats: ${m.map(h=>h.description).join("; ")}.`);let f=[...new Set(t.flatMap(h=>{let y=h.split(" ",1)[0],g=aE[y];return g?[g]:[]}))];f.length>0&&p.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let _=t.length===1?`Missing required option ${t[0]} for type "${i}"`:`Missing required options ${t.join(", ")} for type "${i}"`;throw new l(_,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${i}" in one invocation.`,examples:[...f.map(h=>`pm create --type ${i} ${h} ...`),u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function dE(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Rt(t.tags):[];return Sn(n,t.addTags)}function lE(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=tn(e,"order",n,o=>me(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function mE(e,t,n,r,o,s){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?s:ne(r.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:i,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:rc(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function uE(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:s,author:i,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=jt(t,n,r,o.item_format,s.type_to_folder),g=Ie(t,r),b=Ot(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(G=>b.resolve(G.kind)?.hierarchy),S=await xs({pmRoot:t,author:i,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:v}),T=v,x=[];try{let G=await be(t,r,o.locks.ttl_seconds,i,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let F=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await le(t,o.item_format,s.type_to_folder,void 0,o.schema):void 0;if(await j(t,r,o.id_prefix,o.item_format,s.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);if(F){let N=$(o.schema);ts(F,[...F,c.metadata],r,se=>te(se,N),b)}await Oo({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:$o({pmRoot:t,settings:o,typeToFolder:s.type_to_folder})});let K=await bn(t,i,{required:o.governance.duplicate_detection_mode==="strict"&&h!==!0}),pe=[];try{o.governance.duplicate_detection_mode==="strict"&&h!==!0&&await On(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await he(y,st(c,{format:o.item_format,schema:o.schema,extensionFieldNames:a}));try{let N=Ge({nowIso:f,author:i,op:"create",before:m,after:c,message:u});await Ct(g,N)}catch(N){throw await ln(y),N}T&&(await S(),T=!1),pe=await wn({pmRoot:t,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:y,document:c})}finally{await K()}x=[...F?ms(F,[...F,c.metadata],r):[],...pe,...await W({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await W({path:g,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],pn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Bt(c.metadata,p),changed_fields:p})}finally{await G()}}finally{T&&await S()}return x}async function Pt(e,t){let n=D_(await xS(e)),r=E(process.cwd(),t.path);await HS(r);let o=await A(r),s=$(o.schema),i=Ve(o.schema),a=O(o,R()),c=await nE(n,t,r,o,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=gS(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=rE(n,f);oE(n,f),sE(n);let y=NS(m,n,p,h),g=k(),b=C(fe(n.author),o.author_default),v=yS(n.dep,g,o.id_prefix,b),S=nn("--comment",n.comment,g,b),T=nn("--note",n.note,g,b),x=nn("--learning",n.learning,g,b),G=_c(n.file),F=hc(n.test);F.values=await xn(F.values,b,g);let X=gc(n.doc),K=wS(n.reminder,g),pe=vS(n.event,g),N=IS(n.typeOption),se=Bn(u,N.values,a),ht=R(),Qe=vt(ht),gt=qr(n.field,ht),Be=xu(n,i,u),Ai=new Set(Be.missing_required_flags),Ti=i.definitions.filter(V=>Ai.has(`--${V.cli_flag}`));iE(gt,Be,f);let Kn=FS(se.errors,u),Dt=Kn.map(V=>`--type-option ${V}=<value>`),Gd=[...new Set([...y,...Dt,...Be.missing_required_flags])].sort((V,Fi)=>V.localeCompare(Fi));cE({combinedMissingFlags:Gd,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:Kn,openStatus:s.open_status,type:u,createMode:p,missingRequiredRuntimeFields:Ti}),DS(se.errors,u,m,s);let Ce=await QS({pmRoot:r,settings:o,typeRegistry:a,explicitId:n.id}),yt=n.status!==void 0?fS(n.status,s):_S(m,s),Ci=n.priority!==void 0?GS(n.priority):2,L=f.metadataKeys,Fe=dE(L,n),Ze=tn(L,"deadline",n.deadline,V=>ne(V,new Date(g),"deadline")),Nr=tn(L,"estimated_minutes",n.estimatedMinutes,V=>En(V,"estimated-minutes")),bt=B(L,"acceptance_criteria",n.acceptanceCriteria),Ii=B(L,"definition_of_ready",n.definitionOfReady),He=lE(L,n),Ri=B(L,"goal",n.goal),Fr=B(L,"objective",n.objective),ew=B(L,"value",n.value),tw=B(L,"impact",n.impact),nw=B(L,"outcome",n.outcome),rw=B(L,"why_now",n.whyNow),ow=B(L,"assignee",n.assignee),sw=L.has("author")?void 0:fe(n.author)??b,iw=B(L,"parent",n.parent),jd=await YS(iw,n,L,r),xi=jd.parent,aw=jd.parentSource,cw=B(L,"reviewer",n.reviewer),dw=tn(L,"risk",n.risk,V=>Ee(ws(V),cn,"risk")),lw=tn(L,"confidence",n.confidence,V=>ks(V)),mw=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,qd=o.validation.sprint_release_format,$t=[...c.warnings,...WS(u,Ce,Ze,K.values,pe.values)],Kd=await XS({itemId:Ce,parent:xi,pmRoot:r,settings:o,typeRegistry:a,policy:mw});xi=Kd.parent,$t.push(...Kd.warnings);let zd=F_(L,"sprint",n.sprint,"sprint",qd),uw=zd.value;$t.push(...zd.warnings);let Bd=F_(L,"release",n.release,"release",qd),pw=Bd.value;$t.push(...Bd.warnings);let Hd=B(L,"blocked_by",n.blockedBy),Vd=await ZS({pmRoot:r,settings:o,typeRegistry:a,statusRegistry:s,blockedBy:Hd,dependencyValues:v.values,status:yt,statusExplicit:n.status!==void 0,nowValue:g,author:b}),Oi=Vd.dependencyValues;gr(Ce,Oi),$t.push(...await Yt({pmRoot:r,dependencies:Oi,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ce,createdAt:g}],schema:o.schema})),yt=Vd.status;let fw=B(L,"blocked_reason",n.blockedReason),_w=B(L,"unblock_note",n.unblockNote),hw=B(L,"reporter",n.reporter),gw=tn(L,"severity",n.severity,V=>Ee(vs(V),dn,"severity")),yw=B(L,"environment",n.environment),bw=B(L,"repro_steps",n.reproSteps),Wd=B(L,"resolution",n.resolution),ww=B(L,"expected_result",n.expectedResult),vw=B(L,"actual_result",n.actualResult),kw=B(L,"affected_version",n.affectedVersion),Sw=B(L,"fixed_version",n.fixedVersion),Ew=B(L,"component",n.component),Aw=tn(L,"regression",n.regression,V=>Ss(V)),Tw=B(L,"customer_impact",n.customerImpact),Pi=yc(n.title,"--title"),Li=n.description??"",Mr=n.body??"",Yd=await On({title:Pi,description:Li,body:Mr},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});$t.push(...us(Yd));let Ni=mE(yt,s,o,n,Wd,g),Cw=Ni.closeReason,Iw=yt===s.close_status?g:void 0,Rw=Ni.completedAt;$t.push(...Ni.warnings);let Dr=fa({id:Ce,title:Pi,description:Li,type:u,type_options:se.normalized,status:yt,closed_at:Iw,completed_at:Rw,close_reason:Cw,priority:Ci,tags:Fe,created_at:g,updated_at:g,deadline:Ze,assignee:ow,author:sw,estimated_minutes:Nr,acceptance_criteria:bt,definition_of_ready:Ii,order:He,goal:Ri,objective:Fr,value:ew,impact:tw,outcome:nw,why_now:rw,parent:xi,reviewer:cw,risk:dw,confidence:lw,sprint:uw,release:pw,blocked_by:Hd,blocked_reason:fw,unblock_note:_w,reporter:hw,severity:gw,environment:yw,repro_steps:bw,resolution:Wd,expected_result:ww,actual_result:vw,affected_version:kw,fixed_version:Sw,component:Ew,regression:Aw,customer_impact:Tw,dependencies:Oi,comments:S.values,notes:T.values,learnings:x.values,files:G.values,tests:F.values,docs:X.values,reminders:K.values,events:pe.values,...gt,...Be.values});try{Kr(Dr,ht)}catch(V){throw new l(V instanceof Error?V.message:"Invalid extension item field values",d.USAGE)}let xw=Tt({metadata:Dr,body:Mr},{schema:o.schema,extensionFieldNames:Qe}),Ow={metadata:{},body:""},Jd=[..._].sort((V,Fi)=>V.localeCompare(Fi)),Pw=SS(n.message,Jd),Xd=kS(Dr,Mr,Jd,[...Object.keys(gt),...Object.keys(Be.values??{})]),Lw=await uE({pmRoot:r,type:u,id:Ce,settings:o,typeRegistry:a,author:b,extensionFieldNames:Qe,afterDocument:xw,beforeDocument:Ow,historyMessage:Pw,changedFields:Xd,nowValue:g,similarityCandidate:{title:Pi,description:Li,body:Mr},allowDuplicate:n.allowDuplicate}),Qd=structuredClone(Dr);p==="strict"&&_.has("dependencies")&&(Qd.dependencies=[]);let Nw=C_(Ce,u,yt,s);return j_(u,Ze,K.values,pe.values)&&Uu(`[pm] warning: ${u} '${Ce}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ce} --deadline <ISO>' or 'pm update ${Ce} --event "start=<ISO>,end=<ISO>"'.`),{item:Qd,changed_fields:Xd,warnings:[...$t,...Lw],...Object.fromEntries([["parent_source",aw],["next_transition",Nw],["similarity_advisory",Yd]].filter(V=>V[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]="78f8b369-1802-555d-a8cc-0147c0d8fb08")}catch{}})();var kc=[...lc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...mc,...js],pE=(()=>{let e=new Map;for(let t of kc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Vs=new Map(kc.map(e=>[e.optionKey,e.canonical])),fE=kc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),_E=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),hE=Es({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Y_(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s},r=new Set([...Vs.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!qe(s))continue;let i=o==="rank"?"order":Vs.get(o)??o;n(i),t[o]=void 0}return ve(e,Ts(t,hE))}function J_(e,t,n=[]){return qs({raw:e,supportedFields:fE,resolveDefinition:r=>{let o=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return pE.get(r)??Ks(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var q_=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 K_(e){let t=e.disallowedFlags.flatMap(r=>{let o=q_.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=q_.get(r);return o?[`Replace ${r} with: ${o(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 gE(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let s=(c,m,u)=>{c&&u.push(m)};if(o){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw K_({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let i=[];s(t.status!==void 0,"--status",i),s(t.closeReason!==void 0,"--close-reason",i),s(t.assignee!==void 0,"--assignee",i),s(t.parent!==void 0,"--parent",i),s(t.blockedBy!==void 0,"--blocked-by",i),s(t.blockedReason!==void 0,"--blocked-reason",i),s(t.unblockNote!==void 0,"--unblock-note",i),s(t.dep!==void 0,"--dep",i),s(t.depRemove!==void 0,"--dep-remove",i),s(t.replaceDeps===!0,"--replace-deps",i),s(t.replaceTests===!0,"--replace-tests",i),s(t.replaceFiles===!0,"--replace-files",i),s(t.replaceDocs===!0,"--replace-docs",i),s(t.note!==void 0,"--note",i),s(t.learning!==void 0,"--learning",i),s(t.test!==void 0,"--test",i),s(t.reminder!==void 0,"--reminder",i),s(t.event!==void 0,"--event",i),s(t.clearDeps===!0,"--clear-deps",i),s(t.clearComments===!0,"--clear-comments",i),s(t.clearNotes===!0,"--clear-notes",i),s(t.clearLearnings===!0,"--clear-learnings",i),s(t.clearFiles===!0,"--clear-files",i),s(t.clearTests===!0,"--clear-tests",i),s(t.clearDocs===!0,"--clear-docs",i),s(t.clearReminders===!0,"--clear-reminders",i),s(t.clearEvents===!0,"--clear-events",i);let a=[...n].filter(c=>_E.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw K_({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 yE(e,t){let n=Q(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function bE(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Km({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Q(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Q(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${zm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,d.USAGE);return`workflow_transition_not_allowed: ${o}`}function wE(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:X_(e)}function X_(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(t).toISOString()}function Fn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var vE=["id","kind","type","author","created_at","source_kind"],kE=["id","kind","type","author","created_at","source_kind"];function Q_(e){return e.startsWith("```")||e.includes(`
6
- `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Ho(e)}function Z_(e){return typeof e=="string"?Hr(e)??e.trim():e}function Ys(e,t,n,r){return e?(Se(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let i=s.trim(),a=Q_(i);hr(i,a);let c=a?ie(s,"--dep"):{id:i,kind:"related"};a&&je(c,"--dep",vE);let m=c.id?.trim(),u=Z_((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=tr(Fn(c.source_kind)),f=Fn(c.author);return{id:nr(m,t,p),kind:Ee(u,Ut,"dependency kind"),created_at:wE(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function SE(e,t){return e?(Se(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);let o=Q_(r);if(hr(r,o,"--dep-remove"),o){let s=ie(r,"--dep-remove");je(s,"--dep-remove",kE);let i=s.id?.trim();if(!i)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(i.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${i}"`,d.USAGE);let a=Z_(Fn(s.kind??s.type)),c=tr(Fn(s.source_kind)),m=Fn(s.author),u=Fn(s.created_at);return{id:nr(i,t,c),kind:a?Ee(a,Ut,"dependency kind"):void 0,source_kind:c,author:m,created_at:u?X_(u):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:we(r,t)}})):[]}function Ws(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function EE(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),s=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function AE(e,t,n,r){let o=[...e??[]],s=!1;if(t===void 0){let i=o.filter(a=>a.kind!=="blocked_by");return i.length!==o.length&&(o=i,s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(i=>i.kind==="blocked_by"&&i.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function TE(e,t,n,r,o,s){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await j(n,we(i,r),r,o,s);return a?{id:a.id}:{unresolved:i}}function CE(e,t,n,r,o){let s=AE(e.dependencies,t,n,r);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,o.includes("dependencies")||o.push("dependencies"))}function IE(e){return`${e.path}::${e.scope}`}function RE(e){return`${e.path}::${e.scope}`}function xE(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function eh(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function OE(e){return An(e)}function z_(e,t){let n=zn("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function PE(e,t,n){let r=new Set,o=(s,i)=>{i&&r.add(s)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=J_(e.unset,t,n);for(let i of s.optionKeys)o(i,!0)}return r}function LE(e,t,n,r,o){let s=zr(e,n);if(!s)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=mn(s,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let a=PE(t,r,o);for(let c of i.disabled)if(a.has(z_(c,e)))throw new l(`Option ${ye("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of i.required)if(!a.has(z_(c,e)))throw new l(`Missing required option ${ye("update",c)} for type "${e}"`,d.USAGE)}var NE=new Set(["order","rank"]),FE=zi.filter(e=>!NE.has(e)),th=["tags","closeReason",...FE],ME=["title","description","body","status","closeReason","completedAt","priority","type",...zi,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],DE=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>ne(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>En(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],$E=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Ee(ws(e),cn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>ks(e)}],UE=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Ee(vs(e),dn,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>Ss(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function vc(e,t,n){for(let r of e){let o=t[r.optionKey],s=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!s)){if(s){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new l(`${ye("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function GE(e){return Y_(await Vo(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function Sc(e){return at(e)?await GE(e):Y_(e)}function jE(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 bc(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);bc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),bc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),bc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function qE(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 KE(e){let t={};for(let n of th)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function zE(e,t){let n=KE(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=Vs.get(r)??r;throw new l(`Cannot combine --unset ${s} with ${ye("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 BE(e){let t=(n,r)=>{let o=Vs.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;As(n,ye("update",r),s)};for(let n of th)t(e[n],String(n));t(e.order??e.rank,"order"),Se(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Se(e.event,"--event","Use --clear-events to clear linked events.")}function HE(e,t){let n={};for(let r of ME)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 VE(e){let t=await j(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 Z(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function WE(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return le(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function YE(e){e.before&&ts(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>te(t,e.statusRegistry),Ot())}async function JE(e){await I(e)}function XE(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 QE(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Xo(e.options.parent);if(Zo(e.id,t,e.settings.id_prefix),await j(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=we(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:Qo(r,e.parentReferencePolicy).warnings}}function ZE(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function eA(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await j(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 Z(t,{schema:e.settings.schema}),r=e.options.type!==void 0?ge(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=bE({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function tA(e){if(!e.fieldFlags.status||Q(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],o=[];if(n.length>0){let a=ve(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),c=await mt(e.id,a,e.global);o=c.changed_fields,r.push(...c.warnings)}let s=await dt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...e.workflowTransitionWarnings,...r,...s.warnings,"auto_routed_from_update_to_close"];return{item:s.item,changed_fields:[...o,...s.changed_fields],warnings:i}}function nA(e,t,n,r){return t.title!==void 0&&(e.metadata.title=yc(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")),Q(e.metadata.status,n)??e.metadata.status}var rA=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function oA(e,t){for(let n of rA)e[n]!==void 0&&(delete e[n],t.push(n))}function sA(e,t,n,r,o){let s=yE(n,t.statusRegistry);if(e.metadata.status=s,o.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!te(s,t.statusRegistry)&&te(r,t.statusRegistry)&&oA(e.metadata,o)}function iA(e,t,n,r){if(t.options.status!==void 0&&sA(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!te(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=ne(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function aA(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&te(n,t.statusRegistry)&&!te(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function cA(e,t,n,r){iA(e,t,n,r),aA(e,t,n,r)}function dA(e,t,n){let r=ge(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=OE(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=ge(t.options.type,t.typeRegistry);if(!o)throw new l(Et(t.options.type,t.typeRegistry.types,At(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=o,r=o,n.push("type")}return LE(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),lA(e,t,r,n),r}function lA(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let s=Rs(t.options.typeOption??[]),i=Bn(n,s,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 o=Bn(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=o.normalized}function mA(e,t){let n=new Set(t.map(o=>Ws(o))),r=new Set;return e.filter(o=>{if(!n.has(Ws(o)))return!0;let s=EE(o);return r.has(s)?!1:(r.add(s),!0)})}function uA(e,t,n){let r=t.filter(o=>!e.some(s=>eh(s,o)));if(r.length!==0)throw new l(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,d.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function pA(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=mA(r,t.dependencyUpdates.additions);let o=new Set(r.map(s=>Ws(s)));for(let s of t.dependencyUpdates.additions){let i=Ws(s);o.has(i)||(r.push(s),o.add(i))}}t.dependencyRemovals.length>0&&(uA(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(s=>eh(o,s)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function fA(e,t,n){wc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),wc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),wc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function wc(e,t,n,r,o,s){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],s.push(t))}function _A(e,t,n){B_(e,"files",t.options.file,t.fileUpdates.values,IE,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),hA(e,t,n),B_(e,"docs",t.options.doc,t.docUpdates.values,RE,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function B_(e,t,n,r,o,s,i,a){if(!(n===void 0&&!i.has(t))){if(s)e.metadata[t]=r;else if(i.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(u=>o(u)));for(let u of r){let p=o(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function hA(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=H_(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=H_([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function H_(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=xE(r);n.has(o)||(t.push(r),n.add(o))}return t}function gA(e,t,n){let r=t.options.addTags,o=t.options.removeTags,s=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Rt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Bo(Sn(i,r),o),n.changedFields.push("tags")}vc(DE,t.options,n),bA(e,t,n.changedFields)}function yA(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let s=zo(kn(e.metadata.acceptance_criteria),r,o);if(s.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let i=s.criteria.join("; ");e.metadata.acceptance_criteria!==i&&(i===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=i,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function bA(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=me(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function wA(e,t,n,r){vA(e,t,n.changedFields),kA(e,t,n.changedFields),vc($E,t.options,n),V_(e,t,"sprint",r,n.changedFields),V_(e,t,"release",r,n.changedFields),SA(e,t,n.changedFields),vc(UE,t.options,n)}function vA(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 kA(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 V_(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=es(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,r.push(...s.warnings)}o.push(n)}}function SA(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)&&CE(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function EA(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Cs(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=Is(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function AA(e,t,n){W_(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),W_(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let i=o.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===o)?.cli_flag??i;throw new l(`Cannot combine --unset ${i} with --${c}`,d.USAGE)}nt(e[o],s)||(e[o]=s,n.push(o))}let r=qr(t.options.field,t.extensionRegistrations);for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new l(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,d.USAGE);for(let[o,s]of Object.entries(r))nt(e[o],s)||(e[o]=s,n.push(o))}function W_(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function TA(e,t){let n=structuredClone(e.metadata),r=e.body,o=[],s=[],i=nA(e,t.options,t.statusRegistry,o),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};cA(e,t,i,o),dA(e,t,o),pA(e,t,o),fA(e,t,o),_A(e,t,o),gA(e,t,c),yA(e,t,c),wA(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&gr(e.metadata.id,e.metadata.dependencies),Q(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),EA(e,t,o),AA(a,t,o);try{Kr(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(o)].filter(p=>p==="body"?e.body!==r:!nt(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${kn(n.acceptance_criteria).length}:${kn(m.acceptance_criteria).length}`),{changedFields:u,warnings:s}}async function nh(e,t,n,r={}){t=await Sc(t);let o=E(process.cwd(),n.path);await JE(o);let s=await A(o),i=$(s.schema),a=Ve(s.schema),c=R(),m=vt(c),u=O(s,c),p=s.governance.workflow_enforcement??"off",f=p==="off"?[]:qm(s.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],h=J_(t.unset,a,m),y=new Set(h.optionKeys),g=new Set(h.metadataKeys);Ec(t),qE({definitions:jE(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:g}),gE(e,t,g),zE(t,h),BE(t);let b=C(t.author,s.author_default),v=new Date,S=v.toISOString(),T=Ys(t.dep,s.id_prefix,S,b);gr(e,T.additions);let x=await Yt({pmRoot:o,dependencies:T.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),G=SE(t.depRemove,s.id_prefix),F=nn("--comment",t.comment,S,b),X=t.ownershipMetadataBypass===!0&&F.values?{...F,values:F.values.map(Fe=>({...Fe,author:b}))}:F,K=nn("--note",t.note,S,b),pe=nn("--learning",t.learning,S,b),N=_c(t.file),se=hc(t.test);se.values=await xn(se.values,b,S);let ht=gc(t.doc),Qe=[],gt=await QE({id:e,options:t,unsetTargets:h,pmRoot:o,settings:s,typeRegistry:u,parentReferencePolicy:_}),Be=await TE(t.blockedBy,g.has("blocked_by"),o,s.id_prefix,s.item_format,u.type_to_folder),Ai=Be.id,Ti=[...gt.warnings,...ZE(Be)],Kn=Mo(t,a,t.runtimeFieldCommands),Dt=HE(t,Kn);if(!Object.values(Dt).some(Boolean))return VE({pmRoot:o,id:e,settings:s,typeRegistry:u});Qe.push(...await eA({options:t,fieldFlags:Dt,workflowEnforcement:p,typeWorkflows:f,statusRegistry:i,typeRegistry:u,pmRoot:o,id:e,settings:s}));let Ce=await tA({options:t,fieldFlags:Dt,statusRegistry:i,workflowTransitionWarnings:Qe,global:n,id:e});if(Ce)return Ce;XE(t);let yt=Ot(),Ci=Dt.parent&&!g.has("parent")||T.additions.some(Fe=>yt.resolve(Fe.kind)?.hierarchy),L=await xs({pmRoot:o,author:b,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Ci});try{let Fe=await WE({fieldFlags:Dt,clearedMetadataKeys:g,pmRoot:o,settings:s,typeToFolder:u.type_to_folder}),Ze,Nr,bt=await tp({pmRoot:o,settings:s,typeToFolder:u.type_to_folder,id:e,op:CA(t,r),author:b,message:t.message,resolveHistoryContext:()=>Nr,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(He){Ze=IA({document:He,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),Nr=Ze?{recurrence:Ze}:void 0,Fe=Fe?.map(Fr=>Fr.id===He.metadata.id?structuredClone(He.metadata):Fr);let Ri=TA(He,{options:t,settings:s,typeRegistry:u,statusRegistry:i,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:g,dependencyUpdates:T,dependencyRemovals:G,commentUpdates:X,noteUpdates:K,learningUpdates:pe,fileUpdates:N,testUpdates:se,docUpdates:ht,resolvedParentValue:gt.resolvedParentValue,resolvedBlockedByDependencyId:Ai,runtimeFieldUpdates:Kn,nowValue:v,nowIso:S,author:b,pmRoot:o});return YE({before:Fe,document:He,statusRegistry:i}),Ri}});await L();let Ii=Fe?ms(Fe,Fe.map(He=>He.id===bt.item.id?bt.item:He),bt.item.id):[];return{item:bt.item,changed_fields:bt.changedFields,warnings:[...Qe,...Ti,...x,...Ii,...bt.warnings],...Ze===void 0?{}:{lifecycle_transition:Ze}}}finally{await L()}}function CA(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function IA(e){if(e.recurrenceReason===void 0)return;let t=Q(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!te(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,d.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=Q(n,e.statusRegistry)??n,o=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(i=>{let a=o[i];return typeof a=="string"?[[i,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:s}}async function mt(e,t,n){return nh(e,t,n)}async function rh(e,t,n,r){let o=await nh(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,d.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fada7a33-ad1d-54f1-ae03-c5f8e4568d75")}catch{}})();var sh=1,Tc="update-many",RA=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),xA=["--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(", "),OA={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"},PA=[{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"}],LA={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"},ih=e=>{let t={};for(let[n,r]of Object.entries(e))RA.has(n)||r!==void 0&&(t[n]=r);return t},NA=e=>Object.keys(ih(e)).length>0,ah=e=>typeof e=="string"?e.trim():e,FA=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Ac=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},MA=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??ah(e)},DA={priority:FA,estimatedMinutes:Ac,order:Ac,rank:Ac,regression:MA},$A=(e,t)=>{if(t!==void 0)return(DA[e]??ah)(t)},UA=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return LA[t]??t},Js=(e,t)=>nt(e,t),GA=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],jA=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,qA=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",oh=(e,t)=>t===void 0?void 0:e[t],Mn=e=>Array.isArray(e)?e.length:0,KA=(e,t,n)=>{let r=n[e.addKey],o=oh(n,e.removeKey),s=Mn(r),i=Mn(o),a=n[e.clearKey]===!0,c=oh(n,e.replaceKey)===!0;if(![a,c,s>0,i>0].includes(!0))return;let m=GA(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:qA({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:s,remove_count:i,before_count:jA(e.field,m)}}},zA=(e,t)=>{let n=[];for(let r of PA){let o=KA(r,e,t);o!==void 0&&n.push(o)}return n},BA=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],HA=(e,t)=>{if(![t.tags!==void 0,Mn(t.addTags)>0,Mn(t.removeTags)>0].includes(!0))return;let n=BA(e.tags),r=t.tags===void 0?n:Rt(t.tags),o=Sn(r,t.addTags),s=Bo(o,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!Js(i,s))return{field:"tags",before:n,after:s}},VA=(e,t)=>{let n=e.acceptance_criteria,r=zo(kn(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let o=r.criteria.join("; ");if(!Js(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},WA=(e,t,n)=>{for(let[r,o]of Object.entries(OA)){let s=n[r];if(s===void 0)continue;let i=t[o],a=$A(r,s);Js(i,a)||e.push({field:o,before:i,after:a})}},YA=(e,t,n,r)=>{let o=Mo(n,r,["update_many"]);for(let[s,i]of Object.entries(o)){let a=t[s];Js(a,i)||e.push({field:s,before:a,after:i})}},JA=(e,t,n)=>{for(let r of n??[]){let o=UA(r),s=t[o];s!==void 0&&e.push({field:o,before:s,after:null})}},XA=(e,t,n={})=>{let r=e,o=[],s=HA(r,n);if(s&&o.push(s),WA(o,r,n),Mn(n.addAc)>0||Mn(n.removeAc)>0){let i=VA(r,n);i!==void 0&&o.push(i)}return o.push(...zA(r,n)),YA(o,r,n,t),JA(o,r,n.unset),{id:e.id,changes:o}},QA=(e,t)=>gp(e,t,{strict:!0,flagLabel:"--filter-status"}),ZA=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)},eT=[({update:e})=>{e.priority!==void 0&&An(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=O(t,R());if(!ge(e.type,r))throw new l(Et(e.type,r.types,At(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!Q(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&&ne(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&En(e.estimatedMinutes,"estimated-minutes")}],tT=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let s of eT)s(o)},nT=async e=>{let t=await jo(e.pmRoot,Tc,e.rollbackId,sh),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await qo(t.items,(o,s)=>Wt(o,s,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...zt({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}},rT=async e=>{let t={schema_version:sh,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Go(e.pmRoot,Tc,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},oT=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},Cc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},sT=async e=>{let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:$(n.schema),runtimeFieldRegistry:Ve(n.schema)}},iT=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(dr(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 nT({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},aT=async e=>{QA(e.options.status,e.runtime.statusRegistry);let t=await ct(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let s=XA(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?s:{...s,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await ct(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:oT(e.options.list?.ids,r)}},cT=e=>({outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...Cc(e)}),dT=e=>({...zt({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...Cc(e)}),lT=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(s=>s.changes.length>0).map(s=>s.id));for(let s of e.items){if(!o.has(s.id)){t.push({id:s.id,status:"skipped"});continue}try{let i=Ea({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),a=await mt(s.id,i,e.global);t.push({id:s.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(s.id)}catch(i){t.push({id:s.id,status:"failed",error:un(i)})}}return{rows:t,updatedIds:n}},mT=async e=>{if(e.plan.actionable.length===0)return dT(e.plan);let t=k(),n=Uo(Tc,t),r=new Set(e.plan.actionable.map(p=>p.id)),o=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),s=e.options.checkpoint===!1?void 0:await rT({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),i=await lT({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{...zt({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,...s?{checkpoint:s}:{},updated_count:c,skipped_count:m,failed_count:u,rows:i.rows,ids:i.updatedIds,...Cc(e.plan)}},ch=async(e,t)=>{let n=await sT(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:Ea(await Sc(e.update))});let o=ih(e.update);if(ZA(e.list),r!==void 0)return iT({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!NA(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${xA}), or pass --dry-run for a filter-only preview.`,d.USAGE);tT(e.update,n.settings,n.statusRegistry,n.pmRoot),Ec(e.update);let s=await Yt({pmRoot:n.pmRoot,dependencies:Ys(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:O(n.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await aT({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:s});return await Yt({pmRoot:n.pmRoot,dependencies:Ys(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:O(n.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:i.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:n.settings.schema}),e.dryRun===!0?cT(i):mT({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]="f7e870b6-fd80-5742-bc81-826d8f102d30")}catch{}})();var uT=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],dh=["brief","standard","deep"],uh="plan-step-",Lc="draft",Pc=["bug-investigation","feature-implementation","refactoring-sprint"],lh={"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 pT(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(lh,t)?lh[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${Pc.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Pc[0]}`]});return n.map(r=>({...r}))}function fT(e,t){return t>0?Math.round(e/t*100):0}function ph(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 $e(e){return Array.isArray(e)?e.flatMap(t=>Tn(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Tn(e,{unique:!1}):[]}function Ae(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function fh(e,t=Lc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=$i.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${$i.join(", ")}`,d.USAGE);return r}function Nc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ui.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${Ui.join(", ")}`,d.USAGE);return r}function _h(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ji.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${ji.join(", ")}`,d.USAGE);return r}function _T(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Gi.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${Gi.join(", ")}`,d.USAGE);return n}function hT(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=dh.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${dh.join(", ")}`,d.USAGE);return n}function gT(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 Ic=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function yT(e,t){let n=e,r={},o=[];for(let s of t){let i=s.startsWith("plan.")?s.slice(5):s;if(i.length!==0){if(!Ic.has(i)){o.push(s);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...Ic].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...Ic].join(",")}`}});return r}function Fc(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let s=o.indexOf("=");if(s<=0)throw new l(`Invalid ${t} entry "${o}"; 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[o.slice(0,s).trim().toLowerCase()]=o.slice(s+1).trim()}return n}function Mc(e){let t=Fc(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 Dc(e){let t=Fc(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 $c(e){let t=Fc(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 bT(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=fT(t.completed,t.total),t}function wT(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${uh}${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 Dn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),s=e.find(i=>i.order===o);if(s)return s}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function mh(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 vT(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],o=[];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=mh(i);if(a){o.push({from_step:i.id,...a});continue}r.push(i)}return{targets:r,skipped:o}}let s=new Set;for(let i of t){let a=Dn(e,i);if(s.has(a.id))continue;s.add(a.id);let c=mh(a);if(c){o.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:o}}function kT(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 ST(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function ET(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function Oe(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=bT(n),o=ST(n),s={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Lc,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:ET(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(s.steps=n),t==="deep"&&(s.decisions=e.plan_decisions??[],s.discoveries=e.plan_discoveries??[],s.validation=e.plan_validation??[]),s}function Pe(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!Ta(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function hh(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 AT(e){let t=E(process.cwd(),e.path);await I(t);let n=await A(t);return{pmRoot:t,settings:n}}async function gh(e,t){let n=O(e.settings,R()),r=await j(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 o=await Z(r,{schema:e.settings.schema});return hh(o.document.metadata),{document:o.document,itemId:r.id}}function TT(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of $e(e.related))t.push(`id=${n},kind=related`);for(let n of $e(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of $e(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function CT(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 IT(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||$e(e.dependsOn).length>0||$e(e.link).length>0}function RT(e){let t=e.stepTitle?.trim()||void 0,n=ph(e.step),r=e.template?.trim()?pT(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function xT(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",d.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${Pc[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",d.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function OT(e,t){let n=Nc(e.stepStatus,"pending"),r=Uc(e,"depends_on"),o=Ae(e.file).map(Mc),s=Ae(e.test).map(Dc),i=Ae(e.doc).map($c),a=k();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:s.length>0?s:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function PT(e){let t=RT(e),n=IT(e);if(xT(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[OT(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((o,s)=>({id:`${uh}${String(s+1).padStart(3,"0")}`,order:s+1,title:o,body:t.templateSteps[s]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function yh(e,t,n=[]){ve(e,t),n.length>0&&fp(t,n)}async function LT(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 o=fh(e.mode,Lc),s=_T(e.harness),i=e.fromSearch?.trim(),a=CT(e),{steps:c,hasPerStepDetailOptions:m}=PT(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?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:Ae(e.file),test:Ae(e.test),doc:Ae(e.doc),field:Ae(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:TT(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")};yh(e,f);let _=await Pt(f,t),h=await re({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let b=["plan_mode"];g.metadata.plan_mode=o,s&&(g.metadata.plan_harness=s,b.push("plan_harness"));let v=e.scope?.trim();v&&(g.metadata.plan_scope=v,b.push("plan_scope"));let S=e.resumeContext?.trim();return S&&(g.metadata.plan_resume_context=S,b.push("plan_resume_context")),g.metadata.plan_steps=c,b.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],b.push("plan_validation")),p&&(g.metadata.assignee=p,b.push("assignee")),{changedFields:b}}}),y=Oe(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Pe(_.item.id,y),warnings:[..._.warnings],generated_at:k()}}async function NT(e,t,n){let r=hT(t.depth),o=gT(t.fields),{document:s,itemId:i}=await gh(n,e),a=Oe(s.metadata,o===null?r:"deep");return{action:"show",plan:o===null?a:yT(a,o),next_actions:Pe(i,a),warnings:[],generated_at:k()}}function FT(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function Ye(e){let t=C(e.options.author,e.ctx.settings.author_default),n,r=await re({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){hh(o.metadata);let s=$(e.ctx.settings.schema);if(te(o.metadata.status,s)||Ta(o.metadata.plan_mode))throw new l(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.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=(o.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(o.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,o);n=c.resultStep;let m=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));o.metadata.plan_steps=m;let u=FT(a,o.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function MT(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let o=Nc(t.stepStatus,"pending"),s=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await Ye({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;bh(u,void 0,o,s);let f=DT(u,t,{order:p,title:r,status:o});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Oe(i.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Pe(c,m),warnings:[],generated_at:k()}}function bh(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(s=>s.id!==t&&s.status==="in_progress");if(o)throw new l(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function DT(e,t,n){let r=Uc(t,"depends_on"),o=Ae(t.file).map(Mc),s=Ae(t.test).map(Dc),i=Ae(t.doc).map($c),a=k();return{id:wT(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:s.length>0?s:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function Uc(e,t){let n=$e(e.dependsOn).map(u=>({id:u,kind:t})),r=$e(e.related).map(u=>({id:u,kind:"related"})),o=$e(e.blocks).map(u=>({id:u,kind:"blocks"})),s=$e(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=$e(e.link),a=_h(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,...o,...s,...m]}async function Rc(e,t,n,r){let{document:o,resultStep:s,itemId:i}=await Ye({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=Dn(c,r.stepRef),p=k(),f=r.finalStatus??Nc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return bh(c,u.status==="in_progress"?u.id:void 0,f,_),$T(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Oe(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:s,next_actions:Pe(i,a),warnings:[],generated_at:k()}}function $T(e,t,n,r){UT(e,t,n),GT(e,t),e.status=n,e.updated_at=r,jT(e,n,r)}function UT(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 GT(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=Ae(t.file).map(Mc),o=Ae(t.test).map(Dc),s=Ae(t.doc).map($c);r.length>0&&(e.files=xc(e.files,r)),o.length>0&&(e.tests=xc(e.tests,o)),s.length>0&&(e.docs=xc(e.docs,s))}function xc(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let s=JSON.stringify(o);r.has(s)||(r.add(s),n.push(o))}return n}function jT(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function qT(e,t,n,r,o){let{document:s,itemId:i}=await Ye({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(c){let m=Dn(c,r),u=c.filter(f=>f.id!==m.id),p=Math.max(1,Math.min(o,u.length+1));return u.splice(p-1,0,m),u.forEach((f,_)=>{f.order=_+1,f.updated_at=k()}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=Oe(s.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Pe(i,a),warnings:[],generated_at:k()}}async function KT(e,t,n,r){let{document:o,itemId:s}=await Ye({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=Dn(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=Oe(o.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:k()}}async function zT(e,t,n,r){let o=Uc(t,_h(t.linkKind,"related"));if(o.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let s=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await Ye({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Dn(u,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of o){let b=h(g);y.has(b)||(_.push(g),y.add(b))}if(f.linked_items=_,f.updated_at=k(),s){let g=p.metadata.dependencies??[],b=S=>`${S.kind}:${S.id}`,v=new Set(g.map(b));for(let S of o){let T=S.kind==="depends_on"?"blocked_by":S.kind,x={id:S.id,kind:T,created_at:k(),author:C(t.author,n.settings.author_default)};v.has(b(x))||(g.push(x),v.add(b(x)))}p.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),m=Oe(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Pe(a,m),warnings:[],generated_at:k()}}async function BT(e,t,n,r){let o=$e(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:s,itemId:i,resultStep:a}=await Ye({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=Dn(m,r),p=(u.linked_items??[]).filter(f=>!o.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=k(),{changedSteps:[u.id],resultStep:u}}}),c=Oe(s.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Pe(i,c),warnings:[],generated_at:k()}}async function Oc(e,t,n,r){let o=kT(r,t);if(!o){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 s=C(t.author,n.settings.author_default),{document:i,itemId:a}=await Ye({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,u){let p=k();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:s,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:s,text:o}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Oe(i.metadata,"deep");return{action:r,plan:c,next_actions:Pe(a,c),warnings:[],generated_at:k()}}async function HT(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:o,itemId:s}=await Ye({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Oe(o.metadata,"brief");return{action:"resume",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:k()}}async function VT(e,t,n){let r=fh(t.mode??"approved","approved"),{document:o,itemId:s}=await Ye({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(a,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Oe(o.metadata,"brief");return{action:"approve",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:k()}}function wh(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function WT(e,t){let n=Oe(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Pe(e.itemId,n),warnings:wh(t),generated_at:k()}}function YT(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let s=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${s}`)}return r}async function JT(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Ae(e.options.field)){let s=o.indexOf("=");if(s<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0)throw new l(`Invalid --field entry "${o}"; 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 "${o}"; 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 "${o}"; "${p}" is reserved by materialize and cannot be overridden`,d.USAGE);n[p]=a}for(let o of e.targets){let s={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:YT(e.parent,e.planItemId,o)};yh(e.options,s,["description",...Object.keys(n)]);let i=await Pt(s,{path:e.pmRoot});t.push({id:i.item.id,title:i.item.title,type:e.resolvedTypeName,parent:i.item.parent,tags:i.item.tags??[],from_step:o.id})}return t}function XT(e,t,n){for(let r of t){let o=n.find(a=>a.from_step===r.id);if(!o)continue;let s=e.find(a=>a.id===r.id);if(!s)continue;let i=s.linked_items??[];i.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),s.linked_items=i,s.updated_at=k()}}async function QT(e,t,n){let r=$e(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let o=t.materializeType?.trim()||"Task",s=O(n.settings,R()),i=ge(o,s);if(!i)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await gh(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=vT(u,r);if(p.length===0){if(f.length>0)return WT(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await JT({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await Ye({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(b){return XT(b,p,_),{changedSteps:p.map(v=>v.id)}}}),g=Oe(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Pe(y,g),warnings:wh(f),generated_at:k()}}function ZT(e){if(e.subcommand==="create")return e;let t=ph(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:ve(e.options,{...e.options,stepTitle:t[0]})}:e}function ut(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function rn(e,t){let n=ut(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function eC(e){let t=rn(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 tC={create:(e,t)=>LT(e.options,e.global,t),show:(e,t)=>NT(ut(e,"show"),e.options,t),"add-step":(e,t)=>MT(ut(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=rn(e,"update-step");return Rc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=rn(e,"complete-step");return Rc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=rn(e,"block-step");return Rc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=eC(e);return qT(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=rn(e,"remove-step");return KT(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=rn(e,"link");return zT(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=rn(e,"unlink");return BT(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Oc(ut(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Oc(ut(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Oc(ut(e,"validation"),e.options,t,"validation"),resume:(e,t)=>HT(ut(e,"resume"),e.options,t),approve:(e,t)=>VT(ut(e,"approve"),e.options,t),materialize:(e,t)=>QT(ut(e,"materialize"),e.options,t)};function nC(e){let t=tC[e];if(!t)throw xe({command_path:"plan",token:e,allowed:uT});return t}async function vh(e){let t=await AT(e.global),n=ZT(e);return nC(n.subcommand)(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b59e8e54-f9e0-5cdb-bc59-6dcbf67f278d")}catch{}})();function rC(e,t){return[...new Set([...jr.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,o)=>r.localeCompare(o))}function oC(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Gc(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),s=O(o,R()),i=await j(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!i)throw await it(r,e,o.id_prefix,s.type_to_folder);let a=await Z(i,{schema:o.schema}),c=a.document.metadata,m=k(),u=C(t.author,o.author_default),p=await Zn(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:s.type_to_folder,probeExisting:!1}),f=$(o.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new 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=vt(R()),g=Tt({metadata:h,body:a.document.body},{schema:o.schema,extensionFieldNames:y}),b=await On({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=rC(g.metadata,g.body),S=jt(r,g.metadata.type,p,o.item_format,s.type_to_folder),T=Ie(r,p),x=await be(r,p,o.locks.ttl_seconds,u,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),G={metadata:{},body:""},F,X;try{let K=await bn(r,u,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await On({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let pe=await j(r,p,o.id_prefix,o.item_format,s.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 he(S,st(g,{format:o.item_format,schema:o.schema,extensionFieldNames:y}));try{let N=Ge({nowIso:m,author:u,op:"create",before:G,after:g,message:oC(i.id,t.message)});await Ct(T,N)}catch(N){throw await ln(S),N}X=await wn({pmRoot:r,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:S,document:g})}finally{await K()}F=[...await W({path:S,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:G,after:g,changed_fields:v}),...await W({path:T,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:G,after:g,changed_fields:v})],pn({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Bt(g.metadata,v),changed_fields:v})}finally{await x()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:v,warnings:[...us(b),...X,...F],...b===void 0?{}:{similarity_advisory:b}}}import Xs from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7819b53c-b0e4-50b0-a670-f80b36765085")}catch{}})();async function jc(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),s=C(t.author,o.author_default),i=await np({pmRoot:r,settings:o,id:e,author:s,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?Xs.relative(r,i.targetPath).split(Xs.sep).join("/"):void 0;return{item:i.item,changed_fields:i.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:i.item.status,...a?{target_path:a}:{},history_retained:Xs.relative(r,Ie(r,i.item.id)).split(Xs.sep).join("/"),tombstone_retention:"retain_append_only",warnings:i.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5ddb139-9780-50e0-87a5-621913cb0de4")}catch{}})();async function sC(e){await I(e)}async function qc(e,t,n){let r=E(process.cwd(),n.path);if(await sC(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",d.USAGE);let p=await A(r),f=gn(C(void 0,p.author_default));return await Ru(r),await ls({pmRoot:r,settings:p,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await No(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 iC(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let s=await A(r),i=O(s,R()),a=await j(r,e,s.id_prefix,s.item_format,i.type_to_folder);if(!a)throw await it(r,e,s.id_prefix,i.type_to_folder);let c=we(a.id,s.id_prefix),m=await Z(a,{schema:s.schema}),u=kh(m.document.metadata.title);return await Iu(r,c),await ls({pmRoot:r,settings:s,principal:gn(C(void 0,s.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function iC(e,t){let n=await A(e),r=O(n,R()),o=await j(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let s=await Z(o,{schema:n.schema});return kh(s.document.metadata.title)}function kh(e){return e.trim().length>0?e:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77fa2822-1681-59d5-8388-037cf13c45dd")}catch{}})();var Sh=new Set(["item_format"]),Eh=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"]),aC=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),cC=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),dC={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function lC(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(Sh.has(t)||Eh.has(t)||aC.has(t)||t==="context")return t}function mC(e){let t=e.trim().toLowerCase();return dC[t]??e}function Ah(e,t){let n=lC(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."}:Sh.has(n)?{routable:!0,flag:"format",value:t}:Eh.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:cC.has(n)?mC(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="09703f32-9491-5d3a-9f90-f038d9982e17")}catch{}})();var uC=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Kc=128,pC=1e4;function Th(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>Kc)throw new Error(`A legacy author must contain 1-${Kc} characters.`);return t}function fC(e){let t=e?.trim().toLowerCase();if(!t||!uC.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function _C(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function hC(e,t){let n=new Set;for(let r of(e??[]).slice(0,pC)){let o=r.trim().slice(0,Kc);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function gC(e,t){let n=Th(t.legacy_author),r=fC(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function yC(e,t){if(t.operation==="add")return gC(e,t);if(t.operation==="remove"){let r=Th(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function zc(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function Ch(e,t){let n=e?.version??1,r={...e?.aliases},o=yC(r,t),s={version:o?n+1:n,aliases:_C(r)};return{vocabulary:s,preview:{operation:t.operation,changed:o,version_before:n,version_after:s.version,alias_count:Object.keys(s.aliases).length,residual_author_count:hC(t.observed_authors,s.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2f750f85-6c55-5f0f-b5c0-396764839d2a")}catch{}})();var Ih=["project","global"],pt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},bC=Object.keys(pt).map(e=>pt[e][0]),wC=Object.fromEntries(Object.keys(pt).flatMap(e=>pt[e].map(t=>[t,e]))),vC={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},kC=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],SC=new Set(["metadata_required_fields",...kC]),EC=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),AC=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),TC=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),CC=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),IC=new Set(["governance_preset","governance_create_default_type"]),Lh=e=>SC.has(e),RC=e=>TC.has(e),xC=e=>CC.has(e),OC=e=>IC.has(e);function Bc(e){return e==="definition_of_done"||Lh(e)}function PC(e){if(Ih.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${Ih.join(", ")}`,d.USAGE)}function LC(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw xe({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function NC(e){let t=wC[e];if(t)return t;let n=Yi.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${bC.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function FC(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new 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 MC(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 Nh(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 DC(e){return Vc(e,"test-result-tracking")}function Vc(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,d.USAGE)}function Fh(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 Wc(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 Mh(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 Dh(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 $h(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 Uh(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 Gh(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 jh(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 qh(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)}var $C={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function Rh(e,t){let n=$C[e];if(n)return Vc(t,n);switch(e){case"history_missing_stream_policy":return Nh(t);case"sprint_release_format_policy":return Aa(t);case"parent_reference_policy":case"governance_parent_reference_policy":return Jo(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Wc(t);case"governance_preset":return Mh(t);case"governance_ownership_enforcement":return Dh(t);case"governance_create_mode_default":return $h(t);case"governance_close_validation_default":return Uh(t);case"governance_require_close_reason":return qh(t);case"governance_workflow_enforcement":return Gh(t);case"governance_force_required_for_stale_lock":return jh(t);case"telemetry_tracking":return Fh(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var xh={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"},UC=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function GC(e,t){let n=[...new Set((e??[]).map(s=>s.trim()).filter(s=>s.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(s=>s.toLowerCase().replaceAll("-","_")),o=r.filter(s=>xh[s]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${UC.join(", ")}`,d.USAGE);return[...new Set(r.map(s=>xh[s]))].sort((s,i)=>s.localeCompare(i))}function jC(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,s)=>o.localeCompare(s));if(n){if(r.length>0)throw new l(`Config set ${pt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${pt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function qC(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function KC(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 NC(t)}function Kh(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var zC={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>zc(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function Yc(e,t){return zC[t](e)}function Te(e,t){return t.length===0?e:{...e,warnings:t}}async function BC(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):tt(n),o=de(r);return e==="project"&&await I(r),{pmRoot:r,settingsPath:o}}function HC(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 Oh(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 VC(e,t,n,r,o){let s=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!qi.includes(c))throw new l(`Context --default-depth must be one of ${qi.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,s=!0)}if(t.activityLimit!==void 0){let c=Oh(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,s=!0)}if(t.staleThresholdDays!==void 0){let c=Oh(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,s=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of a){let u=HC(m);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,s=!0)}}return s&&await Re(n.pmRoot,e,"config:set:context"),Te({scope:r,key:"context",context_settings:{default_depth:i.default_depth,activity_limit:i.activity_limit,stale_threshold_days:i.stale_threshold_days,sections:{...i.sections}},settings_path:n.settingsPath,changed:s},o)}function WC(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 YC(e,t,n,r,o,s){if(o===void 0)return s;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 WC(t,o,s);Kh(n);let i=Ah(n,o);if(!i.routable)throw new l(i.reason,d.USAGE);if(i.flag==="criterion"){if(s.criterion!==void 0&&s.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...s,criterion:i.values}}if(i.flag==="format")return{...s,format:i.value};if(s.policy!==void 0&&Rh(n,s.policy)!==Rh(n,i.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${s.policy}". Pass only one.`,d.USAGE);return{...s,policy:i.value}}function JC(e){let t=Object.keys(pt).map(r=>({key:r,aliases:pt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":Bc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:Bc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:vC[r],value:Yc(e.settings,r)})),n=Yi.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Ji(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 Te({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function XC(e){let t=Object.fromEntries(Object.keys(pt).map(n=>[n,Yc(e.settings,n)]));return Te({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function QC(e,t){let n=Yc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Te({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Te({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Te({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Te({...r,criteria:n},e.warnings):Te({...r,policy:n},e.warnings)}async function ZC(e,t,n,r){if(t==="get"){let a=Ji(e.settings,n);return Te({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new 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 s=jm(n,o);if(!s.ok)throw new l(s.error.message,d.USAGE);let i=Io(e.settings,n,s.parsed.value);return i&&await Re(e.target.pmRoot,e.settings,`config:set:${n.path}`),Te({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:s.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function Y(e,t,n){t&&await Re(e.target.pmRoot,e.settings,n)}function Ph(e,t,n){return e!==n||t!==n}function ae(e,t,n,r){return Te({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Hc(e,t,n,r){return Te({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function eI(e,t){let n=MC(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let s=O(e.settings,R()),i=await bp(e.target.pmRoot,n,"config:set:item_format:migrate",s.type_to_folder,e.settings.schema);o={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await Re(e.target.pmRoot,e.settings,"config:set:item_format")}return Te({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function tI(e,t,n){if(t==="history_missing_stream_policy"){let s=Nh(n.policy),i=e.settings.history.missing_stream!==s;return e.settings.history.missing_stream=s,await Y(e,i,"config:set:history_missing_stream_policy"),ae(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let s=Aa(n.policy),i=e.settings.validation.sprint_release_format!==s;return e.settings.validation.sprint_release_format=s,await Y(e,i,"config:set:sprint_release_format_policy"),ae(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let s=Jo(n.policy),i=e.settings.validation.parent_reference!==s||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==s;return e.settings.validation.parent_reference=s,e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,await Y(e,i,"config:set:parent_reference_policy"),ae(e,t,e.settings.validation.parent_reference,i)}let r=Wc(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Y(e,o,"config:set:metadata_validation_profile"),ae(e,t,e.settings.validation.metadata_profile,o)}async function nI(e,t,n){if(t==="metadata_required_fields"){let a=GC(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 Y(e,c,"config:set:metadata_required_fields"),Hc(e,t,[...e.settings.validation.metadata_required_fields],c)}let o={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],s=jC(t,n.criterion,n.clearCriteria),i=s.length!==o.length||s.some((a,c)=>a!==o[c]);return o.splice(0,o.length,...s),await Y(e,i,`config:set:${t}`),Hc(e,t,[...o],i)}async function rI(e,t,n){if(t==="governance_preset"){let c=Mh(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Y(e,m,"config:set:governance_preset"),ae(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Y(e,c,"config:set:governance_create_default_type"),ae(e,t,e.settings.governance.create_default_type??"",c)}if(o.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 s=O(e.settings,R()),i=ge(o,s);if(!i)throw new l(Et(o,s.types,At(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 Y(e,a,"config:set:governance_create_default_type"),ae(e,t,e.settings.governance.create_default_type,a)}async function oI(e,t,n){if(t==="governance_ownership_enforcement"){let s=Dh(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==s;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=s,await Y(e,i,"config:set:governance_ownership_enforcement"),ae(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let s=$h(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==s;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=s,await Y(e,i,"config:set:governance_create_mode_default"),ae(e,t,e.settings.governance.create_mode_default,i)}let r=Uh(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Y(e,o,"config:set:governance_close_validation_default"),ae(e,t,e.settings.governance.close_validation_default,o)}async function sI(e,t,n){if(t==="governance_parent_reference_policy"){let s=Jo(n.policy),i=e.settings.governance.preset!=="custom"||Ph(e.settings.governance.parent_reference,e.settings.validation.parent_reference,s);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,e.settings.validation.parent_reference=s,await Y(e,i,"config:set:governance_parent_reference_policy"),ae(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let s=Wc(n.policy),i=e.settings.governance.preset!=="custom"||Ph(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,s);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=s,e.settings.validation.metadata_profile=s,await Y(e,i,"config:set:governance_metadata_validation_profile"),ae(e,t,e.settings.governance.metadata_profile,i)}let r=Gh(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Y(e,o,"config:set:governance_workflow_enforcement"),ae(e,t,e.settings.governance.workflow_enforcement,o)}async function iI(e,t,n){if(t==="governance_require_close_reason"){let a=qh(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await Y(e,c,"config:set:governance_require_close_reason"),ae(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let o=jh(n.policy)==="enabled",s=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==o;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=o,await Y(e,s,"config:set:governance_force_required_for_stale_lock"),ae(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",s)}async function aI(e,t,n){if(t==="test_result_tracking"){let a=DC(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await Y(e,c,"config:set:test_result_tracking"),ae(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}if(t==="untrusted_linked_test_execution"){let a=Vc(n.policy,"untrusted-linked-test-execution")==="enabled",c=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await Y(e,c,"config:set:untrusted_linked_test_execution"),ae(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",c)}let o=Fh(n.policy)==="enabled",s=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await Y(e,s,"config:set:telemetry_tracking"),ae(e,t,e.settings.telemetry.enabled?"enabled":"disabled",s)}async function cI(e,t,n){let r=FC(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((s,i)=>s!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await Y(e,o,"config:set:definition_of_done"),Hc(e,t,[...e.settings.workflow.definition_of_done],o)}function dI(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",d.USAGE)}function lI(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',d.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",d.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",d.USAGE);return{}}async function mI(e,t){let{operation:n,dryRun:r}=dI(t.policy),o=lI(n,t.value),s;try{s=Ch(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(i){throw new l(i.message,d.USAGE)}return s.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:s.vocabulary},await Y(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${s.preview.version_after}`)),Te({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:zc(r?e.settings.agent_identity?.identity_vocabulary:s.vocabulary),vocabulary_mutation:s.preview,settings_path:e.target.settingsPath,changed:s.preview.changed&&!r},e.warnings)}async function uI(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"?eI(e,n):t==="context"?VC(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?mI(e,n):t==="definition_of_done"?cI(e,t,n):Lh(t)?nI(e,t,n):EC.has(t)?aI(e,t,n):AC.has(t)?iI(e,t,n):RC(t)?oI(e,t,n):xC(t)?sI(e,t,n):OC(t)?rI(e,t,n):tI(e,t,n)}async function zh(e,t,n,r,o,s){let i=PC(e),a=LC(t),c=a==="get"||a==="set"?Co(n):void 0,m=c?void 0:KC(a,n),u=YC(a,n,m,c,s,r),p=await BC(i,o),{settings:f,metadata:_,warnings:h}=await Yu(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:qC(h)};return c?ZC(y,a,c,u):a==="list"?JC(y):a==="export"?XC(y):(Kh(m),a==="get"?QC(y,m):uI(y,m,u))}import KI from"node:fs/promises";import J from"node:path";import zI from"node:readline/promises";import{stdin as BI,stdout as Le}from"node:process";import Xc from"node:fs/promises";import ce from"node:path";import pI from"node:readline/promises";import{stdin as fI,stdout as Qs}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="542cd5ac-e4a7-51fe-8521-d0bacd9e6a07")}catch{}})();var Hh=["ask","add","skip","status"],_I=["AGENTS.md","CLAUDE.md"],hI=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],gI=8,Qc=1,yI="<!-- pm-cli:agent-guidance:start:",bI=`<!-- pm-cli:agent-guidance:start:v${Qc} -->`,Jc="<!-- pm-cli:agent-guidance:end -->",kr="Add workflow guidance later: pm init --agent-guidance add";var wI=()=>pI.createInterface({input:fI,output:Qs});function wr(e,t){let n=ce.relative(e,t);return n.length===0?ce.basename(t):n.split(ce.sep).join("/")}function Bh(e){return e.endsWith(`
4
+ `,{changedFields:["body"]}}});return{item:m.item,appended:c,changed_fields:m.changedFields}}import{readFile as Ov}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]="6d20a21c-ac67-5712-9f63-b10ffc0e2c64")}catch{}})();function bs(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,ke(e,t)}function n_(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 nc(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Wt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Ln(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let s=ae(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function rc(e){return typeof e=="object"&&e!==null&&"code"in e}function hr(e,t){if(!ct(e))throw new l(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,d.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function Pv(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=xt(),o=ct(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",o)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return hr(e,"--stdin"),{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);if(s==="-")return hr(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await Ov(s,"utf8"),emptyFlag:"--file"}}catch(i){if(rc(i)&&Gt(i))throw new l(`--file path not found: ${s}. Use --file - to read stdin.`,d.USAGE);let a=i instanceof Error?i.message:String(i);throw new l(`Failed to read --file path "${s}": ${a}. Use --file - to read stdin.`,d.USAGE)}}async function ws(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 Pv(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 _r(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 o_(e){return e==="comments"?"--stdin":"--add -"}function Lv(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let o=o_(t.collectionKey),s=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 ${o} to read stdin, or use text=${r} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${s} ${o}`,`${s} --add text=${r}`]})}function Nv(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new l(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,d.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});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> ${o_(e.collectionKey)}`]})}function Fv(e,t,n,r,o,s){let i=Wt(e.metadata,t),a=o?i.findIndex(c=>c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],entryIndex:a+1}:(i.push(s({created_at:k(),author:n,text:r})),e.metadata[t]=i,{changedFields:[t],entryIndex:i.length})}async function Nn(e,t,n,r){Nv(r,t);let o=E(process.cwd(),n.path);await R(o);let s=await A(o),i=O(s,I()),a=rr(t.limit);if(r.input.mode==="list"){let g=await G(o,e,s.id_prefix,s.item_format,i.type_to_folder);if(!g)throw new l(`Item ${e} not found`,d.NOT_FOUND);let y=await Q(g,{schema:s.schema}),h=Wt(y.document.metadata,r.collectionKey);return ys(g.id,r.collectionKey,h,a,t.includeMeta===!0)}let c=C(t.author,s.author_default);if(r.input.mode==="delete"){let g=r.deleteOp??r.op,y;try{y=await oe({pmRoot:o,settings:s,id:e,op:g,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(b){let v=Wt(b.metadata,r.collectionKey),S=r_(r.input.index,v.length,r.collectionKey);return n_(v[S],"deleted"),v.splice(S,1),b.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(b){_r(b,r.conflictGuidance)}let h=Wt(y.item,r.collectionKey);return ys(y.item.id,r.collectionKey,h,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";Lv(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 g=r.editOp??r.op,y;try{y=await oe({pmRoot:o,settings:s,id:e,op:g,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(b){let v=Wt(b.metadata,r.collectionKey),S=r_(r.input.index,v.length,r.collectionKey),T=v[S];return n_(T,"edited"),v[S]={...T,text:u,edited_at:k()},b.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(b){_r(b,r.conflictGuidance)}let h=Wt(y.item,r.collectionKey);return ys(y.item.id,r.collectionKey,h,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:h[r.input.index-1]},t.fullHistory===!0)}let p,f=0;try{p=await oe({pmRoot:o,settings:s,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(g){let y=Fv(g,r.collectionKey,c,u,t.ifAbsent===!0,r.createEntry);return f=y.entryIndex,{changedFields:y.changedFields}}})}catch(g){_r(g,r.conflictGuidance)}let _=Wt(p.item,r.collectionKey);return ys(p.item.id,r.collectionKey,_,a,t.includeMeta===!0,{action:"add",entryIndex:f,entry:_[f-1],changedCount:t.ifAbsent===!0?Math.min(p.changedFields.length,1):void 0},t.fullHistory===!0)}function r_(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,s=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${o} index ${e??"(missing)"} out of range (item has ${s})`,d.USAGE)}return e-1}function Mv(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function ys(e,t,n,r,o,s,i=!1){let a=s===void 0||i?nc(n,s!==void 0&&i?void 0:r):s.entry===void 0?[]:[s.entry],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...s?.changedCount===void 0?{}:{changed:s.changedCount===1},...[o,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...Mv(t,s,c)}}(function(){try{var e=typeof window<"u"?window:typeof 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 s_(e,t,n){return[...await bn(xe(e,t),t).catch(()=>[])].reverse().find(s=>s.patch.some(i=>i.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a4d95016-05b9-5272-8044-2649da644e98")}catch{}})();var i_="no_available_next_item";function a_(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 vs(e,t,n,r={}){let o=E(process.cwd(),n.path);await R(o);let s=await A(o),i=D(s.schema),a=C(r.author,s.author_default),c=yn(a),m=null,u=!1,p=[],f=await oe({pmRoot:o,settings:s,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",h=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,Um(_.metadata.status,i)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&h!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let v=await s_(o,_.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:o,settings:s,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 c_(e,t,n={},r={}){let o=Dv(n.maxAttempts),s=await A(E(process.cwd(),t.path)),i={...n,author:C(n.author,s.author_default)},a=await ur({...r,callerAuthor:i.author,limit:String(o)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return $v(c.slice(0,o),e,t,i)}function Dv(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 $v(e,t,n,r={},o=vs){let s=0;for(let a of e){s+=1;try{let c=await o(a.id,t,n,r),m={...c,recommendation:a,attempts:s,available:!0};if(!c.skipped)return m}catch(c){if(!a_(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:C(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[i_]};let i=s===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:i_,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 ks(e,t,n,r={}){let o=E(process.cwd(),n.path);await R(o);let s=await A(o),i=C(r.author,s.author_default),a=yn(i),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await oe({pmRoot:o,settings:s,id:e,op:"release",author:i,message:r.message,force:t,bypassAssigneeConflict:c,mutate(_){return m=_.metadata.assignee??null,!m&&!_.metadata.claim_principal?{changedFields:[]}:(delete _.metadata.assignee,delete _.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(_){_r(_,{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."]})}await Ha({pmRoot:o,principal:a,itemId:u.item.id});let p=D(s.schema),f=_a(u.item.status,p)===_a(p.in_progress_status,p);return{item:u.item,released_by:i,previous_assignee:m,forced:t,...f?{warnings:["released_unclaimed_in_progress"],suggestions:[`${u.item.id} remains ${u.item.status} and unclaimed. If work is paused, run pm pause-task ${u.item.id} to move it to ${p.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]="89e3f65e-8455-5921-bcc1-45cf572d8585")}catch{}})();var Uv=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function d_(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 oc(e,t){return sc(e,t,{operation:"close"})}function sc(e,t,n){let r=d_(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new 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:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function ic(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],s=o.filter(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"&&s.length>0){let m=o.filter(u=>u.kind!=="blocked_by");m.length>0?e.dependencies=m:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...s.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]="0e166cbb-ef9c-5016-89a6-07f287e00a2e")}catch{}})();var Gv=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function jv(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 l_(e){let t=[];for(let n of Gv){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function m_(e,t,n={}){let r=l_(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},s=r.map(a=>`--${a.key.replaceAll("_","-")}`),i=["--pm-path",t,"update",e.id,...r.flatMap((a,c)=>[s[c],o[a.key]?.trim()||"<value>"])];return{missing:s,suggested_retry:Zn(i),suggested_retry_args:i}}async function qv(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let s=o.trim();if(s===n)return!0;if(r.has(s))return!1;r.add(s),o=(await e(s))?.duplicate_of}return!1}function Kv(e){return typeof e!="string"||e.trim().length===0}async function zv(e,t,n,r){let o=n?.trim();if(!o)return;if(o===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 s=O(t,I()),i=new Map,a=async m=>{if(i.has(m))return i.get(m)??null;let u=await G(e,m,t.id_prefix,t.item_format,s.type_to_folder);if(!u)return i.set(m,null),null;let{document:p}=await Q(u,{schema:t.schema});return i.set(m,p.metadata),p.metadata},c=await a(o);if(!c)throw new l(`Duplicate target "${o}" 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 ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await qv(a,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${o}" 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 "${o}" 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 Bv(e,t,n){return e.filter(r=>r.parent===t&&!te(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function Hv(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),o=Uf(e),s=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:o.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let m=r.get(c);return m!==void 0&&te(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function Vv(e,t,n,r,o,s){let i=Hv(n,r,s),a=[];for(let c of i)try{let m=await oe({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(g=>{let y=g.id.trim().toLowerCase();return g.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=s.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${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 Wv(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:s}of r){if(typeof o!="string")continue;let i=o.trim();i.length!==0&&(e[s]=i,n.push(s))}return n}function Yv(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:s}of r)Kv(e[o])&&(e[o]=s,n.push(o));return n}function Jv(e,t,n,r){let o=[];if(t!=="off"){let s=l_(e);if(s.length>0){let i=s.map(a=>a.label);if(t==="strict"){let a=s.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:Zn(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}o.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new 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);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function Xv(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function Qv(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function Zv(e,t){if(te(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,d.CONFLICT,{recovery:m_(e,t.pmRoot,t.options)});let n=Wv(e,t.options),r=Yv(e,t.duplicateOf),o=Jv(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let i=["status","closed_at",...s?["completed_at"]:[],...Xv(e,t.closeReason),...n];if(Sp(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(...Qv(e));let a=ic(e,t.lifecyclePolicy);return i.push(...a.changedFields),o.push(...a.warnings),{changedFields:i,...o.length>0?{warnings:o}:{}}}async function u_(e,t,n,r){let o=E(process.cwd(),r.path);await R(o);let s=await A(o),i=D(s.schema),a=C(n.author,s.author_default),c=O(s,I()).type_to_folder,m=await G(o,e,s.id_prefix,s.item_format,c);if(!m)throw await at(o,e,s.id_prefix,c);let u=await zv(o,s,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=oc({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=jv(n.validateClose)??s.governance.close_validation_default,g=await ue(o,s.item_format,c,void 0,s.schema),y=Bv(g,m.id,i),h=k(),b=n.completedAt===void 0?h:re(n.completedAt,new Date(h),"completed-at"),v=await oe({pmRoot:o,settings:s,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(T){return Zv(T.metadata,{pmRoot:o,statusRegistry:i,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:h,completedAt:b,lifecyclePolicy:p})}}),S=_==="warn"?m_(v.item,o):void 0;return{item:v.item,changed_fields:v.changedFields,...S?{recovery:S}:{},warnings:[...v.warnings,...await Vv(o,s,g,m.id,a,i)]}}function lt(e,t,n,r){return u_(e,t,n,r)}import ek from"fast-json-patch";import ac 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]="7a3effef-6ba8-51ba-ae99-436d4ef69813")}catch{}})();async function p_(e,t,n){let r=await np(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:f_(n),recovered:!0}}function tk(e,t){return ip(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function f_(e){let t=Ea(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Tt(Ht(t))}async function nk(e,t,n,r){let o=await G(e,t,n.id_prefix,n.item_format,r);if(o){let c=xe(e,o.id),m=await Zu({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"});return{id:o.id,historyPath:c,located:o,historyPolicyWarnings:m.warnings}}let s=ve(t,n.id_prefix),i=wa(t),a=s===i?[s]:[s,i];for(let c of a){let m=xe(e,c);if(await P(m))return{id:c,historyPath:m,located:null,historyPolicyWarnings:[]}}throw new l(`Item ${t} not found`,d.NOT_FOUND)}function rk(e,t){let n=tr(e),r=tr(t),o=ek.compare(n,r),s=new Set;for(let i of o){if(i.path==="/body"||i.path.startsWith("/body/")){s.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];s.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(s).sort((i,a)=>i.localeCompare(a))}async function ok(e){if(await K(e.subject.historyPath)!==e.historyRawBeforeLock)throw new l(`History for ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);let n=await G(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),r=n?await p_(n,e.settings,e.history):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 sk(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:f_(t),originalRaw:null}}function ik(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 ak(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await ge(e.existingItemPath,e.resolvedOriginalRaw),await ac.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await ge(e.existingItemPath,e.resolvedOriginalRaw);return}await ac.rm(e.restoredItemPath,{force:!0})}async function ck(e){return[...await W({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 W({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function Yt(e,t,n,r){let o=E(process.cwd(),r.path);await R(o);let s=await A(o),i=O(s,I()),a=await nk(o,e,s,i.type_to_folder),c=a.id,m=await K(a.historyPath),u=await bn(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let p=tk(t,u),f=ap(Ea(u,p.historyIndex),p),_=Vu(f,{schema:s.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 p_(a.located,s,u):null)?.raw??null,h=C(n.author,s.author_default),b=await we(o,c,s.locks.ttl_seconds,h,!!n.force,s.governance.force_required_for_stale_lock,s.locks.wait_ms);try{let{loadedItemUnderLock:v,existingItemPath:S}=await ok({pmRoot:o,resolvedId:c,subject:a,settings:s,typeToFolder:i.type_to_folder,historyRawBeforeLock:m,currentItemRawBeforeLock:y,history:u}),T="toon",x=sk(v,u),U=ik({document:x.document,author:h,force:n.force,enforcement:s.governance.ownership_enforcement,resolvedId:c}),N=rk(x.document,_);await Po({pm_root:o,operation:"restore",before:x.document,after:_,changed_fields:N,sdk:Uo({pmRoot:o,settings:s,typeToFolder:i.type_to_folder})});let ee=it(_,{format:T,schema:s.schema}),z=jt(o,_.metadata.type,c,T,i.type_to_folder),le=await wn(o,h),ne=[];try{await ge(z,ee),S&&z!==S&&await ac.rm(S);let gt=qe({nowIso:k(),author:h,op:"restore",before:x.document,after:_,message:n.message});try{await Ct(a.historyPath,gt)}catch(Ve){throw await ak({existingItemPath:S,resolvedOriginalRaw:x.originalRaw,restoredItemPath:z}),Ve}ne=await vn({pmRoot:o,preferredFormat:s.item_format,typeToFolder:i.type_to_folder,schema:s.schema,itemPath:z,previousItemPath:S??void 0,document:_})}finally{await le()}let Re=await ck({restoredItemPath:z,historyPath:a.historyPath,before:x.document,after:_});fn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:x.document.metadata.status,status:_.metadata.status,previous:Bt(x.document.metadata,N),current:Bt(_.metadata,N),changed_fields:N});let q=u[p.historyIndex],ie=kn(u,!0);return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,version:ie===null?null:ie+p.historyIndex+1,entry_ts:q.ts,entry_op:q.op},changed_fields:N,warnings:[...v?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...U,...ne,...Re]}}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]="a97a3cf0-beef-5967-8f5b-2372a6c9f2f7")}catch{}})();var h_=1,cc="close-many",dk=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function lk(e,t){return mr(e,t,{includePagination:!1})}function mk(e,t){return mr(e,t)}function uk(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 pk(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function fk(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 _k(e,t){let n=D(t.schema),r=O(t,I()),o=await ue(e,t.item_format,r.type_to_folder,void 0,t.schema),s=new Map,i=new Map;for(let a of o){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),te(a.status,n)))continue;let c=s.get(a.parent);c?c.push(a.id):s.set(a.parent,[a.id])}for(let a of s.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:s,parentByChild:i}}function __(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,s=t.get(e),i=[],a=new Set,c=!1;for(;s!==void 0&&!a.has(s);){let m=n?.get(s);if(m!==void 0){o+=m+1;break}a.add(s),i.push(s),o+=1,s=t.get(s)}if(s!==void 0&&a.has(s)&&(c=!0),!c){n?.set(e,o);for(let[m,u]of i.entries())n?.set(u,o-m-1)}return o}async function hk(e){let t=await qo(e.pmRoot,cc,e.rollbackId,h_),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Ko(t.items,(o,s)=>Yt(o,s,{author:e.options.author,message:n,force:!0},e.global));return{...zt({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 gk(e,t,n,r,o){return e.map(s=>{let i=(t.get(s.id)??[]).filter(c=>!n.has(c)),a=!g_(s,r,o);return{id:s.id,title:typeof s.title=="string"?s.title:"",status:s.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function yk(e){let t=await jo(e.pmRoot,cc,e.checkpointId,{schema_version:h_,id:e.checkpointId,created_at:e.nowValue,author:C(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 bk(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await lt(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){t.push({id:r.id,status:"failed",error:pn(o)})}}return{rows:t,closedIds:n}}function wk(e){return typeof e.rollback=="string"?e.rollback:void 0}function vk(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(mk(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function kk(e){if(!lk(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${dk}). Refusing to match every item.`,d.USAGE)}function Sk(e,t){let n=new Map;return[...e].sort((r,o)=>{let s=__(o.id,t,n)-__(r.id,t,n);return s!==0?s:r.id.localeCompare(o.id)})}function g_(e,t,n){return n||!te(e.status,t)}function Ek(e,t,n){return new Set(e.filter(r=>g_(r,t,n)).map(r=>r.id))}async function Ak(e){kk(e.options);let t=D(e.settings.schema),n=fk(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await dt(e.options.status,pk(e.options.list),e.global),{childrenByParent:s,parentByChild:i}=await _k(e.pmRoot,e.settings),a=Sk(o.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],m=c.length===0?[]:(await dt(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,u=new Set(m.map(f=>f.id)),p=Ek(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!u.has(f)),planRows:gk(a,s,p,t,r)}}function Tk(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!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function Ck(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 yk({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 y_(e,t){let n=E(process.cwd(),t.path);await R(n);let r=await A(n),o=e.dryRun===!0,s=wk(e);if(uk(e.list),s!==void 0)return vk(e,s),hk({pmRoot:n,rollbackId:s,options:e,global:t});let i=await Ak({pmRoot:n,settings:r,options:e,global:t});if(o)return Tk(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=k(),m=Go(cc,c),u=await Ck({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 bk({matched:i.matched,closableIds:a,reason:i.reason,closeOptions:p,global:t}),g=f.filter(b=>b.status==="closed").length,y=f.filter(b=>b.status==="skipped").length,h=f.filter(b=>b.status==="failed").length;return{...zt({applied:g,skipped:y,failed:h,unmatched:i.unmatchedIds?.length??0}),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:g,skipped_count:y,failed_count:h,rows:f,ids:_,...i.unmatchedIds!==void 0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}import{readFile as Rk}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]="f761d37b-28df-5176-9e25-762f57aa0abf")}catch{}})();async function dc(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",s=Number(n)+Number(r)+Number(o);if(s===0)return;if(s>1)throw new 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",ct(e))??"",emptyFlag:"--add"};if(r)return hr(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);if(i==="-")return hr(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await Rk(i,"utf8"),emptyFlag:"--file"}}catch(a){if(rc(a)&&Gt(a))throw new l(`--file path not found: ${i}. Use --file - to read stdin.`,d.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${i}": ${c}. Use --file - to read stdin.`,d.USAGE)}}async function Ik(e,t){let n=e.edit,r=e.delete,o=n!==void 0,s=r!==void 0;if(o&&s)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(s){if(await dc(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(o){let c=await dc(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 dc(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 b_(e,t,n){let r=xt(),o=await Ik(t,r),s=o.mode==="add"||o.mode==="edit",i=o.value??"";return Nn(e,t,n,{input:{...o,rawValue:t.add??i,value:s?Ln(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm comments pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="972816c9-b407-5b89-a744-249c9771451f")}catch{}})();async function w_(e,t,n){return Nn(e,t,n,{input:await ws(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Ln(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]="216389a2-fb85-56a0-8ef2-9f41f1321c16")}catch{}})();function xk(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 Ok(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 Pk(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 v_(e,t,n){let r=xk(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let s=r===void 0?void 0:qt(r),i=[t.since,t.eventType].some(g=>g!==void 0),a=Pk(t.since),c=rr(t.limit),m=await Nn(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await ws(s===void 0?t:{add:s},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:g=>Ln(g),createEntry:g=>r===void 0?g:{...g,format:"json",data:r,event_type:Ok(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(g=>{let y=[g.format==="json",g.data!==void 0].every(Boolean),h=[a===void 0,Date.parse(g.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),b=[!u,g.event_type===u].includes(!0);return[!i,[y,h,b].every(Boolean)].includes(!0)}),f=i?nc(p,c):p,_=f.filter(g=>g.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]="d6f359cb-2bc9-5f96-8789-db91512d0bd5")}catch{}})();function gr(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function yr(e,t,n=Ot()){for(let r of t??[])try{fl(e,r.id,r.kind,n)}catch(o){throw new l(pn(o),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function k_(e,t){return(await Q(e,{schema:t})).document.metadata.created_at}async function Lk(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await G(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:k_(n,t.schema)}function Nk(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 Fk(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:s})=>s===null?[]:[[o,s]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await k_(n.get(o),e.context.schema)])));for(let o of e.holders){let s=await Lk(o,e.context);if(s!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(s),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw Nk({holder:o,dependency:i,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function Jt(e){let t=e.registry??Ot(),n=(e.dependencies??[]).filter(i=>!ru(i.source_kind)),r=[...new Set(n.map(i=>i.id))],o=await Promise.all(r.map(async i=>({target:i,located:await G(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=o.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${s.length===1?"":"s"} not found: ${s.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:s,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${s.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await Fk({dependencies:n,missingTargets:s,resolutions:o,holders:e.holders??[],registry:t,context:e}),s.map(i=>`dependency_target_unresolved:${i}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcbb6070-7457-5454-abf1-fa8153c8efd6")}catch{}})();function Ss(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Es(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function As(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(jr.includes(t))return t;let n=pe(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 Ts(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 Mk=new Set(["none","null"]);function Cs(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function ze(e){return e===void 0?!1:Mk.has(e.trim().toLowerCase())}function Rs(e,t,n){if(!ze(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Ee(e,t,n){if(!e||e.length===0||!e.some(s=>ze(s)))return;let o=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${o}`.trim(),d.USAGE)}function Is(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 o=r;if(!o.some(a=>ze(a)))continue;if(o.filter(a=>!ze(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2fcfbe50-039b-5031-8b18-a208908a0d87")}catch{}})();function E_(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,d.USAGE)}function lc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Ae(e,t,n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE);return e}var A_=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Dk(e,t){return t==="defined"?e!==void 0:!!e}function S_(e,t,n){if(!Dk(e,n))return;let r=pe(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function $k(e,t,n){let r=e?re(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 Uk(e){return Array.from(new Set(lc(e).map(t=>Ae(t.toLowerCase(),al,"event weekday")))).sort((t,n)=>Ui(t)-Ui(n))}function Gk(e){return Array.from(new Set(lc(e).map(t=>{let n=pe(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 jk(e,t){return Array.from(new Set(lc(e).map(n=>re(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function T_(e,t,n,r){let o=e.recur_freq?.trim(),s=e.recur_interval?.trim(),i=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![o,s,i,a,c,m,u].some(S=>S!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let f=Ae(o.toLowerCase(),il,"event recurrence frequency"),_=S_(s,"recur_interval",r),g=S_(i,"recur_count",r),y=$k(a,t,n),h=Uk(c),b=Gk(m),v=jk(u,n);return{freq:f,interval:_,count:g,until:y,by_weekday:h.length>0?h: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 C_="--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.",qk="--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).",Kk=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,zk=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,I_=1e3,mc=60*I_,Bk=60*mc;function R_(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 Hk(e,t){let n=new Date(e),r=t.trim(),o=Kk.exec(r);if(o){let a=o[1]==="-"?-1:1,c=Number.parseInt(o[2],10)*a;return R_(n.getTime()+c*mc,r)}let s=zk.exec(r);if(s){let[,a,c,m,u]=s;if(c||m||u){let f=a==="-"?-1:1,_=Number.parseInt(c??"0",10),g=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),h=_*Bk+g*mc+y*I_;return R_(n.getTime()+f*h,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return re(i,n,"event.duration")}function x_(e,t,n,r){if(t&&n)throw new l(qk,d.USAGE);if(n){let s=Hk(e,n);if(s<e)throw new l(C_,d.USAGE);return s===e?void 0:s}if(!t)return;let o=re(t,r,"event.end");if(o<e)throw new l(C_,d.USAGE);if(o!==e)return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var Vk=["at","date","text","title"],Wk=["start","date","end","duration","title","description","location","timezone","all_day",...A_],Yk=["key","value"];function O_(e,t){return t==="trimmed"?e?.trim():e}function Jk(e,t){return t==="defined"?e!==void 0:!!e}function xs(e,t,n){return e.map(r=>{let o=ae(r,"--reminder");Ke(o,"--reminder",Vk);let s=O_(o.at??o.date,n.valueMode),i=O_(o.text??o.title,n.valueMode);if(!s||!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:re(s,t,"reminder.at"),text:a}})}function Os(e,t,n){return e.map(r=>{let o=ae(r,"--event");Ke(o,"--event",Wk);let s=(o.start??o.date)?.trim();if(!s)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let i=re(s,t,"event.start"),a=o.end?.trim(),c=o.duration?.trim(),m=x_(i,a,c,t),u=o.title,p=o.description,f=o.location,_=o.timezone,g=u?.trim(),y=p?.trim(),h=f?.trim(),b=_?.trim(),v=[["title",u,g],["description",p,y],["location",f,h],["timezone",_,b]];for(let[U,N,ee]of v)if(N!==void 0&&!ee)throw new l(`--event ${U} must not be empty`,d.USAGE);let S=o.all_day?.trim(),T=T_(o,i,t,n.recurrenceEmptyNumericGuard),x=Jk(S,n.allDayEmptyGuard)?E_(S,"--event all_day"):void 0;return{start_at:i,end_at:m,title:g,description:y,location:h,all_day:x,timezone:b,recurrence:T}})}function Ps(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 o,s;if(r.includes(",")||r.includes(`
5
+ `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=ae(r,"--type-option");Ke(a,"--type-option",Yk),o=a.key?.trim(),s=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);o=r.slice(0,m).trim(),s=r.slice(m+1).trim()}if(!o||!s)throw new l("--type-option requires key and value",d.USAGE);t[o]=s}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39a36d42-29b1-5f0f-a8b2-f3bfc0ef78c2")}catch{}})();var Xk="hierarchy-integrity";async function Ls(e){let t=e.required?await we(e.pmRoot,Xk,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var Qk=new Set(["event","meeting","reminder","milestone","decision","adr"]);function P_(e,t,n,r){if(Qk.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=Co("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm start-task ${e}`,to_status:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b29e4416-82ab-585c-9456-718e4699566d")}catch{}})();var mt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],Zk=new Set(mt);function L_(e){return zo(e,mt)}function Ns(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!Zk.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw new l(`${t} provides key "${o}" more than once after case normalization`,d.USAGE);n[i]=s}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${mt.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:o,...s}=n;return{...s,command:s.command??o}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64adcc3c-3646-5990-9442-4c4374a2dc7d")}catch{}})();var Zt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",ar,zp,"FORCE_COLOR"]),Ds=/^[A-Za-z_][A-Za-z0-9_]*$/,Qt=["schema","tracker","auto"],N_=["source","isolated","snapshot"];function br(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=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=o.slice(0,s).trim(),a=o.slice(s+1);if(!Ds.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(Zt.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 wr(e,t){if(!e)return;let n=Cn(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(!Ds.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(Zt.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function $s(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 Us(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Qt.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${Qt.join(", ")}`,d.USAGE)}function en(e,t){if(!e)return;let n=e.trim().toLowerCase();if(N_.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${N_.join(", ")}`,d.USAGE)}function tn(e){if(!e)return;let t=Cn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Fn(e,t,n){let r=tn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(s){throw new l(`${t} ${n} includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`,d.USAGE)}return r}}function Gs(e,t){if(!e)return;let n=pe(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 js(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+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 qs(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+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 eS=new Set(mt);function Ks(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tS(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!eS.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw t(`provides key "${o}" more than once after case normalization`);n[i]=s}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${mt.join(", ")}.`);return n}function Xt(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 Fs(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=o.filter(i=>i.length>0);return s.length>0?s:void 0}function F_(e,t,n){let r=Fs(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`)}return r}}function Ms(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 nS(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:Ms(n,"timeout_seconds",t),s=r===void 0?void 0:Ms(r,"timeout",t);if(o!==void 0&&s!==void 0&&o!==s)throw t("timeout and timeout_seconds must match when both are provided");let i=o??s;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function rS(e,t){let n=Xt(e,"scope",t);if(n===void 0)return"project";if(!tt.includes(n))throw t(`field "scope" must be one of: ${tt.join(", ")}`);return n}function oS(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Ks(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Ds.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(Zt.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=s}return Object.keys(r).length>0?r:void 0}function sS(e,t){let n=Fs(e,"env_clear",t);if(n){for(let r of n){if(!Ds.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(Zt.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function iS(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 aS(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=Ms(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 cS(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Ks(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(s)}return Object.keys(r).length>0?r:void 0}function dS(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Ks(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=Ms(s,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function lS(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!Ks(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${mt.join(", ")}.`);let o=tS(e,r),s=Xt(o,"command",r),i=Xt(o,"cmd",r);if(s!==void 0&&i!==void 0&&s!==i)throw r("command and cmd must match when both are provided");let a=s??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=Xt(o,"path",r),m=Xt(o,"pm_context_mode",r);if(m!==void 0&&!Qt.includes(m))throw r(`field "pm_context_mode" must be one of: ${Qt.join(", ")}`);let u=en(Xt(o,"workspace_context_mode",r),`${n} ${t}`),p=Xt(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:rS(o,r),timeout_seconds:nS(o,r),pm_context_mode:m,workspace_context_mode:u,env_set:oS(o,r),env_clear:sS(o,r),shared_host_safe:iS(o,"shared_host_safe",r),assert_stdout_contains:Fs(o,"assert_stdout_contains",r),assert_stdout_regex:F_(o,"assert_stdout_regex",r),assert_stderr_contains:Fs(o,"assert_stderr_contains",r),assert_stderr_regex:F_(o,"assert_stderr_regex",r),assert_stdout_min_lines:aS(o,r),assert_json_field_equals:cS(o,r),assert_json_field_gte:dS(o,r),note:p!==void 0&&p.trim().length>0?p.trim():void 0}}function M_(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,d.USAGE);let r;try{r=JSON.parse(n)}catch(s){throw new l(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return o.map((s,i)=>lS(s,o.length>1?`entry ${i+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0062e981-158a-5e6a-b028-6c7cef0f59ba")}catch{}})();var uc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],pc=[{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"}],D_=[...uc,...pc],zs=[{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 Bs(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let o=r.trim().toLowerCase();if(!o)throw new l("--unset values must not be empty",d.USAGE);if(ze(o))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let s=e.resolveDefinition(o);if(!s)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function Hs(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let s of o){if(s.allow_unset===!1)continue;let i=new Set;if(typeof s.key=="string"&&s.key.length>0&&i.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&i.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(i.add(s.cli_flag.replaceAll("-","_").toLowerCase()),i.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let a of s.cli_aliases)typeof a!="string"||a.length===0||(i.add(a.replaceAll("-","_").toLowerCase()),i.add(a.toLowerCase()));if(i.has(r))return{optionKey:s.key,metadataKey:s.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="002f45a2-edc3-5aa0-9af8-d9b1dfecc097")}catch{}})();var mS={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 uS(e){return mS[e]}function fc(e){return uS(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]="44240cea-9996-5f86-acc5-ac0cfa71c586")}catch{}})();var pS=["strict","progressive"],fS=["lightweight"],j_=new Set(["Reminder","Meeting","Event"]),_S=new Set(["author","created_at","text"]),hc=[...D_,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...zs],hS=(()=>{let e=new Map;for(let t of hc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Vs=new Map(hc.map(e=>[e.optionKey,e.canonical])),gS=hc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function yS(e,t){let n=X(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function bS(e,t){let n=e.default_status;if(n!==void 0){let r=X(n,t);if(r)return r}return t.open_status}function _c(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 wS=Cs();function q_(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s};ze(t.template)&&(t.template=void 0);let r=new Set([...Vs.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!ze(s))continue;let i=o==="rank"?"order":Vs.get(o)??o;n(i),t[o]=void 0}return ke(e,Is(t,wS))}function _e(e){if(e!==void 0)return e}function vS(e,t){return Bs({raw:e,supportedFields:gS,resolveDefinition:n=>hS.get(n)??Hs(n,"create",t)})}var $_=["id","kind","type","author","created_at","source_kind"],Ws=["path","scope","note"];function kS(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ee(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let i=s.trim(),a=Ys(i,$_);gr(i,a);let c=a?ae(s,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",$_);let m=_e(c.id),u=SS(_e(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=or(_e(c.source_kind)),f=_e(c.author);return{id:sr(m,n,p),kind:Ae(u,Ut,"dependency kind"),created_at:_c(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function SS(e){return typeof e=="string"?Vr(e)??e.trim():e}function Ys(e,t){return zo(e,t)?!0:Vo(e)}function rn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Ee(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=ae(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!_S.has(f)).length>0)return{created_at:_c(m.created_at,n),author:_e(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:_c(m.created_at,n),author:_e(m.author)??r,text:p}}),explicitEmpty:!1})}function gc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ee(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),o=Ys(r,Ws);Aa(r,"--file","file path",o);let s=o?ae(n,"--file"):{path:r};if(o&&Ke(s,"--file",Ws),!s.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:s.path,scope:Ae(s.scope??"project",tt,"file scope"),note:_e(s.note)}}),explicitEmpty:!1})}function yc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ee(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),o=Ys(r,mt);Aa(r,"--test","test command",o);let s=o?Ns(ae(n,"--test"),"--test"):{command:r},i=_e(s.command),a=_e(s.path);if(!i)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let c=_e(s.timeout_seconds),m=_e(s.timeout);if(c&&m&&c!==m)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let u=c??m;return{command:i,path:a,scope:Ae(s.scope??"project",tt,"test scope"),timeout_seconds:u?pe(u,"timeout_seconds"):void 0,pm_context_mode:Us(s.pm_context_mode,"--test"),workspace_context_mode:en(s.workspace_context_mode,"--test"),env_set:br(s.env_set,"--test"),env_clear:wr(s.env_clear,"--test"),shared_host_safe:$s(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:tn(s.assert_stdout_contains),assert_stdout_regex:Fn(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:tn(s.assert_stderr_contains),assert_stderr_regex:Fn(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Gs(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:js(s.assert_json_field_equals,"--test"),assert_json_field_gte:qs(s.assert_json_field_gte,"--test"),note:_e(s.note)}}),explicitEmpty:!1})}function bc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ee(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),o=Ys(r,Ws),s=o?ae(n,"--doc"):{path:r};if(o&&Ke(s,"--doc",Ws),!s.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:s.path,scope:Ae(s.scope??"project",tt,"doc scope"),note:_e(s.note)}}),explicitEmpty:!1})}function ES(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ee(e,"--reminder","Use --clear-reminders to clear reminders."),{values:xs(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function AS(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ee(e,"--event","Use --clear-events to clear linked events."),{values:Os(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function TS(e,t,n,r=[]){let o=[...qr.filter(s=>e[s]!==void 0),...r.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(o))}function CS(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function U_(e,t,n){let r=Bn("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function RS(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 K_(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 IS(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(U_(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(U_(r,e.name,"required_create_repeatables"));return n}function xS(e,t,n,r){for(let o of e)if(!(!K_(t,o)&&!n.has(o)))throw new l(`Option ${be("create",o)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function OS(e,t,n){if(t!=="strict")return;let r=e.filter(s=>n.has(s)&&!fc(s));if(r.length===0)return;let o=[...new Set(r.map(s=>be("create",s)))].sort((s,i)=>s.localeCompare(i));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function PS(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ee(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Ps(e),explicitEmpty:!1})}async function LS(e){return await Wo(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function NS(e){return ct(e)?await LS(e):e}function FS(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: ${pS.join(", ")}`,d.USAGE)}function MS(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: ${fS.join(", ")}`,d.USAGE)}function DS(e,t,n){let r=FS(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 $S(e,t,n,r){let o=e.name,s=RS(t),i=IS(e,n),a=un(e,"create",i);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);xS(a.disabled,s,r,o),OS(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&fc(u)?!0:K_(s,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>be("create",u)))].sort((u,p)=>u.localeCompare(p))}var z_=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function US(e,t){let n=[];for(let r of e){let o=r.match(z_);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function GS(e,t){return e.filter(n=>{let r=n.match(z_);return!r||r[2]!==t})}function jS(e,t,n,r){let o=GS(e,t);if(o.length===0)return;let s=B_(n,[],[],r.open_status);throw new l(o.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function qS(e,t){let r=e.options.find(o=>o.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function KS(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function B_(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],i=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of i)a.has(c)||(o.push(...KS(c,e.name,r)),a.add(c));for(let c of n){let m=qS(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function wc(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 zS(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=Array.isArray(o)?[...o]:o;for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=Array.isArray(o)?[...o]:o);return n}function BS(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function HS(){let e=I();return e?e.commands.some(t=>t.action==="templates-show"||BS(t.command)==="templates show"):!1}function VS(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[o,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[o]=s;continue}if(Array.isArray(s)&&s.every(i=>typeof i=="string")){r[o]=[...s];continue}throw new l(`Templates package returned unsupported option value for "${o}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function WS(e,t,n){if(!HS())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await Lo({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let o=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${o}`,d.USAGE)}return VS(r.result,e)}function B(e,t,n){return e.has(t)||n===void 0?void 0:_e(n)}function nn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var YS=new Set(["milestone","meeting","reminder","event"]);function H_(e,t,n,r){let o=t!==void 0,s=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return YS.has(e.toLowerCase())&&!o&&!s&&!i}function JS(e,t,n,r,o){let s=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),H_(e,n,r,o)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function XS(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await Fo(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function QS(e,t,n,r,o,s){let i=ns(Qo(o),t.id_prefix);if(xo(i))return{parent:i,warnings:[]};if(es(r,i,t.id_prefix),await G(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let c=ve(i,t.id_prefix);return{parent:i,warnings:Zo(c,s).warnings}}async function ZS(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await QS(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function eE(e){if(e.explicitId===void 0)return nr(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||bp(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=ve(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 G_(e,t,n,r,o){let s=B(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let i=ts(r,s,o);return{value:i.value,warnings:i.warnings}}async function tE(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:s,status:i,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(s===void 0)return{dependencyValues:u,status:i};let p=ve(s,n.id_prefix),f=await G(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 g=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((y,h)=>y.localeCompare(h))[0]??o.open_status;return{dependencyValues:u,status:g}}function nE(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let o=t.governance.create_default_type?.trim();if(o&&o.length>0&&ye(o,n)){e.type=o;return}ye("Task",n)&&(e.type="Task")}function rE(e,t){return e.options.filter(n=>Bn("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 oE(e,t,n,r,o){let s=e,i=[];if(s.template!==void 0){let g=s.template.trim();if(g.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let y=await WS(g,t,n);s=q_(zS(y,s))}if(s.type===void 0&&nE(s,r,o),s.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let a=ye(s.type,o);if(!a){let g=vp(s.type),y=g?ye(g,o):void 0;if(y)i.push(`type_coercion:${s.type.trim()}:${y}`),s.type=y,a=y;else throw new l(Et(s.type,o.types,At(n,r.schema)),d.USAGE)}let c=Br(a,o);if(!c)throw new l(`Invalid type value "${s.type}"`,d.USAGE);let m=c.name,u=rE(c,s),p=u.map(g=>`${g.key}=${String(s[g.key])}`);if(p.length>0){s.typeOption=[...p,...s.typeOption??[]];for(let g of u)delete s[g.key]}let f=MS(s.schedulePreset);if(f!==void 0&&!j_.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=DS(s.createMode,f,r.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function sE(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of o)if(s.enabled){if(s.values&&s.values.length>0)throw new l(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,d.USAGE);n.add(s.metadataKey),r.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function iE(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=Vs.get(r)??r;throw new l(`Cannot combine --unset ${s} with ${be("create",r)}`,d.USAGE)}}function aE(e){let t=(n,r)=>{let o=Vs.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;Rs(n,be("create",r),s)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function cE(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)}var dE={"--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","--type-option":"--clear-type-options"};function lE(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:s,type:i,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(g=>{let y=g.type==="boolean"?"<true|false>":g.type==="array"?"<json-array>":g.type==="object"?"<json-object>":g.type==="number"?"<number>":g.type==="string_array"||g.repeatable?"<value>":"<string>";return{example:`--${g.cli_flag} ${y}`,description:`--${g.cli_flag} maps to ${g.metadata_key} (${g.type}${g.repeatable?", repeatable":""})`}}),u=[B_(n,r,o,s),...m.map(g=>g.example)].join(" "),p=[`Run "pm create --help --type ${i}" for type-aware required option guidance.`,...t.filter(g=>g==="--title").map(()=>'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".'),j_.has(i)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&p.push(`Required custom field formats: ${m.map(g=>g.description).join("; ")}.`);let f=[...new Set(t.flatMap(g=>{let y=g.split(" ",1)[0],h=dE[y];return h?[h]:[]}))];f.length>0&&p.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let _=t.length===1?`Missing required option ${t[0]} for type "${i}"`:`Missing required options ${t.join(", ")} for type "${i}"`;throw new l(_,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${i}" in one invocation.`,examples:[...f.map(g=>`pm create --type ${i} ${g} ...`),u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function mE(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?It(t.tags):[];return En(n,t.addTags)}function uE(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=nn(e,"order",n,o=>pe(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function pE(e,t,n,r,o,s){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?s:re(r.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:i,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:sc(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function fE(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:s,author:i,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:g}=e,y=jt(t,n,r,o.item_format,s.type_to_folder),h=xe(t,r),b=Ot(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(U=>b.resolve(U.kind)?.hierarchy),S=await Ls({pmRoot:t,author:i,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:v}),T=v,x=[];try{let U=await we(t,r,o.locks.ttl_seconds,i,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let N=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await ue(t,o.item_format,s.type_to_folder,void 0,o.schema):void 0;if(await G(t,r,o.id_prefix,o.item_format,s.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);if(N){let ne=D(o.schema);rs(N,[...N,c.metadata],r,Re=>te(Re,ne),b)}await Po({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:Uo({pmRoot:t,settings:o,typeToFolder:s.type_to_folder})});let z=await wn(t,i,{required:o.governance.duplicate_detection_mode==="strict"&&g!==!0}),le=[];try{o.governance.duplicate_detection_mode==="strict"&&g!==!0&&await Pn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await ge(y,it(c,{format:o.item_format,schema:o.schema,extensionFieldNames:a}));try{let ne=qe({nowIso:f,author:i,op:"create",before:m,after:c,message:u});await Ct(h,ne)}catch(ne){throw await mn(y),ne}T&&(await S(),T=!1),le=await vn({pmRoot:t,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:y,document:c})}finally{await z()}x=[...N?fs(N,[...N,c.metadata],r):[],...le,...await W({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await W({path:h,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],fn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Bt(c.metadata,p),changed_fields:p})}finally{await U()}}finally{T&&await S()}return x}async function Lt(e,t){let n=q_(await NS(e)),r=E(process.cwd(),t.path);await R(r);let o=await A(r),s=D(o.schema),i=Ye(o.schema),a=O(o,I()),c=await oE(n,t,r,o,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=vS(n.unset,i),{explicitUnsets:_,clearOptionKeys:g}=sE(n,f);iE(n,f),aE(n);let y=$S(m,n,p,g),h=k(),b=C(_e(n.author),o.author_default),v=kS(n.dep,h,o.id_prefix,b),S=rn("--comment",n.comment,h,b),T=rn("--note",n.note,h,b),x=rn("--learning",n.learning,h,b),U=gc(n.file),N=yc(n.test);N.values=await On(N.values,b,h);let ee=bc(n.doc),z=ES(n.reminder,h),le=AS(n.event,h),ne=PS(n.typeOption),Re=Hn(u,ne.values,a),q=I(),ie=vt(q),gt=Kr(n.field,q),Ve=Lu(n,i,u),Ci=new Set(Ve.missing_required_flags),Ri=i.definitions.filter(V=>Ci.has(`--${V.cli_flag}`));cE(gt,Ve,f);let zn=US(Re.errors,u),Dt=zn.map(V=>`--type-option ${V}=<value>`),qd=[...new Set([...y,...Dt,...Ve.missing_required_flags])].sort((V,Di)=>V.localeCompare(Di));lE({combinedMissingFlags:qd,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:zn,openStatus:s.open_status,type:u,createMode:p,missingRequiredRuntimeFields:Ri}),jS(Re.errors,u,m,s);let Ie=await eE({pmRoot:r,settings:o,typeRegistry:a,explicitId:n.id}),yt=n.status!==void 0?yS(n.status,s):bS(m,s),Ii=n.priority!==void 0?Tn(n.priority):2,L=f.metadataKeys,De=mE(L,n),et=nn(L,"deadline",n.deadline,V=>re(V,new Date(h),"deadline")),Fr=nn(L,"estimated_minutes",n.estimatedMinutes,V=>An(V,"estimated-minutes")),bt=B(L,"acceptance_criteria",n.acceptanceCriteria),xi=B(L,"definition_of_ready",n.definitionOfReady),We=uE(L,n),Oi=B(L,"goal",n.goal),Mr=B(L,"objective",n.objective),sw=B(L,"value",n.value),iw=B(L,"impact",n.impact),aw=B(L,"outcome",n.outcome),cw=B(L,"why_now",n.whyNow),dw=B(L,"assignee",n.assignee),lw=L.has("author")?void 0:_e(n.author)??b,mw=B(L,"parent",n.parent),Kd=await XS(mw,n,L,r),Pi=Kd.parent,uw=Kd.parentSource,pw=B(L,"reviewer",n.reviewer),fw=nn(L,"risk",n.risk,V=>Ae(Ss(V),dn,"risk")),_w=nn(L,"confidence",n.confidence,V=>As(V)),hw=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,zd=o.validation.sprint_release_format,$t=[...c.warnings,...JS(u,Ie,et,z.values,le.values)],Bd=await ZS({itemId:Ie,parent:Pi,pmRoot:r,settings:o,typeRegistry:a,policy:hw});Pi=Bd.parent,$t.push(...Bd.warnings);let Hd=G_(L,"sprint",n.sprint,"sprint",zd),gw=Hd.value;$t.push(...Hd.warnings);let Vd=G_(L,"release",n.release,"release",zd),yw=Vd.value;$t.push(...Vd.warnings);let Wd=B(L,"blocked_by",n.blockedBy),Yd=await tE({pmRoot:r,settings:o,typeRegistry:a,statusRegistry:s,blockedBy:Wd,dependencyValues:v.values,status:yt,statusExplicit:n.status!==void 0,nowValue:h,author:b}),Li=Yd.dependencyValues;yr(Ie,Li),$t.push(...await Jt({pmRoot:r,dependencies:Li,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ie,createdAt:h}],schema:o.schema})),yt=Yd.status;let bw=B(L,"blocked_reason",n.blockedReason),ww=B(L,"unblock_note",n.unblockNote),vw=B(L,"reporter",n.reporter),kw=nn(L,"severity",n.severity,V=>Ae(Es(V),ln,"severity")),Sw=B(L,"environment",n.environment),Ew=B(L,"repro_steps",n.reproSteps),Jd=B(L,"resolution",n.resolution),Aw=B(L,"expected_result",n.expectedResult),Tw=B(L,"actual_result",n.actualResult),Cw=B(L,"affected_version",n.affectedVersion),Rw=B(L,"fixed_version",n.fixedVersion),Iw=B(L,"component",n.component),xw=nn(L,"regression",n.regression,V=>Ts(V)),Ow=B(L,"customer_impact",n.customerImpact),Ni=wc(n.title,"--title"),Fi=n.description??"",Dr=n.body??"",Xd=await Pn({title:Ni,description:Fi,body:Dr},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});$t.push(..._s(Xd));let Mi=pE(yt,s,o,n,Jd,h),Pw=Mi.closeReason,Lw=yt===s.close_status?h:void 0,Nw=Mi.completedAt;$t.push(...Mi.warnings);let $r=ha({id:Ie,title:Ni,description:Fi,type:u,type_options:Re.normalized,status:yt,closed_at:Lw,completed_at:Nw,close_reason:Pw,priority:Ii,tags:De,created_at:h,updated_at:h,deadline:et,assignee:dw,author:lw,estimated_minutes:Fr,acceptance_criteria:bt,definition_of_ready:xi,order:We,goal:Oi,objective:Mr,value:sw,impact:iw,outcome:aw,why_now:cw,parent:Pi,reviewer:pw,risk:fw,confidence:_w,sprint:gw,release:yw,blocked_by:Wd,blocked_reason:bw,unblock_note:ww,reporter:vw,severity:kw,environment:Sw,repro_steps:Ew,resolution:Jd,expected_result:Aw,actual_result:Tw,affected_version:Cw,fixed_version:Rw,component:Iw,regression:xw,customer_impact:Ow,dependencies:Li,comments:S.values,notes:T.values,learnings:x.values,files:U.values,tests:N.values,docs:ee.values,reminders:z.values,events:le.values,...gt,...Ve.values});try{zr($r,q)}catch(V){throw new l(V instanceof Error?V.message:"Invalid extension item field values",d.USAGE)}let Fw=Tt({metadata:$r,body:Dr},{schema:o.schema,extensionFieldNames:ie}),Mw={metadata:{},body:""},Qd=[..._].sort((V,Di)=>V.localeCompare(Di)),Dw=CS(n.message,Qd),Zd=TS($r,Dr,Qd,[...Object.keys(gt),...Object.keys(Ve.values??{})]),$w=await fE({pmRoot:r,type:u,id:Ie,settings:o,typeRegistry:a,author:b,extensionFieldNames:ie,afterDocument:Fw,beforeDocument:Mw,historyMessage:Dw,changedFields:Zd,nowValue:h,similarityCandidate:{title:Ni,description:Fi,body:Dr},allowDuplicate:n.allowDuplicate}),el=structuredClone($r);p==="strict"&&_.has("dependencies")&&(el.dependencies=[]);let Uw=P_(Ie,u,yt,s);return H_(u,et,z.values,le.values)&&qu(`[pm] warning: ${u} '${Ie}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ie} --deadline <ISO>' or 'pm update ${Ie} --event "start=<ISO>,end=<ISO>"'.`),{item:el,changed_fields:Zd,warnings:[...$t,...$w],...Object.fromEntries([["parent_source",uw],["next_transition",Uw],["similarity_advisory",Xd]].filter(V=>V[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]="5a6614ac-62fd-5680-9eed-447bfb7a167f")}catch{}})();var Ec=[...uc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...pc,...zs],_E=(()=>{let e=new Map;for(let t of Ec)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Js=new Map(Ec.map(e=>[e.optionKey,e.canonical])),hE=Ec.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),gE=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),yE=Cs({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function eh(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s},r=new Set([...Js.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!ze(s))continue;let i=o==="rank"?"order":Js.get(o)??o;n(i),t[o]=void 0}return ke(e,Is(t,yE))}function th(e,t,n=[]){return Bs({raw:e,supportedFields:hE,resolveDefinition:r=>{let o=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return _E.get(r)??Hs(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var V_=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 W_(e){let t=e.disallowedFlags.flatMap(r=>{let o=V_.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=V_.get(r);return o?[`Replace ${r} with: ${o(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 bE(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let s=(c,m,u)=>{c&&u.push(m)};if(o){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw W_({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let i=[];s(t.status!==void 0,"--status",i),s(t.closeReason!==void 0,"--close-reason",i),s(t.assignee!==void 0,"--assignee",i),s(t.parent!==void 0,"--parent",i),s(t.blockedBy!==void 0,"--blocked-by",i),s(t.blockedReason!==void 0,"--blocked-reason",i),s(t.unblockNote!==void 0,"--unblock-note",i),s(t.dep!==void 0,"--dep",i),s(t.depRemove!==void 0,"--dep-remove",i),s(t.replaceDeps===!0,"--replace-deps",i),s(t.replaceTests===!0,"--replace-tests",i),s(t.replaceFiles===!0,"--replace-files",i),s(t.replaceDocs===!0,"--replace-docs",i),s(t.note!==void 0,"--note",i),s(t.learning!==void 0,"--learning",i),s(t.test!==void 0,"--test",i),s(t.reminder!==void 0,"--reminder",i),s(t.event!==void 0,"--event",i),s(t.clearDeps===!0,"--clear-deps",i),s(t.clearComments===!0,"--clear-comments",i),s(t.clearNotes===!0,"--clear-notes",i),s(t.clearLearnings===!0,"--clear-learnings",i),s(t.clearFiles===!0,"--clear-files",i),s(t.clearTests===!0,"--clear-tests",i),s(t.clearDocs===!0,"--clear-docs",i),s(t.clearReminders===!0,"--clear-reminders",i),s(t.clearEvents===!0,"--clear-events",i);let a=[...n].filter(c=>gE.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw W_({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 wE(e,t){let n=X(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function vE(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Bm({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=X(e.fromStatus,e.statusRegistry)??e.fromStatus,r=X(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Hm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,d.USAGE);return`workflow_transition_not_allowed: ${o}`}function kE(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:nh(e)}function nh(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(t).toISOString()}function Mn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var SE=["id","kind","type","author","created_at","source_kind"],EE=["id","kind","type","author","created_at","source_kind"];function rh(e){return e.startsWith("```")||e.includes(`
6
+ `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Vo(e)}function oh(e){return typeof e=="string"?Vr(e)??e.trim():e}function Qs(e,t,n,r){return e?(Ee(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let i=s.trim(),a=rh(i);gr(i,a);let c=a?ae(s,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",SE);let m=c.id?.trim(),u=oh((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=or(Mn(c.source_kind)),f=Mn(c.author);return{id:sr(m,t,p),kind:Ae(u,Ut,"dependency kind"),created_at:kE(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function AE(e,t){return e?(Ee(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);let o=rh(r);if(gr(r,o,"--dep-remove"),o){let s=ae(r,"--dep-remove");Ke(s,"--dep-remove",EE);let i=s.id?.trim();if(!i)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(i.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${i}"`,d.USAGE);let a=oh(Mn(s.kind??s.type)),c=or(Mn(s.source_kind)),m=Mn(s.author),u=Mn(s.created_at);return{id:sr(i,t,c),kind:a?Ae(a,Ut,"dependency kind"):void 0,source_kind:c,author:m,created_at:u?nh(u):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:ve(r,t)}})):[]}function Xs(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function TE(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),s=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function CE(e,t,n,r){let o=[...e??[]],s=!1;if(t===void 0){let i=o.filter(a=>a.kind!=="blocked_by");return i.length!==o.length&&(o=i,s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(i=>i.kind==="blocked_by"&&i.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function RE(e,t,n,r,o,s){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await G(n,ve(i,r),r,o,s);return a?{id:a.id}:{unresolved:i}}function IE(e,t,n,r,o){let s=CE(e.dependencies,t,n,r);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,o.includes("dependencies")||o.push("dependencies"))}function xE(e){return`${e.path}::${e.scope}`}function OE(e){return`${e.path}::${e.scope}`}function PE(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function sh(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function Y_(e,t){let n=Bn("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function LE(e,t,n){let r=new Set,o=(s,i)=>{i&&r.add(s)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=th(e.unset,t,n);for(let i of s.optionKeys)o(i,!0)}return r}function NE(e,t,n,r,o){let s=Br(e,n);if(!s)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=un(s,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let a=LE(t,r,o);for(let c of i.disabled)if(a.has(Y_(c,e)))throw new l(`Option ${be("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of i.required)if(!a.has(Y_(c,e)))throw new l(`Missing required option ${be("update",c)} for type "${e}"`,d.USAGE)}var FE=new Set(["order","rank"]),ME=Hi.filter(e=>!FE.has(e)),ih=["tags","closeReason",...ME],DE=["title","description","body","status","closeReason","completedAt","priority","type",...Hi,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],$E=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>re(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>An(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],UE=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Ae(Ss(e),dn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>As(e)}],GE=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Ae(Es(e),ln,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>Ts(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Sc(e,t,n){for(let r of e){let o=t[r.optionKey],s=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!s)){if(s){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new l(`${be("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function jE(e){return eh(await Wo(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function Ac(e){return ct(e)?await jE(e):eh(e)}function qE(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 vc(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 Tc(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);vc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),vc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),vc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function KE(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 zE(e){let t={};for(let n of ih)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function BE(e,t){let n=zE(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=Js.get(r)??r;throw new l(`Cannot combine --unset ${s} with ${be("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 HE(e){let t=(n,r)=>{let o=Js.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;Rs(n,be("update",r),s)};for(let n of ih)t(e[n],String(n));t(e.order??e.rank,"order"),Ee(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Ee(e.event,"--event","Use --clear-events to clear linked events.")}function VE(e,t){let n={};for(let r of DE)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 WE(e){let t=await G(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await at(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await Q(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function YE(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return ue(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function JE(e){e.before&&rs(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>te(t,e.statusRegistry),Ot())}function XE(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 QE(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=ns(Qo(e.options.parent),e.settings.id_prefix);if(xo(t))return{resolvedParentValue:t,warnings:[]};if(es(e.id,t,e.settings.id_prefix),await G(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=ve(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:Zo(r,e.parentReferencePolicy).warnings}}function ZE(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function eA(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await G(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await at(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await Q(t,{schema:e.settings.schema}),r=e.options.type!==void 0?ye(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=vE({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function tA(e){if(!e.fieldFlags.status||X(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],o=[];if(n.length>0){let a=ke(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),c=await ut(e.id,a,e.global);o=c.changed_fields,r.push(...c.warnings)}let s=await lt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...e.workflowTransitionWarnings,...r,...s.warnings,"auto_routed_from_update_to_close"];return{item:s.item,changed_fields:[...o,...s.changed_fields],warnings:i}}function nA(e,t,n,r){return t.title!==void 0&&(e.metadata.title=wc(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")),X(e.metadata.status,n)??e.metadata.status}var rA=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function oA(e,t){for(let n of rA)e[n]!==void 0&&(delete e[n],t.push(n))}function sA(e,t,n,r,o){let s=wE(n,t.statusRegistry);if(e.metadata.status=s,o.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!te(s,t.statusRegistry)&&te(r,t.statusRegistry)&&oA(e.metadata,o)}function iA(e,t,n,r){if(t.options.status!==void 0&&sA(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!te(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=re(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function aA(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&te(n,t.statusRegistry)&&!te(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function cA(e,t,n,r){iA(e,t,n,r),aA(e,t,n,r)}function dA(e,t,n){let r=ye(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=Tn(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=ye(t.options.type,t.typeRegistry);if(!o)throw new l(Et(t.options.type,t.typeRegistry.types,At(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=o,r=o,n.push("type")}return NE(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),lA(e,t,r,n),r}function lA(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let s=Ps(t.options.typeOption??[]),i=Hn(n,s,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 o=Hn(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=o.normalized}function mA(e,t){let n=new Set(t.map(o=>Xs(o))),r=new Set;return e.filter(o=>{if(!n.has(Xs(o)))return!0;let s=TE(o);return r.has(s)?!1:(r.add(s),!0)})}function uA(e,t,n){let r=t.filter(o=>!e.some(s=>sh(s,o)));if(r.length!==0)throw new l(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,d.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function pA(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=mA(r,t.dependencyUpdates.additions);let o=new Set(r.map(s=>Xs(s)));for(let s of t.dependencyUpdates.additions){let i=Xs(s);o.has(i)||(r.push(s),o.add(i))}}t.dependencyRemovals.length>0&&(uA(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(s=>sh(o,s)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function fA(e,t,n){kc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),kc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),kc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function kc(e,t,n,r,o,s){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],s.push(t))}function _A(e,t,n){J_(e,"files",t.options.file,t.fileUpdates.values,xE,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),hA(e,t,n),J_(e,"docs",t.options.doc,t.docUpdates.values,OE,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function J_(e,t,n,r,o,s,i,a){if(!(n===void 0&&!i.has(t))){if(s)e.metadata[t]=r;else if(i.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(u=>o(u)));for(let u of r){let p=o(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function hA(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=X_(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=X_([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function X_(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=PE(r);n.has(o)||(t.push(r),n.add(o))}return t}function gA(e,t,n){let r=t.options.addTags,o=t.options.removeTags,s=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?It(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Ho(En(i,r),o),n.changedFields.push("tags")}Sc($E,t.options,n),bA(e,t,n.changedFields)}function yA(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let s=Bo(Sn(e.metadata.acceptance_criteria),r,o);if(s.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let i=s.criteria.join("; ");e.metadata.acceptance_criteria!==i&&(i===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=i,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function bA(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=pe(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function wA(e,t,n,r){vA(e,t,n.changedFields),kA(e,t,n.changedFields),Sc(UE,t.options,n),Q_(e,t,"sprint",r,n.changedFields),Q_(e,t,"release",r,n.changedFields),SA(e,t,n.changedFields),Sc(GE,t.options,n)}function vA(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 kA(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 Q_(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=ts(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,r.push(...s.warnings)}o.push(n)}}function SA(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)&&IE(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function EA(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=xs(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=Os(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function AA(e,t,n){Z_(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),Z_(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let i=o.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===o)?.cli_flag??i;throw new l(`Cannot combine --unset ${i} with --${c}`,d.USAGE)}rt(e[o],s)||(e[o]=s,n.push(o))}let r=Kr(t.options.field,t.extensionRegistrations);for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new l(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,d.USAGE);for(let[o,s]of Object.entries(r))rt(e[o],s)||(e[o]=s,n.push(o))}function Z_(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function TA(e,t){let n=structuredClone(e.metadata),r=e.body,o=[],s=[],i=nA(e,t.options,t.statusRegistry,o),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};cA(e,t,i,o),dA(e,t,o),pA(e,t,o),fA(e,t,o),_A(e,t,o),gA(e,t,c),yA(e,t,c),wA(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&yr(e.metadata.id,e.metadata.dependencies),X(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),EA(e,t,o),AA(a,t,o);try{zr(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(o)].filter(p=>p==="body"?e.body!==r:!rt(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${Sn(n.acceptance_criteria).length}:${Sn(m.acceptance_criteria).length}`),{changedFields:u,warnings:s}}async function ah(e,t,n,r={}){t=await Ac(t);let o=E(process.cwd(),n.path);await R(o);let s=await A(o),i=D(s.schema),a=Ye(s.schema),c=I(),m=vt(c),u=O(s,c),p=s.governance.workflow_enforcement??"off",f=p==="off"?[]:zm(s.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],g=th(t.unset,a,m),y=new Set(g.optionKeys),h=new Set(g.metadataKeys);Tc(t),KE({definitions:qE(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:h}),bE(e,t,h),BE(t,g),HE(t);let b=C(t.author,s.author_default),v=new Date,S=v.toISOString(),T=Qs(t.dep,s.id_prefix,S,b);yr(e,T.additions);let x=await Jt({pmRoot:o,dependencies:T.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),U=AE(t.depRemove,s.id_prefix),N=rn("--comment",t.comment,S,b),ee=t.ownershipMetadataBypass===!0&&N.values?{...N,values:N.values.map(De=>({...De,author:b}))}:N,z=rn("--note",t.note,S,b),le=rn("--learning",t.learning,S,b),ne=gc(t.file),Re=yc(t.test);Re.values=await On(Re.values,b,S);let q=bc(t.doc),ie=[],gt=await QE({id:e,options:t,unsetTargets:g,pmRoot:o,settings:s,typeRegistry:u,parentReferencePolicy:_}),Ve=await RE(t.blockedBy,h.has("blocked_by"),o,s.id_prefix,s.item_format,u.type_to_folder),Ci=Ve.id,Ri=[...gt.warnings,...ZE(Ve)],zn=Do(t,a,t.runtimeFieldCommands),Dt=VE(t,zn);if(!Object.values(Dt).some(Boolean))return WE({pmRoot:o,id:e,settings:s,typeRegistry:u});ie.push(...await eA({options:t,fieldFlags:Dt,workflowEnforcement:p,typeWorkflows:f,statusRegistry:i,typeRegistry:u,pmRoot:o,id:e,settings:s}));let Ie=await tA({options:t,fieldFlags:Dt,statusRegistry:i,workflowTransitionWarnings:ie,global:n,id:e});if(Ie)return Ie;XE(t);let yt=Ot(),Ii=Dt.parent&&!h.has("parent")||T.additions.some(De=>yt.resolve(De.kind)?.hierarchy),L=await Ls({pmRoot:o,author:b,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Ii});try{let De=await YE({fieldFlags:Dt,clearedMetadataKeys:h,pmRoot:o,settings:s,typeToFolder:u.type_to_folder}),et,Fr,bt=await op({pmRoot:o,settings:s,typeToFolder:u.type_to_folder,id:e,op:CA(t,r),author:b,message:t.message,resolveHistoryContext:()=>Fr,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(We){et=RA({document:We,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),Fr=et?{recurrence:et}:void 0,De=De?.map(Mr=>Mr.id===We.metadata.id?structuredClone(We.metadata):Mr);let Oi=TA(We,{options:t,settings:s,typeRegistry:u,statusRegistry:i,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:h,dependencyUpdates:T,dependencyRemovals:U,commentUpdates:ee,noteUpdates:z,learningUpdates:le,fileUpdates:ne,testUpdates:Re,docUpdates:q,resolvedParentValue:gt.resolvedParentValue,resolvedBlockedByDependencyId:Ci,runtimeFieldUpdates:zn,nowValue:v,nowIso:S,author:b,pmRoot:o});return JE({before:De,document:We,statusRegistry:i}),Oi}});await L();let xi=De?fs(De,De.map(We=>We.id===bt.item.id?bt.item:We),bt.item.id):[];return{item:bt.item,changed_fields:bt.changedFields,warnings:[...ie,...Ri,...x,...xi,...bt.warnings],...et===void 0?{}:{lifecycle_transition:et}}}finally{await L()}}function CA(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function RA(e){if(e.recurrenceReason===void 0)return;let t=X(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!te(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,d.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=X(n,e.statusRegistry)??n,o=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(i=>{let a=o[i];return typeof a=="string"?[[i,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:s}}async function ut(e,t,n){return ah(e,t,n)}async function ch(e,t,n,r){let o=await ah(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,d.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fada7a33-ad1d-54f1-ae03-c5f8e4568d75")}catch{}})();var lh=1,Rc="update-many",IA=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),xA=["--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(", "),OA={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"},PA=[{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"}],LA={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"},mh=e=>{let t={};for(let[n,r]of Object.entries(e))IA.has(n)||r!==void 0&&(t[n]=r);return t},NA=e=>Object.keys(mh(e)).length>0,uh=e=>typeof e=="string"?e.trim():e,FA=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Cc=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},MA=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??uh(e)},DA={priority:FA,estimatedMinutes:Cc,order:Cc,rank:Cc,regression:MA},$A=(e,t)=>{if(t!==void 0)return(DA[e]??uh)(t)},UA=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return LA[t]??t},Zs=(e,t)=>rt(e,t),GA=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],jA=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,qA=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",dh=(e,t)=>t===void 0?void 0:e[t],Dn=e=>Array.isArray(e)?e.length:0,KA=(e,t,n)=>{let r=n[e.addKey],o=dh(n,e.removeKey),s=Dn(r),i=Dn(o),a=n[e.clearKey]===!0,c=dh(n,e.replaceKey)===!0;if(![a,c,s>0,i>0].includes(!0))return;let m=GA(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:qA({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:s,remove_count:i,before_count:jA(e.field,m)}}},zA=(e,t)=>{let n=[];for(let r of PA){let o=KA(r,e,t);o!==void 0&&n.push(o)}return n},BA=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],HA=(e,t)=>{if(![t.tags!==void 0,Dn(t.addTags)>0,Dn(t.removeTags)>0].includes(!0))return;let n=BA(e.tags),r=t.tags===void 0?n:It(t.tags),o=En(r,t.addTags),s=Ho(o,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!Zs(i,s))return{field:"tags",before:n,after:s}},VA=(e,t)=>{let n=e.acceptance_criteria,r=Bo(Sn(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 o=r.criteria.join("; ");if(!Zs(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},WA=(e,t,n)=>{for(let[r,o]of Object.entries(OA)){let s=n[r];if(s===void 0)continue;let i=t[o],a=$A(r,s);Zs(i,a)||e.push({field:o,before:i,after:a})}},YA=(e,t,n,r)=>{let o=Do(n,r,["update_many"]);for(let[s,i]of Object.entries(o)){let a=t[s];Zs(a,i)||e.push({field:s,before:a,after:i})}},JA=(e,t,n)=>{for(let r of n??[]){let o=UA(r),s=t[o];s!==void 0&&e.push({field:o,before:s,after:null})}},XA=(e,t,n={})=>{let r=e,o=[],s=HA(r,n);if(s&&o.push(s),WA(o,r,n),Dn(n.addAc)>0||Dn(n.removeAc)>0){let i=VA(r,n);i!==void 0&&o.push(i)}return o.push(...zA(r,n)),YA(o,r,n,t),JA(o,r,n.unset),{id:e.id,changes:o}},QA=(e,t)=>wp(e,t,{strict:!0,flagLabel:"--filter-status"}),ZA=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)},eT=[({update:e})=>{e.priority!==void 0&&Tn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=O(t,I());if(!ye(e.type,r))throw new l(Et(e.type,r.types,At(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!X(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&&re(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&An(e.estimatedMinutes,"estimated-minutes")}],tT=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let s of eT)s(o)},nT=async e=>{let t=await qo(e.pmRoot,Rc,e.rollbackId,lh),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Ko(t.items,(o,s)=>Yt(o,s,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...zt({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}},rT=async e=>{let t={schema_version:lh,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await jo(e.pmRoot,Rc,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},oT=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},Ic=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},sT=async e=>{let t=E(process.cwd(),e.path);await R(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:D(n.schema),runtimeFieldRegistry:Ye(n.schema)}},iT=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(mr(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 nT({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},aT=async e=>{QA(e.options.status,e.runtime.statusRegistry);let t=await dt(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let s=XA(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?s:{...s,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await dt(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:oT(e.options.list?.ids,r)}},cT=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:[],...Ic(e)}),dT=e=>({...zt({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:[],...Ic(e)}),lT=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(s=>s.changes.length>0).map(s=>s.id));for(let s of e.items){if(!o.has(s.id)){t.push({id:s.id,status:"skipped"});continue}try{let i=Ta({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),a=await ut(s.id,i,e.global);t.push({id:s.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(s.id)}catch(i){t.push({id:s.id,status:"failed",error:pn(i)})}}return{rows:t,updatedIds:n}},mT=async e=>{if(e.plan.actionable.length===0)return dT(e.plan);let t=k(),n=Go(Rc,t),r=new Set(e.plan.actionable.map(p=>p.id)),o=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),s=e.options.checkpoint===!1?void 0:await rT({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),i=await lT({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{...zt({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,...s?{checkpoint:s}:{},updated_count:c,skipped_count:m,failed_count:u,rows:i.rows,ids:i.updatedIds,...Ic(e.plan)}},ph=async(e,t)=>{let n=await sT(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:Ta(await Ac(e.update))});let o=mh(e.update);if(ZA(e.list),r!==void 0)return iT({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!NA(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${xA}), or pass --dry-run for a filter-only preview.`,d.USAGE);tT(e.update,n.settings,n.statusRegistry,n.pmRoot),Tc(e.update);let s=await Jt({pmRoot:n.pmRoot,dependencies:Qs(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:O(n.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await aT({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:s});return await Jt({pmRoot:n.pmRoot,dependencies:Qs(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:O(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?cT(i):mT({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]="f7e870b6-fd80-5742-bc81-826d8f102d30")}catch{}})();var uT=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],fh=["brief","standard","deep"],gh="plan-step-",Fc="draft",Nc=["bug-investigation","feature-implementation","refactoring-sprint"],_h={"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 pT(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(_h,t)?_h[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${Nc.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Nc[0]}`]});return n.map(r=>({...r}))}function fT(e,t){return t>0?Math.round(e/t*100):0}function yh(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function Ge(e){return Array.isArray(e)?e.flatMap(t=>Cn(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Cn(e,{unique:!1}):[]}function Te(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function bh(e,t=Fc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Gi.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${Gi.join(", ")}`,d.USAGE);return r}function Mc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ji.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${ji.join(", ")}`,d.USAGE);return r}function wh(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ki.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${Ki.join(", ")}`,d.USAGE);return r}function _T(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=qi.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${qi.join(", ")}`,d.USAGE);return n}function hT(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=fh.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${fh.join(", ")}`,d.USAGE);return n}function gT(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 xc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function yT(e,t){let n=e,r={},o=[];for(let s of t){let i=s.startsWith("plan.")?s.slice(5):s;if(i.length!==0){if(!xc.has(i)){o.push(s);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...xc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...xc].join(",")}`}});return r}function Dc(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let s=o.indexOf("=");if(s<=0)throw new l(`Invalid ${t} entry "${o}"; 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[o.slice(0,s).trim().toLowerCase()]=o.slice(s+1).trim()}return n}function $c(e){let t=Dc(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 Uc(e){let t=Dc(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 Gc(e){let t=Dc(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 bT(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=fT(t.completed,t.total),t}function wT(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${gh}${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 $n(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),s=e.find(i=>i.order===o);if(s)return s}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function hh(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 vT(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],o=[];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=hh(i);if(a){o.push({from_step:i.id,...a});continue}r.push(i)}return{targets:r,skipped:o}}let s=new Set;for(let i of t){let a=$n(e,i);if(s.has(a.id))continue;s.add(a.id);let c=hh(a);if(c){o.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:o}}function kT(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 ST(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function ET(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 Le(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=bT(n),o=ST(n),s={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Fc,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:ET(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(s.steps=n),t==="deep"&&(s.decisions=e.plan_decisions??[],s.discoveries=e.plan_discoveries??[],s.validation=e.plan_validation??[]),s}function Ne(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&&!Ra(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function vh(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 AT(e){let t=E(process.cwd(),e.path);await R(t);let n=await A(t);return{pmRoot:t,settings:n}}async function kh(e,t){let n=O(e.settings,I()),r=await G(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 o=await Q(r,{schema:e.settings.schema});return vh(o.document.metadata),{document:o.document,itemId:r.id}}function TT(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of Ge(e.related))t.push(`id=${n},kind=related`);for(let n of Ge(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of Ge(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function CT(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 RT(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||Ge(e.dependsOn).length>0||Ge(e.link).length>0}function IT(e){let t=e.stepTitle?.trim()||void 0,n=yh(e.step),r=e.template?.trim()?pT(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function xT(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 ${Nc[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 OT(e,t){let n=Mc(e.stepStatus,"pending"),r=jc(e,"depends_on"),o=Te(e.file).map($c),s=Te(e.test).map(Uc),i=Te(e.doc).map(Gc),a=k();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:s.length>0?s:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function PT(e){let t=IT(e),n=RT(e);if(xT(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[OT(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((o,s)=>({id:`${gh}${String(s+1).padStart(3,"0")}`,order:s+1,title:o,body:t.templateSteps[s]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function Sh(e,t,n=[]){ke(e,t),n.length>0&&gp(t,n)}async function LT(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 o=bh(e.mode,Fc),s=_T(e.harness),i=e.fromSearch?.trim(),a=CT(e),{steps:c,hasPerStepDetailOptions:m}=PT(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?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:Te(e.file),test:Te(e.test),doc:Te(e.doc),field:Te(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:TT(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")};Sh(e,f);let _=await Lt(f,t),g=await oe({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(h){let b=["plan_mode"];h.metadata.plan_mode=o,s&&(h.metadata.plan_harness=s,b.push("plan_harness"));let v=e.scope?.trim();v&&(h.metadata.plan_scope=v,b.push("plan_scope"));let S=e.resumeContext?.trim();return S&&(h.metadata.plan_resume_context=S,b.push("plan_resume_context")),h.metadata.plan_steps=c,b.push("plan_steps"),a&&(h.metadata.plan_validation=[...h.metadata.plan_validation??[],a],b.push("plan_validation")),p&&(h.metadata.assignee=p,b.push("assignee")),{changedFields:b}}}),y=Le(g.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Ne(_.item.id,y),warnings:[..._.warnings],generated_at:k()}}async function NT(e,t,n){let r=hT(t.depth),o=gT(t.fields),{document:s,itemId:i}=await kh(n,e),a=Le(s.metadata,o===null?r:"deep");return{action:"show",plan:o===null?a:yT(a,o),next_actions:Ne(i,a),warnings:[],generated_at:k()}}function FT(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function Xe(e){let t=C(e.options.author,e.ctx.settings.author_default),n,r=await oe({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){vh(o.metadata);let s=D(e.ctx.settings.schema);if(te(o.metadata.status,s)||Ra(o.metadata.plan_mode))throw new l(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.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=(o.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(o.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,o);n=c.resultStep;let m=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));o.metadata.plan_steps=m;let u=FT(a,o.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function MT(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let o=Mc(t.stepStatus,"pending"),s=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await Xe({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;Eh(u,void 0,o,s);let f=DT(u,t,{order:p,title:r,status:o});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Le(i.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Ne(c,m),warnings:[],generated_at:k()}}function Eh(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(s=>s.id!==t&&s.status==="in_progress");if(o)throw new l(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function DT(e,t,n){let r=jc(t,"depends_on"),o=Te(t.file).map($c),s=Te(t.test).map(Uc),i=Te(t.doc).map(Gc),a=k();return{id:wT(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:s.length>0?s:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function jc(e,t){let n=Ge(e.dependsOn).map(u=>({id:u,kind:t})),r=Ge(e.related).map(u=>({id:u,kind:"related"})),o=Ge(e.blocks).map(u=>({id:u,kind:"blocks"})),s=Ge(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=Ge(e.link),a=wh(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,...o,...s,...m]}async function Oc(e,t,n,r){let{document:o,resultStep:s,itemId:i}=await Xe({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=$n(c,r.stepRef),p=k(),f=r.finalStatus??Mc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return Eh(c,u.status==="in_progress"?u.id:void 0,f,_),$T(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Le(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:s,next_actions:Ne(i,a),warnings:[],generated_at:k()}}function $T(e,t,n,r){UT(e,t,n),GT(e,t),e.status=n,e.updated_at=r,jT(e,n,r)}function UT(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 GT(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=Te(t.file).map($c),o=Te(t.test).map(Uc),s=Te(t.doc).map(Gc);r.length>0&&(e.files=Pc(e.files,r)),o.length>0&&(e.tests=Pc(e.tests,o)),s.length>0&&(e.docs=Pc(e.docs,s))}function Pc(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let s=JSON.stringify(o);r.has(s)||(r.add(s),n.push(o))}return n}function jT(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function qT(e,t,n,r,o){let{document:s,itemId:i}=await Xe({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(c){let m=$n(c,r),u=c.filter(f=>f.id!==m.id),p=Math.max(1,Math.min(o,u.length+1));return u.splice(p-1,0,m),u.forEach((f,_)=>{f.order=_+1,f.updated_at=k()}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=Le(s.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Ne(i,a),warnings:[],generated_at:k()}}async function KT(e,t,n,r){let{document:o,itemId:s}=await Xe({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=$n(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=Le(o.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Ne(s,i),warnings:[],generated_at:k()}}async function zT(e,t,n,r){let o=jc(t,wh(t.linkKind,"related"));if(o.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let s=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await Xe({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=$n(u,r),_=f.linked_items??[],g=h=>`${h.kind}:${h.id}`,y=new Set(_.map(g));for(let h of o){let b=g(h);y.has(b)||(_.push(h),y.add(b))}if(f.linked_items=_,f.updated_at=k(),s){let h=p.metadata.dependencies??[],b=S=>`${S.kind}:${S.id}`,v=new Set(h.map(b));for(let S of o){let T=S.kind==="depends_on"?"blocked_by":S.kind,x={id:S.id,kind:T,created_at:k(),author:C(t.author,n.settings.author_default)};v.has(b(x))||(h.push(x),v.add(b(x)))}p.metadata.dependencies=h}return{changedSteps:[f.id],resultStep:f}}}),m=Le(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ne(a,m),warnings:[],generated_at:k()}}async function BT(e,t,n,r){let o=Ge(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:s,itemId:i,resultStep:a}=await Xe({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=$n(m,r),p=(u.linked_items??[]).filter(f=>!o.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=k(),{changedSteps:[u.id],resultStep:u}}}),c=Le(s.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Ne(i,c),warnings:[],generated_at:k()}}async function Lc(e,t,n,r){let o=kT(r,t);if(!o){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 s=C(t.author,n.settings.author_default),{document:i,itemId:a}=await Xe({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,u){let p=k();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:s,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:s,text:o}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Le(i.metadata,"deep");return{action:r,plan:c,next_actions:Ne(a,c),warnings:[],generated_at:k()}}async function HT(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:o,itemId:s}=await Xe({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Le(o.metadata,"brief");return{action:"resume",plan:i,next_actions:Ne(s,i),warnings:[],generated_at:k()}}async function VT(e,t,n){let r=bh(t.mode??"approved","approved"),{document:o,itemId:s}=await Xe({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(a,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Le(o.metadata,"brief");return{action:"approve",plan:i,next_actions:Ne(s,i),warnings:[],generated_at:k()}}function Ah(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function WT(e,t){let n=Le(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ne(e.itemId,n),warnings:Ah(t),generated_at:k()}}function YT(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let s=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${s}`)}return r}async function JT(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Te(e.options.field)){let s=o.indexOf("=");if(s<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0)throw new l(`Invalid --field entry "${o}"; 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 "${o}"; 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 "${o}"; "${p}" is reserved by materialize and cannot be overridden`,d.USAGE);n[p]=a}for(let o of e.targets){let s={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:YT(e.parent,e.planItemId,o)};Sh(e.options,s,["description",...Object.keys(n)]);let i=await Lt(s,{path:e.pmRoot});t.push({id:i.item.id,title:i.item.title,type:e.resolvedTypeName,parent:i.item.parent,tags:i.item.tags??[],from_step:o.id})}return t}function XT(e,t,n){for(let r of t){let o=n.find(a=>a.from_step===r.id);if(!o)continue;let s=e.find(a=>a.id===r.id);if(!s)continue;let i=s.linked_items??[];i.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),s.linked_items=i,s.updated_at=k()}}async function QT(e,t,n){let r=Ge(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let o=t.materializeType?.trim()||"Task",s=O(n.settings,I()),i=ye(o,s);if(!i)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await kh(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=vT(u,r);if(p.length===0){if(f.length>0)return WT(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await JT({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:g,itemId:y}=await Xe({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(b){return XT(b,p,_),{changedSteps:p.map(v=>v.id)}}}),h=Le(g.metadata,"standard");return{action:"materialize",plan:h,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ne(y,h),warnings:Ah(f),generated_at:k()}}function ZT(e){if(e.subcommand==="create")return e;let t=yh(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:ke(e.options,{...e.options,stepTitle:t[0]})}:e}function pt(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function on(e,t){let n=pt(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function eC(e){let t=on(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 tC={create:(e,t)=>LT(e.options,e.global,t),show:(e,t)=>NT(pt(e,"show"),e.options,t),"add-step":(e,t)=>MT(pt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=on(e,"update-step");return Oc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=on(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=on(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=eC(e);return qT(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=on(e,"remove-step");return KT(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=on(e,"link");return zT(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=on(e,"unlink");return BT(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Lc(pt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Lc(pt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Lc(pt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>HT(pt(e,"resume"),e.options,t),approve:(e,t)=>VT(pt(e,"approve"),e.options,t),materialize:(e,t)=>QT(pt(e,"materialize"),e.options,t)};function nC(e){let t=tC[e];if(!t)throw Pe({command_path:"plan",token:e,allowed:uT});return t}async function Th(e){let t=await AT(e.global),n=ZT(e);return nC(n.subcommand)(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b59e8e54-f9e0-5cdb-bc59-6dcbf67f278d")}catch{}})();function rC(e,t){return[...new Set([...qr.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,o)=>r.localeCompare(o))}function oC(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function qc(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await A(r),s=O(o,I()),i=await G(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!i)throw await at(r,e,o.id_prefix,s.type_to_folder);let a=await Q(i,{schema:o.schema}),c=a.document.metadata,m=k(),u=C(t.author,o.author_default),p=await nr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:s.type_to_folder,probeExisting:!1}),f=D(o.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let g={...c,id:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete g.closed_at,delete g.completed_at,delete g.close_reason,delete g.test_runs;let y=vt(I()),h=Tt({metadata:g,body:a.document.body},{schema:o.schema,extensionFieldNames:y}),b=await Pn({title:h.metadata.title,description:h.metadata.description,body:h.body,excludeIds:[i.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=rC(h.metadata,h.body),S=jt(r,h.metadata.type,p,o.item_format,s.type_to_folder),T=xe(r,p),x=await we(r,p,o.locks.ttl_seconds,u,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),U={metadata:{},body:""},N,ee;try{let z=await wn(r,u,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await Pn({title:h.metadata.title,description:h.metadata.description,body:h.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let le=await G(r,p,o.id_prefix,o.item_format,s.type_to_folder);if(le)throw new l(`Cannot copy to ${p}: an item with that id already exists at ${le.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${le.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await ge(S,it(h,{format:o.item_format,schema:o.schema,extensionFieldNames:y}));try{let ne=qe({nowIso:m,author:u,op:"create",before:U,after:h,message:oC(i.id,t.message)});await Ct(T,ne)}catch(ne){throw await mn(S),ne}ee=await vn({pmRoot:r,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:S,document:h})}finally{await z()}N=[...await W({path:S,scope:"project",op:"create",item_id:h.metadata.id,item_type:h.metadata.type,before:U,after:h,changed_fields:v}),...await W({path:T,scope:"project",op:"create:history",item_id:h.metadata.id,item_type:h.metadata.type,before:U,after:h,changed_fields:v})],fn({id:h.metadata.id,op:"create",item_type:h.metadata.type,status:h.metadata.status,current:Bt(h.metadata,v),changed_fields:v})}finally{await x()}return{source_id:i.id,item:structuredClone(h.metadata),changed_fields:v,warnings:[..._s(b),...ee,...N],...b===void 0?{}:{similarity_advisory:b}}}import ei from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7819b53c-b0e4-50b0-a670-f80b36765085")}catch{}})();async function Kc(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await A(r),s=C(t.author,o.author_default),i=await sp({pmRoot:r,settings:o,id:e,author:s,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?ei.relative(r,i.targetPath).split(ei.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:ei.relative(r,xe(r,i.item.id)).split(ei.sep).join("/"),tombstone_retention:"retain_append_only",warnings:i.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5ddb139-9780-50e0-87a5-621913cb0de4")}catch{}})();async function sC(e){await R(e)}async function zc(e,t,n){let r=E(process.cwd(),n.path);if(await sC(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=yn(C(void 0,p.author_default));return await Pu(r),await ps({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 Fo(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 iC(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let s=await A(r),i=O(s,I()),a=await G(r,e,s.id_prefix,s.item_format,i.type_to_folder);if(!a)throw await at(r,e,s.id_prefix,i.type_to_folder);let c=ve(a.id,s.id_prefix),m=await Q(a,{schema:s.schema}),u=Ch(m.document.metadata.title);return await Ou(r,c),await ps({pmRoot:r,settings:s,principal:yn(C(void 0,s.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function iC(e,t){let n=await A(e),r=O(n,I()),o=await G(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let s=await Q(o,{schema:n.schema});return Ch(s.document.metadata.title)}function Ch(e){return e.trim().length>0?e:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77fa2822-1681-59d5-8388-037cf13c45dd")}catch{}})();var Rh=new Set(["item_format"]),Ih=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"]),aC=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),cC=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),dC={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function lC(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(Rh.has(t)||Ih.has(t)||aC.has(t)||t==="context")return t}function mC(e){let t=e.trim().toLowerCase();return dC[t]??e}function xh(e,t){let n=lC(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."}:Rh.has(n)?{routable:!0,flag:"format",value:t}:Ih.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:cC.has(n)?mC(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="09703f32-9491-5d3a-9f90-f038d9982e17")}catch{}})();var uC=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Bc=128,pC=1e4;function Oh(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>Bc)throw new Error(`A legacy author must contain 1-${Bc} characters.`);return t}function fC(e){let t=e?.trim().toLowerCase();if(!t||!uC.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function _C(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function hC(e,t){let n=new Set;for(let r of(e??[]).slice(0,pC)){let o=r.trim().slice(0,Bc);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function gC(e,t){let n=Oh(t.legacy_author),r=fC(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function yC(e,t){if(t.operation==="add")return gC(e,t);if(t.operation==="remove"){let r=Oh(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function Hc(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function Ph(e,t){let n=e?.version??1,r={...e?.aliases},o=yC(r,t),s={version:o?n+1:n,aliases:_C(r)};return{vocabulary:s,preview:{operation:t.operation,changed:o,version_before:n,version_after:s.version,alias_count:Object.keys(s.aliases).length,residual_author_count:hC(t.observed_authors,s.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2f750f85-6c55-5f0f-b5c0-396764839d2a")}catch{}})();var Lh=["project","global"],ft={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},bC=Object.keys(ft).map(e=>ft[e][0]),wC=Object.fromEntries(Object.keys(ft).flatMap(e=>ft[e].map(t=>[t,e]))),vC={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},kC=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],SC=new Set(["metadata_required_fields",...kC]),EC=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),AC=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),TC=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),CC=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),RC=new Set(["governance_preset","governance_create_default_type"]),$h=e=>SC.has(e),IC=e=>TC.has(e),xC=e=>CC.has(e),OC=e=>RC.has(e);function Vc(e){return e==="definition_of_done"||$h(e)}function PC(e){if(Lh.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${Lh.join(", ")}`,d.USAGE)}function LC(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Pe({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function NC(e){let t=wC[e];if(t)return t;let n=Xi.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${bC.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function FC(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new 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 MC(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 Uh(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 DC(e){return Yc(e,"test-result-tracking")}function Yc(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,d.USAGE)}function Gh(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 Jc(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 jh(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 qh(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 Kh(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 zh(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 Bh(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 Hh(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 Vh(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)}var $C={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function Nh(e,t){let n=$C[e];if(n)return Yc(t,n);switch(e){case"history_missing_stream_policy":return Uh(t);case"sprint_release_format_policy":return Ca(t);case"parent_reference_policy":case"governance_parent_reference_policy":return Xo(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Jc(t);case"governance_preset":return jh(t);case"governance_ownership_enforcement":return qh(t);case"governance_create_mode_default":return Kh(t);case"governance_close_validation_default":return zh(t);case"governance_require_close_reason":return Vh(t);case"governance_workflow_enforcement":return Bh(t);case"governance_force_required_for_stale_lock":return Hh(t);case"telemetry_tracking":return Gh(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var Fh={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"},UC=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function GC(e,t){let n=[...new Set((e??[]).map(s=>s.trim()).filter(s=>s.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(s=>s.toLowerCase().replaceAll("-","_")),o=r.filter(s=>Fh[s]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${UC.join(", ")}`,d.USAGE);return[...new Set(r.map(s=>Fh[s]))].sort((s,i)=>s.localeCompare(i))}function jC(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,s)=>o.localeCompare(s));if(n){if(r.length>0)throw new l(`Config set ${ft[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${ft[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function qC(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function KC(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 NC(t)}function Wh(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var zC={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>Hc(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function Xc(e,t){return zC[t](e)}function Ce(e,t){return t.length===0?e:{...e,warnings:t}}async function BC(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):nt(n),o=me(r);return e==="project"&&await R(r),{pmRoot:r,settingsPath:o}}function HC(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 Mh(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 VC(e,t,n,r,o){let s=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!zi.includes(c))throw new l(`Context --default-depth must be one of ${zi.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,s=!0)}if(t.activityLimit!==void 0){let c=Mh(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,s=!0)}if(t.staleThresholdDays!==void 0){let c=Mh(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,s=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of a){let u=HC(m);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,s=!0)}}return s&&await Oe(n.pmRoot,e,"config:set:context"),Ce({scope:r,key:"context",context_settings:{default_depth:i.default_depth,activity_limit:i.activity_limit,stale_threshold_days:i.stale_threshold_days,sections:{...i.sections}},settings_path:n.settingsPath,changed:s},o)}function WC(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 YC(e,t,n,r,o,s){if(o===void 0)return s;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 WC(t,o,s);Wh(n);let i=xh(n,o);if(!i.routable)throw new l(i.reason,d.USAGE);if(i.flag==="criterion"){if(s.criterion!==void 0&&s.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...s,criterion:i.values}}if(i.flag==="format")return{...s,format:i.value};if(s.policy!==void 0&&Nh(n,s.policy)!==Nh(n,i.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${s.policy}". Pass only one.`,d.USAGE);return{...s,policy:i.value}}function JC(e){let t=Object.keys(ft).map(r=>({key:r,aliases:ft[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":Vc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:Vc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:vC[r],value:Xc(e.settings,r)})),n=Xi.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Qi(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 Ce({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function XC(e){let t=Object.fromEntries(Object.keys(ft).map(n=>[n,Xc(e.settings,n)]));return Ce({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function QC(e,t){let n=Xc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Ce({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Ce({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Ce({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Ce({...r,criteria:n},e.warnings):Ce({...r,policy:n},e.warnings)}async function ZC(e,t,n,r){if(t==="get"){let a=Qi(e.settings,n);return Ce({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new 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 s=Km(n,o);if(!s.ok)throw new l(s.error.message,d.USAGE);let i=Io(e.settings,n,s.parsed.value);return i&&await Oe(e.target.pmRoot,e.settings,`config:set:${n.path}`),Ce({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:s.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function Y(e,t,n){t&&await Oe(e.target.pmRoot,e.settings,n)}function Dh(e,t,n){return e!==n||t!==n}function ce(e,t,n,r){return Ce({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Wc(e,t,n,r){return Ce({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function eR(e,t){let n=MC(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let s=O(e.settings,I()),i=await kp(e.target.pmRoot,n,"config:set:item_format:migrate",s.type_to_folder,e.settings.schema);o={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await Oe(e.target.pmRoot,e.settings,"config:set:item_format")}return Ce({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function tR(e,t,n){if(t==="history_missing_stream_policy"){let s=Uh(n.policy),i=e.settings.history.missing_stream!==s;return e.settings.history.missing_stream=s,await Y(e,i,"config:set:history_missing_stream_policy"),ce(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let s=Ca(n.policy),i=e.settings.validation.sprint_release_format!==s;return e.settings.validation.sprint_release_format=s,await Y(e,i,"config:set:sprint_release_format_policy"),ce(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let s=Xo(n.policy),i=e.settings.validation.parent_reference!==s||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==s;return e.settings.validation.parent_reference=s,e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,await Y(e,i,"config:set:parent_reference_policy"),ce(e,t,e.settings.validation.parent_reference,i)}let r=Jc(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Y(e,o,"config:set:metadata_validation_profile"),ce(e,t,e.settings.validation.metadata_profile,o)}async function nR(e,t,n){if(t==="metadata_required_fields"){let a=GC(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 Y(e,c,"config:set:metadata_required_fields"),Wc(e,t,[...e.settings.validation.metadata_required_fields],c)}let o={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],s=jC(t,n.criterion,n.clearCriteria),i=s.length!==o.length||s.some((a,c)=>a!==o[c]);return o.splice(0,o.length,...s),await Y(e,i,`config:set:${t}`),Wc(e,t,[...o],i)}async function rR(e,t,n){if(t==="governance_preset"){let c=jh(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Y(e,m,"config:set:governance_preset"),ce(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Y(e,c,"config:set:governance_create_default_type"),ce(e,t,e.settings.governance.create_default_type??"",c)}if(o.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 s=O(e.settings,I()),i=ye(o,s);if(!i)throw new l(Et(o,s.types,At(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 Y(e,a,"config:set:governance_create_default_type"),ce(e,t,e.settings.governance.create_default_type,a)}async function oR(e,t,n){if(t==="governance_ownership_enforcement"){let s=qh(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==s;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=s,await Y(e,i,"config:set:governance_ownership_enforcement"),ce(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let s=Kh(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==s;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=s,await Y(e,i,"config:set:governance_create_mode_default"),ce(e,t,e.settings.governance.create_mode_default,i)}let r=zh(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Y(e,o,"config:set:governance_close_validation_default"),ce(e,t,e.settings.governance.close_validation_default,o)}async function sR(e,t,n){if(t==="governance_parent_reference_policy"){let s=Xo(n.policy),i=e.settings.governance.preset!=="custom"||Dh(e.settings.governance.parent_reference,e.settings.validation.parent_reference,s);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,e.settings.validation.parent_reference=s,await Y(e,i,"config:set:governance_parent_reference_policy"),ce(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let s=Jc(n.policy),i=e.settings.governance.preset!=="custom"||Dh(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,s);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=s,e.settings.validation.metadata_profile=s,await Y(e,i,"config:set:governance_metadata_validation_profile"),ce(e,t,e.settings.governance.metadata_profile,i)}let r=Bh(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Y(e,o,"config:set:governance_workflow_enforcement"),ce(e,t,e.settings.governance.workflow_enforcement,o)}async function iR(e,t,n){if(t==="governance_require_close_reason"){let a=Vh(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await Y(e,c,"config:set:governance_require_close_reason"),ce(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let o=Hh(n.policy)==="enabled",s=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==o;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=o,await Y(e,s,"config:set:governance_force_required_for_stale_lock"),ce(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",s)}async function aR(e,t,n){if(t==="test_result_tracking"){let a=DC(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await Y(e,c,"config:set:test_result_tracking"),ce(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}if(t==="untrusted_linked_test_execution"){let a=Yc(n.policy,"untrusted-linked-test-execution")==="enabled",c=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await Y(e,c,"config:set:untrusted_linked_test_execution"),ce(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",c)}let o=Gh(n.policy)==="enabled",s=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await Y(e,s,"config:set:telemetry_tracking"),ce(e,t,e.settings.telemetry.enabled?"enabled":"disabled",s)}async function cR(e,t,n){let r=FC(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((s,i)=>s!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await Y(e,o,"config:set:definition_of_done"),Wc(e,t,[...e.settings.workflow.definition_of_done],o)}function dR(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",d.USAGE)}function lR(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',d.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",d.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",d.USAGE);return{}}async function mR(e,t){let{operation:n,dryRun:r}=dR(t.policy),o=lR(n,t.value),s;try{s=Ph(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(i){throw new l(i.message,d.USAGE)}return s.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:s.vocabulary},await Y(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${s.preview.version_after}`)),Ce({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:Hc(r?e.settings.agent_identity?.identity_vocabulary:s.vocabulary),vocabulary_mutation:s.preview,settings_path:e.target.settingsPath,changed:s.preview.changed&&!r},e.warnings)}async function uR(e,t,n){if(n.clearCriteria===!0&&!Vc(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?eR(e,n):t==="context"?VC(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?mR(e,n):t==="definition_of_done"?cR(e,t,n):$h(t)?nR(e,t,n):EC.has(t)?aR(e,t,n):AC.has(t)?iR(e,t,n):IC(t)?oR(e,t,n):xC(t)?sR(e,t,n):OC(t)?rR(e,t,n):tR(e,t,n)}async function Yh(e,t,n,r,o,s){let i=PC(e),a=LC(t),c=a==="get"||a==="set"?Ro(n):void 0,m=c?void 0:KC(a,n),u=YC(a,n,m,c,s,r),p=await BC(i,o),{settings:f,metadata:_,warnings:g}=await Qu(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:qC(g)};return c?ZC(y,a,c,u):a==="list"?JC(y):a==="export"?XC(y):(Wh(m),a==="get"?QC(y,m):uR(y,m,u))}import KR from"node:fs/promises";import J from"node:path";import zR from"node:readline/promises";import{stdin as BR,stdout as Fe}from"node:process";import Zc from"node:fs/promises";import de from"node:path";import pR from"node:readline/promises";import{stdin as fR,stdout as ti}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]="542cd5ac-e4a7-51fe-8521-d0bacd9e6a07")}catch{}})();var Xh=["ask","add","skip","status"],_R=["AGENTS.md","CLAUDE.md"],hR=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],gR=8,ed=1,yR="<!-- pm-cli:agent-guidance:start:",bR=`<!-- pm-cli:agent-guidance:start:v${ed} -->`,Qc="<!-- pm-cli:agent-guidance:end -->",Sr="Add workflow guidance later: pm init --agent-guidance add";var wR=()=>pR.createInterface({input:fR,output:ti});function vr(e,t){let n=de.relative(e,t);return n.length===0?de.basename(t):n.split(de.sep).join("/")}function Jh(e){return e.endsWith(`
7
7
  `)?e:`${e}
8
- `}function vI(e){return e.includes(`\r
8
+ `}function vR(e){return e.includes(`\r
9
9
  `)?`\r
10
10
  `:`
11
- `}function Vh(e){let t=e.indexOf(yI);if(t===-1)return null;let n=e.indexOf(Jc,t);return n===-1?null:{start_index:t,end_index:n+Jc.length}}function kI(e){return Vh(e)!==null}function SI(e,t="<your project test command>"){return[bI,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Jc,""].join(e)}function EI(e,t="<your project test command>"){let n=vI(e),r=SI(n,t),o=Vh(e);if(o){let a=e.slice(o.end_index),c=a.startsWith(`\r
11
+ `}function Qh(e){let t=e.indexOf(yR);if(t===-1)return null;let n=e.indexOf(Qc,t);return n===-1?null:{start_index:t,end_index:n+Qc.length}}function kR(e){return Qh(e)!==null}function SR(e,t="<your project test command>"){return[bR,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Qc,""].join(e)}function ER(e,t="<your project test command>"){let n=vR(e),r=SR(n,t),o=Qh(e);if(o){let a=e.slice(o.end_index),c=a.startsWith(`\r
12
12
  `)?a.slice(2):a.startsWith(`
13
- `)?a.slice(1):a,m=Bh(`${e.slice(0,o.start_index)}${r}${c}`);return{next_content:m,changed:m!==e}}let s=e.length===0?"":e.endsWith(`
13
+ `)?a.slice(1):a,m=Jh(`${e.slice(0,o.start_index)}${r}${c}`);return{next_content:m,changed:m!==e}}let s=e.length===0?"":e.endsWith(`
14
14
  `)?`
15
15
  `:`
16
16
 
17
- `,i=Bh(`${e}${s}${r}`);return{next_content:i,changed:i!==e}}async function AI(e){if(await P(ce.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Xc.readFile(ce.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=TI(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await P(ce.join(e,"pnpm-lock.yaml"))?"pnpm test":await P(ce.join(e,"bun.lock"))||await P(ce.join(e,"bun.lockb"))?"bun run test":await P(ce.join(e,"yarn.lock"))?"yarn test":"npm test"}function TI(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function CI(e,t){let n=ce.dirname(e);return ce.basename(e)==="pm"&&ce.basename(n)===".agents"?ce.dirname(n):ce.resolve(t,e)}function II(e,t){let n=e.find(o=>ce.basename(o.file_path)==="AGENTS.md"&&o.exists);if(n)return n.file_path;let r=e.find(o=>o.exists);return r?r.file_path:ce.join(t,"AGENTS.md")}function RI(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 xI(e){let t=wI();try{Qs.write(`
17
+ `,i=Jh(`${e}${s}${r}`);return{next_content:i,changed:i!==e}}async function AR(e){if(await P(de.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Zc.readFile(de.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=TR(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await P(de.join(e,"pnpm-lock.yaml"))?"pnpm test":await P(de.join(e,"bun.lock"))||await P(de.join(e,"bun.lockb"))?"bun run test":await P(de.join(e,"yarn.lock"))?"yarn test":"npm test"}function TR(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function CR(e,t){let n=de.dirname(e);return de.basename(e)==="pm"&&de.basename(n)===".agents"?de.dirname(n):de.resolve(t,e)}function RR(e,t){let n=e.find(o=>de.basename(o.file_path)==="AGENTS.md"&&o.exists);if(n)return n.file_path;let r=e.find(o=>o.exists);return r?r.file_path:de.join(t,"AGENTS.md")}function IR(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 xR(e){let t=wR();try{ti.write(`
18
18
  Agent guidance check
19
- `),Qs.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
20
- `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return Qs.write(`
21
- `),RI(n,!0)}finally{t.close()}}function Wh(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:Qc,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 Yh(e){let t=[];for(let n of _I){let r=ce.join(e,n),o=await P(r);if(!o){t.push({file_path:r,exists:o,has_guidance:!1,has_marker:!1});continue}let s=await Xc.readFile(r,"utf8"),i=s.toLowerCase(),a=hI.filter(m=>i.includes(m)),c=kI(s);t.push({file_path:r,exists:o,has_guidance:c||a.length>=gI,has_marker:c})}return t}function Sr(e,t){e.includes(t)||e.push(t)}function OI(e,t){let n=Wh(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function PI(e,t=ce.dirname(e)){let r=await P(e)?await Xc.readFile(e,"utf8"):"",o=EI(r,await AI(t));return o.changed?(await he(e,o.next_content),{changed:!0,warnings:await W({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function LI(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=>wr(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>wr(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>wr(e.projectRoot,t.file_path))}}async function NI(e,t,n){return e?await Yh(n):t}function vr(e,t,n){e.state={...e.state,...n,template_version:Qc,last_checked_files:t}}async function Jh(e,t){if(t.presentBefore)return;let n=await PI(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function FI(e,t){t||(e.warnings.push("agent_guidance:missing"),Sr(e.nextSteps,kr))}function MI(e,t){e.skipped=!0,vr(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Sr(e.nextSteps,kr)}async function DI(e,t){await Jh(e,t),vr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function $I(e,t){e.state.declined&&vr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function UI(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Sr(e.nextSteps,kr)}async function GI(e,t){if(e.prompted=!0,await xI(t.targetRelativePath)){await Jh(e,t),vr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,vr(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Sr(e.nextSteps,kr)}function jI(e){e.warnings.push("agent_guidance:missing_non_interactive"),Sr(e.nextSteps,kr)}async function qI(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(FI(n,t.presentBefore),n):t.mode==="skip"?(MI(n,t.checkedFiles),n):t.mode==="add"?(await DI(n,t),n):t.presentBefore?($I(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(UI(n),n):t.interactive?(await GI(n,t),n):(jI(n),n)}async function Xh(e){let t=CI(e.pm_root,e.cwd),n=await Yh(t),r=II(n,t),o=wr(t,r),s=n.map(u=>wr(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await qI(Wh(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:o,checkedFiles:s,presentBefore:i,projectRoot:t}),c=OI(e.settings,a.state);return n=await NI(a.applied,n,t),{summary:LI({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:o,prompted:a.prompted,applied:a.applied,skipped:a.skipped,state:a.state}),warnings:a.warnings,next_steps:a.nextSteps,settings_changed:c.changed}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d06d4db7-8ab7-5a9f-84df-508bd305ea23")}catch{}})();var ed=Symbol.for("pm.sdk.init-invocation-cwd");var HI=()=>zI.createInterface({input:BI,output:Le});function VI(){return structuredClone(wt)}var WI=["minimal","default","strict"];function Zh(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: ${WI.join(", ")}`,d.USAGE)}function YI(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return Pm(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${Om.join(", ")}`,d.USAGE)}}}function JI(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 Zc(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:J.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function XI(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(o!==void 0){if(t.path!==void 0||Zc(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=J.resolve(e,o),u=J.join(m,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:m}}}if(t.path===void 0&&Zc(n)){let m=J.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let s=E(e,t.path),i=J.join(J.resolve(e),".agents","pm"),a=J.dirname(J.dirname(s)),c=J.resolve(s)===i?"current":"ancestor";return{pmRoot:s,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:s,workspace_root:a,discovery:c,requested_cwd:J.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:s}}}function QI(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(Zc(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&&It(e)!==It(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 ${It(e)}`,`pm init --id-prefix ${It(t)}`]});return t}function ZI(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: ${Hh.join(", ")}`,d.USAGE)}function eR(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function eg(e,t){let n=il[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function tR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nR(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(tR).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function rR(e,t,n){let r=Ao(t.schema),o=ot(e,r.files.types,rt.types),i=Rm(await z(o)),a=[],c=[];for(let m of Lm(n)){let u=xm(i,m);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await We({pmRoot:e,filePath:o,raw:So(i),op:"init:type-preset",author:C(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:o}}async function oR(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",J.join(".agents","pm")];for(let n of t)if(await P(J.join(e,n)))return!0;return!1}async function sR(e,t,n){if(!t||n||await P(J.join(e,"settings.json"))||!await oR(e))return;let r=J.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 tg(e,t){let n=[],r=[];for(let o of t){let s=o?J.join(e,o):e,i=await P(s);await KI.mkdir(s,{recursive:!0}),i?r.push(`already_exists:${s}`):n.push(s),r.push(...await W({path:s,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function iR(e,t){let n=HI();try{Le.write(`pm init setup wizard (agent-optimized)
22
- `),Le.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
19
+ `),ti.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
20
+ `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return ti.write(`
21
+ `),IR(n,!0)}finally{t.close()}}function Zh(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:ed,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 eg(e){let t=[];for(let n of _R){let r=de.join(e,n),o=await P(r);if(!o){t.push({file_path:r,exists:o,has_guidance:!1,has_marker:!1});continue}let s=await Zc.readFile(r,"utf8"),i=s.toLowerCase(),a=hR.filter(m=>i.includes(m)),c=kR(s);t.push({file_path:r,exists:o,has_guidance:c||a.length>=gR,has_marker:c})}return t}function Er(e,t){e.includes(t)||e.push(t)}function OR(e,t){let n=Zh(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function PR(e,t=de.dirname(e)){let r=await P(e)?await Zc.readFile(e,"utf8"):"",o=ER(r,await AR(t));return o.changed?(await ge(e,o.next_content),{changed:!0,warnings:await W({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function LR(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=>vr(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>vr(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>vr(e.projectRoot,t.file_path))}}async function NR(e,t,n){return e?await eg(n):t}function kr(e,t,n){e.state={...e.state,...n,template_version:ed,last_checked_files:t}}async function tg(e,t){if(t.presentBefore)return;let n=await PR(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function FR(e,t){t||(e.warnings.push("agent_guidance:missing"),Er(e.nextSteps,Sr))}function MR(e,t){e.skipped=!0,kr(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Er(e.nextSteps,Sr)}async function DR(e,t){await tg(e,t),kr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function $R(e,t){e.state.declined&&kr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function UR(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Er(e.nextSteps,Sr)}async function GR(e,t){if(e.prompted=!0,await xR(t.targetRelativePath)){await tg(e,t),kr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,kr(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Er(e.nextSteps,Sr)}function jR(e){e.warnings.push("agent_guidance:missing_non_interactive"),Er(e.nextSteps,Sr)}async function qR(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(FR(n,t.presentBefore),n):t.mode==="skip"?(MR(n,t.checkedFiles),n):t.mode==="add"?(await DR(n,t),n):t.presentBefore?($R(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(UR(n),n):t.interactive?(await GR(n,t),n):(jR(n),n)}async function ng(e){let t=CR(e.pm_root,e.cwd),n=await eg(t),r=RR(n,t),o=vr(t,r),s=n.map(u=>vr(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await qR(Zh(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:o,checkedFiles:s,presentBefore:i,projectRoot:t}),c=OR(e.settings,a.state);return n=await NR(a.applied,n,t),{summary:LR({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:o,prompted:a.prompted,applied:a.applied,skipped:a.skipped,state:a.state}),warnings:a.warnings,next_steps:a.nextSteps,settings_changed:c.changed}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d06d4db7-8ab7-5a9f-84df-508bd305ea23")}catch{}})();var nd=Symbol.for("pm.sdk.init-invocation-cwd");var HR=()=>zR.createInterface({input:BR,output:Fe});function VR(){return structuredClone(wt)}var WR=["minimal","default","strict"];function og(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: ${WR.join(", ")}`,d.USAGE)}function YR(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return Nm(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${Lm.join(", ")}`,d.USAGE)}}}function JR(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 td(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:J.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function XR(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(o!==void 0){if(t.path!==void 0||td(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=J.resolve(e,o),u=J.join(m,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:m}}}if(t.path===void 0&&td(n)){let m=J.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let s=E(e,t.path),i=J.join(J.resolve(e),".agents","pm"),a=J.dirname(J.dirname(s)),c=J.resolve(s)===i?"current":"ancestor";return{pmRoot:s,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:s,workspace_root:a,discovery:c,requested_cwd:J.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:s}}}function QR(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(td(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&&Rt(e)!==Rt(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 ${Rt(e)}`,`pm init --id-prefix ${Rt(t)}`]});return t}function ZR(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: ${Xh.join(", ")}`,d.USAGE)}function eI(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function sg(e,t){let n=cl[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function tI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nI(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(tI).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function rI(e,t,n){let r=To(t.schema),o=st(e,r.files.types,ot.types),i=Om(await K(o)),a=[],c=[];for(let m of Fm(n)){let u=Pm(i,m);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await Je({pmRoot:e,filePath:o,raw:Eo(i),op:"init:type-preset",author:C(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:o}}async function oI(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",J.join(".agents","pm")];for(let n of t)if(await P(J.join(e,n)))return!0;return!1}async function sI(e,t,n){if(!t||n||await P(J.join(e,"settings.json"))||!await oI(e))return;let r=J.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 ig(e,t){let n=[],r=[];for(let o of t){let s=o?J.join(e,o):e,i=await P(s);await KR.mkdir(s,{recursive:!0}),i?r.push(`already_exists:${s}`):n.push(s),r.push(...await W({path:s,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function iI(e,t){let n=HR();try{Fe.write(`pm init setup wizard (agent-optimized)
22
+ `),Fe.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
23
23
 
24
- `),Le.write(`1/3 Item ID prefix
25
- `),Le.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
26
- `);let r=await n.question(`Item ID prefix [${e}]: `),o=r.trim().length>0?It(r):e;Le.write(`
24
+ `),Fe.write(`1/3 Item ID prefix
25
+ `),Fe.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
26
+ `);let r=await n.question(`Item ID prefix [${e}]: `),o=r.trim().length>0?Rt(r):e;Fe.write(`
27
27
  2/3 Governance preset
28
- `),Le.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
29
- `),Le.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
30
- `),Le.write(`strict: ownership blocking, strict create defaults, close validation strict.
31
- `);let s=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),i=s.trim().length>0?s.trim():"minimal",a="minimal";try{a=Zh(i)}catch{Le.write(`Unrecognized governance preset "${i}"; using minimal.
32
- `)}Le.write(`
28
+ `),Fe.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
29
+ `),Fe.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
30
+ `),Fe.write(`strict: ownership blocking, strict create defaults, close validation strict.
31
+ `);let s=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),i=s.trim().length>0?s.trim():"minimal",a="minimal";try{a=og(i)}catch{Fe.write(`Unrecognized governance preset "${i}"; using minimal.
32
+ `)}Fe.write(`
33
33
  3/3 Project telemetry
34
- `),Le.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
35
- `);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=eR(m,t);return Le.write(`
36
- `),{prefix:o,preset:a,telemetry_enabled:u}}finally{n.close()}}function aR(e){return{presetFromOption:Zh(e.preset),useDefaults:e.defaults===!0,authorFromOption:JI(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:ZI(e.agentGuidance),typePreset:YI(e.typePreset)}}function cR(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function dR(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function lR(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(eg(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function mR(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=cR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return dR(e.settingsPath,n,e.options.force===!0,e.target),lR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Re(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function uR(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await iR(t,wt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let s=n??"minimal",i=VI();i.id_prefix=t,eg(i,s);let a=Fo()?.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 Re(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function Qh(e){return e.settingsExists?await mR(e):await uR({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function pR(e){let t=await Xh({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 Re(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function fR(e,t){let n=[],r=[],o=await Mm(e,t.schema);for(let s of o.created_paths)n.push(s),r.push(...await W({path:s,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function _R(e){if(e.typePreset===void 0)return;let t=await rR(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await W({path:t.file,scope:"project",op:"init:type_preset"})),t}async function hR(e){let n=O(e.settings,R()).folders.filter(o=>!Ki.includes(o)),r=await tg(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function gR(e){let t=J.resolve(e.tracker_root),n=J.dirname(t);return J.basename(t)==="pm"&&J.basename(n)===".agents"?J.dirname(n):e.workspace_root}async function yR(e,t,n,r){if(!e)return;let o=await In("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let s=nR(o),i=s.packages.filter(a=>!a.ok).map(a=>a.alias);if(!s.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 s}function bR(e){let t=r=>xo([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function wR(e,t,n,r=zp){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function vR(e,t,n,r){if(e==null||n==="status")return;let o=await ua(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Er(e,t,n={}){let r=t[ed],o=typeof r=="string"?r:process.cwd(),s=XI(o,t,e,n.workspace),i=s.pmRoot;e=QI(s.prefixArg,n.idPrefix);let a=aR(n);await sR(i,s.target.mode==="tracker-path",n.force===!0);let c=[],m=[],u=J.join(i,"settings.json"),p=await P(u),f;p&&(f=await Qh({pmRoot:i,settingsPath:u,settingsExists:p,normalizedPrefix:It(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:s.target}));let _=await tg(i,Ki);c.push(..._.createdDirs),m.push(..._.warnings),f??=await Qh({pmRoot:i,settingsPath:u,settingsExists:p,normalizedPrefix:It(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:s.target});let{settings:h}=f,y=gR(s.target),g=await rs(y??J.dirname(i)),b=y??g,v=await pR({pmRoot:i,cwd:b??o,agentGuidanceMode:a.agentGuidanceMode,settings:h,warnings:m}),S=await fR(i,h);c.push(...S.createdDirs),m.push(...S.warnings);let T=await _R({pmRoot:i,settings:h,typePreset:a.typePreset,warnings:m});T&&(h=await A(i)),await hR({pmRoot:i,settings:h,createdDirs:c,warnings:m}),await vR(b,i,a.agentGuidanceMode,m),!p&&n.mergeFence!==!1&&a.agentGuidanceMode!=="status"&&await wR(i,g,m);let x=await yR(a.installBundledPackages,t,i,m),G=bR({installBundledPackages:a.installBundledPackages,registeredTypePreset:T,agentGuidanceNextSteps:v.next_steps,target:s.target});return{ok:!0,path:i,target:s.target,settings:h,created_dirs:c,warnings:m,governance_preset:h.governance.preset,wizard_used:f.wizardUsed,...T?{registered_type_preset:T}:{},...x?{installed_packages:x}:{},next_steps:G,agent_guidance:v}}import IR from"node:fs/promises";import rd 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 rg=10,on="https://schema.unbrained.dev/pm/eval-query-set/v1";var Zs={schema:on,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Ke=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},kR=new Set(["keyword","semantic","hybrid"]);function ng(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function SR(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),o=ng(r,n),s=Array.from({length:t.size},()=>1),i=ng(s,n);return i===0?0:o/i}function ER(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function td(e,t,n){let r=Math.min(n,e.length),o=0;for(let s=0;s<r;s+=1)t.has(e[s])&&(o+=1);return o}function AR(e,t,n){return n<=0?0:td(e,t,n)/n}function TR(e,t,n){return t.size===0?0:td(e,t,n)/t.size}function og(e,t,n){return{ndcg:SR(e,t,n),mrr:ER(e,t,n),precision:AR(e,t,n),recall:TR(e,t,n),relevant_total:t.size,retrieved_relevant:td(e,t,n)}}function sg(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function CR(e,t){if(typeof e!="object"||e===null)throw new Ke(`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 Ke(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Ke(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(s=>typeof s!="string"))throw new Ke(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(s=>s.trim()).filter(s=>s.length>0))];if(o.length===0)throw new Ke(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!kR.has(n.mode)))throw new Ke(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function nd(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==on)throw new Ke(`Unsupported eval query set schema; expected "${on}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new Ke('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Ke("Eval query set must contain at least one query");return{schema:on,queries:n.map((r,o)=>CR(r,o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cc9405b-d2b8-59aa-893f-54892595788a")}catch{}})();var RR=rd.join("search","eval-queries.json"),od={schema:on,examples:[JSON.stringify(Zs)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},xR=new Set(["keyword","semantic","hybrid"]),OR=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!xR.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},PR=e=>{if(e===void 0||e==="")return rg;let t=dl(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},LR=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},Lt=e=>Math.round(e*1e4)/1e4,NR=async e=>{try{return await IR.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...od,examples:[`echo '${JSON.stringify(Zs)}' > ${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,od)}},MR=e=>{try{return nd(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,od)}},DR=async e=>MR(FR(await NR(e),e)),$R=(e,t)=>t?rd.resolve(process.cwd(),t):rd.join(e,RR),UR=async(e,t,n,r)=>{let o=e.mode??t,i=(await ur(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=og(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:Lt(a.ndcg),mrr:Lt(a.mrr),precision:Lt(a.precision),recall:Lt(a.recall)}}},GR=(e,t,n,r)=>{let o=sg(n);return{k:e,query_count:t.length,aggregate:{ndcg:Lt(o.ndcg),mrr:Lt(o.mrr),precision:Lt(o.precision),recall:Lt(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||o.ndcg>=r}},ig=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=PR(e.k),o=OR(e.mode),s=LR(e.failUnder),i=$R(n,e.queries),a=await DR(i),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await UR(u,o,r,t);m.push(f),c.push(p)}return GR(r,c,m,s)};import{readFile as jR,writeFile as qR}from"node:fs/promises";import KR 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]="5dc5f70c-0b04-51bb-983b-49b15be11587")}catch{}})();var ag=["item","history","relationship","json"];function zR(e){let t=e.trim().toLowerCase();if(ag.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${ag.join(", ")}.`,d.USAGE)}function BR(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 sd(e,t){try{return await jR(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function HR(e){let t=E(process.cwd(),e.path);return await P(de(t))?A(t):null}function VR(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function cg(e,t){let n=zR(e.artifact),r=BR(e.prefer),o=KR.resolve(e.outputPath??e.oursPath),[s,i,a]=await Promise.all([sd(e.basePath,"base"),sd(e.oursPath,"ours"),sd(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=lf(s,i,a);c=_.merged,p.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=mf(s,i,a);c=_.merged,p.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await HR(t),h=VR(e.itemPath??o,_),y=vt(R()),g=uf(s,i,a,{format:h,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"});if(c=g.merged,u.push(...g.conflict_fields),p.item={fields_from_theirs:g.fields_from_theirs,union_fields:g.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let b=Mu(c,{format:h,schema:_?.schema,extensionFieldNames:y}),v=b.metadata,S=[...new Set([...g.fields_from_theirs,...g.union_fields,...g.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:g.fields_from_theirs,unionFields:g.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,df(T==="body"?b.body:v[T])])),decisions:g.conflict_decisions}}}else{let _=pf(s,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await qR(o,c,"utf8"),m!==void 0){let _=await ff(m);_!==null&&(p.receipt=sr(_))}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 value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&p.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:u.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:k()}}import{readFile as WR}from"node:fs/promises";import YR 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]="3a3372be-37e4-578a-8be9-9ad7bc585dbd")}catch{}})();var JR=4;function dg(e){let t=e.checks.find(a=>a.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,s=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,i=Array.isArray(o)?o.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:s,coordinates:i}}async function XR(e,t){let n=[];for(let r of t){let o;try{o=await WR(YR.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let s=o.split(/\r?\n/)[r.history_line-1];if(s===void 0||s.trim().length===0)continue;let i;try{i=JSON.parse(s)}catch{continue}let a=wf(i,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!bf(a)||a.eventTimestamp===void 0||Lo(a.eventTimestamp,yf)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function QR(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;let t=new Map;for(let n of e.candidates){let r=t.get(n.item_id)??[];r.push(n),t.set(n.item_id,r)}for(let[n,r]of t)await ir(n,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:r.map(o=>({receipt_id:o.receipt_id,original_history_line:o.history_line,original_event_ts:o.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function ZR(e){try{return{status:"fulfilled",value:await ir(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function ex(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function tx(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>hf(e.gitWorkspaceRoot??process.cwd(),r,{requireExisting:!0}))),n.length}async function lg(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await ar(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),s=dg(o),i=await XR(r,s.coordinates),a=await rs(r),c=await _f(a??process.cwd(),{includeLossless:!0,pmRoot:r});if(c.invalid_evidence_count>0)throw new l(`Merge reconciliation refused ${c.invalid_evidence_count} invalid receipt evidence file(s).`,d.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let m=await QR({candidates:i,options:e,global:t}),u=c.receipts,p=new Map;for(let N of u){let se=p.get(N.item_id)??[];se.push(N),p.set(N.item_id,se)}let f=Object.fromEntries([...p].map(([N,se])=>[N,{merge:{receipts:se.map(sr)}}])),_=Object.fromEntries([...p].map(([N,se])=>[N,{gitWorkspaceRoot:a,receipts:se}])),h=await os({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:f,...u.length>0?{mergeReceiptProofById:_}:{}},t),y=new Set(h.streams.map(N=>N.id)),g=[...p.keys()].filter(N=>!y.has(N)),b=await cf(g,JR,N=>ZR({id:N,dryRun:n,options:e,global:t,auditContext:f[N],mergeReceiptProof:_[N]}));ex({receiptOnlyIds:g,results:b,repair:h});let v=await tx({dryRun:n,pendingReceipts:u,repair:h,gitWorkspaceRoot:a}),S=await cs({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),T=m===0?o:await ar(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),x=dg(T),G=S.checks.every(N=>N.status==="ok"),F=n?u.length===0:v===u.length,X=[h.totals.failed===0,G,F,x.count===0,!x.truncated].every(Boolean),K=s.truncated||x.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,pe=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",K,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:X?["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.",K,...i.length>0&&m===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(N=>N!==void 0);return{ok:X,dry_run:n,repair:h,receipts:{pending_before:u.length,reconciled:v,summaries:u.map(sr),missing_history_references_before:s.count,legacy_disposition_eligible:i.length,legacy_disposition_recorded:m,missing_history_references_after:x.count},validation:S,guidance:pe,generated_at:S.generated_at}}import{createHash as nx}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01043e67-99d4-5b68-a1b2-33f35f5cef5f")}catch{}})();var pg=1,fg=/^[A-Za-z0-9_-]+$/,rx=100,mg=1e3;var iq=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function ze(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function ox(e){return nx("sha256").update(qt({type:ze(e.type),author:ze(e.author),item:ze(e.item),harness:ze(e.harness),agent_instance:ze(e.agentInstance),provenance:ze(e.provenanceFilter)})).digest("hex").slice(0,24)}function ug(e,t){let n={version:pg,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 sx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===pg,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 ix(e,t){let n=e.trim();if(n.length===0||n.length>4096||!fg.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(!sx(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function ax(e){let t=e??rx;if(!Number.isSafeInteger(t)||t<0||t>mg)throw new l(`Mutation event limit must be an integer from 0 to ${mg}.`,d.USAGE,{code:"invalid_event_limit"});return t}function cx(e,t){let n=e?.trim();if(!n)return{};if(fg.test(n))return{cursor:ix(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 dx(e,t){let n=await _a(e,t);if(n===null){if(!await Du(e))return{...await $u(e,t),source:"authoritative_history"};n=await _a(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 lx(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 ei(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=ax(e.limit),r=lx(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 o=await A(t),s=o.agent_identity.identity_vocabulary,i=kp(o.agent_identity.harness_signals),a=Sp({provenance:e.provenanceFilter},i),c=ze(e.harness),m=ox(e),{cursor:u,sinceTimestamp:p}=cx(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:ze(e.type),authors:ze(e.author),harnesses:c,harness_alias_authors:c?Object.entries(s.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:ze(e.agentInstance),provenance:[...a].map(([y,g])=>({dimension:y,values:[...g]})),stream_ids:ze(e.item),limit:n},_=await dx(t,f),h=_.events.map(y=>({...r==="row"?{cursor:ug(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:Ep(y.entry,s,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:ug(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Ap(_.events.map(y=>y.entry),s,i)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c7c75b13-7317-5089-9869-7e6e22ed95b2")}catch{}})();var mx="1h",ux="now",px="+1d";function Nt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function _g(e,t,n){let r={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};return ve(n,r)}async function hg(e,t,n,r){let o=_g(e,t,n),s=[];return Nt(s,"start",n.start??ux),n.end!==void 0?Nt(s,"end",n.end):Nt(s,"duration",n.duration??mx),Nt(s,"location",n.location),Nt(s,"timezone",n.timezone),n.allDay===!0&&Nt(s,"all_day","true"),o.event=[s.join(",")],Pt(o,r)}function gg(e,t,n){return hg("Meeting",e,t,n)}function yg(e,t,n){return hg("Event",e,t,n)}function bg(e,t,n){let r=_g("Reminder",e,t),o=[];return Nt(o,"at",t.at??px),Nt(o,"text",t.text??e),r.reminder=[o.join(",")],Pt(r,n)}import Tr from"node:crypto";import{cp as vg,lstat as bx,mkdir as sn,readFile as $n,readdir as ad,rename as Eg,rm as dd,writeFile as ni}from"node:fs/promises";import D from"node:path";import{constants as Ft}from"node:os";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1c74b5a9-67b8-597c-98de-a4487691081f")}catch{}})();var wg=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"}]]),fx=/^[a-z][a-z0-9_]{0,63}$/u,_x=new Map([[Ft.errno.EACCES,"EACCES"],[Ft.errno.EDQUOT,"EDQUOT"],[Ft.errno.EMFILE,"EMFILE"],[Ft.errno.ENFILE,"ENFILE"],[Ft.errno.ENOMEM,"ENOMEM"],[Ft.errno.ENOSPC,"ENOSPC"],[Ft.errno.EPERM,"EPERM"],[Ft.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),hx={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function gx(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&wg.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:_x.get(Math.abs(t.errno))??null}function yx(e,t,n={}){let r=gx(e);if(r===null)return null;if(!fx.test(t))throw new l("Host environment operation labels must be bounded identifiers.",d.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=wg.get(r);return new l(`Host filesystem operation ${t} ${o.summary}.`,d.GENERIC_FAILURE,{code:n.codes?.[o.category]??hx[o.category].code,reason:r,required:o.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[o.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function ti(e,t,n={}){try{return await t()}catch(r){throw yx(r,e,n)??r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2580e043-8675-5070-b57e-30cae333228c")}catch{}})();var Ag="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var Tg=D.join("runtime","workspace-snapshots"),wx=new Set(["checkpoints","locks","runtime","search","transactions"]),vx=/^[a-z0-9][a-z0-9._-]*$/,Ar="sdk-workspace-transaction",id={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Cg={renameEntry:Eg,removeEntry:async e=>{await dd(e,{recursive:!0,force:!0})}},cd=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await $n(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==Ar||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await he(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
37
- `)}};async function Ig(e,t=""){let n=await ad(D.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((s,i)=>s.name.localeCompare(i.name))){if(t.length===0&&wx.has(o.name))continue;let s=D.posix.join(t.replaceAll(D.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${s}`);if(o.isDirectory())r.push(...await Ig(e,s));else if(o.isFile())r.push(s);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${s}`)}return r}async function Rg(e){let t=await Ig(e),n=Tr.createHash("sha256"),r=[],o=0;for(let i of t){let a=await $n(D.join(e,i));r.push(a),o+=a.byteLength,n.update(i),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let s=n.digest("hex");return{manifest:{schema:Ag,fingerprint:s,files:t,bytes:o},contents:r}}function kg(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
38
- `).filter(t=>t.trim().length>0).length}async function kx(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),s=await Promise.all(o.map(async i=>[i,await $n(D.join(e,i))]));for(let[i,a]of s)n.set(i,a)}return n}function ld(e){if(!vx.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 xg(e,t){return ti(`workspace_snapshot_${e}`,t,{codes:{capacity:id.capacity.code,permission:id.permission.code,resource:id.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function an(e){return D.join(e,Tg)}function Og(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 Pg(e,t){try{return JSON.parse(await $n(e,"utf8"))}catch(n){throw kt(n)?Og(t):n}}async function Sg(e,t,n){try{await dd(e,{recursive:n})}catch(r){throw kt(r)?Og(t):r}}async function Sx(e,t,n=Cg){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 Ex(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(s){throw await r.renameEntry(n,t),await r.removeEntry(e),s}await r.removeEntry(n)}async function Ax(e,t){return ld(t),/^[a-f0-9]{64}$/.test(t)?t:(await Pg(D.join(an(e),"refs",`${t}.json`),t)).fingerprint}async function md(e,t={}){if(t.name!==void 0&&(ld(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new 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 Rg(e),o=an(e),s=D.join(o,"objects",n.fingerprint),i=!1;try{i=(await bx(s)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&kt(a)))throw a}if(!i){let a=D.join(o,"objects",`.create-${process.pid}-${Tr.randomUUID()}`);await xg("create_object",async()=>{await sn(D.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=D.join(a,"files",m);await sn(D.dirname(u),{recursive:!0}),await ni(u,r[c])}await ni(D.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
39
- `,"utf8"),await sn(D.dirname(s),{recursive:!0})}),i=await Sx(a,s)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=D.join(o,"refs");await sn(c,{recursive:!0});let m=D.join(c,`.ref-${process.pid}-${Tr.randomUUID()}`);await ni(m,`${JSON.stringify(a,null,2)}
40
- `,"utf8"),await Eg(m,D.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function Cr(e,t){let n=await Ax(e,t),r=await Pg(D.join(an(e),"objects",n,"manifest.json"),t);if(r.schema!==Ag||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 ud(e){let t=an(e),n=await ad(D.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&kt(o))return[];throw o}),r=await ad(D.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&kt(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Cr(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await $n(D.join(t,"refs",o),"utf8"))))}}async function pd(e,t){let n=await Cr(e,t),{manifest:r,contents:o}=await Rg(e),s=new Map(r.files.map((p,f)=>[p,o[f]])),i=await kx(D.join(an(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),m=new Set([...a,...c]);for(let p of m){let f=s.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=kg(s.get(p)),_=kg(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 Lg(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",o=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,i=await be(e,Ar,o,r,!1,!1,s),a=new cd(Br(e,Ar),r,o);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await pd(e,t),f=await Cr(e,t),_=await md(e),h=f.fingerprint,y=an(e),g=D.join(y,"objects",h,"files"),b=D.dirname(e),v=D.basename(e);c=D.join(b,`.${v}.restore-${Tr.randomUUID()}`);let S=D.join(b,`.${v}.backup-${Tr.randomUUID()}`);await xg("restore_stage",async()=>{await sn(c,{recursive:!0}),await vg(g,c,{recursive:!0,force:!1}),await sn(D.join(c,"runtime"),{recursive:!0}),await vg(y,D.join(c,Tg),{recursive:!0,force:!1})});let T=await Hu({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:p.changed_file_count,removed_file_count:p.removed_file_count,removed_item_count:p.removed_item_count,affected_history_stream_count:p.affected_history_stream_count,removed_history_entry_count:p.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:s}),x=D.relative(c,T.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let G=Br(c,Ar);return await sn(D.dirname(G),{recursive:!0}),await ni(G,await $n(Br(e,Ar)),{flag:"wx"}),m=!0,await Ex(c,e,S,Cg,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:x,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([dd(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function Ng(e,t){ld(t);let n=an(e);if(!/^[a-f0-9]{64}$/.test(t))return await Sg(D.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await ud(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Sg(D.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]="41227e35-6354-5208-997b-e8a1cf696bf9")}catch{}})();function Ir(e){let t={...e.args,...e.options};return ve(e.options,t)}function ft(e,t){let n=w(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Un(e){return typeof e=="string"?[e]:ke(e)}function Fg(e){return ig(Ir(e),e.global)}function Mg(e){let t=Ir(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 ei({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Un(t.type),author:Un(t.author),item:Un(t.item),limit:t.limit===void 0?void 0:Me(t.limit,"limit"),full:t.full===!0,cursorMode:r,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Un(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Un(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Un(t.provenanceFilter)}})}function Dg(e){let t=Ir(e),n=ft(t,"subcommand");if(n==="install")return Kp({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return lg({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return gf({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return cg({artifact:ft(t,"artifact"),basePath:ft(t,"basePath"),oursPath:ft(t,"oursPath"),theirsPath:ft(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw xe({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function $g(e){let t=Ir(e),n=ft(t,"subcommand");if(n==="position")return Kf(e.global);if(n!=="snapshot")throw xe({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??ft(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return md(o,{name:w(t,"name")});if(r==="list")return ud(o);let s=ft(t,"target");if(r==="inspect")return Cr(o,s);if(r==="delete")return Ng(o,s);if(r==="restore")return t.dryRun===!0?pd(o,s):Lg(o,s,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Me(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Me(t.lockWaitMs,"lockWaitMs")});throw xe({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function ri(e){let t=Ir(e),n=ft(t,"title");return e.action==="meet"?gg(n,t,e.global):e.action==="event"?yg(n,t,e.global):bg(n,t,e.global)}import $x from"node:path";import Tx from"node:fs/promises";import Ug from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5c70da27-21f6-5d31-b506-96e1818996d6")}catch{}})();var Cx="templates",Ix=".json",Rx=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,xx=Ro.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),Ox=new Set(xx);function Px(e){let t=e.trim();if(!Rx.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 Gg(e){return Ug.join(e,Cx)}function jg(e,t){return Ug.join(Gg(e),`${t}${Ix}`)}async function Lx(e){await I(e)}function qg(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function Nx(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(Ox.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(s=>typeof s=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return qg(t)}function Fx(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[o,s]of Object.entries(n)){let i=o.trim();if(i.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof s=="string"){r[i]=s;continue}if(Array.isArray(s)&&s.every(a=>typeof a=="string")){r[i]=[...s];continue}throw new l(`Template "${t}" contains invalid value for option "${i}".`,d.GENERIC_FAILURE)}return qg(r)}function Mx(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,o=Fx(r.options,t),s=k();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:s,updated_at:typeof r.updated_at=="string"?r.updated_at:s,options:o}}async function Dx(e,t){let n=await z(jg(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return Mx(n,t)}async function fd(e,t,n){let r=E(process.cwd(),n.path);await Lx(r);let o=Px(e),s=Nx(t);if(Object.keys(s).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let i=k(),a=jg(r,o),c=i;await P(a)&&(c=(await Dx(r,o)).created_at);let m={name:o,created_at:c,updated_at:i,options:s},u=await A(r);return await Tx.mkdir(Gg(r),{recursive:!0}),await We({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
41
- `,op:"templates:save",author:C(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]="f65b4f1f-5501-5829-a04b-d4fbcfb59f5c")}catch{}})();var Hg=["list","show","apply","lint"],Ux="schema-types",Gx="schema-statuses",jx="schema-fields";function oi(){let e=R();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Vg(){let{profiles:e,warnings:t}=Nm(oi());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:Um(n.definition)})),warnings:t,generated_at:k()}}function Wg(e){let t;try{t=Eo(e,oi())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...Gm(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function Yg(e){let t;try{t=Eo(e,oi())}catch(o){throw new l(o instanceof Error?o.message:String(o),d.USAGE)}let{resolved:n}=t,r=iu(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:k()}}function qx(e,t){return $x.join(e,"templates",`${t}.json`)}async function Kx(e,t){let n=await z(qx(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function Kg(e,t,n,r){let o=new Map;for(let s of r.templates){let i=await Kx(e,s.name);i!==void 0&&o.set(s.name,i)}return{typesRaw:await z(ot(e,t.files.types,rt.types)),statusesRaw:await z(ot(e,t.files.statuses,rt.statuses)),fieldsRaw:await z(ot(e,t.files.fields,rt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Gn(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function zg(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Gn(t.types.changes),statuses:Gn(t.statuses.changes),fields:Gn(t.fields.changes),workflows:Gn(t.workflows.changes.map(s=>({key:s.type,status:s.status}))),config:Gn(t.config.changes),templates:Gn(t.templates.changes.map(s=>({key:s.name,status:s.status}))),packages:t.packages,warnings:[...new Set(o)].sort((s,i)=>s.localeCompare(i)),generated_at:k()}}async function zx(e){await I(e)}function Bx(e){try{let t=Eo(e,oi());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function Jg(e,t,n){let r=E(process.cwd(),n.path);await zx(r);let o=Bx(e),s=o.profile,i=o.warnings,a=t.dryRun===!0,c=await A(r),m=Ao(c.schema);if(a){let b=await Kg(r,m,c,s),v=Bg(s,b);return zg(s,v,!1,!0,[...i])}let u=C(t.author,c.author_default),p=Wu(c),f=!!t.force,_=[...i],h=[],y=async b=>{h.push(await be(r,b,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(Ux),await y(Gx),await y(jx);let b=await Kg(r,m,c,s);if(g=Bg(s,b),g.types.changed){let v=ot(r,m.files.types,rt.types);await We({pmRoot:r,filePath:v,raw:So(g.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(s.types.map(x=>Im(x).name)),T=g.types.file.definitions.filter(x=>S.has(x.name));await Yp(r,T,_,"profile:apply-type-folder"),_.push(...await W({path:v,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let v=ot(r,m.files.statuses,rt.statuses);await We({pmRoot:r,filePath:v,raw:$m(g.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await W({path:v,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let v=ot(r,m.files.fields,rt.fields);await We({pmRoot:r,filePath:v,raw:Fm(g.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await W({path:v,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let v of g.config.changes){if(v.status==="unchanged")continue;let S=Co(v.key);S!==void 0&&Io(c,S,v.value)}c.schema.type_workflows=g.workflows.result,await Re(r,c,"profile:apply-config")}for(let v of g.templates.changes)v.status!=="unchanged"&&await fd(v.name,{...v.options},n)}finally{for(let b of h.reverse())try{await b()}catch{}}return zg(s,g,g.changed,!1,_)}function Bg(e,t){try{return au(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import Qg from"node:fs/promises";import Zg 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 Hx(e,t,n){let r=new Set,o=[];for(let s of e){let i=s.trim();if(i.length===0||r.has(i))continue;r.add(i);let a=t.get(i);if(a===void 0){o.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){o.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return o}function Vx(e,t){let n=[...e].sort((o,s)=>s.entries-o.entries||o.id.localeCompare(s.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function Xg(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return Hx(t.ids,n,t.minEntries)}return Vx(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]="26c39ecd-5d72-5cc9-b22b-6abc33fbf4ac")}catch{}})();function Wx(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 s=Number.parseInt(n,10),i=vn(t);if(!Number.isSafeInteger(s)||s<i+1||s>i+t.length+1)throw new l(`history-compact --before version must be between ${i+1} and ${i+t.length+1}.`,d.USAGE);let a=s-i-1;return{kind:"version",raw:n,compactCount:a,retainedCount:t.length-a}}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 o=0;for(let[s,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 ${s+1}.`,d.GENERIC_FAILURE);if(a>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function Yx(e,t){let n=Do(),r=Do();for(let o=0;o<e.length;o+=1){let s=e[o];n=va(n,s.patch,o+1,s.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}async function Jx(e,t,n){let r=e.located?await Z(e.located,{schema:t.schema}):null;if(!r)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let o=n[n.length-1];return{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:Gu.some(s=>(o.item_hash_version===void 0||o.item_hash_version===s)&&Ku(Qn(r.document),s).includes(o.after_hash))}}function Xx(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 Qx(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 Zx(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=Yx(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=vn(e.historyEntries,!0),s=Ge({nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:Ht(Do()),after:Ht(t),message:Qx(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:ju(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),i=e.historyEntries[e.boundary.compactCount-1],a=[qu({...s,before_hash:e.historyEntries[0].before_hash,after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...r];return e.dryRun||a.push(Ge({nowIso:k(),author:e.author,op:"history_compact",before:Ht(n),after:Ht(n),message:Xx(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function eO(e){return ip({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})=>sp({historyPath:e.historyPath,nextHistoryRaw:Bu(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>W({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function _d(e,t,n){let r=E(process.cwd(),n.path);await I(r);let o=await A(r),s=O(o,R()),i=await ap(r,e,o,s.type_to_folder),a=i.historyPath,c=await z(a);if(c===null)throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let m=await yn(a,i.id);if(m.length===0)throw new l(`No history entries exist for ${i.id}; nothing to compact.`,d.USAGE);let u=ha(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=Wx(t.before,m),f=p.compactCount>0,_=!!t.dryRun,h=C(t.author,o.author_default),y=[];f||y.push("history_compact_noop_before_boundary");let g=await Jx(i,o,m);g.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:S}=Zx({historyEntries:m,boundary:p,changed:f,dryRun:_,author:h,options:t}),T=ha(b);if(!T.ok)throw new l(`history-compact produced an invalid rewritten chain (${T.errors.join(", ")}).`,d.GENERIC_FAILURE);f&&!_&&y.push(...await eO({pmRoot:r,subject:i,settings:o,typeRegistry:s,historyRawBeforeLock:c,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:h,force:t.force,loadedItem:g.loadedItem,historyPath:a,rewrittenEntries:b}));let x=vn(m,!0),G=p.retainedCount>0&&x!==null?x+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:G},history:{path:a,entries_scanned:m.length,entries_after:b.length,baseline_entry_added:v,audit_entry_added:S,verify_ok:T.ok,verify_errors:T.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:g.matchedChainBefore},warnings:[...new Set(y)].sort((F,X)=>F.localeCompare(X)),generated_at:k()}}var tO=3;function nO(e){let t=Yo(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:Wo(t)}}function ey(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 rO(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function oO(e){let t=$(e.settings.schema),n=ds(t),r=await le(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),s=Zg.join(e.pmRoot,"history"),i=[],a=[];if(!await P(s))return{candidates:i,preselectionErrors:a};let c=(await Qg.readdir(s)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=Zg.join(s,m),p=m.slice(0,-6);try{let f=await Qg.readFile(u,"utf8");await fn({path:u,scope:"project"}),i.push({id:p,entries:rO(f),bucket:o.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:i,preselectionErrors:a}}async function sO(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await _d(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function ty(e,t){let n=nO(e),r=E(process.cwd(),t.path);await I(r);let o=await A(r),s=O(o,R()),{candidates:i,preselectionErrors:a}=await oO({pmRoot:r,settings:o,typeToFolder:s.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??tO,u=o.history.compact_policy,p=c==="scan"&&e.allOver===void 0&&u.enabled,f=e.allOver??(p?u.max_entries:void 0),_=Xg(i,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),h=!!e.dryRun,y=[...a],g={streams_considered:i.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let b of _){let v=await sO({row:b,options:n,dryRun:h,global:t});if(y.push(v.result),!v.selected){g.items_skipped+=1;continue}g.selected+=1,v.compacted&&(g.items_compacted+=1),v.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:h,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:p},totals:g,results:y,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4888a558-7f50-5c28-8e29-fcd19180cbd4")}catch{}})();function ny(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return vf(n,t),t?os(e.options,e.global):ir(n,e.options,e.global)}function ry(e){let t=e.options.ids,n=Yo(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:Wo(n),o=Me(e.options.allOver??e.options.all_over,"history-compact allOver"),s=Me(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),i=w(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(i==="closed"||i==="all-streams")&&a.push(i);let c=[...new Set(a)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let m=c[0];return ey(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?_d(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):ty({ids:r,scope:m,allOver:o,minEntries:s,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function si(e){return To("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08dcee99-5572-5133-b76a-6a50e4e292e7")}catch{}})();async function hd(e,t,n,r){let o=t.trim();if(o.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",d.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let s=E(process.cwd(),r.path),i=$((await A(s)).schema),a=i.open_status,c=si(i),m=n.status??a,u=Q(m,i)??m;if(u!==a&&u!==c)throw new l(`Reopen target status must be ${a} or ${c}; received ${m}.`,d.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([a,c])],suggested_retry:`pm item reopen ${e} "${o}" --status ${a}`,suggested_retry_args:["item","reopen",e,o,"--status",a]}});let p=await rh(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:p.item,changed_fields:p.changed_fields,warnings:p.warnings,recurrence:p.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="55869854-565d-52d2-8dca-b66aade074bb")}catch{}})();function oy(e,t){let n=e.id??w(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function sy(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function iy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=De(e.args,e.options);return Ue(await dt(oy(e,r),sy(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function ay(e){let{changedFields:t,idOnly:n,runnerOptions:r}=De(e.args,e.options);return Ue(await hd(oy(e,r),sy(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2ef0de1-bc44-5550-862c-f3929334fbef")}catch{}})();function cy(e,t,n){let r;if(typeof e.lines=="string")r=ss(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");r=ss(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5ceccf7d-78cb-5750-8e4b-793efa6e716c")}catch{}})();var iO=oa("list").properties.outputSession,aO={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:{...iO},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},dy={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},oe={type:"string",description:"pm item id, for example pm-abc1."},cO=`Operation name (one of): ${Zi.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,dO={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."}},lO={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function U(e,t=[]){return{...dy,properties:{...dy.properties,...e},required:t}}var mO=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:U({action:{type:"string",enum:[...Zi],description:cO},id:oe,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...aO},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:U({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:U({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:U({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid, options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:U({query:{type:"string"},options:{type:"object"},...lO},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:U({options:{type:"object"},...dO})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:U({id:oe,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:U({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:U({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:oe,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:U({id:oe,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:U({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:oe,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:U({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:U({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:oe,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:U({id:oe,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:U({id:oe,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:U({id:oe,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:U({id:oe,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:U({id:oe,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:U({id:oe,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:U({subcommand:{type:"string",enum:[...Xm]},id:oe,target:oe,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:U({id:oe,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:U({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:U({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:U({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Schema mutations write workspace config files, not item history.",inputSchema:U({subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset"],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or custom field key (show-field/add-field/remove-field). Required for those subcommands."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...Mi]},description:`Lifecycle roles for add-status: ${Mi.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys."}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:U({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:U({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:U({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],uO={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"},pO=mO.map(e=>{let t=uO[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:oa(t,{properties:n,required:r})}});function ly(){return pO.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1506e8bc-3350-5ef5-a40a-44509eb59317")}catch{}})();var my=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"]]]),fO=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],vy=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ai=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"]),Rr=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"]),ky=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"]]),Sy=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"]]),Ey=new Map([...Sy.entries()].flatMap(([e,t])=>_t(t).map(n=>[n,e]))),Ay=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Ty=new Map(Ay.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),_O=10,hO=20,uy=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."]]),Cy=[["init",ql],["install",zl],["uninstall",Bl],["explore",Hl],["manage",Ql],["describe",Vl],["reload",Zl],["doctor",em],["catalog",tm],["adopt",nm],["adopt-all",Wl],["activate",Yl],["deactivate",Jl],["migrate",Xl]],gO=[...Cy.map(([e,t])=>e==="init"?[e,Kl]:[e,t]),["upgrade",Wn]],yO=[...Cy.map(([e,t])=>[`extension ${e}`,t]),...gO.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",to],["config",jl],["extension",no],["package",Vn],["packages",Vn],["install",rm],["create",co],["item mutate",km],["item complete",Sm],["item reopen",Em],["copy",lo],["focus",mo],["update",uo],["update-many",po],["upgrade",Wn],["calendar",Yn],["cal",Yn],["context",Jn],["ctx",Jn],["get",_o],["search",wo],["eval",Tm],["workspace",St],["workspace position",[]],["workspace snapshot",St],["workspace snapshot create",St],["workspace snapshot list",St],["workspace snapshot inspect",St],["workspace snapshot restore",St],["workspace snapshot delete",St],["next",bo],["aggregate",Xr],["deps",go],["graph",yo],["guide",ho],["reindex",om],["history",Qr],["history-compact",$l],["history-redact",Ml],["history-repair",Dl],["history-author-acknowledge",Zr],["merge",Fl],["schema",Ul],["profile",Gl],["plan",eo],["restore",am],["delete",cm],["close",sm],["close-many",ro],["append",oo],["claim",im],["release",dm],["start-task",lm],["pause-task",mm],["close-task",um],["comments",xl],["notes",Ol],["learnings",Pl],["files",Ll],["docs",Nl],["test",_m],["test-all",hm],["telemetry",gm],["test-runs",ym],["gc",bm],["stats",so],["duplicates",io],["validate",wm],["health",ao],["assurance",vm],...Cm,["contracts",vo],["completion",ko],["activity",fo],...[...vy].map(e=>[e,Jr])],wd=new Map(yO);function bO(e){let t=Ey.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function py(e){return Xi.includes(e)?_e(e):e.startsWith("extension-")?_e(`extension ${e.slice(10)}`):e.startsWith("package-")?_e(`package ${e.slice(8)}`):e.startsWith("item-")?_e(`item ${e.slice(5)}`):e.startsWith("test-runs-")?_e(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?_e(`templates ${e.slice(10)}`):ai.has(e)?Sy.get(e)??_e(e):null}function wO(e,t){return e.command_path===null?!1:_t(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `)||t.startsWith(`${n} `))}function _t(e){return e.split("|").map(t=>_e(t)).filter(t=>t.length>0)}function vO(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let s of _t(o.command_path)){let i=s.split(" ").filter(a=>a.length>0);if(i.length!==0)for(let a=i.length;a>0;a-=1){let c=i.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,s)=>o.localeCompare(s))}function ii(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function xr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function kO(e,t){if(!t)return{...e};let r=xr(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:r}}function gd(e,t){let r=xr(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function _e(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Iy(e){return e.replace(/\s+/g,"-")}function Je(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function fy(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=Je(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function yd(e,t,n){n&&(e[t]=!0)}function _y(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 SO(e){let t=_y(e.long,"long"),n=_y(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),yd(o,"required",e.required===!0),yd(o,"repeatable",e.repeatable===!0),yd(o,"list",e.list===!0);let s=Je(e.description);s&&(o.description=s);let i=Je(e.value_name);i&&(o.value_name=i);let a=[Je(e.value_type),Je(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(o.value_type=a),o}function Ry(e){let t=new Map;for(let r of e){let o=_e(r.target_command);if(o.length===0)continue;let s=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;s.sourceDedupe.has(i)||(s.sourceDedupe.add(i),s.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=SO(a);if(!c)continue;let m=`${c.flag}|${c.short??""}`;s.dedupe.has(m)||(s.dedupe.add(m),s.flags.push(c))}t.set(o,s)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((s,i)=>{let a=s.layer.localeCompare(i.layer);return a!==0?a:(s.name??"").localeCompare(i.name??"")})});return n}function EO(e){let t=Ry(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let i=_e(s.command);if(i.length===0)continue;let a=Je(s.action)??Iy(i),c=Array.isArray(s.arguments)?s.arguments.map(m=>{let u=Je(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:Je(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{command:i,action:a,source:{layer:s.layer,name:s.name},description:Je(s.description),intent:Je(s.intent),arguments:c,flags:t.get(i)?.flags??[],examples:fy(s.examples),failure_hints:fy(s.failure_hints)})}let r=new Set;for(let s of e.handlers)r.add(_e(s));for(let s of n.keys())r.add(s);for(let s of t.keys())r.add(s);let o=[];for(let s of[...r].sort((i,a)=>i.localeCompare(a))){let i=n.get(s);o.push(AO(s,i,t.get(s)?.flags??[]))}return o}function AO(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Iy(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function TO(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(o,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function CO(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 IO(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function RO(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=CO(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let s=TO(o);!s||n[s]!==void 0||(n[s]=IO(o,e.action),o.required===!0&&r.push(s))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function xO(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 OO(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((s,i)=>s.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let i=`${s.flag}|${s.short??""}`;if(!o.has(i))o.add(i),r.flags.push(s);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);a&&xO(a,s)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function PO(e,t=A){let n={mode:wt.extensions.policy.mode,trust_mode:wt.extensions.policy.trust_mode,default_sandbox_profile:wt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await P(de(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),s=await Vr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),i=await Wr({...s,loaded:s.loaded});return{handlers:new Set(i.commands.handlers.map(c=>_e(c.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function LO(e,t={}){let n=new Map;for(let r of Qi){let o=ai.has(r);if(o&&!t.includePackageOwnedActions)continue;let s=py(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:s})}if(t.includePackageOwnedActions)for(let r of ai)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:py(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:_e(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function NO(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?_t(e.command_path):[],r=n.some(i=>t.handlers.has(i)),o=n.map(i=>ky.get(i)).find(i=>typeof i=="string"),s=t.disabledReason===null&&r;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function xy(e){return wd.get(e)??Yr}function FO(e){return Rr.has(e)?!1:wd.has(e)}function MO(e){return vy.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function hy(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function DO(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function $O(e){let t=new Map;for(let r of e.definitions){let o=hy(r.cli_flag);if(!o)continue;let s=r.cli_aliases.map(a=>DO(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>hy(a)).filter(a=>a!==null&&a!==o);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=s?{flag:o,short:s}:{flag:o},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,o]of t.entries())n.set(r,Wi(o.flags));return n}function gy(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let s=`${o.flag}|${o.short??""}`;r.has(s)||(r.add(s),n.push(o))}return Wi(n)}function UO(e,t,n,r){return e.map(o=>{let s=FO(o),i=s?xy(o):[],a=n.get(MO(o))??[],c=t.get(o),m=gy(i,a),u=gy(m,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:o,flags:u,...r?{canonical_command:bd(o),visibility:vu(bd(o)),positionals:Cl(o)?.slots??[],flag_invocations:wu(o,u)}:{},provider:p,extension_sources:c?.sources}}).sort((o,s)=>o.command.localeCompare(s.command))}function GO(e,t=Hn){let n=new Set(e),r=new Map;for(let o of Ay){let s=o.aliases.filter(i=>n.has(i));r.set(o.canonical,{canonical:o.canonical,aliases:s,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let s=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};s.aliases.includes(o.alias)||s.aliases.push(o.alias),s.contracts.push(o),r.set(o.canonical,s)}return[...r.values()].map(({contracts:o,...s})=>o.length===0?s:{...s,contracts:o}).sort((o,s)=>o.canonical.localeCompare(s.canonical))}function jO(){return{create_string_options:cu,create_repeatable_options:Ro,update_string_options:du,update_repeatable_options:lu,list_string_options:kl,search_string_options:Sl,calendar_string_options:El,context_string_options:Al,activity_string_options:Tl}}function yy(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=mn(e,"create",n),o=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(o.map(a=>ye("create",a)))].sort((a,c)=>a.localeCompare(c)),i=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:o,required_flags:s,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function qO(e){let t={},n={};for(let r of[...e.types].sort((o,s)=>o.localeCompare(s))){let o=e.by_type[r];t[r]=yy(o,"strict"),n[r]=yy(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function KO(e,t){let n=xr(e);if(n.length===0)return e;let r=!1,o=n.map(s=>{let i=s.properties;if(typeof i!="object"||i===null)return s;let a=i.action;return typeof a!="object"||a===null||a.const!=="create"?s:(r=!0,{...s,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function zO(e){let t=ii(e.action)!==void 0||ii(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,s=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=ii(e.action),u=ii(e.command),p=!r&&!c&&!o&&!s&&!i&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:o,flagsOnly:s,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function BO(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 HO(e,t=A){try{return await t(e)}catch{return structuredClone(wt)}}async function VO(e,t){let n=await HO(t),r=await PO(e),o=O(n,r.registrations??R()),s=Ve(n.schema),i=EO(r);return{settings:n,runtimeProbe:r,typeRegistry:o,statusRegistry:$(n.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:$O(s),createRequiredOptionContracts:qO(o),extensionContracts:i,mergedExtensionContracts:OO(i),extensionFlagMap:Ry(r.flagRegistrations)}}function by(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ai.has(e.selectedAction)||e.selectedCommand!==void 0&&Rr.has(e.selectedCommand))}function WO(e,t){let n=LO(t,{includePackageOwnedActions:by(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(eu);return n.filter(o=>!r.has(o.action))}return by(e)&&e.selectedCommand!==void 0&&Rr.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:bO(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function YO(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 JO(e,t){return[...new Set([...Xi.filter(n=>!Rr.has(n)),...[...wd.keys()].filter(n=>!Rr.has(n)),...e.flatMap(n=>n.command_path?_t(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>_e(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function XO(e,t){let n=t.slice(0,_O),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),s=t.slice(0,hO),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: ${o}.`,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:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function QO(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 ZO(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 eP(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(s=>s.startsWith(`${e.selectedCommand} `));if(r.length>0)throw XO(e.selectedCommand,r);let o=ky.get(e.selectedCommand);throw o?QO(e.selectedCommand,o):ZO(e.selectedCommand)}function tP(e,t){let n=WO(e,t.mergedExtensionContracts);YO(e,n);let r=JO(n,t.mergedExtensionContracts);eP(e,r);let o=e.selectedCommand?Ey.get(e.selectedCommand):void 0,s=e.selectedCommand?n.filter(m=>o?m.action===o:wO(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.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?s.filter(m=>m.action===e.selectedAction):s,a=[...new Map(i.map(m=>NO(m,t.runtimeProbe)).map(m=>[o?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:s,scopedActionDescriptors:i,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function nP(e){return new Set(xr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function rP(e){let t=su,n=xr(t),r=nP(t),o=e.filter(s=>!r.has(s.action)).map(s=>RO(s));return o.length>0?{...t,oneOf:[...n,...o]}:t}function wy(e,t,n){let r=new Set(t.actionDescriptors.map(s=>s.action)),o=e.selectedAction?kO(n,e.selectedAction):e.selectedCommand?gd(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):gd(n,r);return e.runtimeOnly&&!e.selectedAction?gd(o,new Set(t.actions)):o}function oP(e,t,n){let r=rP(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?KO(wy(e,n,r),t.createRequiredOptionContracts):wy(e,n,r);return{mergedSchema:r,filteredSchema:s}}function sP(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?vO(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function iP(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Hn.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function bd(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":Ty.get(t)??t}var aP=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"],["upgrade","Upgrade"]]),cP=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function dP(e,t){let n=uy.get(e)??(e.includes(" ")?void 0:uy.get(bd(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>_t(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 o=e.split(" "),s=o.at(-1),i=o.slice(0,-1).join(" "),a=aP.get(s),c=cP.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function lP(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(_e))].filter(s=>s.length>0).sort((s,i)=>s.localeCompare(i)).map(s=>{let i=ea(s,{generateFallback:!0}),a=s.split(" ")[0],c=Ty.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),m=new Set([...xy(s).map(f=>f.flag),...t.filter(f=>_t(f.command).includes(s)).flatMap(f=>f.flags.map(_=>_.flag))]),u=(my.get(s)??my.get(c)??fO).filter(f=>m.has(f)),p=dP(s,t);return{command:s,intent:p.intent,...o||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:i.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...i.default_max_estimated_tokens_by_format}}:{}}})}function mP(e){return e.map(t=>({budget:ea(t,{generateFallback:!0}),envelope:Eu(t)}))}function uP(e){let t=new Map;for(let n of e){let r=uu(n),o=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,s=o.join(","),i=t.get(s)??{commands:[],exit_codes:o};i.commands.push(n),t.set(s,i)}return[...t.values()]}function pP(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>_t(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>_t(o.command).some(s=>r.has(s)))}return t.extensionContracts}function fP(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 _P(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,s])=>[o,[...new Set(s.map(i=>`--${i.cli_flag}`))].sort((i,a)=>i.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Bm],services:[...Hm],policy_modes:[...Vm],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Jm],trust_modes:[...Wm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Ym],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...el],create_modes:[...tl],close_validation_modes:[...nl],workflow_enforcement_modes:[...rl]},e.relationship_kind_contracts=[...ll,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,s)=>o.kind.localeCompare(s.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function hP(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 gP(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=UO(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let s=new Set(r);e.list_projections=Object.entries(Cu).filter(([i])=>s.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...Tu],compact_fields:[...Au]}))}e.command_aliases=o}}function yP(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=jO();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function bP(e,t,n,r){e.command_summaries=lP(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...tu],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(_e))].filter(o=>na(o)!==void 0).sort((o,s)=>o.localeCompare(s)).map(o=>({command:o,modes:[...ru(o).keys()]}))}:{}},e.grammar_contracts={nouns:Kt.nouns,shared_verbs:Kt.shared_verbs,scope_before_verb:Kt.scope_before_verb,visible_top_level_ceiling:Kt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Kt.ceiling_raise_requires_pm_item,positional_shape_budget:Kt.positional_shape_budget,positional_shape_count:new Set(Vi.map(({slots:o})=>Rl(o))).size,positional_action_count:Hi.length,positional_action_parents:[...new Set(Hi.map(({parent:o})=>o))].sort((o,s)=>o.localeCompare(s)),...r.includePositionalSignatures?{positional_signatures:Vi}:{}}}async function Oy(e,t){let n=zO(e);BO(n);let r=E(process.cwd(),t.path),o=await VO(t,r),s=tP(n,o),i=oP(n,o,s),a=sP(n,s),c=iP(n,a),m=fP(n,i,s,c),u=pP(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&bP(m,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return m;let f=GO(s.commandCatalog);return n.flagsOnly&&!n.fullOutput||_P(m,o,n),hP(m,n,i,u),gP(m,n,o,c,f),yP(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...Rp],gate_triggers:[...Ip]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=Il),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=ly(),m.context_intents=hu(),m.read_output_dimensions=ta,m.error_codes=bu,m.command_output_contracts=mP(c),m.diagnostic_output_contracts=nu,m.command_exit_contracts={vocabulary:mu,command_sets:uP(c)}),m}import nL from"node:fs/promises";import Yy 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 ci(e,t,n,r,o,s="min"){let i=o==="min"?e-t:t-e,a=s==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&a<0}function wP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,s=null,i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let 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)||(ci(f,i,p,o,"min")&&(i=f,o=p),ci(f,a,p,s,"max","max")&&(a=f,s=p))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:s}}function Py(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:h})=>wP(_,h)),s=0,i=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of o){if(s+=_.lines,i+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);ci(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);ci(h,u,_.id,c?.id??null,"max")&&(u=h,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...o].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...o].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:s,total_bytes:i,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as kP}from"node:crypto";import{execFile as SP}from"node:child_process";import Fy from"node:path";import{promisify as EP}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 Ly=1;function vP(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function vd(e){if(e===null)return{format_version:Ly,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!==Ly||!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(!vP(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]="c2e1edc9-c454-5cfa-85c8-e9fb0a76a296")}catch{}})();var AP=EP(SP),TP=50,Ny=1e3,CP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function My(e){let t=e.trim().toLowerCase();if(!CP.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 IP(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 Or(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 RP(e){let t=e??TP;if(!Number.isSafeInteger(t)||t<0||t>Ny)throw new l(`Improvement observation limit must be an integer from 0 to ${Ny}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Dy(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 xP(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=My(n.metric),o=IP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let s=await PP(e,n.revision),i=Or(n.source,"source"),a=Or(n.itemId,"itemId"),c=Or(n.unit,"unit"),m=Or(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,r,i??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Dy(n.observedAt??k(),"observedAt"),...s,author:C(n.author,t.author_default),...a===void 0?{}:{item_id:a},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:kP("sha256").update(qt(u)).digest("hex").slice(0,24),...u}}function OP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new 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(o=>o.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 PP(e,t){let n=Or(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await AP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:cl(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function LP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function $y(e,t={}){let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await xP(n,r,e),s=Fy.join(n,"improvement-ledger.json"),i=await Vu({pmRoot:n,filePath:s,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=vd(a),m=OP(c,o);return m?{raw:a,result:m}:(c.observations.push(o),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${qt(c)}
42
- `,result:o})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function Uy(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await I(t);let n=e.metric===void 0?void 0:My(e.metric),r=e.since===void 0?void 0:Dy(e.since,"since"),o=RP(e.limit),i=vd(await z(Fy.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,o),total:i.length,truncated:i.length>o,trends:[...a].map(([,c])=>LP(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 Gy(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 NP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function FP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function kd(e=Xn,t=hn){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function MP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function Sd(e,t=hn,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let s of t){let i=`${o.agent_harness}\0${s}`,a=r.get(i)??{harness:o.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=o.agent_provenance?.[s];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(i,a)}return[...r.values()].map(o=>{let s=o.observed+o.unavailable;return{...o,coverage:s===0?null:o.observed/s,inert:s>=n&&o.observed===0}}).sort((o,s)=>o.harness.localeCompare(s.harness)||o.dimension.localeCompare(s.dimension))}function DP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let u=`${c.agent_harness}\0${m}`,p=o.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),o.set(u,p)}let s=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[u])=>m.localeCompare(u)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),i=s.filter(c=>c.entries>=r),a=i.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:i.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:s,failures:a}}function $P(e){let t=[...e].sort((s,i)=>s.ts.localeCompare(i.ts)||s.author.localeCompare(i.author)||s.op.localeCompare(i.op)||s.before_hash.localeCompare(i.before_hash)||s.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let s of t){let i=s.agent_episode,a=Gy(s),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(s);continue}let u={id:a.id,...i?.label===void 0?{}:{label:i.label},...i?.parent_id===void 0?{}:{parent_id:i.parent_id},source:a.source,entries:[s],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let o=[];for(let s of n.values()){let i=s.parent_id?r.get(s.parent_id):void 0;i&&NP(s,i,r)?i.children.push(s):o.push(s)}return FP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var UP=1e4,jy=1e5,GP=1e3,jP=30,qP=["append","comment","docs","file","learning","note","test_run"];function KP(e){let t=e??UP;if(!Number.isSafeInteger(t)||t<1||t>jy)throw new l(`History analytics event limit must be an integer from 1 to ${jy}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function qy(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 zP(e){let t=e?.trim();if(!t)return new Date(Date.now()-jP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*s).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new 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 Ky(e,t){let n=KP(t.eventLimit),r=zP(t.since),o=[],s=r,i=!1;for(;o.length<n;){let a=await ei({pmRoot:e,since:s,limit:Math.min(GP,n-o.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),i=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:i,...i?{next_cursor:s}:{},source:"history_event_index"}}}function BP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function HP(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 VP(e){return qP.some(t=>e.startsWith(t))}function zy(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 WP(e,t,n){let r=new Map,o=new Map,s=new Map;for(let i of t){let a=BP(i.entry,e),c=HP(i.entry),m=o.get(i.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&o.set(i.item_id,u),!a)continue;let p=zy(r,a);p.events+=1,VP(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,s.set(i.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:s}}function YP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of o){let i=t.get(s);i&&(zy(e,i).defectEscapes+=1)}}}function JP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function XP(e,t,n,r,o,s){let{buckets:i,lastCloseValue:a}=WP(e,t,r);return YP(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>JP(c,m,o,s)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function QP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),s=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(s)?1:Math.max(1,(s-o)/864e5)}function ZP(e,t,n){let r=kd(t),o=Sd(e,hn,n),s=o.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),i=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:o,inert:s,undeclared:i,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...i.map(a=>`provenance_dimension_undeclared:${a}`)]}}function By(e,t=Xn,n={}){let r=qy(n.minimumSample);return{...ZP(e.events.map(o=>o.entry),t,r),window:e.receipt}}function Hy(e,t,n,r={}){let o=qy(r.minimumSample),s=QP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>XP(i,e.events,t,n,o,s)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var eL=32;function tL(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let s=o.slice(0,o.indexOf("=")).trim();r.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Pr(e,t){let n=tL(e).map(o=>{let[s,...i]=o.split(","),a=s.indexOf("="),c=s.slice(0,a).trim(),m=s.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${o}"; 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(o=>[o.name,o])).values()].sort((o,s)=>o.name.localeCompare(s.name)).slice(0,eL)}function Vy(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function Wy(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,i)=>i.recorded_at.localeCompare(s.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b56db1fc-d989-5d18-8b29-336a03f1e525")}catch{}})();function rL(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function oL(e,t,n,r,o){let s=lr(e,"type",r),i=new Set(s.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),m=(o?[...s.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=rL([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>o||f>0));return{byType:m,byStatus:p,omitted:o?0:a.length+Object.values(u).filter(f=>f===0).length}}function sL(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function iL(e){let t=Yy.join(e,"history");if(!await P(t))return[];await fn({path:t,scope:"project"});let n=(await nL.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,s)=>o.localeCompare(s)),r=[];for(let o of n){let s=Yy.join(t,o),i=await z(s);i!==null&&(await fn({path:s,scope:"project"}),r.push({id:o.slice(0,-6),raw:i}))}return r}async function aL(e,t){let n=[],r=k();for(let o of Pr(t.observe,r))n.push(await $y({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function cL(e,t,n){let r={};return t.byAssignee&&(r.assignee=lr(e,"assignee",n)),t.byTag&&(r.tag=lr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=lr(e,"priority",n)),r}async function dL(e,t,n,r,o){let s={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},i=o.provenanceCoverage||o.fleetAttribution?await Ky(e,s):void 0;return{provenanceCoverage:o.provenanceCoverage&&i?By(i,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:o.fleetAttribution&&i?Hy(i,t,r,s):void 0}}function lL(e,t,n,r,o){let s=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...s?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:k()}}async function Ed(e,t={}){let n=E(process.cwd(),e.path);await I(n);let r=await A(n),o=await aL(e,t),s=O(r,R()),i=$(r.schema),a=t.fieldUtilization?await ep(n,r.item_format,s.type_to_folder,void 0,r.schema):await le(n,r.item_format,s.type_to_folder,void 0,r.schema);await Xu({pmRoot:n,settings:r,itemIds:a.map(S=>S.id),commandLabel:"stats"});let c=ds(i),m=oL(a,s.types,i.definitions.map(S=>S.id),c,t.includeEmpty===!0),u=await iL(n),p=0;for(let S of u)p+=sL(S.raw);let f=t.storage?Py(u):void 0,_=t.metadataCoverage?$f(a,c):void 0,h=cL(a,t,c),y=t.fieldUtilization?Uf(a):void 0,g=t.measurements===!0||o.length>0?await Uy({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:b,fleetAttribution:v}=await dL(n,a,r,i.terminal_statuses,t);return lL({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:o,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 Jy(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:ke(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 mL from"node:fs/promises";import Mt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad3110ca-e85b-5a7e-b0a1-591796c298eb")}catch{}})();var tb=Mt.join("runtime","telemetry","events.jsonl"),nb=Mt.join("runtime","telemetry","state.json"),uL=Mt.join("runtime","telemetry"),pL=20,Xy=["status","flush","stats","clear"],Qy=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Ad=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Zy=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},fL=e=>({command:Ad(e.event.command,"<unknown>"),eventType:Ad(e.event.event_type,"unknown"),eventSchemaVersion:Zy(e.event.schema_version),clientSchemaVersion:Zy(e.client_schema_version)}),_L=()=>({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:{}}),hL=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},gL=e=>{let t=e?.command_resolution;return Ad(t,"")||void 0},rb=(e,t)=>{e[t]=(e[t]??0)+1},yL=(e,t)=>{let n=hL(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=gL(t);r!==void 0&&rb(e.resolution_counts,r)},bL=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,eb=(e,t)=>{t!==void 0&&e.add(t)},wL=(e,t)=>{let n=fL(t),r=e.get(n.command)??_L();r.count+=1,r.max_attempts=Math.max(r.max_attempts,bL(t.attempts)),rb(r.event_type_counts,n.eventType),eb(r.event_schema_versions,n.eventSchemaVersion),eb(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&yL(r,t.event.payload),e.set(n.command,r)},vL=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((s,i)=>s-i),o=Object.entries(t.resolution_counts).sort((s,i)=>s[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,i)=>s[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,i)=>s-i),client_schema_versions:[...t.client_schema_versions].sort((s,i)=>s-i),...r.length>0?{duration_p50_ms:Qy(r,.5),duration_p95_ms:Qy(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},kL=e=>{let t=(e??"status").trim().toLowerCase();if(Xy.includes(t))return t;throw xe({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Xy,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Td=()=>{throw new l("--limit must be a positive integer",d.USAGE)},ob=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Td():e,SL=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Td():ob(Number.parseInt(t,10))},EL=e=>e===void 0?pL:typeof e=="number"?ob(e):typeof e=="string"?SL(e):Td(),AL=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},TL=e=>{try{let t=JSON.parse(e);return AL(t)?t:void 0}catch{return}},CL=e=>e===null?[]:e.split(`
43
- `).map(t=>t.trim()).filter(t=>t.length>0),sb=e=>{let t=CL(e),n=[],r=0;for(let o of t){let s=TL(o);s===void 0?r+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},IL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),RL=e=>{try{let t=JSON.parse(e);return IL(t)?t:{}}catch{return{}}},xL=async e=>{let t=await z(e);return t===null||t.trim().length===0?{}:RL(t)},di=e=>e??null,li=async e=>{let t=await A(e),n=Mt.join(e,tb),r=Mt.join(e,nb),o=await z(n),s=sb(o),i=await xL(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:di(i.last_attempted_flush_at),last_successful_flush_at:di(i.last_successful_flush_at),last_failed_flush_at:di(i.last_failed_flush_at),last_failed_flush_error:di(i.last_failed_flush_error)}},OL=e=>{let t=new Map;for(let n of e)wL(t,n);return[...t.entries()].map(([n,r])=>vL(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},PL=async(e,t)=>({action:"telemetry",subcommand:"status",status:await li(t.globalPmRoot),generated_at:k()}),LL=async(e,t)=>{let n=await li(t.globalPmRoot);await vp(t.globalPmRoot);let r=await li(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),s=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:s,queue_drained:s,status:r,generated_at:k()}},NL=async(e,t)=>{let n=EL(e.limit),r=await z(t.queuePath),o=sb(r),s=OL(o.entries),i=s.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:s.length>i.length,stats:i,generated_at:k()}},FL=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 Re(t.globalPmRoot,n,"telemetry:clear");let o=Mt.join(t.globalPmRoot,uL),s=await P(o);return await mL.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:s&&!await P(o),queue_exists_after:await P(t.queuePath),state_exists_after:await P(t.statePath),status:await li(t.globalPmRoot),generated_at:k()}},ML={status:PL,flush:LL,stats:NL,clear:FL};async function ib(e,t){let n=kL(e.subcommand),r=tt(process.cwd());return ML[n](e,{globalPmRoot:r,queuePath:Mt.join(r,tb),statePath:Mt.join(r,nb)})}import{spawn as Tb}from"node:child_process";import{cp as xd,mkdir as _i,mkdtemp as Cb,open as Od,readdir as Pd,rm as Lr,symlink as Ib}from"node:fs/promises";import{tmpdir as Rb}from"node:os";import H from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62af7c1e-c1c7-529e-ab30-117103ac4607")}catch{}})();var ab=20;function DL(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return ab;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?ab:t}function Cd(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let s=Lo(r.recorded_at,o.recorded_at);if(s!==0)return s;let i=r.run_id.localeCompare(o.run_id);return i!==0?i:r.kind.localeCompare(o.kind)}),n=DL();return t.length>n?t.slice(t.length-n):t}async function mi(e){await re({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=Cd([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a6a3402-dae3-56f8-b9ba-a4f6f8a47cda")}catch{}})();var cb=100;function Id(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 $L(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=cb?n:`${n.slice(0,cb-3)}...`}function db(e){return e.map((t,n)=>`${n+1}. ${$L(t)}`).join("; ")}function UL(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 GL(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function lb(e,t){let n=UL(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,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 o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let s=[],i=[];for(let a=0;a<e.length;a+=1)GL(e[a],o)&&(i.push(e[a]),s.push(a+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${db(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:s,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let o=Id(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${db(e)}`,d.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="03f2f710-3b96-5671-85fa-d8ea4726ee86")}catch{}})();var fi=20*1024*1024,jL=3e3,qL=1e4,KL=5e3,mb=120,zL=new Set(["locks","extensions","runtime"]),BL=new Set(["history","index","search","extensions","locks","runtime"]),HL=[/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],VL=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,WL=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,YL=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 Fd(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 JL(){return Fd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",jL)}function XL(){return Fd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",qL)}function QL(){return Fd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",KL)}function ZL(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 eN(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function Md(e){let t=0,n=0,r=0,o=0;for(let s of e){let i=s.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(r+=1),i.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function tN(e){let t=e??"project";if(!et.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function hi(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Xt.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${Xt.join(", ")}`,d.USAGE)}function nN(e){return Zt(e??"source","--workspace-context")}function xb(e,t,n){return n?t:Zt(e.workspace_context_mode,"linked test")??t}function Ob(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:hi(e.pm_context_mode)}function Pb(e,t){return e==="auto"?t?"tracker":"schema":e}function rN(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 oN(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 sN(e,t){let n={};if(!e)return n;for(let r of e){let o=yr(r,t);if(o)for(let[s,i]of Object.entries(o))n[s]=i}return n}function iN(e,t){if(!e)return[];let n=[];for(let r of e){let o=br(r,t);o&&n.push(...o)}return[...new Set(n)]}function aN(e){let t=gi(e);return cr(t).some(n=>Fa(n)!==null)}function Lb(e){let t=gi(e);return cr(t).some(n=>{let r=Fa(n);if(!r)return!1;let o=Pf(r);return o?YL.has(o.subcommand):!1})}function ui(e){if(e)return Rf.has(e.subcommand)?Rn(e.args,xf)?.subcommand:e.subcommand}function ub(e,t){if(e==="npx"||e==="bunx")return as(t)?.command;if(e==="pnpm")return ui(Rn(t,Af));if(e==="npm")return ui(Rn(t,Tf));if(e==="yarn")return ui(Rn(t,Cf));if(e==="bun")return ui(Rn(t,If))}function pi(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function Rd(e){return!e||!Da(e.command)&&!Of(e.command)?!1:is(e.args)==="test-all"}var Nb=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])]),cN=new Set(["npx","bunx"]);function Fb(e){let t=e.split(" ").filter(i=>i.length>0),n=Ma(t);if(n.length===0)return!1;let[r,...o]=n,s=Nb.get(r);if(s){let i=o.findIndex(a=>s.test(a));return i>=0?Fb(o.slice(i+1).join(" ")):!1}return Da(r)||$a(r)?is(o)==="test-all":r==="node"&&o.length>0&&$a(o[0])?is(o.slice(1))==="test-all":cN.has(r)?Rd(as(o)):r==="pnpm"?Rd(Ua(o)):r==="npm"?Rd(Ga(o)):!1}function Mb(e){let t=gi(e);return cr(t).some(n=>Fb(n))}function Db(e){if(Mb(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function gi(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function $b(e){let t=e.split(" ").filter(i=>i.length>0),n=Ma(t);if(n.length===0)return!1;let[r,...o]=n,s=Nb.get(r);if(s){let i=o.findIndex(a=>s.test(a));return i>=0&&$b(o.slice(i+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?dN(o):lN(r,o)}function dN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function lN(e,t){return e==="npx"||e==="bunx"?pi(as(t)?.command):e==="pnpm"||e==="npm"?pi((e==="pnpm"?Ua(t):Ga(t))?.command)||pi(ub(e,t)):(e==="yarn"||e==="bun")&&pi(ub(e,t))}function mN(e){if(Mb(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function uN(e){return e?e.map(pN):[]}function pN(e){let t=e.trim(),n=I_(t)?Os(ie(e,"--add"),"--add"):{command:t},r=ue(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return Db(r),{command:r,path:ue(n.path),scope:tN(n.scope),timeout_seconds:fN(ue(n.timeout_seconds),ue(n.timeout)),pm_context_mode:Ms(ue(n.pm_context_mode),"--add"),workspace_context_mode:Zt(ue(n.workspace_context_mode),"--add"),env_set:yr(ue(n.env_set),"--add"),env_clear:br(ue(n.env_clear),"--add"),shared_host_safe:Fs(ue(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:en(ue(n.assert_stdout_contains)),assert_stdout_regex:Nn(ue(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:en(ue(n.assert_stderr_contains)),assert_stderr_regex:Nn(ue(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Ds(ue(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:$s(ue(n.assert_json_field_equals),"--add"),assert_json_field_gte:Us(ue(n.assert_json_field_gte),"--add"),note:ue(n.note)}}function ue(e){let t=e?.trim();return t&&t.length>0?t:void 0}function fN(e,t){if(e&&t&&e!==t)throw new 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(me(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function _N(e){return e?e.flatMap(t=>{let n=O_(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",d.USAGE);Db(o)}return n}):[]}function hN(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 o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:o}}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 o=ie(n,"--remove"),s=o.path!==void 0?"path":"command",i=o.path??o.command;if(!i?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:s,value:i.trim()}}return{kind:"either",value:n}}):[]}function gN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function yN(e){try{e.stdin?.end()}catch{}}function Ub(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=mb?t:`${t.slice(0,mb-3)}...`}function Gb(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Ld(e){try{process.stderr.write(`${e}
44
- `)}catch{}}function bN(e,t){if(!Gb(t))return null;let n=Ub(e.command),r=Date.now();Ld(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let s=Date.now()-r;Ld(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},XL());return o.unref?.(),o}function wN(e,t,n,r){if(!Gb(r))return;let o=Ub(e.command),s=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let m=t.exitCode===null?"null":String(t.exitCode),u=c.length>0?` ${c.join(" ")}`:"";Ld(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${s}${u} command="${o}"`)}async function pb(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Tb("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function vN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function kN(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await pb(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{pb(r)},JL()),t.forceKillTimer.unref?.()}}function SN(e){return new Promise(t=>{let n=!1,r=null,o=(s,i=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,i)=>{n||(r=setTimeout(()=>{o({code:s,signal:i},!0)},QL()),r.unref?.())}),e.on("close",(s,i)=>{o({code:s,signal:i})})})}function EN(e,t,n,r,o){return Tb(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function fb(e){let t=await Od(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,fi),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>fi}}finally{await t.close()}}async function AN(e,t,n,r,o,s=process.cwd()){let i=Date.now(),a=await Cb(H.join(Rb(),"pm-linked-test-output-"));try{let c=H.join(a,"stdout.log"),m=H.join(a,"stderr.log"),[u,p]=await Promise.all([Od(c,"w"),Od(m,"w")]),f;try{f=EN(e,n,u.fd,p.fd,s)}catch(K){throw await Promise.all([u.close(),p.close()]),K}let _=SN(f),h;f.on("error",K=>{h=K.message}),await Promise.all([u.close(),p.close()]),yN(f);let y={heartbeat:bN(r,o),forceKillTimer:null,timedOutTimer:null},g=kN(f,y),b=!1;y.timedOutTimer=setTimeout(()=>{b=!0,g()},t),y.timedOutTimer.unref?.();let{code:v,signal:S}=await _;vN(y);let[T,x]=await Promise.all([fb(c),fb(m)]),G=T.truncated||x.truncated,F=G?`
45
- [pm linked-test output truncated at ${fi} bytes per stream; the child process continued to completion]
46
- `:"",X={stdout:`${T.text}${F}`,stderr:x.text,exitCode:v,signal:S,timedOut:b,maxBufferExceeded:!1,outputTruncated:G,spawnError:h};return wN(r,X,i,o),X}finally{await Lr(a,{recursive:!0,force:!0})}}function TN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${fi} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function CN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
47
- `);return HL.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>VL.test(n)&&WL.test(n))}function IN(e){return CN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function RN(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function yi(e){let t=RN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function _b(e,t){for(let[n,r]of Object.entries(t.env_set))Qt.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)Qt.has(n.toUpperCase())||delete e[n]}function xN(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function ON(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function PN(e,t,n){return{env_set:sN(e,"--env-set"),env_clear:iN(t,"--env-clear"),shared_host_safe:n===!0}}async function qn(e,t,n=!1,r=_i){if(await P(e))try{await ti("seed_linked_test",async()=>{if(await r(H.dirname(t),{recursive:!0}),n){await xd(e,t,{recursive:!0,force:!0});return}await xd(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&kt(o))return;throw o}}async function hb(e,t,n){await qn(de(n.projectPmRoot),de(e)),await qn(H.join(n.projectPmRoot,"extensions"),H.join(e,"extensions"),!0),await qn(de(n.globalPmRoot),de(t)),await qn(H.join(n.globalPmRoot,"extensions"),H.join(t,"extensions"),!0)}async function gb(e,t){if(!await P(e))return;let n=await Pd(e,{withFileTypes:!0});for(let r of n){if(zL.has(r.name))continue;let o=H.join(e,r.name),s=H.join(t,r.name);if(r.isDirectory()){await qn(o,s,!0);continue}r.isFile()&&await qn(o,s)}}async function yb(e,t){let n=await z(de(e));if(n===null||await P(ga(e)))return;let r=await A(t);await Lr(ga(t),{force:!0}),await Lr(de(t),{force:!0}),await We({pmRoot:t,filePath:de(t),raw:n,op:"settings:write",author:C(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function jn(e){if(!await P(e))return 0;let t=0,n=await Pd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||BL.has(r.name))continue;let o=H.join(e,r.name),s;try{s=await Pd(o,{withFileTypes:!0})}catch{continue}for(let i of s)i.isFile()&&al.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function LN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function NN(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let r of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isInteger(o)||o<0)return[];t.push(o);continue}t.push(r)}return t}function bb(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=NN(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let s of r){if(typeof s=="number"){if(!Array.isArray(o)||s>=o.length)return{found:!1,value:void 0};o=o[s];continue}if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,s))return{found:!1,value:void 0};o=o[s]}return{found:!0,value:o}}function FN(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function MN(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?nt(e,t):Object.is(e,t)}function DN(e,t,n){let r=[];r.push(...wb("stdout",t,e.assert_stdout_contains)),r.push(...vb("stdout",t,e.assert_stdout_regex)),r.push(...wb("stderr",n,e.assert_stderr_contains)),r.push(...vb("stderr",n,e.assert_stderr_regex)),r.push(...$N(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(s).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,m]of Object.entries(o)){let u=bb(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=FN(m);MN(u.value,p)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(u.value)})`)}for(let[c,m]of Object.entries(s)){let u=bb(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 wb(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function vb(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(s){r.push(`${e} regex assertion is invalid: /${o}/ (${s instanceof Error?s.message:String(s)})`)}return r}function $N(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var UN=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],GN=[/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu,/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu,/\bTests?\s+[1-9]\d*\s+passed\b/iu,/\b[1-9]\d*\s+passed\b/iu,/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu];function jN(e,t){let n=`${e}
48
- ${t}`;for(let r of UN)if(r.regex.test(n))return{code:r.code};return null}function qN(e,t){let n=`${e}
49
- ${t}`;return GN.some(r=>r.test(n))}function kb(e){let t=gi(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:cr(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&$b(n))}function KN(e){return{root:e,schemaProjectPmPath:H.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:H.join(e,"schema","global"),trackerProjectPmPath:H.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:H.join(e,"tracker","global"),workspaceSnapshotRoot:H.join(e,"workspace","project"),workspaceIsolatedRoot:H.join(e,"workspace","isolated")}}function zN(e,t,n){return e.some(r=>xb(r,t,n)==="snapshot")}async function BN(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await _i(H.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await xd(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(o){let s=H.relative(t,o);return s?!s.split(H.sep).some(i=>n.has(i)):!0}});let r=H.join(t,"node_modules");await P(r)&&await Ib(r,H.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function HN(e,t){let n=H.join(e,".agents"),r=H.join(n,"pm");await _i(n,{recursive:!0}),await Lr(r,{recursive:!0,force:!0}),await Ib(t,r,process.platform==="win32"?"junction":"dir")}async function VN(e,t=Er,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 WN(e,t,n){t&&(await hb(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await hb(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await gb(t.projectPmRoot,e.trackerProjectPmPath),await gb(t.globalPmRoot,e.trackerGlobalPmPath),await yb(t.projectPmRoot,e.trackerProjectPmPath),await yb(t.globalPmRoot,e.trackerGlobalPmPath)))}function YN(e,t,n){return e.some(r=>{let o=r.command??"",s=o.length>0&&Lb(o),i=n?.autoPmContext===!0&&s?"auto":Ob(r,t,n?.overrideLinkedPmContext===!0);return Pb(i,s)==="tracker"})}async function JN(e,t){return{sourceProjectItemCount:t?await jn(t.projectPmRoot):0,sourceGlobalItemCount:t?await jn(t.globalPmRoot):0,schemaProjectItemCount:await jn(e.schemaProjectPmPath),schemaGlobalItemCount:await jn(e.schemaGlobalPmPath),trackerProjectItemCount:await jn(e.trackerProjectPmPath),trackerGlobalItemCount:await jn(e.trackerGlobalPmPath)}}function XN(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:a,trust:e.trust}}async function QN(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?hi(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?aN(n):!1,o=r&&n?Lb(n):!1,s=e.options?.autoPmContext===!0&&o,i=s?"auto":Ob(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Pb(i,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await HN(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await ja(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await ja(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:XN({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function Sb(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Nd(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function ZN(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function eF(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return ZN(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function tF(e){if(!e.linkedTest.command)return Sb(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=mN(e.linkedTest.command);return t?Sb(e.linkedTest,e.executionContext,t):null}function nF(e){let t=tF(e);if(t)return t;let n=eF(e);if(n)return n;let r=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,o=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(r||o){let s=oN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),i=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Nd(e.linkedTest,e.executionContext,`${i} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${s}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!rN(e.linkedTest)?Nd(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function rF(e){let t=ON(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return _b(n,e.runtimeDirectives),_b(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&xN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[or]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[or]="read_only"),n}function oF(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 Eb(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.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function sF(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:LN(e.execution),failure_category:IN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:TN(e.execution,e.timeoutMs)}}function iF(e){if(e.options?.failOnEmptyTestRun===!0||kb(e.linkedTest.command??"")){let n=jN(e.execution.stdout,e.execution.stderr);if(n)return Eb({...e,emptyRunSignal:n});if(kb(e.linkedTest.command??"")&&!qN(e.execution.stdout,e.execution.stderr))return Eb({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let t=DN(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Nd(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):oF(e.linkedTest,e.executionContext,e.execution)}async function aF(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await AN(t,n,rF(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?iF({...e,execution:r}):sF({...e,execution:r,timeoutMs:n})}async function Dd(e,t,n){let r=[],o=await Cb(H.join(Rb(),"pm-linked-test-")),s=KN(o),i=hi(n?.pmContext),a=nN(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=PN(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,p=Nf(),f=YN(e,i,n),_=zN(e,a,n?.overrideLinkedWorkspaceContext===!0),h=await Lf(p);try{await VN(s,Er,f),await _i(s.workspaceIsolatedRoot,{recursive:!0}),await WN(s,u,f),_&&await BN(s,p);let y=await JN(s,u);for(let g=0;g<e.length;g+=1){let b=e[g],v=xb(b,a,n?.overrideLinkedWorkspaceContext===!0),S=await QN({linkedTest:b,layout:s,counts:y,sourceRoots:u,runLevelPmContextMode:i,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:v,currentSourceRef:h,sourceWorkspaceRoot:p}),T=nF({linkedTest:b,executionContext:S.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:S.linkedOverridePmContextMode,options:n});if(T){r.push(T);continue}r.push(await aF({linkedTest:b,index:g,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:S.executionContext,options:n}))}}finally{await Lr(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function cF(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,s=await j(n,t,r.id_prefix,r.item_format,o);if(!s)throw new l(`Item ${t} not found`,d.NOT_FOUND);let i=await Z(s,{schema:r.schema});return{itemId:s.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function dF(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function lF(e,t){let n=[...e];for(let r of t)n.some(o=>dF(o,r))||n.push(r);return n}function mF(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((s,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:o,removed:e.length-o.length}}function uF(e,t,n,r){return mF(lF(e,t),n,r)}function pF(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function fF(e){if(pF(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --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 _F(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:s,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return cF({id:t,pmRoot:r,settings:o,typeToFolder:s});let m=0,u=await re({pmRoot:r,settings:o,id:t,op:i.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=uF(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:nt(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 hF(e,t){fF(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Id(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?lb(t,n):void 0,o=e.timeout===void 0?void 0:me(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:hi(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function gF(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Dd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:tt(process.cwd())}})}function yF(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=Md(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function bF(e){let t=eN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=k(),s=Pr(e.options.measure,o);return{run_id:ZL("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function wF(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:s,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let m=bF({options:t,runStartedAt:s,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return m;try{return await mi({pmRoot:n,settings:r,itemId:o,author:C(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:${o}:${u instanceof Error?u.message:String(u)}`),m}}function Ab(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,o).trim(),i=e.metricBelow.slice(o+1).trim(),a=Number(i);if(o<=0||s.length===0||i.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",d.USAGE);r=Vy(t,s,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Wy(t,e.metricDiff)}}async function vF(e,t,n){if(e.acknowledgeLinkedTests===!0)return Ff(t,n,k())}async function bi(e,t,n){let r=xt(),o=E(process.cwd(),n.path);await I(o);let s=await A(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);Pr(t.measure,"validation"),Ab(t,[],void 0);let i=O(s,R()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...uN(a),..._N(c)],p=await xn(u,C(t.author,s.author_default),k())??[],f=hN(m),_=gN(t.removeIndex),h=await _F({id:e,options:t,pmRoot:o,settings:s,typeToFolder:i.type_to_folder,adds:p,removes:f,removeIndexes:_}),y=hF(t,h.tests),g=await vF(t,o,h.tests),b=t.run===!0?k():void 0,v=await gF({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests}),S=yi(v),T=t.run===!0&&t.failOnSkipped===!0&&v.some(K=>K.status==="skipped"),x=yF(t,y.runSelection,v);g&&x.push(`linked_test_trust_acknowledged:${g.acknowledged}`);let G=await wF({options:t,pmRoot:o,settings:s,itemId:h.itemId,runStartedAt:b,runResults:v,failOnSkippedTriggered:T,warnings:x}),F=G?Cd([...h.testRuns,G]):h.testRuns,X=Ab(t,F,G);return{ok:v.every(K=>K.status!=="failed")&&T!==!0,id:h.itemId,tests:h.tests,run_results:v,failure_categories:S,selection:y.runSelection?{selector:y.runSelection.selector,requested:y.runSelection.requested,selected_indexes:y.runSelection.selected_indexes,selected_count:y.runSelection.selected_count,skipped_count:y.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:T?!0:void 0,warnings:x.length>0?x:void 0,changed:h.changed,count:h.tests.length,...h.removed>0?{removed:h.removed}:{},...X}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d3405c0-14e6-51f5-97a1-355438fd0199")}catch{}})();var kF=(e,t)=>{if(e===void 0)return;let n=Q(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},SF=e=>{if(e===void 0)return;let t=me(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},jb=(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},EF=e=>e instanceof Error?e.message:String(e),AF=()=>{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)}`},TF=e=>e.trim().replaceAll(/\s+/g," "),CF=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),IF=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),RF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},xF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},wi=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),qb=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),OF=e=>typeof e=="number"?e:void 0,PF=e=>{let t={assert_stdout_contains:wi(e.assert_stdout_contains),assert_stdout_regex:wi(e.assert_stdout_regex),assert_stderr_contains:wi(e.assert_stderr_contains),assert_stderr_regex:wi(e.assert_stderr_regex),assert_stdout_min_lines:OF(e.assert_stdout_min_lines),assert_json_field_equals:qb(e.assert_json_field_equals),assert_json_field_gte:qb(e.assert_json_field_gte)};return JSON.stringify(t)},LF=e=>{let t=$d(e.command);return t!==void 0?`command:${e.scope}:${TF(t)}`:`path:${e.scope}:${$d(e.path)??""}`},Kb=e=>{let t=CF(e.env_set),n=IF(e.env_clear),r=RF(e.pm_context_mode),o=xF(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",i=PF(e);return`${LF(e)}:${t}:${n}:${r}:${o}:${s}:${i}`},NF=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,FF=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},MF=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},vi=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
50
- `)}catch{}},DF=async(e,t,n)=>{let r=[],o=0;for(let s of e){let i=await bi(s.id,{run:!1},{...t,path:n});o+=i.tests.length,r.push({item:s,tests:i.tests})}return{itemTests:r,linkedTests:o}},$F=async e=>{let t=$(e.settings.schema),n=O(e.settings,R()),r=kF(e.options.status,t),o=jb(e.options.limit,"--limit"),s=jb(e.options.offset,"--offset")??0,a=(await le(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:o===void 0?a.slice(s):a.slice(s,s+o),statusFilter:r,limitFilter:o,offsetFilter:s}},UF=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=Kb(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,NF(t.get(o),r.timeout_seconds))}return t},GF=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=Kb(u),f=t.seenTestKeys.has(p);if(!f){t.seenTestKeys.add(p);let _=t.effectiveTimeoutByKey.get(p);n.push(_===void 0?u:{...u,timeout_seconds:_})}return{test:u,key:p,duplicate:f}}),o=n.length>0?await Dd(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],s=0,i=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=o[s];return s+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=FF(i),c=yi(i),m=await KF(e,a,i,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}}},jF=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),qF=e=>e?!0:void 0,KF=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=jF(t,r.options);await mi({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:k(),recorded_at:k(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:qF(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${EF(o)}`]}return[]},zF=()=>{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},$d=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},BF=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:tt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:UF(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:AF(),trackingAttempt:zF(),trackingResumedFrom:$d(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),HF=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:yi([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},VF=async(e,t,n)=>{for(let[r,o]of e.entries()){vi(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let s=await GF(o,t);MF(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),vi(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}},WF=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=Md(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}`)},YF=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}),JF=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(" "),XF=async(e,t)=>{let n=E(process.cwd(),t.path);await I(n);let r=await A(n),o=await $F({pmRoot:n,settings:r,options:e}),s=SF(e.timeout),i=k(),a=await DF(o.filteredItems,t,n);return vi(e,JF({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:s,runStartedAt:i}},QF=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}},zb=async(e,t)=>{let n=await XF(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=HF(e,n.linkedTests,n.filteredItems),s=BF({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await VF(n.itemTests,s,r),WF(e,r);let i=QF({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return vi(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),YF({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2643d11d-befc-5a87-8bec-760951eec4d0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="863df651-49e0-552f-a7f0-92c3cc9a12a2")}catch{}})();function Bb(){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]="feba1227-c2a2-5ca3-83e6-3fd2780e6cbb")}catch{}})();var Vb=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:Su().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{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 package install <target> --project","pm package 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 package 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 merge report","pm merge reconcile --dry-run","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:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"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"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm remind <title> --at <when> --parent <ID>","pm event <title> --start <when> --parent <ID>","pm meet <title> --start <when> --duration <span> --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Record the reminder or event under the item that owns the work, then confirm it appears in the agenda summary of a context read.",commands:["pm remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."}],related:["workflows","quickstart","extensions"]}],Hb=new Map;for(let e of Vb){Hb.set(e.id,e);for(let t of e.aliases)Hb.set(t,e)}function Ud(){return Vb.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]="4bf2b42b-91f3-5850-b1f1-d8a01525860c")}catch{}})();var xH=[...$r],OH=[...Ur],ZF=new Set(Hn.filter(e=>e.hidden).map(e=>e.alias)),PH=ku("full").filter(e=>!ZF.has(e)),LH=M(Jr),NH=M(Xr),FH=M(oo),MH=M(lo),DH=M(mo),$H=M(pm),UH=M(fm),GH=M(co),jH=M(_o),qH=M(uo),KH=M(po),zH=M(ro),BH=M(fo),HH=M(Qr),VH=M(Zr,!1),WH=M(Am),YH=M(Yn),JH=M(Jn),XH=M(bo),QH=M(go),ZH=M(io),eV=M(yo),tV=M(ho),nV=M(wo),rV=M(so),oV=M(ao),sV=M(to),iV=M(vo),aV=M(eo);var eM=M(ko),cV=`${eM} bash zsh fish`,dV=nM(Ud()),tM="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",lV=`${tM} upgrade`,mV=M(no),uV=M(Vn),pV=M(Wn);var fV=Yr.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function nM(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0224a672-e326-5555-a4b4-1fa3550d9e61")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1cbb3565-26d8-5657-b724-602658bec852")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="099c7cda-4a92-553c-ad60-00e185b5971b")}catch{}})();var Xb=Symbol("pm.active-extension-host-context");function Ne(e){return{fullChangedFields:!0,options:e}}var q=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[Xb]=!0,n}run(t,n={}){return Qb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Bf(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return wa(await this.list(ba(t)))}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}append(t,n,r={}){return this.runTyped("append",{id:t,...Ne(rr(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,s={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:s})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,s){return this.runTyped("plan",{...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...s===void 0?{}:{reorderTo:s},options:rr(r,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Ne(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ne(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Ne(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ne(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ne(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ne(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ne(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ne(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...Ne(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ne(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ne(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ne(r)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function oM(e={},t={}){return new q(t).context(e)}function sM(e={},t={}){return new q(t).list(e)}function iM(e={},t={}){return new q(t).listAllComplete(e)}function aM(e,t={},n={}){return new q(n).search(e,t)}function cM(e,t={},n={}){return new q(n).get(e,t)}function dM(e={},t={}){return new q(t).next(e)}function lM(e={},t={}){return new q(t).aggregate(e)}function mM(e,t={},n={}){return new q(n).comments(e,t)}function uM(e,t={},n={}){return new q(n).notes(e,t)}function pM(e,t={},n={}){return new q(n).learnings(e,t)}function fM(e,t={},n={}){return new q(n).files(e,t)}function _M(e,t={},n={}){return new q(n).filesDiscover(e,t)}function hM(e,t={},n={}){return new q(n).docs(e,t)}function gM(e,t={},n={}){return new q(n).deps(e,t)}function yM(e,t={},n={},r={}){return new q(r).graph(e,t,n)}function bM(e,t,n={},r={}){return new q(r).append(e,t,n)}function wM(e={},t={}){return new q(t).create(e)}function vM(e,t={},n={}){return new q(n).update(e,t)}function kM(e,t,n={},r={}){return new q(r).reopen(e,t,n)}function SM(e,t,n={},r={}){return new q(r).close(e,t,n)}function EM(e,t={},n={}){return new q(n).claim(e,t)}function AM(e={},t={}){return new q(t).claimNext(e)}function TM(e,t={},n={}){return new q(n).release(e,t)}function CM(e,t={},n={}){return new q(n).copy(e,t)}function IM(e,t={},n={}){return new q(n).delete(e,t)}function RM(e,t,n={},r={}){return new q(r).restore(e,t,n)}function xM(e,t={},n={}){return new q(n).focus(e,t)}function Xe(e,t){let n=w(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}var Wb=pu(),OM=new rM;function ki(){sa(fl()),ia(_l()),aa(hl()),ca(gl()),da(yl()),la(bl()),ma(wl())}async function PM(e,t,n,r){return fu(()=>t===void 0?Wb.read(()=>Yb(e,n,r)):Wb.write(()=>NM(t,()=>Yb(e,n,r))))}async function Yb(e,t,n){let r=E(t,e.path);if(e.noExtensions)return ki(),Za({pmRoot:r},()=>n(null));if(!await P(de(r)))return ki(),n(null);let o=null,s;try{let i=await A(r),a=await Vr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Wr({...a,loaded:a.loaded});s={loadResult:a,activationResult:c},sa(c.hooks),ia(c.commands),aa(c.parsers),ca(c.preflight),da(c.services),la(c.renderers),ma(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){ki(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Za({pmRoot:r,packages:o?.packages},()=>n(o))}finally{ki(),s&&await vl(s.loadResult,s.activationResult).catch(()=>{})}}async function LM(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let s=Cn(e),a=o.registrations.commands.find(m=>Cn(m.action)===s)?.command??o.commands.handlers.find(m=>Cn(m.command)===s)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=await Po({command:xa(a),args:ke(n.args??t.args),options:Oa(t,n),global:r,pm_root:o.pmRoot,sdk:Yf(o.pmRoot,q.forActiveExtensionHost({pmRoot:o.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 NM(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function FM(e){let t=Xe(e,"action"),n=Cn(t),r=Ei(Vf,n),o=r?.action??n,s={...e,action:o};return r?.options!==void 0&&(s.options={...r.options,...Bi(e.options)}),o==="package"&&(s.options={...Bi(s.options),vocabulary:"package"}),{action:o,args:s}}async function Qb(e){let t=FM(e),n=Ca(t.args),r=Dp(t.action),o=w(t.args,"cwd"),s=o??process.cwd();t.action==="init"&&(n[ed]=s),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(s,n.path));try{return e[Xb]===!0||OM.getStore()===!0?await Jb(t.action,t.args,n,null):await PM(n,o,s,i=>Jb(t.action,t.args,n,i))}finally{r&&Ya()}}function Ei(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Si(e){return w(e.args,"target")??w(e.options,"target")}function ee(e,t=e.options){return e.id??Xe(t,"id")}async function MM(e){let t=_n("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),Wa(await ct(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function DM(e){let t=Xe(e.args,"query"),n=_n("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Wa(await ur(t,n,e.global),n)}async function $M(e){let{changedFields:t,idOnly:n,runnerOptions:r}=De(e.args,e.options);return Ue(await Pt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function UM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=De(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Ue(await Gc(ee(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function GM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=De(e.args,e.options);return Ue(await mt(ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function jM(e){let t=hs(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),f_(ee(e),t,e.global)}function Zb(e,t){return Ef(cy(e.options,t,Me),e.global)}function qM(e){let t=ke(e.options.lookupPath);if(t&&t.length>0)return Zb(e,t);let n=ee(e);return e.options.discover===!0?Na(n,Ra(e.options),e.global):Sf(n,ns(e.options),e.global)}function KM(e){return ib({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:Fp(e.args,e.options)},e.global)}function zM(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),ar(e.global,t)}function BM(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);let n=w(e.args,"value")??w(e.options,"value"),r=w(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return zh(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),r,e.global,w(e.options,"policy")===void 0?n:void 0)}function HM(e){let t=e.options;return Cp(Tp(t),e.global)}function VM(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 WM(e){let t=w(e.args,"subcommand")??Xe(e.options,"subcommand"),n=e.options;return vh({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:YM(e),reorderTo:VM(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function YM(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function JM(e){let t=w(e.args,"subcommand")??Xe(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:w(e.args,"name")??w(e.options,"name"),author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ke(n)}}function XM(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,a=Ei({list:()=>Qp(t.global),show:()=>Zp(r,t.global),"show-status":()=>ef(r,t.global),"list-fields":()=>rf(t.global),"show-field":()=>of(r,t.global),"remove-type":()=>Wp(r,{author:o,force:s},t.global),"remove-field":()=>nf(r,{author:o,force:s},t.global),"remove-status":()=>Xp(r,{author:o,force:s},t.global),"apply-preset":()=>sf(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:o,force:s},t.global)},n);return a?a():null}function QM(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return tf(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:ke(i),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:s,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:ke(a),author:r,force:o},t.global)}function ZM(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.role??t.options.role;return Jp(n,{role:i===void 0?void 0:ke(i),alias:s,description:w(t.args,"description")??w(t.options,"description"),order:Me(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function eD(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e;return Vp(n,{description:w(t.args,"description")??w(t.options,"description"),defaultStatus:w(t.args,"defaultStatus")??w(t.args,"default_status")??w(t.options,"defaultStatus")??w(t.options,"default_status"),folder:w(t.args,"folder")??w(t.options,"folder"),alias:s,author:r,force:o},t.global)}function tD(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,i=w(t.args,"to")??Xe(t.options,"to"),a=w(t.args,"migrationId")??w(t.args,"migration_id")??w(t.options,"migrationId")??w(t.options,"migration_id"),c=w(t.args,"fieldTypeScope")??w(t.options,"fieldTypeScope")??w(t.args,"type")??w(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:i}:n==="rename-field"?{kind:"rename-field",from:r??"",to:i,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:i};return Bp(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:s},t.global)}function nD(e){let t=JM(e),n=XM(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return tD(t);if(t.subcommand==="add-field")return QM(t);if(t.subcommand==="add-status")return ZM(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?af({minCount:Me(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):eD(t);throw xe({command_path:"schema",token:t.subcommand,allowed:Hp,exit_code:64})}function rD(e){let t=w(e.args,"subcommand")??Xe(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),s=Ei({list:()=>Vg(),show:()=>Wg(r),lint:()=>Yg(r),apply:()=>Jg(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(!s)throw xe({command_path:"profile",token:t,allowed:Hg,exit_code:64});return s()}async function oD(e){let{changedFields:t,idOnly:n,runnerOptions:r}=De(e.args,e.options);return Ue(await Qf(ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function sD(e){let{changedFields:t,runnerOptions:n}=De(e.args,e.options);return Ue(await ch(La(n),e.global),{changedFields:t})}async function iD(e){let{changedFields:t,runnerOptions:n}=De(e.args,e.options),r=w(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Ue(await p_(Pa(o),e.global),{changedFields:t})}async function aD(e){let{changedFields:t,idOnly:n,runnerOptions:r}=De(e.args,e.options),o=w(r,"target")??Xe(e.args,"target");return Ue(await Wt(ee(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function cD(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=si($(n.schema)),o=ee(e),s=await ys(o,e.force,e.global,e.options),i=await mt(o,rr(e.options,{status:r,force:e.force},["assignee"]),e.global);return{id:o,action:"start_task",claim:s,update:i}}async function dD(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=ee(e),o=$(n.schema).open_status,s=await mt(r,rr(e.options,{status:o,force:e.force},["assignee"]),e.global),i=await bs(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:s,release:i}}async function lD(e){let t=ee(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await dt(t,n,{...e.options,force:e.force},e.global),o=await bs(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:o}}function mD(e){let t={...e.args,...e.options};return Pp(Xe(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),Up(t),e.global)}function uD(e){return jp(E(process.cwd(),e.global.path),{...e.args,...e.options})}var pD={init:e=>Er(w(e.args,"prefix"),e.global,e.options),context:e=>Ba(_n("context",e.options),e.global),next:e=>mr(_n("next",e.options),e.global),eval:Fg,events:Mg,merge:Dg,workspace:$g,meet:ri,event:ri,remind:ri,list:MM,get:e=>{let t=ee(e);return Ha(t,e.global,_n("get",e.options,[t]))},search:DM,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ke(e.options.status);return Va(e.global,{...t.length===0?{}:{status:t},since:w(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Me(e.options.limit,"limit")})},create:$M,copy:UM,focus:e=>qc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:GM,"item-reopen":ay,restore:aD,claim:e=>e.options.next===!0||e.args.next===!0?s_(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):ys(ee(e),e.force,e.global,e.options),release:e=>bs(ee(e),e.force,e.global,e.options),"start-task":cD,"pause-task":dD,"close-task":lD,close:iy,comments:jM,notes:e=>h_(ee(e),hs(e.options),e.global),learnings:e=>__(ee(e),hs(e.options),e.global),files:qM,docs:e=>kf(ee(e),ns(e.options),e.global),test:e=>bi(ee(e),e.options,e.global),"test-all":e=>zb(e.options,e.global),telemetry:KM,validate:e=>cs(e.options,e.global,{runUpdate:(t,n,r)=>mt(t,n,r)}),health:zM,assurance:e=>Mf(e.args,e.options,e.global),contracts:e=>Oy(e.options,e.global),config:BM,activity:HM,aggregate:e=>qa(e.options,e.global),extension:e=>In(Si(e),e.options,e.global),package:e=>In(Si(e),e.options,e.global),install:e=>In(Si(e),{...e.options,install:!0},e.global),upgrade:e=>jf(Si(e),e.options,e.global),delete:e=>jc(ee(e),e.options,e.global),deps:e=>Op(ee(e),e.options,e.global),graph:mD,"files-discover":e=>Na(ee(e),e.options,e.global),"files-lookup":e=>Zb(e,ke(e.options.paths)),history:e=>Gf(ee(e),e.options,e.global),"history-redact":e=>cp(ee(e),e.options,e.global),"history-repair":ny,"history-compact":ry,"history-author-acknowledge":uD,plan:WM,schema:nD,profile:rD,stats:e=>Ed(e.global,Jy(e.options)),append:oD,"update-many":sD,"close-many":iD,gc:e=>qf(e.global,e.options)};async function Jb(e,t,n,r){let o=Ia(t,e);ra(e,o),ou(e,o);let s={action:e,args:t,options:o,id:w(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},i=Ei(pD,e),a=i?await i(s):await LM(e,t,o,n,r);o.resolvedOutputFormat="json";let c=yu(e,o,a);return await Jf(E(process.cwd(),n.path),c),c}var fD={closeManyOptionsFromFlat:Pa,extensionOptionsFromArgs:Oa,globalOptions:Ca,mutationListOptions:$p,normalizeActionName:Cn,normalizeCommandPath:xa,normalizeMcpUpdateOptions:Gp,normalizeMcpOptionsArrays:Mp,optionsWithAuthor:Ia,readRequiredString:Xe,readScalarString:Lp,readScalarStringAllowBlank:Np,readStringArray:ke,updateManyOptionsFromFlat:La,withAddNoteOption:ns,withFilesDiscoveryOptions:Ra,withMutationCompaction:De};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=fD);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cea03617-5e90-5683-a9d1-289087ed4646")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cc0d4dd1-20e8-59d4-acb5-9f8ed639d35f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f44898af-0809-51e1-a6fb-74716c0971f5")}catch{}})();export{hn as AGENT_PROVENANCE_DIMENSIONS,Ou as BASELINE_ITEM_FORMAT_VERSION,Zw as BUILTIN_AGENT_PROVENANCE_ADAPTERS,Xn as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,$r as BUILTIN_ITEM_TYPE_VALUES,Gr as CONFIDENCE_TEXT_VALUES,Pu as CURRENT_ITEM_FORMAT_VERSION,Ut as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,dn as ISSUE_SEVERITY_VALUES,Zd as ITEM_TYPE_VALUES,Ja as PM_CLI_EXPECTED_ERROR_NAME,Kw as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,jw as PM_READ_OUTPUT_DIMENSIONS,qw as PM_READ_OUTPUT_OPTION_FLAGS,ta as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,q as PmClient,cn as RISK_VALUES,pv as SEMANTIC_ATTRIBUTION_LIMITS,Ur as STATUS_VALUES,Qw as agentSessionEnvironment,lM as aggregate,kd as analyzeAgentProvenanceDescriptorCoverage,Ww as analyzeSdkCliParameterCompleteness,bM as append,Bw as applyReadOutputDimensions,Mw as applyReadOutputSessionReferences,Dw as attachReadOutputSessionReceipt,Yw as boundAgentEpisodeIdentity,Tt as canonicalDocument,EM as claim,AM as claimNext,Fu as classifyItemFormatVersion,SM as close,mM as comments,oM as context,CM as copy,wM as create,Wf as createPmCliExpectedError,Gw as decodeReadOutputContinuationCursor,IM as deleteItem,gM as deps,iv as detectAgentIdentity,dv as detectHarnessIdentity,av as diagnoseAgentIdentity,hM as docs,Lu as effectiveItemFormatVersion,Bb as emptyImportedDocument,Uw as encodeReadOutputContinuationCursor,DP as evaluateSemanticAttributionCoverage,mv as explainSourceTraceability,fM as files,_M as filesDiscover,xM as focus,cM as get,yM as graph,$P as groupHistoryByEpisode,o_ as isAlreadyClaimedError,ps as isPmCliExpectedError,Hw as isReadOutputBudgetExceeded,pM as learnings,sM as list,tv as listAgentProvenanceAdapters,iM as listAllComplete,dM as next,rv as normalizeAgentProvenanceAdapterValue,Nu as normalizeItemFormatVersion,we as normalizeItemId,Q as normalizeStatusInput,uM as notes,k as nowIso,Fw as parseReadOutputSession,ss as parseSourceLineRange,Fo as readAuthorEnvironment,$w as readOutputSessionRemainingTokens,Ka as recordClaimSemanticAttribution,ls as recordFocusSemanticAttribution,za as recordReleaseSemanticAttribution,nv as registerAgentProvenanceAdapters,ev as registerHarnessSignalDescriptors,TM as release,kM as reopen,Jw as resolveAgentSessionContextFromSignals,lv as resolveAuthorIdentity,Gy as resolveHistoryEpisodeGroupIdentity,zw as resolveReadOutputDimensions,Vw as resolveReadOutputEncoding,na as resolveReadOutputSurface,uv as resolveSemanticLineageIds,RM as restore,Qb as runAction,Xw as runWithAgentSessionContext,ov as runWithHarnessDetectionSignals,sv as runWithWorkspaceHarnessSignalDescriptors,aM as search,fv as semanticAttributionAffinity,st as serializeItemDocument,MP as summarizeAgentModelProvenance,Sd as summarizeAgentProvenance,vM as update,ra as validateReadOutputOptions,cv as writeAuthorEnvironment};
34
+ `),Fe.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
35
+ `);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=eI(m,t);return Fe.write(`
36
+ `),{prefix:o,preset:a,telemetry_enabled:u}}finally{n.close()}}function aI(e){return{presetFromOption:og(e.preset),useDefaults:e.defaults===!0,authorFromOption:JR(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:ZR(e.agentGuidance),typePreset:YR(e.typePreset)}}function cI(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 dI(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function lI(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&&(sg(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 mI(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=cI({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return dI(e.settingsPath,n,e.options.force===!0,e.target),lI({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Oe(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function uI(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await iI(t,wt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let s=n??"minimal",i=VR();i.id_prefix=t,sg(i,s);let a=Mo()?.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 Oe(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function rg(e){return e.settingsExists?await mI(e):await uI({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function pI(e){let t=await ng({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 Oe(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function fI(e,t){let n=[],r=[],o=await $m(e,t.schema);for(let s of o.created_paths)n.push(s),r.push(...await W({path:s,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function _I(e){if(e.typePreset===void 0)return;let t=await rI(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await W({path:t.file,scope:"project",op:"init:type_preset"})),t}async function hI(e){let n=O(e.settings,I()).folders.filter(o=>!Bi.includes(o)),r=await ig(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function gI(e){let t=J.resolve(e.tracker_root),n=J.dirname(t);return J.basename(t)==="pm"&&J.basename(n)===".agents"?J.dirname(n):e.workspace_root}async function yI(e,t,n,r){if(!e)return;let o=await In("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let s=nI(o),i=s.packages.filter(a=>!a.ok).map(a=>a.alias);if(!s.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 s}function bI(e){let t=r=>Zn([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function wI(e,t,n,r=Hp){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function vI(e,t,n,r){if(e==null||n==="status")return;let o=await fa(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Ar(e,t,n={}){let r=t[nd],o=typeof r=="string"?r:process.cwd(),s=XR(o,t,e,n.workspace),i=s.pmRoot;e=QR(s.prefixArg,n.idPrefix);let a=aI(n);await sI(i,s.target.mode==="tracker-path",n.force===!0);let c=[],m=[],u=J.join(i,"settings.json"),p=await P(u),f;p&&(f=await rg({pmRoot:i,settingsPath:u,settingsExists:p,normalizedPrefix:Rt(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:s.target}));let _=await ig(i,Bi);c.push(..._.createdDirs),m.push(..._.warnings),f??=await rg({pmRoot:i,settingsPath:u,settingsExists:p,normalizedPrefix:Rt(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:s.target});let{settings:g}=f,y=gI(s.target),h=await ss(y??J.dirname(i)),b=y??h,v=await pI({pmRoot:i,cwd:b??o,agentGuidanceMode:a.agentGuidanceMode,settings:g,warnings:m}),S=await fI(i,g);c.push(...S.createdDirs),m.push(...S.warnings);let T=await _I({pmRoot:i,settings:g,typePreset:a.typePreset,warnings:m});T&&(g=await A(i)),await hI({pmRoot:i,settings:g,createdDirs:c,warnings:m}),await vI(b,i,a.agentGuidanceMode,m),!p&&n.mergeFence!==!1&&a.agentGuidanceMode!=="status"&&await wI(i,h,m);let x=await yI(a.installBundledPackages,t,i,m),U=bI({installBundledPackages:a.installBundledPackages,registeredTypePreset:T,agentGuidanceNextSteps:v.next_steps,target:s.target});return{ok:!0,path:i,target:s.target,settings:g,created_dirs:c,warnings:m,governance_preset:g.governance.preset,wizard_used:f.wizardUsed,...T?{registered_type_preset:T}:{},...x?{installed_packages:x}:{},next_steps:U,agent_guidance:v}}import RI from"node:fs/promises";import sd 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 cg=10,sn="https://schema.unbrained.dev/pm/eval-query-set/v1";var ni={schema:sn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Be=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},kI=new Set(["keyword","semantic","hybrid"]);function ag(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function SI(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),o=ag(r,n),s=Array.from({length:t.size},()=>1),i=ag(s,n);return i===0?0:o/i}function EI(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function rd(e,t,n){let r=Math.min(n,e.length),o=0;for(let s=0;s<r;s+=1)t.has(e[s])&&(o+=1);return o}function AI(e,t,n){return n<=0?0:rd(e,t,n)/n}function TI(e,t,n){return t.size===0?0:rd(e,t,n)/t.size}function dg(e,t,n){return{ndcg:SI(e,t,n),mrr:EI(e,t,n),precision:AI(e,t,n),recall:TI(e,t,n),relevant_total:t.size,retrieved_relevant:rd(e,t,n)}}function lg(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function CI(e,t){if(typeof e!="object"||e===null)throw new Be(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new Be(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Be(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(s=>typeof s!="string"))throw new Be(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(s=>s.trim()).filter(s=>s.length>0))];if(o.length===0)throw new Be(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!kI.has(n.mode)))throw new Be(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function od(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==sn)throw new Be(`Unsupported eval query set schema; expected "${sn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new Be('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Be("Eval query set must contain at least one query");return{schema:sn,queries:n.map((r,o)=>CI(r,o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cc9405b-d2b8-59aa-893f-54892595788a")}catch{}})();var II=sd.join("search","eval-queries.json"),id={schema:sn,examples:[JSON.stringify(ni)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},xI=new Set(["keyword","semantic","hybrid"]),OI=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!xI.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},PI=e=>{if(e===void 0||e==="")return cg;let t=ml(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},LI=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},Nt=e=>Math.round(e*1e4)/1e4,NI=async e=>{try{return await RI.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...id,examples:[`echo '${JSON.stringify(ni)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},FI=(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,id)}},MI=e=>{try{return od(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,id)}},DI=async e=>MI(FI(await NI(e),e)),$I=(e,t)=>t?sd.resolve(process.cwd(),t):sd.join(e,II),UI=async(e,t,n,r)=>{let o=e.mode??t,i=(await pr(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=dg(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:Nt(a.ndcg),mrr:Nt(a.mrr),precision:Nt(a.precision),recall:Nt(a.recall)}}},GI=(e,t,n,r)=>{let o=lg(n);return{k:e,query_count:t.length,aggregate:{ndcg:Nt(o.ndcg),mrr:Nt(o.mrr),precision:Nt(o.precision),recall:Nt(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||o.ndcg>=r}},mg=async(e,t)=>{let n=E(process.cwd(),t.path);await R(n);let r=PI(e.k),o=OI(e.mode),s=LI(e.failUnder),i=$I(n,e.queries),a=await DI(i),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await UI(u,o,r,t);m.push(f),c.push(p)}return GI(r,c,m,s)};import{readFile as jI,writeFile as qI}from"node:fs/promises";import KI 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]="22b1f103-54de-5a63-a2d2-2f99181a73e2")}catch{}})();var ug=["item","history","relationship","json"];function zI(e){let t=e.trim().toLowerCase();if(ug.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${ug.join(", ")}.`,d.USAGE)}function BI(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 ad(e,t){try{return await jI(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function HI(e){let t=E(process.cwd(),e.path);return await P(me(t))?A(t):null}function VI(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function pg(e,t){let n=zI(e.artifact),r=BI(e.prefer),o=KI.resolve(e.outputPath??e.oursPath),[s,i,a]=await Promise.all([ad(e.basePath,"base"),ad(e.oursPath,"ours"),ad(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=uf(s,i,a);c=_.merged,p.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=pf(s,i,a);c=_.merged,p.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await HI(t),g=VI(e.itemPath??o,_),y=vt(I()),h=ff(s,i,a,{format:g,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"});if(c=h.merged,u.push(...h.conflict_fields),p.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let b=Uu(c,{format:g,schema:_?.schema,extensionFieldNames:y}),v=b.metadata,S=[...new Set([...h.fields_from_theirs,...h.union_fields,...h.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,mf(T==="body"?b.body:v[T])])),decisions:h.conflict_decisions,operation:await hf(process.cwd(),e.itemPath)}}}else{let _=_f(s,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await qI(o,c,"utf8"),m!==void 0){let _=await yf(m);_!==null&&(p.receipt=Vt(_))}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 value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&p.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:u.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd45ee09-e4c3-5fc6-8253-1f1dc709a3a8")}catch{}})();async function fg(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await gf(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Pt(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Pt(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:r,message:e.message??"Settle rebase receipt after exact original Git state restoration",auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...Vt(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await is(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as WI}from"node:fs/promises";import YI 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]="2696d75a-02f4-5c16-b77e-7798e7d020f9")}catch{}})();var JI=4;function _g(e){let t=e.checks.find(a=>a.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,s=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,i=Array.isArray(o)?o.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:s,coordinates:i}}async function XI(e,t){let n=[];for(let r of t){let o;try{o=await WI(YI.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let s=o.split(/\r?\n/)[r.history_line-1];if(s===void 0||s.trim().length===0)continue;let i;try{i=JSON.parse(s)}catch{continue}let a=Sf(i,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!kf(a)||a.eventTimestamp===void 0||No(a.eventTimestamp,vf)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function QI(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;let t=new Map;for(let n of e.candidates){let r=t.get(n.item_id)??[];r.push(n),t.set(n.item_id,r)}for(let[n,r]of t)await Pt(n,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:r.map(o=>({receipt_id:o.receipt_id,original_history_line:o.history_line,original_event_ts:o.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function ZI(e){try{return{status:"fulfilled",value:await Pt(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function ex(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function tx(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>is(e.gitWorkspaceRoot??process.cwd(),r,{requireExisting:!0}))),n.length}async function hg(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await cr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),s=_g(o),i=await XI(r,s.coordinates),a=await ss(r),c=await bf(a??process.cwd(),{includeLossless:!0,pmRoot:r});if(c.invalid_evidence_count>0)throw new l(`Merge reconciliation refused ${c.invalid_evidence_count} invalid receipt evidence file(s).`,d.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let m=await QI({candidates:i,options:e,global:t}),u=c.receipts,p=await fg({cwd:a,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),f=new Set(p),_=new Map;for(let q of u.filter(ie=>!f.has(ie.id))){let ie=_.get(q.item_id)??[];ie.push(q),_.set(q.item_id,ie)}let g=Object.fromEntries([..._].map(([q,ie])=>[q,{merge:{receipts:ie.map(Vt)}}])),y=Object.fromEntries([..._].map(([q,ie])=>[q,{gitWorkspaceRoot:a,receipts:ie}])),h=await as({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:g,...u.length>0?{mergeReceiptProofById:y}:{}},t),b=new Set(h.streams.map(q=>q.id)),v=[..._.keys()].filter(q=>!b.has(q)),S=await lf(v,JI,q=>ZI({id:q,dryRun:n,options:e,global:t,auditContext:g[q],mergeReceiptProof:y[q]}));ex({receiptOnlyIds:v,results:S,repair:h});let T=await tx({dryRun:n,pendingReceipts:u,repair:h,gitWorkspaceRoot:a}),x=await ms({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),U=m===0?o:await cr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),N=_g(U),ee=x.checks.every(q=>q.status==="ok"),z=n?u.length===0:T+p.length===u.length,le=[h.totals.failed===0,ee,z,N.count===0,!N.truncated].every(Boolean),ne=s.truncated||N.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,Re=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",ne,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:le?["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.",ne,...i.length>0&&m===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(q=>q!==void 0);return{ok:le,dry_run:n,repair:h,receipts:{pending_before:u.length,reconciled:T,abandoned:p.length,summaries:u.map(Vt),missing_history_references_before:s.count,legacy_disposition_eligible:i.length,legacy_disposition_recorded:m,missing_history_references_after:N.count},validation:x,guidance:Re,generated_at:x.generated_at}}import{createHash as nx}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01043e67-99d4-5b68-a1b2-33f35f5cef5f")}catch{}})();var bg=1,wg=/^[A-Za-z0-9_-]+$/,rx=100,gg=1e3;var aq=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function He(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function ox(e){return nx("sha256").update(qt({type:He(e.type),author:He(e.author),item:He(e.item),harness:He(e.harness),agent_instance:He(e.agentInstance),provenance:He(e.provenanceFilter)})).digest("hex").slice(0,24)}function yg(e,t){let n={version:bg,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 sx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===bg,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 ix(e,t){let n=e.trim();if(n.length===0||n.length>4096||!wg.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(!sx(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function ax(e){let t=e??rx;if(!Number.isSafeInteger(t)||t<0||t>gg)throw new l(`Mutation event limit must be an integer from 0 to ${gg}.`,d.USAGE,{code:"invalid_event_limit"});return t}function cx(e,t){let n=e?.trim();if(!n)return{};if(wg.test(n))return{cursor:ix(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 dx(e,t){let n=await ga(e,t);if(n===null){if(!await Gu(e))return{...await ju(e,t),source:"authoritative_history"};n=await ga(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 lx(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 ri(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await R(t);let n=ax(e.limit),r=lx(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 o=await A(t),s=o.agent_identity.identity_vocabulary,i=Ap(o.agent_identity.harness_signals),a=Tp({provenance:e.provenanceFilter},i),c=He(e.harness),m=ox(e),{cursor:u,sinceTimestamp:p}=cx(e.since,m),f={...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:He(e.type),authors:He(e.author),harnesses:c,harness_alias_authors:c?Object.entries(s.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:He(e.agentInstance),provenance:[...a].map(([y,h])=>({dimension:y,values:[...h]})),stream_ids:He(e.item),limit:n},_=await dx(t,f),g=_.events.map(y=>({...r==="row"?{cursor:yg(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:Cp(y.entry,s,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:g,count:g.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:yg(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Rp(_.events.map(y=>y.entry),s,i)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c7c75b13-7317-5089-9869-7e6e22ed95b2")}catch{}})();var mx="1h",ux="now",px="+1d";function Ft(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function vg(e,t,n){let r={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};return ke(n,r)}async function kg(e,t,n,r){let o=vg(e,t,n),s=[];return Ft(s,"start",n.start??ux),n.end!==void 0?Ft(s,"end",n.end):Ft(s,"duration",n.duration??mx),Ft(s,"location",n.location),Ft(s,"timezone",n.timezone),n.allDay===!0&&Ft(s,"all_day","true"),o.event=[s.join(",")],Lt(o,r)}function Sg(e,t,n){return kg("Meeting",e,t,n)}function Eg(e,t,n){return kg("Event",e,t,n)}function Ag(e,t,n){let r=vg("Reminder",e,t),o=[];return Ft(o,"at",t.at??px),Ft(o,"text",t.text??e),r.reminder=[o.join(",")],Lt(r,n)}import Cr from"node:crypto";import{cp as Tg,lstat as fx,mkdir as an,readFile as Un,readdir as dd,rename as Ig,rm as md,writeFile as oi}from"node:fs/promises";import M 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]="8a0d8f6e-f4ff-5a0c-9205-d28e03df72b9")}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]="2580e043-8675-5070-b57e-30cae333228c")}catch{}})();var xg="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var Og=M.join("runtime","workspace-snapshots"),_x=new Set(["checkpoints","locks","runtime","search","transactions"]),hx=/^[a-z0-9][a-z0-9._-]*$/,Tr="sdk-workspace-transaction",cd={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Pg={renameEntry:Ig,removeEntry:async e=>{await md(e,{recursive:!0,force:!0})}},ld=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 Un(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!==Tr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await ge(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
37
+ `)}};async function Lg(e,t=""){let n=await dd(M.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((s,i)=>s.name.localeCompare(i.name))){if(t.length===0&&_x.has(o.name))continue;let s=M.posix.join(t.replaceAll(M.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${s}`);if(o.isDirectory())r.push(...await Lg(e,s));else if(o.isFile())r.push(s);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${s}`)}return r}async function Ng(e){let t=await Lg(e),n=Cr.createHash("sha256"),r=[],o=0;for(let i of t){let a=await Un(M.join(e,i));r.push(a),o+=a.byteLength,n.update(i),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let s=n.digest("hex");return{manifest:{schema:xg,fingerprint:s,files:t,bytes:o},contents:r}}function Cg(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
38
+ `).filter(t=>t.trim().length>0).length}async function gx(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),s=await Promise.all(o.map(async i=>[i,await Un(M.join(e,i))]));for(let[i,a]of s)n.set(i,a)}return n}function ud(e){if(!hx.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 Fg(e,t){return Vn(`workspace_snapshot_${e}`,t,{codes:{capacity:cd.capacity.code,permission:cd.permission.code,resource:cd.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function cn(e){return M.join(e,Og)}function Mg(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 Dg(e,t){try{return JSON.parse(await Un(e,"utf8"))}catch(n){throw kt(n)?Mg(t):n}}async function Rg(e,t,n){try{await md(e,{recursive:n})}catch(r){throw kt(r)?Mg(t):r}}async function yx(e,t,n=Pg){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function bx(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(s){throw await r.renameEntry(n,t),await r.removeEntry(e),s}await r.removeEntry(n)}async function wx(e,t){return ud(t),/^[a-f0-9]{64}$/.test(t)?t:(await Dg(M.join(cn(e),"refs",`${t}.json`),t)).fingerprint}async function pd(e,t={}){if(t.name!==void 0&&(ud(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 Ng(e),o=cn(e),s=M.join(o,"objects",n.fingerprint),i=!1;try{i=(await fx(s)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&kt(a)))throw a}if(!i){let a=M.join(o,"objects",`.create-${process.pid}-${Cr.randomUUID()}`);await Fg("create_object",async()=>{await an(M.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=M.join(a,"files",m);await an(M.dirname(u),{recursive:!0}),await oi(u,r[c])}await oi(M.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
39
+ `,"utf8"),await an(M.dirname(s),{recursive:!0})}),i=await yx(a,s)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=M.join(o,"refs");await an(c,{recursive:!0});let m=M.join(c,`.ref-${process.pid}-${Cr.randomUUID()}`);await oi(m,`${JSON.stringify(a,null,2)}
40
+ `,"utf8"),await Ig(m,M.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function Rr(e,t){let n=await wx(e,t),r=await Dg(M.join(cn(e),"objects",n,"manifest.json"),t);if(r.schema!==xg||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 fd(e){let t=cn(e),n=await dd(M.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&kt(o))return[];throw o}),r=await dd(M.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&kt(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Rr(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await Un(M.join(t,"refs",o),"utf8"))))}}async function _d(e,t){let n=await Rr(e,t),{manifest:r,contents:o}=await Ng(e),s=new Map(r.files.map((p,f)=>[p,o[f]])),i=await gx(M.join(cn(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=s.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=Cg(s.get(p)),_=Cg(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 $g(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",o=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,i=await we(e,Tr,o,r,!1,!1,s),a=new ld(Hr(e,Tr),r,o);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await _d(e,t),f=await Rr(e,t),_=await pd(e),g=f.fingerprint,y=cn(e),h=M.join(y,"objects",g,"files"),b=M.dirname(e),v=M.basename(e);c=M.join(b,`.${v}.restore-${Cr.randomUUID()}`);let S=M.join(b,`.${v}.backup-${Cr.randomUUID()}`);await Fg("restore_stage",async()=>{await an(c,{recursive:!0}),await Tg(h,c,{recursive:!0,force:!1}),await an(M.join(c,"runtime"),{recursive:!0}),await Tg(y,M.join(c,Og),{recursive:!0,force:!1})});let T=await Yu({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:p.changed_file_count,removed_file_count:p.removed_file_count,removed_item_count:p.removed_item_count,affected_history_stream_count:p.affected_history_stream_count,removed_history_entry_count:p.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:s}),x=M.relative(c,T.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let U=Hr(c,Tr);return await an(M.dirname(U),{recursive:!0}),await oi(U,await Un(Hr(e,Tr)),{flag:"wx"}),m=!0,await bx(c,e,S,Pg,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:x,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([md(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function Ug(e,t){ud(t);let n=cn(e);if(!/^[a-f0-9]{64}$/.test(t))return await Rg(M.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await fd(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Rg(M.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]="41227e35-6354-5208-997b-e8a1cf696bf9")}catch{}})();function Ir(e){let t={...e.args,...e.options};return ke(e.options,t)}function _t(e,t){let n=w(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Gn(e){return typeof e=="string"?[e]:Se(e)}function Gg(e){return mg(Ir(e),e.global)}function jg(e){let t=Ir(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 ri({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Gn(t.type),author:Gn(t.author),item:Gn(t.item),limit:t.limit===void 0?void 0:$e(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:Gn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Gn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Gn(t.provenanceFilter)}})}function qg(e){let t=Ir(e),n=_t(t,"subcommand");if(n==="install")return Bp({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return hg({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return wf({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return pg({artifact:_t(t,"artifact"),basePath:_t(t,"basePath"),oursPath:_t(t,"oursPath"),theirsPath:_t(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw Pe({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Kg(e){let t=Ir(e),n=_t(t,"subcommand");if(n==="position")return Hf(e.global);if(n!=="snapshot")throw Pe({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??_t(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return pd(o,{name:w(t,"name")});if(r==="list")return fd(o);let s=_t(t,"target");if(r==="inspect")return Rr(o,s);if(r==="delete")return Ug(o,s);if(r==="restore")return t.dryRun===!0?_d(o,s):$g(o,s,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:$e(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:$e(t.lockWaitMs,"lockWaitMs")});throw Pe({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function si(e){let t=Ir(e),n=_t(t,"title");return e.action==="meet"?Sg(n,t,e.global):e.action==="event"?Eg(n,t,e.global):Ag(n,t,e.global)}import Lx from"node:path";import vx from"node:fs/promises";import zg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5c70da27-21f6-5d31-b506-96e1818996d6")}catch{}})();var kx="templates",Sx=".json",Ex=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ax=Oo.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),Tx=new Set(Ax);function Cx(e){let t=e.trim();if(!Ex.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 Bg(e){return zg.join(e,kx)}function Hg(e,t){return zg.join(Bg(e),`${t}${Sx}`)}async function Rx(e){await R(e)}function Vg(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function Ix(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(Tx.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(s=>typeof s=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return Vg(t)}function xx(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[o,s]of Object.entries(n)){let i=o.trim();if(i.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof s=="string"){r[i]=s;continue}if(Array.isArray(s)&&s.every(a=>typeof a=="string")){r[i]=[...s];continue}throw new l(`Template "${t}" contains invalid value for option "${i}".`,d.GENERIC_FAILURE)}return Vg(r)}function Ox(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,o=xx(r.options,t),s=k();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:s,updated_at:typeof r.updated_at=="string"?r.updated_at:s,options:o}}async function Px(e,t){let n=await K(Hg(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return Ox(n,t)}async function hd(e,t,n){let r=E(process.cwd(),n.path);await Rx(r);let o=Cx(e),s=Ix(t);if(Object.keys(s).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let i=k(),a=Hg(r,o),c=i;await P(a)&&(c=(await Px(r,o)).created_at);let m={name:o,created_at:c,updated_at:i,options:s},u=await A(r);return await vx.mkdir(Bg(r),{recursive:!0}),await Je({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
41
+ `,op:"templates:save",author:C(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]="f65b4f1f-5501-5829-a04b-d4fbcfb59f5c")}catch{}})();var Xg=["list","show","apply","lint"],Nx="schema-types",Fx="schema-statuses",Mx="schema-fields";function ii(){let e=I();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Qg(){let{profiles:e,warnings:t}=Mm(ii());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:jm(n.definition)})),warnings:t,generated_at:k()}}function Zg(e){let t;try{t=Ao(e,ii())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...qm(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function ey(e){let t;try{t=Ao(e,ii())}catch(o){throw new l(o instanceof Error?o.message:String(o),d.USAGE)}let{resolved:n}=t,r=du(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:k()}}function Dx(e,t){return Lx.join(e,"templates",`${t}.json`)}async function $x(e,t){let n=await K(Dx(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function Wg(e,t,n,r){let o=new Map;for(let s of r.templates){let i=await $x(e,s.name);i!==void 0&&o.set(s.name,i)}return{typesRaw:await K(st(e,t.files.types,ot.types)),statusesRaw:await K(st(e,t.files.statuses,ot.statuses)),fieldsRaw:await K(st(e,t.files.fields,ot.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function jn(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function Yg(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:jn(t.types.changes),statuses:jn(t.statuses.changes),fields:jn(t.fields.changes),workflows:jn(t.workflows.changes.map(s=>({key:s.type,status:s.status}))),config:jn(t.config.changes),templates:jn(t.templates.changes.map(s=>({key:s.name,status:s.status}))),packages:t.packages,warnings:[...new Set(o)].sort((s,i)=>s.localeCompare(i)),generated_at:k()}}async function Ux(e){await R(e)}function Gx(e){try{let t=Ao(e,ii());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function ty(e,t,n){let r=E(process.cwd(),n.path);await Ux(r);let o=Gx(e),s=o.profile,i=o.warnings,a=t.dryRun===!0,c=await A(r),m=To(c.schema);if(a){let b=await Wg(r,m,c,s),v=Jg(s,b);return Yg(s,v,!1,!0,[...i])}let u=C(t.author,c.author_default),p=Xu(c),f=!!t.force,_=[...i],g=[],y=async b=>{g.push(await we(r,b,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},h;try{await y(Nx),await y(Fx),await y(Mx);let b=await Wg(r,m,c,s);if(h=Jg(s,b),h.types.changed){let v=st(r,m.files.types,ot.types);await Je({pmRoot:r,filePath:v,raw:Eo(h.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(s.types.map(x=>xm(x).name)),T=h.types.file.definitions.filter(x=>S.has(x.name));await Xp(r,T,_,"profile:apply-type-folder"),_.push(...await W({path:v,scope:"project",op:"profile:apply-types"}))}if(h.statuses.changed){let v=st(r,m.files.statuses,ot.statuses);await Je({pmRoot:r,filePath:v,raw:Gm(h.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await W({path:v,scope:"project",op:"profile:apply-statuses"}))}if(h.fields.changed){let v=st(r,m.files.fields,ot.fields);await Je({pmRoot:r,filePath:v,raw:Dm(h.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await W({path:v,scope:"project",op:"profile:apply-fields"}))}if(h.config.changed||h.workflows.changed){for(let v of h.config.changes){if(v.status==="unchanged")continue;let S=Ro(v.key);S!==void 0&&Io(c,S,v.value)}c.schema.type_workflows=h.workflows.result,await Oe(r,c,"profile:apply-config")}for(let v of h.templates.changes)v.status!=="unchanged"&&await hd(v.name,{...v.options},n)}finally{for(let b of g.reverse())try{await b()}catch{}}return Yg(s,h,h.changed,!1,_)}function Jg(e,t){try{return lu(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import ry from"node:fs/promises";import oy 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 jx(e,t,n){let r=new Set,o=[];for(let s of e){let i=s.trim();if(i.length===0||r.has(i))continue;r.add(i);let a=t.get(i);if(a===void 0){o.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){o.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return o}function qx(e,t){let n=[...e].sort((o,s)=>s.entries-o.entries||o.id.localeCompare(s.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function ny(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return jx(t.ids,n,t.minEntries)}return qx(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]="26c39ecd-5d72-5cc9-b22b-6abc33fbf4ac")}catch{}})();function Kx(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 s=Number.parseInt(n,10),i=kn(t);if(!Number.isSafeInteger(s)||s<i+1||s>i+t.length+1)throw new l(`history-compact --before version must be between ${i+1} and ${i+t.length+1}.`,d.USAGE);let a=s-i-1;return{kind:"version",raw:n,compactCount:a,retainedCount:t.length-a}}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 o=0;for(let[s,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 ${s+1}.`,d.GENERIC_FAILURE);if(a>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function zx(e,t){let n=$o(),r=$o();for(let o=0;o<e.length;o+=1){let s=e[o];n=Sa(n,s.patch,o+1,s.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}async function Bx(e,t,n){let r=e.located?await Q(e.located,{schema:t.schema}):null;if(!r)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let o=n[n.length-1];return{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:Ku.some(s=>(o.item_hash_version===void 0||o.item_hash_version===s)&&Hu(tr(r.document),s).includes(o.after_hash))}}function Hx(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 Vx(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 Wx(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=zx(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=kn(e.historyEntries,!0),s=qe({nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:Ht($o()),after:Ht(t),message:Vx(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:zu(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),i=e.historyEntries[e.boundary.compactCount-1],a=[Bu({...s,before_hash:e.historyEntries[0].before_hash,after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...r];return e.dryRun||a.push(qe({nowIso:k(),author:e.author,op:"history_compact",before:Ht(n),after:Ht(n),message:Hx(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Yx(e){return dp({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})=>cp({historyPath:e.historyPath,nextHistoryRaw:Wu(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>W({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function gd(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await A(r),s=O(o,I()),i=await lp(r,e,o,s.type_to_folder),a=i.historyPath,c=await K(a);if(c===null)throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let m=await bn(a,i.id);if(m.length===0)throw new l(`No history entries exist for ${i.id}; nothing to compact.`,d.USAGE);let u=ya(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=Kx(t.before,m),f=p.compactCount>0,_=!!t.dryRun,g=C(t.author,o.author_default),y=[];f||y.push("history_compact_noop_before_boundary");let h=await Bx(i,o,m);h.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:S}=Wx({historyEntries:m,boundary:p,changed:f,dryRun:_,author:g,options:t}),T=ya(b);if(!T.ok)throw new l(`history-compact produced an invalid rewritten chain (${T.errors.join(", ")}).`,d.GENERIC_FAILURE);f&&!_&&y.push(...await Yx({pmRoot:r,subject:i,settings:o,typeRegistry:s,historyRawBeforeLock:c,currentItemRawBeforeLock:h.currentItemRawBeforeLock,author:g,force:t.force,loadedItem:h.loadedItem,historyPath:a,rewrittenEntries:b}));let x=kn(m,!0),U=p.retainedCount>0&&x!==null?x+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:U},history:{path:a,entries_scanned:m.length,entries_after:b.length,baseline_entry_added:v,audit_entry_added:S,verify_ok:T.ok,verify_errors:T.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:h.matchedChainBefore},warnings:[...new Set(y)].sort((N,ee)=>N.localeCompare(ee)),generated_at:k()}}var Jx=3;function Xx(e){let t=Jo(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:Yo(t)}}function sy(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 Qx(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function Zx(e){let t=D(e.settings.schema),n=us(t),r=await ue(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),s=oy.join(e.pmRoot,"history"),i=[],a=[];if(!await P(s))return{candidates:i,preselectionErrors:a};let c=(await ry.readdir(s)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=oy.join(s,m),p=m.slice(0,-6);try{let f=await ry.readFile(u,"utf8");await _n({path:u,scope:"project"}),i.push({id:p,entries:Qx(f),bucket:o.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:i,preselectionErrors:a}}async function eO(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 gd(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 iy(e,t){let n=Xx(e),r=E(process.cwd(),t.path);await R(r);let o=await A(r),s=O(o,I()),{candidates:i,preselectionErrors:a}=await Zx({pmRoot:r,settings:o,typeToFolder:s.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??Jx,u=o.history.compact_policy,p=c==="scan"&&e.allOver===void 0&&u.enabled,f=e.allOver??(p?u.max_entries:void 0),_=ny(i,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),g=!!e.dryRun,y=[...a],h={streams_considered:i.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let b of _){let v=await eO({row:b,options:n,dryRun:g,global:t});if(y.push(v.result),!v.selected){h.items_skipped+=1;continue}h.selected+=1,v.compacted&&(h.items_compacted+=1),v.errored&&(h.items_errored+=1)}return{bulk:!0,dry_run:g,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:p},totals:h,results:y,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4888a558-7f50-5c28-8e29-fcd19180cbd4")}catch{}})();function ay(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return Ef(n,t),t?as(e.options,e.global):Pt(n,e.options,e.global)}function cy(e){let t=e.options.ids,n=Jo(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:Yo(n),o=$e(e.options.allOver??e.options.all_over,"history-compact allOver"),s=$e(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),i=w(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(i==="closed"||i==="all-streams")&&a.push(i);let c=[...new Set(a)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let m=c[0];return sy(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?gd(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):iy({ids:r,scope:m,allOver:o,minEntries:s,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function ai(e){return Co("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08dcee99-5572-5133-b76a-6a50e4e292e7")}catch{}})();async function yd(e,t,n,r){let o=t.trim();if(o.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",d.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let s=E(process.cwd(),r.path),i=D((await A(s)).schema),a=i.open_status,c=ai(i),m=n.status??a,u=X(m,i)??m;if(u!==a&&u!==c)throw new l(`Reopen target status must be ${a} or ${c}; received ${m}.`,d.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([a,c])],suggested_retry:`pm item reopen ${e} "${o}" --status ${a}`,suggested_retry_args:["item","reopen",e,o,"--status",a]}});let p=await ch(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:p.item,changed_fields:p.changed_fields,warnings:p.warnings,recurrence:p.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="55869854-565d-52d2-8dca-b66aade074bb")}catch{}})();function dy(e,t){let n=e.id??w(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function ly(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function my(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options);return je(await lt(dy(e,r),ly(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function uy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options);return je(await yd(dy(e,r),ly(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2ef0de1-bc44-5550-862c-f3929334fbef")}catch{}})();function py(e,t,n){let r;if(typeof e.lines=="string")r=cs(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=cs(`${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]="5ceccf7d-78cb-5750-8e4b-793efa6e716c")}catch{}})();var tO=ia("list").properties.outputSession,nO={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:{...tO},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},fy={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},se={type:"string",description:"pm item id, for example pm-abc1."},rO=`Operation name (one of): ${ta.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,oO={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."}},sO={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 $(e,t=[]){return{...fy,properties:{...fy.properties,...e},required:t}}var iO=[{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:$({action:{type:"string",enum:[...ta],description:rO},id:se,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."},...nO},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:$({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{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:$({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:$({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:$({query:{type:"string"},options:{type:"object"},...sO},["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:$({options:{type:"object"},...oO})},{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:$({id:se,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:$({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:$({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:$({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:se,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:$({id:se,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:$({id:se,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:$({id:se,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:$({id:se,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:$({id:se,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:$({id:se,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:$({id:se,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. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. 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:$({id:se,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:$({id:se,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:$({id:se,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:$({id:se,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:$({id:se,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:$({id:se,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:$({subcommand:{type:"string",enum:[...Zm]},id:se,target:se,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:$({id:se,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:$({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:$({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:$({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:$({subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset"],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or custom field key (show-field/add-field/remove-field). Required for those subcommands."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...$i]},description:`Lifecycle roles for add-status: ${$i.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys."}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:$({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:$({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:$({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."}})}],aO={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"},cO=iO.map(e=>{let t=aO[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:ia(t,{properties:n,required:r})}});function _y(){return cO.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="188569e7-c809-5f28-a714-d531f57be1d9")}catch{}})();var hy=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"]]]),dO=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Ty=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),di=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),xr=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"]),Cy=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"]]),Ry=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"]]),Iy=new Map([...Ry.entries()].flatMap(([e,t])=>ht(t).map(n=>[n,e]))),xy=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Oy=new Map(xy.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),lO=10,mO=20,gy=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks from evidence."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["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."]]),Py=[["init",zl],["install",Hl],["uninstall",Vl],["explore",Wl],["manage",em],["describe",Yl],["reload",tm],["doctor",nm],["catalog",rm],["adopt",om],["adopt-all",Jl],["activate",Xl],["deactivate",Ql],["migrate",Zl]],uO=[...Py.map(([e,t])=>e==="init"?[e,Bl]:[e,t]),["upgrade",Jn]],pO=[...Py.map(([e,t])=>[`extension ${e}`,t]),...uO.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",no],["config",Kl],["extension",ro],["package",Yn],["packages",Yn],["install",sm],["create",lo],["item mutate",Em],["item complete",Am],["item reopen",Tm],["copy",mo],["focus",uo],["update",po],["update-many",fo],["upgrade",Jn],["calendar",Xn],["cal",Xn],["context",Qn],["ctx",Qn],["get",ho],["search",vo],["eval",Rm],["workspace",St],["workspace position",[]],["workspace snapshot",St],["workspace snapshot create",St],["workspace snapshot list",St],["workspace snapshot inspect",St],["workspace snapshot restore",St],["workspace snapshot delete",St],["next",wo],["aggregate",Qr],["deps",yo],["graph",bo],["guide",go],["reindex",im],["history",Zr],["history-compact",Gl],["history-redact",$l],["history-repair",Ul],["history-author-acknowledge",eo],["merge",Dl],["schema",jl],["profile",ql],["plan",to],["restore",dm],["delete",lm],["close",am],["close-many",oo],["append",so],["claim",cm],["release",mm],["start-task",um],["pause-task",pm],["close-task",fm],["comments",Pl],["notes",Ll],["learnings",Nl],["files",Fl],["docs",Ml],["test",gm],["test-all",ym],["telemetry",bm],["test-runs",wm],["gc",vm],["stats",io],["duplicates",ao],["validate",km],["health",co],["assurance",Sm],...Im,["contracts",ko],["completion",So],["activity",_o],...[...Ty].map(e=>[e,Xr])],kd=new Map(pO);function fO(e){let t=Iy.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function yy(e){return Zi.includes(e)?he(e):e.startsWith("extension-")?he(`extension ${e.slice(10)}`):e.startsWith("package-")?he(`package ${e.slice(8)}`):e.startsWith("item-")?he(`item ${e.slice(5)}`):e.startsWith("test-runs-")?he(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?he(`templates ${e.slice(10)}`):di.has(e)?Ry.get(e)??he(e):null}function _O(e,t){return e.command_path===null?!1:ht(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `)||t.startsWith(`${n} `))}function ht(e){return e.split("|").map(t=>he(t)).filter(t=>t.length>0)}function hO(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let s of ht(o.command_path)){let i=s.split(" ").filter(a=>a.length>0);if(i.length!==0)for(let a=i.length;a>0;a-=1){let c=i.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,s)=>o.localeCompare(s))}function ci(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Or(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function gO(e,t){if(!t)return{...e};let r=Or(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:r}}function bd(e,t){let r=Or(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function he(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Ly(e){return e.replace(/\s+/g,"-")}function Qe(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function by(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=Qe(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function wd(e,t,n){n&&(e[t]=!0)}function wy(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 yO(e){let t=wy(e.long,"long"),n=wy(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),wd(o,"required",e.required===!0),wd(o,"repeatable",e.repeatable===!0),wd(o,"list",e.list===!0);let s=Qe(e.description);s&&(o.description=s);let i=Qe(e.value_name);i&&(o.value_name=i);let a=[Qe(e.value_type),Qe(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(o.value_type=a),o}function Ny(e){let t=new Map;for(let r of e){let o=he(r.target_command);if(o.length===0)continue;let s=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;s.sourceDedupe.has(i)||(s.sourceDedupe.add(i),s.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=yO(a);if(!c)continue;let m=`${c.flag}|${c.short??""}`;s.dedupe.has(m)||(s.dedupe.add(m),s.flags.push(c))}t.set(o,s)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((s,i)=>{let a=s.layer.localeCompare(i.layer);return a!==0?a:(s.name??"").localeCompare(i.name??"")})});return n}function bO(e){let t=Ny(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let i=he(s.command);if(i.length===0)continue;let a=Qe(s.action)??Ly(i),c=Array.isArray(s.arguments)?s.arguments.map(m=>{let u=Qe(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:Qe(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{command:i,action:a,source:{layer:s.layer,name:s.name},description:Qe(s.description),intent:Qe(s.intent),arguments:c,flags:t.get(i)?.flags??[],examples:by(s.examples),failure_hints:by(s.failure_hints)})}let r=new Set;for(let s of e.handlers)r.add(he(s));for(let s of n.keys())r.add(s);for(let s of t.keys())r.add(s);let o=[];for(let s of[...r].sort((i,a)=>i.localeCompare(a))){let i=n.get(s);o.push(wO(s,i,t.get(s)?.flags??[]))}return o}function wO(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Ly(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function vO(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(o,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function kO(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 SO(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function EO(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=kO(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let s=vO(o);!s||n[s]!==void 0||(n[s]=SO(o,e.action),o.required===!0&&r.push(s))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function AO(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 TO(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((s,i)=>s.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let i=`${s.flag}|${s.short??""}`;if(!o.has(i))o.add(i),r.flags.push(s);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);a&&AO(a,s)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function CO(e,t=A){let n={mode:wt.extensions.policy.mode,trust_mode:wt.extensions.policy.trust_mode,default_sandbox_profile:wt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await P(me(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),s=await Wr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),i=await Yr({...s,loaded:s.loaded});return{handlers:new Set(i.commands.handlers.map(c=>he(c.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function RO(e,t={}){let n=new Map;for(let r of ea){let o=di.has(r);if(o&&!t.includePackageOwnedActions)continue;let s=yy(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:s})}if(t.includePackageOwnedActions)for(let r of di)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:yy(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:he(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function IO(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?ht(e.command_path):[],r=n.some(i=>t.handlers.has(i)),o=n.map(i=>Cy.get(i)).find(i=>typeof i=="string"),s=t.disabledReason===null&&r;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function Fy(e){return kd.get(e)??Jr}function xO(e){return xr.has(e)?!1:kd.has(e)}function OO(e){return Ty.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function vy(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function PO(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function LO(e){let t=new Map;for(let r of e.definitions){let o=vy(r.cli_flag);if(!o)continue;let s=r.cli_aliases.map(a=>PO(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>vy(a)).filter(a=>a!==null&&a!==o);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=s?{flag:o,short:s}:{flag:o},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,o]of t.entries())n.set(r,Ji(o.flags));return n}function ky(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let s=`${o.flag}|${o.short??""}`;r.has(s)||(r.add(s),n.push(o))}return Ji(n)}function NO(e,t,n,r){return e.map(o=>{let s=xO(o),i=s?Fy(o):[],a=n.get(OO(o))??[],c=t.get(o),m=ky(i,a),u=ky(m,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:o,flags:u,...r?{canonical_command:vd(o),visibility:Eu(vd(o)),positionals:Il(o)?.slots??[],flag_invocations:Su(o,u)}:{},provider:p,extension_sources:c?.sources}}).sort((o,s)=>o.command.localeCompare(s.command))}function FO(e,t=Wn){let n=new Set(e),r=new Map;for(let o of xy){let s=o.aliases.filter(i=>n.has(i));r.set(o.canonical,{canonical:o.canonical,aliases:s,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let s=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};s.aliases.includes(o.alias)||s.aliases.push(o.alias),s.contracts.push(o),r.set(o.canonical,s)}return[...r.values()].map(({contracts:o,...s})=>o.length===0?s:{...s,contracts:o}).sort((o,s)=>o.canonical.localeCompare(s.canonical))}function MO(){return{create_string_options:mu,create_repeatable_options:Oo,update_string_options:uu,update_repeatable_options:pu,list_string_options:El,search_string_options:Al,calendar_string_options:Tl,context_string_options:Cl,activity_string_options:Rl}}function Sy(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=un(e,"create",n),o=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(o.map(a=>be("create",a)))].sort((a,c)=>a.localeCompare(c)),i=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:o,required_flags:s,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function DO(e){let t={},n={};for(let r of[...e.types].sort((o,s)=>o.localeCompare(s))){let o=e.by_type[r];t[r]=Sy(o,"strict"),n[r]=Sy(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function $O(e,t){let n=Or(e);if(n.length===0)return e;let r=!1,o=n.map(s=>{let i=s.properties;if(typeof i!="object"||i===null)return s;let a=i.action;return typeof a!="object"||a===null||a.const!=="create"?s:(r=!0,{...s,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function UO(e){let t=ci(e.action)!==void 0||ci(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,s=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=ci(e.action),u=ci(e.command),p=!r&&!c&&!o&&!s&&!i&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:o,flagsOnly:s,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function GO(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 jO(e,t=A){try{return await t(e)}catch{return structuredClone(wt)}}async function qO(e,t){let n=await jO(t),r=await CO(e),o=O(n,r.registrations??I()),s=Ye(n.schema),i=bO(r);return{settings:n,runtimeProbe:r,typeRegistry:o,statusRegistry:D(n.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:LO(s),createRequiredOptionContracts:DO(o),extensionContracts:i,mergedExtensionContracts:TO(i),extensionFlagMap:Ny(r.flagRegistrations)}}function Ey(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&di.has(e.selectedAction)||e.selectedCommand!==void 0&&xr.has(e.selectedCommand))}function KO(e,t){let n=RO(t,{includePackageOwnedActions:Ey(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(nu);return n.filter(o=>!r.has(o.action))}return Ey(e)&&e.selectedCommand!==void 0&&xr.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:fO(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function zO(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 BO(e,t){return[...new Set([...Zi.filter(n=>!xr.has(n)),...[...kd.keys()].filter(n=>!xr.has(n)),...e.flatMap(n=>n.command_path?ht(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>he(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function HO(e,t){let n=t.slice(0,lO),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),s=t.slice(0,mO),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: ${o}.`,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:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function VO(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 WO(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 YO(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(s=>s.startsWith(`${e.selectedCommand} `));if(r.length>0)throw HO(e.selectedCommand,r);let o=Cy.get(e.selectedCommand);throw o?VO(e.selectedCommand,o):WO(e.selectedCommand)}function JO(e,t){let n=KO(e,t.mergedExtensionContracts);zO(e,n);let r=BO(n,t.mergedExtensionContracts);YO(e,r);let o=e.selectedCommand?Iy.get(e.selectedCommand):void 0,s=e.selectedCommand?n.filter(m=>o?m.action===o:_O(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.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?s.filter(m=>m.action===e.selectedAction):s,a=[...new Map(i.map(m=>IO(m,t.runtimeProbe)).map(m=>[o?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:s,scopedActionDescriptors:i,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function XO(e){return new Set(Or(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function QO(e){let t=cu,n=Or(t),r=XO(t),o=e.filter(s=>!r.has(s.action)).map(s=>EO(s));return o.length>0?{...t,oneOf:[...n,...o]}:t}function Ay(e,t,n){let r=new Set(t.actionDescriptors.map(s=>s.action)),o=e.selectedAction?gO(n,e.selectedAction):e.selectedCommand?bd(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):bd(n,r);return e.runtimeOnly&&!e.selectedAction?bd(o,new Set(t.actions)):o}function ZO(e,t,n){let r=QO(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?$O(Ay(e,n,r),t.createRequiredOptionContracts):Ay(e,n,r);return{mergedSchema:r,filteredSchema:s}}function eP(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?hO(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function tP(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Wn.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function vd(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":Oy.get(t)??t}var nP=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"],["upgrade","Upgrade"]]),rP=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function oP(e,t){let n=gy.get(e)??(e.includes(" ")?void 0:gy.get(vd(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>ht(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 o=e.split(" "),s=o.at(-1),i=o.slice(0,-1).join(" "),a=nP.get(s),c=rP.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function sP(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(he))].filter(s=>s.length>0).sort((s,i)=>s.localeCompare(i)).map(s=>{let i=na(s,{generateFallback:!0}),a=s.split(" ")[0],c=Oy.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),m=new Set([...Fy(s).map(f=>f.flag),...t.filter(f=>ht(f.command).includes(s)).flatMap(f=>f.flags.map(_=>_.flag))]),u=(hy.get(s)??hy.get(c)??dO).filter(f=>m.has(f)),p=oP(s,t);return{command:s,intent:p.intent,...o||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:i.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...i.default_max_estimated_tokens_by_format}}:{}}})}function iP(e){return e.map(t=>({budget:na(t,{generateFallback:!0}),envelope:Cu(t)}))}function aP(e){let t=new Map;for(let n of e){let r=_u(n),o=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,s=o.join(","),i=t.get(s)??{commands:[],exit_codes:o};i.commands.push(n),t.set(s,i)}return[...t.values()]}function cP(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>ht(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>ht(o.command).some(s=>r.has(s)))}return t.extensionContracts}function dP(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 lP(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,s])=>[o,[...new Set(s.map(i=>`--${i.cli_flag}`))].sort((i,a)=>i.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Vm],services:[...Wm],policy_modes:[...Ym],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Qm],trust_modes:[...Jm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Xm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...nl],create_modes:[...rl],close_validation_modes:[...ol],workflow_enforcement_modes:[...sl]},e.relationship_kind_contracts=[...ul,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,s)=>o.kind.localeCompare(s.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function mP(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 uP(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=NO(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let s=new Set(r);e.list_projections=Object.entries(xu).filter(([i])=>s.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...Iu],compact_fields:[...Ru]}))}e.command_aliases=o}}function pP(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=MO();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function fP(e,t,n,r){e.command_summaries=sP(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...ou],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(he))].filter(o=>oa(o)!==void 0).sort((o,s)=>o.localeCompare(s)).map(o=>({command:o,modes:[...iu(o).keys()]}))}:{}},e.grammar_contracts={nouns:Kt.nouns,shared_verbs:Kt.shared_verbs,scope_before_verb:Kt.scope_before_verb,visible_top_level_ceiling:Kt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Kt.ceiling_raise_requires_pm_item,positional_shape_budget:Kt.positional_shape_budget,positional_shape_count:new Set(Yi.map(({slots:o})=>Ol(o))).size,positional_action_count:Wi.length,positional_action_parents:[...new Set(Wi.map(({parent:o})=>o))].sort((o,s)=>o.localeCompare(s)),...r.includePositionalSignatures?{positional_signatures:Yi}:{}}}async function My(e,t){let n=UO(e);GO(n);let r=E(process.cwd(),t.path),o=await qO(t,r),s=JO(n,o),i=ZO(n,o,s),a=eP(n,s),c=tP(n,a),m=dP(n,i,s,c),u=cP(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&fP(m,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return m;let f=FO(s.commandCatalog);return n.flagsOnly&&!n.fullOutput||lP(m,o,n),mP(m,n,i,u),uP(m,n,o,c,f),pP(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...Pp],gate_triggers:[...Op]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=xl),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=_y(),m.context_intents=bu(),m.read_output_dimensions=ra,m.error_codes=ku,m.command_output_contracts=iP(c),m.diagnostic_output_contracts=su,m.command_exit_contracts={vocabulary:fu,command_sets:aP(c)}),m}import XP from"node:fs/promises";import eb from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed44fc89-8b6e-5c83-a4f4-ced4e9031dac")}catch{}})();function li(e,t,n,r,o,s="min"){let i=o==="min"?e-t:t-e,a=s==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&a<0}function _P(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,s=null,i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let 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)||(li(f,i,p,o,"min")&&(i=f,o=p),li(f,a,p,s,"max","max")&&(a=f,s=p))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:s}}function Dy(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:g})=>_P(_,g)),s=0,i=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of o){if(s+=_.lines,i+=_.bytes,_.oldest_ts!==null){let g=Date.parse(_.oldest_ts);li(g,m,_.id,a?.id??null,"min")&&(m=g,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let g=Date.parse(_.newest_ts);li(g,u,_.id,c?.id??null,"max")&&(u=g,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...o].sort((_,g)=>g.bytes-_.bytes||_.id.localeCompare(g.id)).slice(0,r),f=r===0?[]:[...o].sort((_,g)=>g.lines-_.lines||_.id.localeCompare(g.id)).slice(0,r);return{total_streams:e.length,total_lines:s,total_bytes:i,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as gP}from"node:crypto";import{execFile as yP}from"node:child_process";import Gy from"node:path";import{promisify as bP}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="939d5f93-d287-5c1c-bc78-d013f76735f2")}catch{}})();var $y=1;function hP(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 Sd(e){if(e===null)return{format_version:$y,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!==$y||!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(!hP(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]="c2e1edc9-c454-5cfa-85c8-e9fb0a76a296")}catch{}})();var wP=bP(yP),vP=50,Uy=1e3,kP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function jy(e){let t=e.trim().toLowerCase();if(!kP.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 SP(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 Pr(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 EP(e){let t=e??vP;if(!Number.isSafeInteger(t)||t<0||t>Uy)throw new l(`Improvement observation limit must be an integer from 0 to ${Uy}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function qy(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 AP(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=jy(n.metric),o=SP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let s=await CP(e,n.revision),i=Pr(n.source,"source"),a=Pr(n.itemId,"itemId"),c=Pr(n.unit,"unit"),m=Pr(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,r,i??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:qy(n.observedAt??k(),"observedAt"),...s,author:C(n.author,t.author_default),...a===void 0?{}:{item_id:a},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:gP("sha256").update(qt(u)).digest("hex").slice(0,24),...u}}function TP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new 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(o=>o.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 CP(e,t){let n=Pr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await wP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:ll(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function RP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function Ky(e,t={}){let n=E(process.cwd(),t.path);await R(n);let r=await A(n),o=await AP(n,r,e),s=Gy.join(n,"improvement-ledger.json"),i=await Ju({pmRoot:n,filePath:s,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Sd(a),m=TP(c,o);return m?{raw:a,result:m}:(c.observations.push(o),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${qt(c)}
42
+ `,result:o})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function zy(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await R(t);let n=e.metric===void 0?void 0:jy(e.metric),r=e.since===void 0?void 0:qy(e.since,"since"),o=EP(e.limit),i=Sd(await K(Gy.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,o),total:i.length,truncated:i.length>o,trends:[...a].map(([,c])=>RP(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 By(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 IP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function xP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function Ed(e=er,t=gn){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function OP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function Ad(e,t=gn,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let s of t){let i=`${o.agent_harness}\0${s}`,a=r.get(i)??{harness:o.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=o.agent_provenance?.[s];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(i,a)}return[...r.values()].map(o=>{let s=o.observed+o.unavailable;return{...o,coverage:s===0?null:o.observed/s,inert:s>=n&&o.observed===0}}).sort((o,s)=>o.harness.localeCompare(s.harness)||o.dimension.localeCompare(s.dimension))}function PP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let u=`${c.agent_harness}\0${m}`,p=o.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),o.set(u,p)}let s=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[u])=>m.localeCompare(u)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),i=s.filter(c=>c.entries>=r),a=i.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:i.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:s,failures:a}}function LP(e){let t=[...e].sort((s,i)=>s.ts.localeCompare(i.ts)||s.author.localeCompare(i.author)||s.op.localeCompare(i.op)||s.before_hash.localeCompare(i.before_hash)||s.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let s of t){let i=s.agent_episode,a=By(s),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(s);continue}let u={id:a.id,...i?.label===void 0?{}:{label:i.label},...i?.parent_id===void 0?{}:{parent_id:i.parent_id},source:a.source,entries:[s],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let o=[];for(let s of n.values()){let i=s.parent_id?r.get(s.parent_id):void 0;i&&IP(s,i,r)?i.children.push(s):o.push(s)}return xP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var NP=1e4,Hy=1e5,FP=1e3,MP=30,DP=["append","comment","docs","file","learning","note","test_run"];function $P(e){let t=e??NP;if(!Number.isSafeInteger(t)||t<1||t>Hy)throw new l(`History analytics event limit must be an integer from 1 to ${Hy}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function Vy(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 UP(e){let t=e?.trim();if(!t)return new Date(Date.now()-MP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*s).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new 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 Wy(e,t){let n=$P(t.eventLimit),r=UP(t.since),o=[],s=r,i=!1;for(;o.length<n;){let a=await ri({pmRoot:e,since:s,limit:Math.min(FP,n-o.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),i=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:i,...i?{next_cursor:s}:{},source:"history_event_index"}}}function GP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function jP(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 qP(e){return DP.some(t=>e.startsWith(t))}function Yy(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 KP(e,t,n){let r=new Map,o=new Map,s=new Map;for(let i of t){let a=GP(i.entry,e),c=jP(i.entry),m=o.get(i.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&o.set(i.item_id,u),!a)continue;let p=Yy(r,a);p.events+=1,qP(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,s.set(i.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:s}}function zP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of o){let i=t.get(s);i&&(Yy(e,i).defectEscapes+=1)}}}function BP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function HP(e,t,n,r,o,s){let{buckets:i,lastCloseValue:a}=KP(e,t,r);return zP(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>BP(c,m,o,s)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function VP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),s=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(s)?1:Math.max(1,(s-o)/864e5)}function WP(e,t,n){let r=Ed(t),o=Ad(e,gn,n),s=o.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),i=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:o,inert:s,undeclared:i,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...i.map(a=>`provenance_dimension_undeclared:${a}`)]}}function Jy(e,t=er,n={}){let r=Vy(n.minimumSample);return{...WP(e.events.map(o=>o.entry),t,r),window:e.receipt}}function Xy(e,t,n,r={}){let o=Vy(r.minimumSample),s=VP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>HP(i,e.events,t,n,o,s)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var YP=32;function JP(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let s=o.slice(0,o.indexOf("=")).trim();r.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Lr(e,t){let n=JP(e).map(o=>{let[s,...i]=o.split(","),a=s.indexOf("="),c=s.slice(0,a).trim(),m=s.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${o}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,f;for(let _ of i){let g=_.indexOf("="),y=_.slice(0,g).trim(),h=_.slice(g+1).trim();if(y==="unit"&&h.length>0)p=h;else if(y==="threshold"&&h.length>0&&Number.isFinite(Number(h)))f=Number(h);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(o=>[o.name,o])).values()].sort((o,s)=>o.name.localeCompare(s.name)).slice(0,YP)}function Qy(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function Zy(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,i)=>i.recorded_at.localeCompare(s.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b56db1fc-d989-5d18-8b29-336a03f1e525")}catch{}})();function QP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function ZP(e,t,n,r,o){let s=lr(e,"type",r),i=new Set(s.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),m=(o?[...s.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=QP([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>o||f>0));return{byType:m,byStatus:p,omitted:o?0:a.length+Object.values(u).filter(f=>f===0).length}}function eL(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function tL(e){let t=eb.join(e,"history");if(!await P(t))return[];await _n({path:t,scope:"project"});let n=(await XP.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,s)=>o.localeCompare(s)),r=[];for(let o of n){let s=eb.join(t,o),i=await K(s);i!==null&&(await _n({path:s,scope:"project"}),r.push({id:o.slice(0,-6),raw:i}))}return r}async function nL(e,t){let n=[],r=k();for(let o of Lr(t.observe,r))n.push(await Ky({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function rL(e,t,n){let r={};return t.byAssignee&&(r.assignee=lr(e,"assignee",n)),t.byTag&&(r.tag=lr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=lr(e,"priority",n)),r}async function oL(e,t,n,r,o){let s={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},i=o.provenanceCoverage||o.fleetAttribution?await Wy(e,s):void 0;return{provenanceCoverage:o.provenanceCoverage&&i?Jy(i,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:o.fleetAttribution&&i?Xy(i,t,r,s):void 0}}function sL(e,t,n,r,o){let s=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...s?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:k()}}async function Td(e,t={}){let n=E(process.cwd(),e.path);await R(n);let r=await A(n),o=await nL(e,t),s=O(r,I()),i=D(r.schema),a=t.fieldUtilization?await rp(n,r.item_format,s.type_to_folder,void 0,r.schema):await ue(n,r.item_format,s.type_to_folder,void 0,r.schema);await ep({pmRoot:n,settings:r,itemIds:a.map(S=>S.id),commandLabel:"stats"});let c=us(i),m=ZP(a,s.types,i.definitions.map(S=>S.id),c,t.includeEmpty===!0),u=await tL(n),p=0;for(let S of u)p+=eL(S.raw);let f=t.storage?Dy(u):void 0,_=t.metadataCoverage?Gf(a,c):void 0,g=rL(a,t,c),y=t.fieldUtilization?jf(a):void 0,h=t.measurements===!0||o.length>0?await zy({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:b,fleetAttribution:v}=await oL(n,a,r,i.terminal_statuses,t);return sL({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:g,storage:f,fieldUtilization:y,improvementLedger:h,recordedObservations:o,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 tb(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:Se(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 iL from"node:fs/promises";import Mt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad3110ca-e85b-5a7e-b0a1-591796c298eb")}catch{}})();var ib=Mt.join("runtime","telemetry","events.jsonl"),ab=Mt.join("runtime","telemetry","state.json"),aL=Mt.join("runtime","telemetry"),cL=20,nb=["status","flush","stats","clear"],rb=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Cd=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,ob=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},dL=e=>({command:Cd(e.event.command,"<unknown>"),eventType:Cd(e.event.event_type,"unknown"),eventSchemaVersion:ob(e.event.schema_version),clientSchemaVersion:ob(e.client_schema_version)}),lL=()=>({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:{}}),mL=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},uL=e=>{let t=e?.command_resolution;return Cd(t,"")||void 0},cb=(e,t)=>{e[t]=(e[t]??0)+1},pL=(e,t)=>{let n=mL(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=uL(t);r!==void 0&&cb(e.resolution_counts,r)},fL=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,sb=(e,t)=>{t!==void 0&&e.add(t)},_L=(e,t)=>{let n=dL(t),r=e.get(n.command)??lL();r.count+=1,r.max_attempts=Math.max(r.max_attempts,fL(t.attempts)),cb(r.event_type_counts,n.eventType),sb(r.event_schema_versions,n.eventSchemaVersion),sb(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&pL(r,t.event.payload),e.set(n.command,r)},hL=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((s,i)=>s-i),o=Object.entries(t.resolution_counts).sort((s,i)=>s[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,i)=>s[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,i)=>s-i),client_schema_versions:[...t.client_schema_versions].sort((s,i)=>s-i),...r.length>0?{duration_p50_ms:rb(r,.5),duration_p95_ms:rb(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},gL=e=>{let t=(e??"status").trim().toLowerCase();if(nb.includes(t))return t;throw Pe({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:nb,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)},db=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Rd():e,yL=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Rd():db(Number.parseInt(t,10))},bL=e=>e===void 0?cL:typeof e=="number"?db(e):typeof e=="string"?yL(e):Rd(),wL=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},vL=e=>{try{let t=JSON.parse(e);return wL(t)?t:void 0}catch{return}},kL=e=>e===null?[]:e.split(`
43
+ `).map(t=>t.trim()).filter(t=>t.length>0),lb=e=>{let t=kL(e),n=[],r=0;for(let o of t){let s=vL(o);s===void 0?r+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},SL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),EL=e=>{try{let t=JSON.parse(e);return SL(t)?t:{}}catch{return{}}},AL=async e=>{let t=await K(e);return t===null||t.trim().length===0?{}:EL(t)},mi=e=>e??null,ui=async e=>{let t=await A(e),n=Mt.join(e,ib),r=Mt.join(e,ab),o=await K(n),s=lb(o),i=await AL(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:mi(i.last_attempted_flush_at),last_successful_flush_at:mi(i.last_successful_flush_at),last_failed_flush_at:mi(i.last_failed_flush_at),last_failed_flush_error:mi(i.last_failed_flush_error)}},TL=e=>{let t=new Map;for(let n of e)_L(t,n);return[...t.entries()].map(([n,r])=>hL(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},CL=async(e,t)=>({action:"telemetry",subcommand:"status",status:await ui(t.globalPmRoot),generated_at:k()}),RL=async(e,t)=>{let n=await ui(t.globalPmRoot);await Ep(t.globalPmRoot);let r=await ui(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),s=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:s,queue_drained:s,status:r,generated_at:k()}},IL=async(e,t)=>{let n=bL(e.limit),r=await K(t.queuePath),o=lb(r),s=TL(o.entries),i=s.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:s.length>i.length,stats:i,generated_at:k()}},xL=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 Oe(t.globalPmRoot,n,"telemetry:clear");let o=Mt.join(t.globalPmRoot,aL),s=await P(o);return await iL.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:s&&!await P(o),queue_exists_after:await P(t.queuePath),state_exists_after:await P(t.statePath),status:await ui(t.globalPmRoot),generated_at:k()}},OL={status:CL,flush:RL,stats:IL,clear:xL};async function mb(e,t){let n=gL(e.subcommand),r=nt(process.cwd());return OL[n](e,{globalPmRoot:r,queuePath:Mt.join(r,ib),statePath:Mt.join(r,ab)})}import{spawn as Ob}from"node:child_process";import{cp as Pd,mkdir as gi,mkdtemp as Pb,open as Ld,readdir as Nd,rm as Nr,symlink as Lb}from"node:fs/promises";import{tmpdir as Nb}from"node:os";import H from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62af7c1e-c1c7-529e-ab30-117103ac4607")}catch{}})();var ub=20;function PL(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return ub;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?ub:t}function Id(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let s=No(r.recorded_at,o.recorded_at);if(s!==0)return s;let i=r.run_id.localeCompare(o.run_id);return i!==0?i:r.kind.localeCompare(o.kind)}),n=PL();return t.length>n?t.slice(t.length-n):t}async function pi(e){await oe({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=Id([...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 pb=100;function xd(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 LL(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=pb?n:`${n.slice(0,pb-3)}...`}function fb(e){return e.map((t,n)=>`${n+1}. ${LL(t)}`).join("; ")}function NL(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 FL(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function _b(e,t){let n=NL(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,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 o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let s=[],i=[];for(let a=0;a<e.length;a+=1)FL(e[a],o)&&(i.push(e[a]),s.push(a+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${fb(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:s,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let o=xd(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${fb(e)}`,d.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="03f2f710-3b96-5671-85fa-d8ea4726ee86")}catch{}})();var hi=20*1024*1024,ML=3e3,DL=1e4,$L=5e3,hb=120,UL=new Set(["locks","extensions","runtime"]),GL=new Set(["history","index","search","extensions","locks","runtime"]),jL=[/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],qL=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,KL=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,zL=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 Dd(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 BL(){return Dd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",ML)}function HL(){return Dd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",DL)}function VL(){return Dd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",$L)}function WL(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 YL(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function $d(e){let t=0,n=0,r=0,o=0;for(let s of e){let i=s.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(r+=1),i.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function JL(e){let t=e??"project";if(!tt.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function yi(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Qt.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${Qt.join(", ")}`,d.USAGE)}function XL(e){return en(e??"source","--workspace-context")}function Fb(e,t,n){return n?t:en(e.workspace_context_mode,"linked test")??t}function Mb(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:yi(e.pm_context_mode)}function Db(e,t){return e==="auto"?t?"tracker":"schema":e}function QL(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 ZL(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 eN(e,t){let n={};if(!e)return n;for(let r of e){let o=br(r,t);if(o)for(let[s,i]of Object.entries(o))n[s]=i}return n}function tN(e,t){if(!e)return[];let n=[];for(let r of e){let o=wr(r,t);o&&n.push(...o)}return[...new Set(n)]}function nN(e){let t=bi(e);return dr(t).some(n=>Da(n)!==null)}function $b(e){let t=bi(e);return dr(t).some(n=>{let r=Da(n);if(!r)return!1;let o=Ff(r);return o?zL.has(o.subcommand):!1})}function fi(e){if(e)return Pf.has(e.subcommand)?xn(e.args,Lf)?.subcommand:e.subcommand}function gb(e,t){if(e==="npx"||e==="bunx")return ls(t)?.command;if(e==="pnpm")return fi(xn(t,Rf));if(e==="npm")return fi(xn(t,If));if(e==="yarn")return fi(xn(t,xf));if(e==="bun")return fi(xn(t,Of))}function _i(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function Od(e){return!e||!Ua(e.command)&&!Nf(e.command)?!1:ds(e.args)==="test-all"}var Ub=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])]),rN=new Set(["npx","bunx"]);function Gb(e){let t=e.split(" ").filter(i=>i.length>0),n=$a(t);if(n.length===0)return!1;let[r,...o]=n,s=Ub.get(r);if(s){let i=o.findIndex(a=>s.test(a));return i>=0?Gb(o.slice(i+1).join(" ")):!1}return Ua(r)||Ga(r)?ds(o)==="test-all":r==="node"&&o.length>0&&Ga(o[0])?ds(o.slice(1))==="test-all":rN.has(r)?Od(ls(o)):r==="pnpm"?Od(ja(o)):r==="npm"?Od(qa(o)):!1}function jb(e){let t=bi(e);return dr(t).some(n=>Gb(n))}function qb(e){if(jb(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function bi(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function Kb(e){let t=e.split(" ").filter(i=>i.length>0),n=$a(t);if(n.length===0)return!1;let[r,...o]=n,s=Ub.get(r);if(s){let i=o.findIndex(a=>s.test(a));return i>=0&&Kb(o.slice(i+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?oN(o):sN(r,o)}function oN(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"?_i(ls(t)?.command):e==="pnpm"||e==="npm"?_i((e==="pnpm"?ja(t):qa(t))?.command)||_i(gb(e,t)):(e==="yarn"||e==="bun")&&_i(gb(e,t))}function iN(e){if(jb(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function aN(e){return e?e.map(cN):[]}function cN(e){let t=e.trim(),n=L_(t)?Ns(ae(e,"--add"),"--add"):{command:t},r=fe(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return qb(r),{command:r,path:fe(n.path),scope:JL(n.scope),timeout_seconds:dN(fe(n.timeout_seconds),fe(n.timeout)),pm_context_mode:Us(fe(n.pm_context_mode),"--add"),workspace_context_mode:en(fe(n.workspace_context_mode),"--add"),env_set:br(fe(n.env_set),"--add"),env_clear:wr(fe(n.env_clear),"--add"),shared_host_safe:$s(fe(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:tn(fe(n.assert_stdout_contains)),assert_stdout_regex:Fn(fe(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:tn(fe(n.assert_stderr_contains)),assert_stderr_regex:Fn(fe(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Gs(fe(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:js(fe(n.assert_json_field_equals),"--add"),assert_json_field_gte:qs(fe(n.assert_json_field_gte),"--add"),note:fe(n.note)}}function fe(e){let t=e?.trim();return t&&t.length>0?t:void 0}function dN(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(pe(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function lN(e){return e?e.flatMap(t=>{let n=M_(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",d.USAGE);qb(o)}return n}):[]}function mN(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 o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:o}}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 o=ae(n,"--remove"),s=o.path!==void 0?"path":"command",i=o.path??o.command;if(!i?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:s,value:i.trim()}}return{kind:"either",value:n}}):[]}function uN(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 pN(e){try{e.stdin?.end()}catch{}}function zb(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=hb?t:`${t.slice(0,hb-3)}...`}function Bb(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Fd(e){try{process.stderr.write(`${e}
44
+ `)}catch{}}function fN(e,t){if(!Bb(t))return null;let n=zb(e.command),r=Date.now();Fd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let s=Date.now()-r;Fd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},HL());return o.unref?.(),o}function _N(e,t,n,r){if(!Bb(r))return;let o=zb(e.command),s=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let m=t.exitCode===null?"null":String(t.exitCode),u=c.length>0?` ${c.join(" ")}`:"";Fd(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${s}${u} command="${o}"`)}async function yb(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Ob("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 hN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function gN(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 yb(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{yb(r)},BL()),t.forceKillTimer.unref?.()}}function yN(e){return new Promise(t=>{let n=!1,r=null,o=(s,i=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,i)=>{n||(r=setTimeout(()=>{o({code:s,signal:i},!0)},VL()),r.unref?.())}),e.on("close",(s,i)=>{o({code:s,signal:i})})})}function bN(e,t,n,r,o){return Ob(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function bb(e){let t=await Ld(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,hi),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>hi}}finally{await t.close()}}async function wN(e,t,n,r,o,s=process.cwd()){let i=Date.now(),a=await Pb(H.join(Nb(),"pm-linked-test-output-"));try{let c=H.join(a,"stdout.log"),m=H.join(a,"stderr.log"),[u,p]=await Promise.all([Ld(c,"w"),Ld(m,"w")]),f;try{f=bN(e,n,u.fd,p.fd,s)}catch(z){throw await Promise.all([u.close(),p.close()]),z}let _=yN(f),g;f.on("error",z=>{g=z.message}),await Promise.all([u.close(),p.close()]),pN(f);let y={heartbeat:fN(r,o),forceKillTimer:null,timedOutTimer:null},h=gN(f,y),b=!1;y.timedOutTimer=setTimeout(()=>{b=!0,h()},t),y.timedOutTimer.unref?.();let{code:v,signal:S}=await _;hN(y);let[T,x]=await Promise.all([bb(c),bb(m)]),U=T.truncated||x.truncated,N=U?`
45
+ [pm linked-test output truncated at ${hi} bytes per stream; the child process continued to completion]
46
+ `:"",ee={stdout:`${T.text}${N}`,stderr:x.text,exitCode:v,signal:S,timedOut:b,maxBufferExceeded:!1,outputTruncated:U,spawnError:g};return _N(r,ee,i,o),ee}finally{await Nr(a,{recursive:!0,force:!0})}}function vN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${hi} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function kN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
47
+ `);return jL.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>qL.test(n)&&KL.test(n))}function SN(e){return kN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function EN(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function wi(e){let t=EN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function wb(e,t){for(let[n,r]of Object.entries(t.env_set))Zt.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)Zt.has(n.toUpperCase())||delete e[n]}function AN(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??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function CN(e,t,n){return{env_set:eN(e,"--env-set"),env_clear:tN(t,"--env-clear"),shared_host_safe:n===!0}}async function Kn(e,t,n=!1,r=gi){if(await P(e))try{await Vn("seed_linked_test",async()=>{if(await r(H.dirname(t),{recursive:!0}),n){await Pd(e,t,{recursive:!0,force:!0});return}await Pd(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&kt(o))return;throw o}}async function vb(e,t,n){await Kn(me(n.projectPmRoot),me(e)),await Kn(H.join(n.projectPmRoot,"extensions"),H.join(e,"extensions"),!0),await Kn(me(n.globalPmRoot),me(t)),await Kn(H.join(n.globalPmRoot,"extensions"),H.join(t,"extensions"),!0)}async function kb(e,t){if(!await P(e))return;let n=await Nd(e,{withFileTypes:!0});for(let r of n){if(UL.has(r.name))continue;let o=H.join(e,r.name),s=H.join(t,r.name);if(r.isDirectory()){await Kn(o,s,!0);continue}r.isFile()&&await Kn(o,s)}}async function Sb(e,t){let n=await K(me(e));if(n===null||await P(ba(e)))return;let r=await A(t);await Nr(ba(t),{force:!0}),await Nr(me(t),{force:!0}),await Je({pmRoot:t,filePath:me(t),raw:n,op:"settings:write",author:C(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function qn(e){if(!await P(e))return 0;let t=0,n=await Nd(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||GL.has(r.name))continue;let o=H.join(e,r.name),s;try{s=await Nd(o,{withFileTypes:!0})}catch{continue}for(let i of s)i.isFile()&&dl.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function RN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function IN(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let r of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isInteger(o)||o<0)return[];t.push(o);continue}t.push(r)}return t}function Eb(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=IN(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let s of r){if(typeof s=="number"){if(!Array.isArray(o)||s>=o.length)return{found:!1,value:void 0};o=o[s];continue}if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,s))return{found:!1,value:void 0};o=o[s]}return{found:!0,value:o}}function xN(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 ON(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?rt(e,t):Object.is(e,t)}function PN(e,t,n){let r=[];r.push(...Ab("stdout",t,e.assert_stdout_contains)),r.push(...Tb("stdout",t,e.assert_stdout_regex)),r.push(...Ab("stderr",n,e.assert_stderr_contains)),r.push(...Tb("stderr",n,e.assert_stderr_regex)),r.push(...LN(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(s).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,m]of Object.entries(o)){let u=Eb(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=xN(m);ON(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(s)){let u=Eb(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 Ab(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function Tb(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(s){r.push(`${e} regex assertion is invalid: /${o}/ (${s instanceof Error?s.message:String(s)})`)}return r}function LN(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},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],FN=[/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu,/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu,/\bTests?\s+[1-9]\d*\s+passed\b/iu,/\b[1-9]\d*\s+passed\b/iu,/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu];function MN(e,t){let n=`${e}
48
+ ${t}`;for(let r of NN)if(r.regex.test(n))return{code:r.code};return null}function DN(e,t){let n=`${e}
49
+ ${t}`;return FN.some(r=>r.test(n))}function Cb(e){let t=bi(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:dr(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&Kb(n))}function $N(e){return{root:e,schemaProjectPmPath:H.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:H.join(e,"schema","global"),trackerProjectPmPath:H.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:H.join(e,"tracker","global"),workspaceSnapshotRoot:H.join(e,"workspace","project"),workspaceIsolatedRoot:H.join(e,"workspace","isolated")}}function UN(e,t,n){return e.some(r=>Fb(r,t,n)==="snapshot")}async function GN(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await gi(H.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await Pd(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(o){let s=H.relative(t,o);return s?!s.split(H.sep).some(i=>n.has(i)):!0}});let r=H.join(t,"node_modules");await P(r)&&await Lb(r,H.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function jN(e,t){let n=H.join(e,".agents"),r=H.join(n,"pm");await gi(n,{recursive:!0}),await Nr(r,{recursive:!0,force:!0}),await Lb(t,r,process.platform==="win32"?"junction":"dir")}async function qN(e,t=Ar,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 KN(e,t,n){t&&(await vb(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await vb(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await kb(t.projectPmRoot,e.trackerProjectPmPath),await kb(t.globalPmRoot,e.trackerGlobalPmPath),await Sb(t.projectPmRoot,e.trackerProjectPmPath),await Sb(t.globalPmRoot,e.trackerGlobalPmPath)))}function zN(e,t,n){return e.some(r=>{let o=r.command??"",s=o.length>0&&$b(o),i=n?.autoPmContext===!0&&s?"auto":Mb(r,t,n?.overrideLinkedPmContext===!0);return Db(i,s)==="tracker"})}async function BN(e,t){return{sourceProjectItemCount:t?await qn(t.projectPmRoot):0,sourceGlobalItemCount:t?await qn(t.globalPmRoot):0,schemaProjectItemCount:await qn(e.schemaProjectPmPath),schemaGlobalItemCount:await qn(e.schemaGlobalPmPath),trackerProjectItemCount:await qn(e.trackerProjectPmPath),trackerGlobalItemCount:await qn(e.trackerGlobalPmPath)}}function HN(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:a,trust:e.trust}}async function VN(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?yi(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?nN(n):!1,o=r&&n?$b(n):!1,s=e.options?.autoPmContext===!0&&o,i=s?"auto":Mb(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Db(i,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await jN(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await Ka(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Ka(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:HN({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function Rb(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Md(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 WN(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function YN(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return WN(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function JN(e){if(!e.linkedTest.command)return Rb(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=iN(e.linkedTest.command);return t?Rb(e.linkedTest,e.executionContext,t):null}function XN(e){let t=JN(e);if(t)return t;let n=YN(e);if(n)return n;let r=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,o=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(r||o){let s=ZL({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),i=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Md(e.linkedTest,e.executionContext,`${i} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${s}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!QL(e.linkedTest)?Md(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function QN(e){let t=TN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return wb(n,e.runtimeDirectives),wb(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&AN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[ar]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[ar]="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 Ib(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.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function eF(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:RN(e.execution),failure_category:SN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:vN(e.execution,e.timeoutMs)}}function tF(e){if(e.options?.failOnEmptyTestRun===!0||Cb(e.linkedTest.command??"")){let n=MN(e.execution.stdout,e.execution.stderr);if(n)return Ib({...e,emptyRunSignal:n});if(Cb(e.linkedTest.command??"")&&!DN(e.execution.stdout,e.execution.stderr))return Ib({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let t=PN(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Md(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):ZN(e.linkedTest,e.executionContext,e.execution)}async function nF(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await wN(t,n,QN(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?tF({...e,execution:r}):eF({...e,execution:r,timeoutMs:n})}async function Ud(e,t,n){let r=[],o=await Pb(H.join(Nb(),"pm-linked-test-")),s=$N(o),i=yi(n?.pmContext),a=XL(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=CN(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,p=Df(),f=zN(e,i,n),_=UN(e,a,n?.overrideLinkedWorkspaceContext===!0),g=await Mf(p);try{await qN(s,Ar,f),await gi(s.workspaceIsolatedRoot,{recursive:!0}),await KN(s,u,f),_&&await GN(s,p);let y=await BN(s,u);for(let h=0;h<e.length;h+=1){let b=e[h],v=Fb(b,a,n?.overrideLinkedWorkspaceContext===!0),S=await VN({linkedTest:b,layout:s,counts:y,sourceRoots:u,runLevelPmContextMode:i,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:v,currentSourceRef:g,sourceWorkspaceRoot:p}),T=XN({linkedTest:b,executionContext:S.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:S.linkedOverridePmContextMode,options:n});if(T){r.push(T);continue}r.push(await nF({linkedTest:b,index:h,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:S.executionContext,options:n}))}}finally{await Nr(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function rF(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,s=await G(n,t,r.id_prefix,r.item_format,o);if(!s)throw new l(`Item ${t} not found`,d.NOT_FOUND);let i=await Q(s,{schema:r.schema});return{itemId:s.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function oF(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function sF(e,t){let n=[...e];for(let r of t)n.some(o=>oF(o,r))||n.push(r);return n}function iF(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((s,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:o,removed:e.length-o.length}}function aF(e,t,n,r){return iF(sF(e,t),n,r)}function cF(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function dF(e){if(cF(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --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 lF(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:s,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return rF({id:t,pmRoot:r,settings:o,typeToFolder:s});let m=0,u=await oe({pmRoot:r,settings:o,id:t,op:i.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=aF(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(g=>`${g.kind}=${g.value}`),...c.map(g=>`index=${g}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return p.metadata.tests=_.tests,{changedFields:rt(f,_.tests)?[]:["tests"]}}});return{itemId:u.item.id,tests:u.item.tests??[],testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:m}}function mF(e,t){dF(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:xd(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?_b(t,n):void 0,o=e.timeout===void 0?void 0:pe(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:yi(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function uF(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Ud(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:nt(process.cwd())}})}function pF(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=$d(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function fF(e){let t=YL(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=k(),s=Lr(e.options.measure,o);return{run_id:WL("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function _F(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:s,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let m=fF({options:t,runStartedAt:s,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return m;try{return await pi({pmRoot:n,settings:r,itemId:o,author:C(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:${o}:${u instanceof Error?u.message:String(u)}`),m}}function xb(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,o).trim(),i=e.metricBelow.slice(o+1).trim(),a=Number(i);if(o<=0||s.length===0||i.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",d.USAGE);r=Qy(t,s,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Zy(t,e.metricDiff)}}async function hF(e,t,n){if(e.acknowledgeLinkedTests===!0)return $f(t,n,k())}async function vi(e,t,n){let r=xt(),o=E(process.cwd(),n.path);await R(o);let s=await A(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);Lr(t.measure,"validation"),xb(t,[],void 0);let i=O(s,I()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...aN(a),...lN(c)],p=await On(u,C(t.author,s.author_default),k())??[],f=mN(m),_=uN(t.removeIndex),g=await lF({id:e,options:t,pmRoot:o,settings:s,typeToFolder:i.type_to_folder,adds:p,removes:f,removeIndexes:_}),y=mF(t,g.tests),h=await hF(t,o,g.tests),b=t.run===!0?k():void 0,v=await uF({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests}),S=wi(v),T=t.run===!0&&t.failOnSkipped===!0&&v.some(z=>z.status==="skipped"),x=pF(t,y.runSelection,v);h&&x.push(`linked_test_trust_acknowledged:${h.acknowledged}`);let U=await _F({options:t,pmRoot:o,settings:s,itemId:g.itemId,runStartedAt:b,runResults:v,failOnSkippedTriggered:T,warnings:x}),N=U?Id([...g.testRuns,U]):g.testRuns,ee=xb(t,N,U);return{ok:v.every(z=>z.status!=="failed")&&T!==!0,id:g.itemId,tests:g.tests,run_results:v,failure_categories:S,selection:y.runSelection?{selector:y.runSelection.selector,requested:y.runSelection.requested,selected_indexes:y.runSelection.selected_indexes,selected_count:y.runSelection.selected_count,skipped_count:y.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:T?!0:void 0,warnings:x.length>0?x:void 0,changed:g.changed,count:g.tests.length,...g.removed>0?{removed:g.removed}:{},...ee}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d3405c0-14e6-51f5-97a1-355438fd0199")}catch{}})();var gF=(e,t)=>{if(e===void 0)return;let n=X(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},yF=e=>{if(e===void 0)return;let t=pe(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},Hb=(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},bF=e=>e instanceof Error?e.message:String(e),wF=()=>{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)}`},vF=e=>e.trim().replaceAll(/\s+/g," "),kF=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),SF=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),EF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},AF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},ki=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Vb=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),TF=e=>typeof e=="number"?e:void 0,CF=e=>{let t={assert_stdout_contains:ki(e.assert_stdout_contains),assert_stdout_regex:ki(e.assert_stdout_regex),assert_stderr_contains:ki(e.assert_stderr_contains),assert_stderr_regex:ki(e.assert_stderr_regex),assert_stdout_min_lines:TF(e.assert_stdout_min_lines),assert_json_field_equals:Vb(e.assert_json_field_equals),assert_json_field_gte:Vb(e.assert_json_field_gte)};return JSON.stringify(t)},RF=e=>{let t=Gd(e.command);return t!==void 0?`command:${e.scope}:${vF(t)}`:`path:${e.scope}:${Gd(e.path)??""}`},Wb=e=>{let t=kF(e.env_set),n=SF(e.env_clear),r=EF(e.pm_context_mode),o=AF(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",i=CF(e);return`${RF(e)}:${t}:${n}:${r}:${o}:${s}:${i}`},IF=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,xF=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},OF=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Si=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
50
+ `)}catch{}},PF=async(e,t,n)=>{let r=[],o=0;for(let s of e){let i=await vi(s.id,{run:!1},{...t,path:n});o+=i.tests.length,r.push({item:s,tests:i.tests})}return{itemTests:r,linkedTests:o}},LF=async e=>{let t=D(e.settings.schema),n=O(e.settings,I()),r=gF(e.options.status,t),o=Hb(e.options.limit,"--limit"),s=Hb(e.options.offset,"--offset")??0,a=(await ue(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:o===void 0?a.slice(s):a.slice(s,s+o),statusFilter:r,limitFilter:o,offsetFilter:s}},NF=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=Wb(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,IF(t.get(o),r.timeout_seconds))}return t},FF=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=Wb(u),f=t.seenTestKeys.has(p);if(!f){t.seenTestKeys.add(p);let _=t.effectiveTimeoutByKey.get(p);n.push(_===void 0?u:{...u,timeout_seconds:_})}return{test:u,key:p,duplicate:f}}),o=n.length>0?await Ud(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],s=0,i=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=o[s];return s+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=xF(i),c=wi(i),m=await $F(e,a,i,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}}},MF=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),DF=e=>e?!0:void 0,$F=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=MF(t,r.options);await pi({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:k(),recorded_at:k(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:DF(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${bF(o)}`]}return[]},UF=()=>{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},Gd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},GF=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:nt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:NF(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:wF(),trackingAttempt:UF(),trackingResumedFrom:Gd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),jF=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:wi([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},qF=async(e,t,n)=>{for(let[r,o]of e.entries()){Si(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let s=await FF(o,t);OF(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),Si(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}},KF=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=$d(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},zF=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}),BF=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(" "),HF=async(e,t)=>{let n=E(process.cwd(),t.path);await R(n);let r=await A(n),o=await LF({pmRoot:n,settings:r,options:e}),s=yF(e.timeout),i=k(),a=await PF(o.filteredItems,t,n);return Si(e,BF({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:s,runStartedAt:i}},VF=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}},Yb=async(e,t)=>{let n=await HF(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=jF(e,n.linkedTests,n.filteredItems),s=GF({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await qF(n.itemTests,s,r),KF(e,r);let i=VF({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Si(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),zF({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2643d11d-befc-5a87-8bec-760951eec4d0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="863df651-49e0-552f-a7f0-92c3cc9a12a2")}catch{}})();function Jb(){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]="feba1227-c2a2-5ca3-83e6-3fd2780e6cbb")}catch{}})();var Qb=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:Tu().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{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 package install <target> --project","pm package 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 package 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 merge report","pm merge reconcile --dry-run","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:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"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"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm remind <title> --at <when> --parent <ID>","pm event <title> --start <when> --parent <ID>","pm meet <title> --start <when> --duration <span> --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Record the reminder or event under the item that owns the work, then confirm it appears in the agenda summary of a context read.",commands:["pm remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."}],related:["workflows","quickstart","extensions"]}],Xb=new Map;for(let e of Qb){Xb.set(e.id,e);for(let t of e.aliases)Xb.set(t,e)}function jd(){return Qb.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]="4bf2b42b-91f3-5850-b1f1-d8a01525860c")}catch{}})();var OH=[...Ur],PH=[...Gr],WF=new Set(Wn.filter(e=>e.hidden).map(e=>e.alias)),LH=Au("full").filter(e=>!WF.has(e)),NH=F(Xr),FH=F(Qr),MH=F(so),DH=F(mo),$H=F(uo),UH=F(_m),GH=F(hm),jH=F(lo),qH=F(ho),KH=F(po),zH=F(fo),BH=F(oo),HH=F(_o),VH=F(Zr),WH=F(eo,!1),YH=F(Cm),JH=F(Xn),XH=F(Qn),QH=F(wo),ZH=F(yo),eV=F(ao),tV=F(bo),nV=F(go),rV=F(vo),oV=F(io),sV=F(co),iV=F(no),aV=F(ko),cV=F(to);var YF=F(So),dV=`${YF} bash zsh fish`,lV=XF(jd()),JF="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",mV=`${JF} upgrade`,uV=F(ro),pV=F(Yn),fV=F(Jn);var _V=Jr.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function XF(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0224a672-e326-5555-a4b4-1fa3550d9e61")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1cbb3565-26d8-5657-b724-602658bec852")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="422ff60b-97b1-5477-a7b8-ed4f983155e0")}catch{}})();var nw=Symbol("pm.active-extension-host-context");function Me(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[nw]=!0,n}run(t,n={}){return rw({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Wf(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return ka(await this.list(va(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,...Me(ir(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,s={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:s})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,s){return this.runTyped("plan",{...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...s===void 0?{}:{reorderTo:s},options:ir(r,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Me(t))}update(t,n={}){return this.runTyped("update",{id:t,...Me(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Me(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Me(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Me(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Me(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Me(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Me(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},...Me(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Me(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Me(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Me(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 ZF(e={},t={}){return new j(t).context(e)}function eM(e={},t={}){return new j(t).list(e)}function tM(e={},t={}){return new j(t).listAllComplete(e)}function nM(e,t={},n={}){return new j(n).search(e,t)}function rM(e,t={},n={}){return new j(n).get(e,t)}function oM(e={},t={}){return new j(t).next(e)}function sM(e={},t={}){return new j(t).aggregate(e)}function iM(e,t={},n={}){return new j(n).comments(e,t)}function aM(e,t={},n={}){return new j(n).notes(e,t)}function cM(e,t={},n={}){return new j(n).learnings(e,t)}function dM(e,t={},n={}){return new j(n).files(e,t)}function lM(e,t={},n={}){return new j(n).filesDiscover(e,t)}function mM(e,t={},n={}){return new j(n).docs(e,t)}function uM(e,t={},n={}){return new j(n).deps(e,t)}function pM(e,t={},n={},r={}){return new j(r).graph(e,t,n)}function fM(e,t,n={},r={}){return new j(r).append(e,t,n)}function _M(e={},t={}){return new j(t).create(e)}function hM(e,t={},n={}){return new j(n).update(e,t)}function gM(e,t,n={},r={}){return new j(r).reopen(e,t,n)}function yM(e,t,n={},r={}){return new j(r).close(e,t,n)}function bM(e,t={},n={}){return new j(n).claim(e,t)}function wM(e={},t={}){return new j(t).claimNext(e)}function vM(e,t={},n={}){return new j(n).release(e,t)}function kM(e,t={},n={}){return new j(n).copy(e,t)}function SM(e,t={},n={}){return new j(n).delete(e,t)}function EM(e,t,n={},r={}){return new j(r).restore(e,t,n)}function AM(e,t={},n={}){return new j(n).focus(e,t)}function Ze(e,t){let n=w(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}var Zb=hu(),TM=new QF;function Ei(){aa(hl()),ca(gl()),da(yl()),la(bl()),ma(wl()),ua(vl()),pa(kl())}async function CM(e,t,n,r){return gu(()=>t===void 0?Zb.read(()=>ew(e,n,r)):Zb.write(()=>IM(t,()=>ew(e,n,r))))}async function ew(e,t,n){let r=E(t,e.path);if(e.noExtensions)return Ei(),tc({pmRoot:r},()=>n(null));if(!await P(me(r)))return Ei(),n(null);let o=null,s;try{let i=await A(r),a=await Wr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Yr({...a,loaded:a.loaded});s={loadResult:a,activationResult:c},aa(c.hooks),ca(c.commands),da(c.parsers),la(c.preflight),ma(c.services),ua(c.renderers),pa(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){Ei(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await tc({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Ei(),s&&await Sl(s.loadResult,s.activationResult).catch(()=>{})}}async function RM(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let s=Rn(e),a=o.registrations.commands.find(m=>Rn(m.action)===s)?.command??o.commands.handlers.find(m=>Rn(m.command)===s)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=await Lo({command:Pa(a),args:Se(n.args??t.args),options:La(t,n),global:r,pm_root:o.pmRoot,sdk:Qf(o.pmRoot,j.forActiveExtensionHost({pmRoot:o.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 IM(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function xM(e){let t=Ze(e,"action"),n=Rn(t),r=Ti(Jf,n),o=r?.action??n,s={...e,action:o};return r?.options!==void 0&&(s.options={...r.options,...Vi(e.options)}),o==="package"&&(s.options={...Vi(s.options),vocabulary:"package"}),{action:o,args:s}}async function rw(e){let t=xM(e),n=Ia(t.args),r=Up(t.action),o=w(t.args,"cwd"),s=o??process.cwd();t.action==="init"&&(n[nd]=s),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(s,n.path));try{return e[nw]===!0||TM.getStore()===!0?await tw(t.action,t.args,n,null):await CM(n,o,s,i=>tw(t.action,t.args,n,i))}finally{r&&Xa()}}function Ti(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ai(e){return w(e.args,"target")??w(e.options,"target")}function Z(e,t=e.options){return e.id??Ze(t,"id")}async function OM(e){let t=hn("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),Ja(await dt(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function PM(e){let t=Ze(e.args,"query"),n=hn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Ja(await pr(t,n,e.global),n)}async function LM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options);return je(await Lt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function NM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return je(await qc(Z(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function FM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options);return je(await ut(Z(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function MM(e){let t=bs(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")),b_(Z(e),t,e.global)}function ow(e,t){return Cf(py(e.options,t,$e),e.global)}function DM(e){let t=Se(e.options.lookupPath);if(t&&t.length>0)return ow(e,t);let n=Z(e);return e.options.discover===!0?Ma(n,Oa(e.options),e.global):Tf(n,os(e.options),e.global)}function $M(e){return mb({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:Dp(e.args,e.options)},e.global)}function UM(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),cr(e.global,t)}function GM(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);let n=w(e.args,"value")??w(e.options,"value"),r=w(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return Yh(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),r,e.global,w(e.options,"policy")===void 0?n:void 0)}function jM(e){let t=e.options;return xp(Ip(t),e.global)}function qM(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 KM(e){let t=w(e.args,"subcommand")??Ze(e.options,"subcommand"),n=e.options;return Th({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:zM(e),reorderTo:qM(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function zM(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function BM(e){let t=w(e.args,"subcommand")??Ze(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:w(e.args,"name")??w(e.options,"name"),author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:Se(n)}}function HM(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,a=Ti({list:()=>ef(t.global),show:()=>tf(r,t.global),"show-status":()=>nf(r,t.global),"list-fields":()=>sf(t.global),"show-field":()=>af(r,t.global),"remove-type":()=>Jp(r,{author:o,force:s},t.global),"remove-field":()=>of(r,{author:o,force:s},t.global),"remove-status":()=>Zp(r,{author:o,force:s},t.global),"apply-preset":()=>cf(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:o,force:s},t.global)},n);return a?a():null}function VM(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return rf(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:Se(i),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:s,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:Se(a),author:r,force:o},t.global)}function WM(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.role??t.options.role;return Qp(n,{role:i===void 0?void 0:Se(i),alias:s,description:w(t.args,"description")??w(t.options,"description"),order:$e(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function YM(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e;return Yp(n,{description:w(t.args,"description")??w(t.options,"description"),defaultStatus:w(t.args,"defaultStatus")??w(t.args,"default_status")??w(t.options,"defaultStatus")??w(t.options,"default_status"),folder:w(t.args,"folder")??w(t.options,"folder"),alias:s,author:r,force:o},t.global)}function JM(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,i=w(t.args,"to")??Ze(t.options,"to"),a=w(t.args,"migrationId")??w(t.args,"migration_id")??w(t.options,"migrationId")??w(t.options,"migration_id"),c=w(t.args,"fieldTypeScope")??w(t.options,"fieldTypeScope")??w(t.args,"type")??w(t.options,"type"),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 Vp(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:s},t.global)}function XM(e){let t=BM(e),n=HM(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return JM(t);if(t.subcommand==="add-field")return VM(t);if(t.subcommand==="add-status")return WM(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?df({minCount:$e(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):YM(t);throw Pe({command_path:"schema",token:t.subcommand,allowed:Wp,exit_code:64})}function QM(e){let t=w(e.args,"subcommand")??Ze(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),s=Ti({list:()=>Qg(),show:()=>Zg(r),lint:()=>ey(r),apply:()=>ty(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(!s)throw Pe({command_path:"profile",token:t,allowed:Xg,exit_code:64});return s()}async function ZM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options);return je(await t_(Z(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function eD(e){let{changedFields:t,runnerOptions:n}=Ue(e.args,e.options);return je(await ph(Fa(n),e.global),{changedFields:t})}async function tD(e){let{changedFields:t,runnerOptions:n}=Ue(e.args,e.options),r=w(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),je(await y_(Na(o),e.global),{changedFields:t})}async function nD(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ue(e.args,e.options),o=w(r,"target")??Ze(e.args,"target");return je(await Yt(Z(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function rD(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=ai(D(n.schema)),o=Z(e),s=await vs(o,e.force,e.global,e.options),i=await ut(o,ir(e.options,{status:r,force:e.force},["assignee"]),e.global);return{id:o,action:"start_task",claim:s,update:i}}async function oD(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=Z(e),o=D(n.schema).open_status,s=await ut(r,ir(e.options,{status:o,force:e.force},["assignee"]),e.global),i=await ks(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:s,release:i}}async function sD(e){let t=Z(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await lt(t,n,{...e.options,force:e.force},e.global),o=await ks(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:o}}function iD(e){let t={...e.args,...e.options};return Np(Ze(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),jp(t),e.global)}function aD(e){return Kp(E(process.cwd(),e.global.path),{...e.args,...e.options})}var cD={init:e=>Ar(w(e.args,"prefix"),e.global,e.options),context:e=>Va(hn("context",e.options),e.global),next:e=>ur(hn("next",e.options),e.global),eval:Gg,events:jg,merge:qg,workspace:Kg,meet:si,event:si,remind:si,list:OM,get:e=>{let t=Z(e);return Wa(t,e.global,hn("get",e.options,[t]))},search:PM,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:Se(e.options.status);return Ya(e.global,{exhaustive:e.options.exhaustive===!0,...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:$e(e.options.limit,"limit")})},create:LM,copy:NM,focus:e=>zc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:FM,"item-reopen":uy,restore:nD,claim:e=>e.options.next===!0||e.args.next===!0?c_(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):vs(Z(e),e.force,e.global,e.options),release:e=>ks(Z(e),e.force,e.global,e.options),"start-task":rD,"pause-task":oD,"close-task":sD,close:my,comments:MM,notes:e=>v_(Z(e),bs(e.options),e.global),learnings:e=>w_(Z(e),bs(e.options),e.global),files:DM,docs:e=>Af(Z(e),os(e.options),e.global),test:e=>vi(Z(e),e.options,e.global),"test-all":e=>Yb(e.options,e.global),telemetry:$M,validate:e=>ms(e.options,e.global,{runUpdate:(t,n,r)=>ut(t,n,r)}),health:UM,assurance:e=>qf(e.args,e.options,e.global),contracts:e=>My(e.options,e.global),config:GM,activity:jM,aggregate:e=>za(e.options,e.global),extension:e=>In(Ai(e),e.options,e.global),package:e=>In(Ai(e),e.options,e.global),install:e=>In(Ai(e),{...e.options,install:!0},e.global),upgrade:e=>zf(Ai(e),e.options,e.global),delete:e=>Kc(Z(e),e.options,e.global),deps:e=>Lp(Z(e),e.options,e.global),graph:iD,"files-discover":e=>Ma(Z(e),e.options,e.global),"files-lookup":e=>ow(e,Se(e.options.paths)),history:e=>Kf(Z(e),e.options,e.global),"history-redact":e=>mp(Z(e),e.options,e.global),"history-repair":ay,"history-compact":cy,"history-author-acknowledge":aD,plan:KM,schema:XM,profile:QM,stats:e=>Td(e.global,tb(e.options)),append:ZM,"update-many":eD,"close-many":tD,gc:e=>Bf(e.global,e.options)};async function tw(e,t,n,r){let o=xa(t,e);sa(e,o),au(e,o);let s={action:e,args:t,options:o,id:w(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},i=Ti(cD,e),a=i?await i(s):await RM(e,t,o,n,r);o.resolvedOutputFormat="json";let c=vu(e,o,a);return await Zf(E(process.cwd(),n.path),c),c}var dD={closeManyOptionsFromFlat:Na,extensionOptionsFromArgs:La,globalOptions:Ia,mutationListOptions:Gp,normalizeActionName:Rn,normalizeCommandPath:Pa,normalizeMcpUpdateOptions:qp,normalizeMcpOptionsArrays:$p,optionsWithAuthor:xa,readRequiredString:Ze,readScalarString:Fp,readScalarStringAllowBlank:Mp,readStringArray:Se,updateManyOptionsFromFlat:Fa,withAddNoteOption:os,withFilesDiscoveryOptions:Oa,withMutationCompaction:Ue};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=dD);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cea03617-5e90-5683-a9d1-289087ed4646")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cc0d4dd1-20e8-59d4-acb5-9f8ed639d35f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f44898af-0809-51e1-a6fb-74716c0971f5")}catch{}})();export{gn as AGENT_PROVENANCE_DIMENSIONS,Nu as BASELINE_ITEM_FORMAT_VERSION,ov as BUILTIN_AGENT_PROVENANCE_ADAPTERS,er as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,Ur as BUILTIN_ITEM_TYPE_VALUES,jr as CONFIDENCE_TEXT_VALUES,Fu as CURRENT_ITEM_FORMAT_VERSION,Ut as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,ln as ISSUE_SEVERITY_VALUES,tl as ITEM_TYPE_VALUES,Qa as PM_CLI_EXPECTED_ERROR_NAME,Ww as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,Hw as PM_READ_OUTPUT_DIMENSIONS,Vw as PM_READ_OUTPUT_OPTION_FLAGS,ra as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,j as PmClient,dn as RISK_VALUES,yv as SEMANTIC_ATTRIBUTION_LIMITS,Gr as STATUS_VALUES,rv as agentSessionEnvironment,sM as aggregate,Ed as analyzeAgentProvenanceDescriptorCoverage,Zw as analyzeSdkCliParameterCompleteness,fM as append,Jw as applyReadOutputDimensions,jw as applyReadOutputSessionReferences,qw as attachReadOutputSessionReceipt,ev as boundAgentEpisodeIdentity,Tt as canonicalDocument,bM as claim,wM as claimNext,$u as classifyItemFormatVersion,yM as close,iM as comments,ZF as context,kM as copy,_M as create,Xf as createPmCliExpectedError,Bw as decodeReadOutputContinuationCursor,SM as deleteItem,uM as deps,mv as detectAgentIdentity,fv as detectHarnessIdentity,uv as diagnoseAgentIdentity,mM as docs,Mu as effectiveItemFormatVersion,Jb as emptyImportedDocument,zw as encodeReadOutputContinuationCursor,PP as evaluateSemanticAttributionCoverage,hv as explainSourceTraceability,dM as files,lM as filesDiscover,AM as focus,rM as get,pM as graph,LP as groupHistoryByEpisode,a_ as isAlreadyClaimedError,hs as isPmCliExpectedError,Xw as isReadOutputBudgetExceeded,cM as learnings,eM as list,iv as listAgentProvenanceAdapters,tM as listAllComplete,oM as next,cv as normalizeAgentProvenanceAdapterValue,Du as normalizeItemFormatVersion,ve as normalizeItemId,X as normalizeStatusInput,aM as notes,k as nowIso,Gw as parseReadOutputSession,cs as parseSourceLineRange,Mo as readAuthorEnvironment,Kw as readOutputSessionRemainingTokens,Ba as recordClaimSemanticAttribution,ps as recordFocusSemanticAttribution,Ha as recordReleaseSemanticAttribution,av as registerAgentProvenanceAdapters,sv as registerHarnessSignalDescriptors,vM as release,gM as reopen,tv as resolveAgentSessionContextFromSignals,_v as resolveAuthorIdentity,By as resolveHistoryEpisodeGroupIdentity,Yw as resolveReadOutputDimensions,Qw as resolveReadOutputEncoding,oa as resolveReadOutputSurface,gv as resolveSemanticLineageIds,EM as restore,rw as runAction,nv as runWithAgentSessionContext,dv as runWithHarnessDetectionSignals,lv as runWithWorkspaceHarnessSignalDescriptors,nM as search,bv as semanticAttributionAffinity,it as serializeItemDocument,OP as summarizeAgentModelProvenance,Ad as summarizeAgentProvenance,hM as update,sa as validateReadOutputOptions,pv as writeAuthorEnvironment};
51
51
  //# sourceMappingURL=sdk-core.js.map