@unbrained/pm-cli 2026.11.10 → 2026.11.11

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 (120) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +12 -0
  3. package/dist/cli/commander-usage.js +2 -2
  4. package/dist/cli/error-guidance.js +3 -3
  5. package/dist/cli/help-json-payload.js +1 -1
  6. package/dist/cli/main.js +4 -4
  7. package/dist/cli/runtime/refusal-credential-redaction.js +2 -0
  8. package/dist/cli-bundle/bundle-manifest.json +1 -1
  9. package/dist/cli-bundle/chunks/{chunk-NNE63MSM.js → chunk-4RHXGQMK.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-YSWD2NXB.js → chunk-5N3JMGXU.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-TBBWPEF5.js → chunk-DIWTFDU7.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-OJ2KEDUX.js → chunk-DV7WBAKQ.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-F6FBGLR7.js → chunk-EBAHNZJT.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-BSJSGDA3.js → chunk-FM375BHH.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-F7P2NZEG.js → chunk-GOLQYO6M.js} +4 -4
  16. package/dist/cli-bundle/chunks/chunk-GZ52WAY2.js +124 -0
  17. package/dist/cli-bundle/chunks/{chunk-EHDGHFMJ.js → chunk-JESMEJTD.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-CZETQYKO.js → chunk-JLQ7O6UV.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-FYD6LSJA.js → chunk-L3SA3354.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-U7LILCUN.js → chunk-NIOOJ3AG.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-WNEUWDUE.js → chunk-PZI6CR24.js} +46 -46
  22. package/dist/cli-bundle/chunks/{chunk-NZAFLDSH.js → chunk-QCTA2UFR.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-4FLAKTZW.js → chunk-SPERPX27.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-T2MNRM3S.js → chunk-SVVFJPNW.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-5CAMQHEW.js → chunk-WEAF3OY4.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-UL64P6MR.js → chunk-WWW5WHHJ.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-X7NM5HVQ.js → chunk-XJUYJXHZ.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-L4WWG2H6.js → chunk-XN2BRWDD.js} +2 -2
  29. package/dist/cli-bundle/chunks/chunk-Z4YEH7VQ.js +2 -0
  30. package/dist/cli-bundle/chunks/{chunk-7NAAW5EX.js → chunk-ZJDYBXMC.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-4AASUCHO.js → chunk-ZSL6U53K.js} +2 -2
  32. package/dist/cli-bundle/chunks/{item-revision-M7KXLQXF.js → item-revision-LNIHK36Q.js} +2 -2
  33. package/dist/cli-bundle/chunks/item-transaction-TMUYPSMR.js +2 -0
  34. package/dist/cli-bundle/chunks/{mutation-admission-374UR7NI.js → mutation-admission-WZY22LVH.js} +2 -2
  35. package/dist/cli-bundle/chunks/{register-list-query-GSB7PP5P.js → register-list-query-DYGPLVRL.js} +2 -2
  36. package/dist/cli-bundle/chunks/{register-mutation-ZBF6ITYK.js → register-mutation-MP5JCBAJ.js} +2 -2
  37. package/dist/cli-bundle/chunks/{register-operations-PWF6GOHE.js → register-operations-QEASK3EF.js} +2 -2
  38. package/dist/cli-bundle/chunks/{register-setup-QDZ2Y3CI.js → register-setup-G66U2WFV.js} +2 -2
  39. package/dist/cli-bundle/chunks/{stage-67WGPKPH.js → stage-VIDXGF3T.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-WK773UVA.js → chunk-2ZS3I5ZP.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-33EK522E.js +26 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-BE2GK2G7.js → chunk-3A6XMQZJ.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-PAGW6A2X.js → chunk-3FN4ON2Z.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-3DWNH72D.js → chunk-3SH3L3DB.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-ALLOWZSH.js → chunk-6ICHSVEY.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-QK7FX4O5.js → chunk-6TJXTKZD.js} +4 -4
  47. package/dist/cli-bundle/focused-chunks/{chunk-QHGGO7SY.js → chunk-AXPRCCYM.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-UIZVD36C.js → chunk-DW5S67LO.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-HTMQDNVC.js → chunk-GBW2EAAG.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-ZBOCYFBE.js → chunk-HIKZYZ26.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-QCHCEFTO.js → chunk-JYWVRXLD.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-M5FZTPFA.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-2SQUWQP3.js → chunk-MK7UQEE5.js} +18 -18
  54. package/dist/cli-bundle/focused-chunks/{chunk-2Y4H4LIX.js → chunk-NMU3QFAU.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-LY3JXL25.js → chunk-NP5C2TQM.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-RFMKS7VD.js → chunk-NSOXVVQX.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-WJHDUON5.js → chunk-NY65XTX7.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-67M7E2Z3.js → chunk-P6KYUJD4.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{chunk-LWMPQRJT.js → chunk-UCUESVFW.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-NZQYHPUN.js → chunk-V27M5UQH.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-3K2MYE7R.js → chunk-VVGXPF4W.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{item-revision-XC4ZJ7MY.js → item-revision-B3BIG66B.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{item-transaction-CVGK4RJP.js → item-transaction-4JDWOXNB.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{mutation-admission-N27D5H64.js → mutation-admission-577MXOGD.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{stage-KPK2UHVO.js → stage-EKYWEU2Y.js} +2 -2
  66. package/dist/cli-bundle/main.js +32 -32
  67. package/dist/cli-bundle/sdk-authoring.js +1 -1
  68. package/dist/cli-bundle/sdk-contracts.js +1 -1
  69. package/dist/cli-bundle/sdk-core.js +1 -1
  70. package/dist/cli-bundle/sdk-governance.js +1 -1
  71. package/dist/cli-bundle/sdk-graph.js +1 -1
  72. package/dist/cli-bundle/sdk-merge.js +57 -57
  73. package/dist/cli-bundle/sdk-query.js +1 -1
  74. package/dist/cli-bundle/sdk-runtime.js +1 -1
  75. package/dist/cli-bundle/sdk-testing.js +1 -1
  76. package/dist/cli-bundle/sdk.js +11 -11
  77. package/dist/core/sentry/instrument.js +1 -1
  78. package/dist/core/shared/secret-rules.d.ts +18 -2
  79. package/dist/core/shared/secret-rules.js +4 -2
  80. package/dist/core/shared/url-credentials.d.ts +37 -0
  81. package/dist/core/shared/url-credentials.js +2 -0
  82. package/dist/core/telemetry/runtime.js +2 -2
  83. package/dist/sdk/command-line.d.ts +1 -1
  84. package/dist/sdk/command-line.js +1 -1
  85. package/dist/sdk/index.d.ts +1 -1
  86. package/dist/sdk/index.js +1 -1
  87. package/dist/sdk/lifecycle/item-revision.js +1 -1
  88. package/dist/sdk/public-surface.json +1 -1
  89. package/docs/CODEX_PLUGIN.md +2 -1
  90. package/docs/CONFIGURATION.md +16 -0
  91. package/docs/MUTATION_INTEGRITY.md +65 -0
  92. package/docs/README.md +2 -2
  93. package/docs/SDK.md +16 -0
  94. package/marketplace.json +1 -1
  95. package/package.json +2 -1
  96. package/packages/pm-beads/package.json +1 -1
  97. package/packages/pm-calendar/package.json +1 -1
  98. package/packages/pm-command-kit/package.json +1 -1
  99. package/packages/pm-digital-twin/package.json +1 -1
  100. package/packages/pm-governance-audit/package.json +1 -1
  101. package/packages/pm-guide-shell/package.json +1 -1
  102. package/packages/pm-kanban/package.json +1 -1
  103. package/packages/pm-lifecycle-hooks/package.json +1 -1
  104. package/packages/pm-linked-test-adapters/package.json +1 -1
  105. package/packages/pm-search-advanced/package.json +1 -1
  106. package/packages/pm-templates/package.json +1 -1
  107. package/packages/pm-todos/package.json +1 -1
  108. package/packages/pm-vcs/package.json +1 -1
  109. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  110. package/plugins/pm-claude/package.json +1 -1
  111. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  112. package/plugins/pm-codex/package.json +1 -1
  113. package/plugins/pm-codex/plugin.json +1 -1
  114. package/runtime-dependencies.json +1 -1
  115. package/dist/cli-bundle/chunks/chunk-D727C4RO.js +0 -122
  116. package/dist/cli-bundle/chunks/chunk-UFPLZ6LZ.js +0 -2
  117. package/dist/cli-bundle/chunks/item-transaction-4N5P34GO.js +0 -2
  118. package/dist/cli-bundle/focused-chunks/chunk-56MIAFEN.js +0 -24
  119. package/dist/cli-bundle/focused-chunks/chunk-U7HWWEJ2.js +0 -2
  120. package/docs/CHATGPT_CODEX_PLUGIN_IMPLEMENTATION.md +0 -776
@@ -1,4 +1,4 @@
1
- import{A as al,B as T_,C as C_,n as Uu,o as vi,p as zu,q as Hu,r as ki,s as Or,t as Ac,u as Tc,v as Si,y as gf,z as yf}from"./chunk-3K2MYE7R.js";import{a as I_,f as R_,h as un,m as O_,o as zr,r as oa,s as x_,t as P_,x as $_}from"./chunk-UIZVD36C.js";import{$ as $h,Aa as Gh,Ab as Aa,Ba as qh,Ca as Kh,Da as zh,Ea as Hh,Fa as Bh,Ga as _n,H as fh,Ha as Wh,Hb as wg,I as _h,Ia as Vh,Ib as vg,J as hh,Ja as Yh,Jb as bg,K as gh,Ka as va,L as yh,La as Jh,M as wh,Ma as Xh,N as vh,Na as Qh,Nb as kg,O as bh,Oa as Zh,Ob as Lg,P as kh,Pa as ng,Q as Sh,Qa as ba,R as Eh,Ra as Qt,S as Ah,Sa as rg,T as Th,Ta as ka,U as Ch,V as Ih,W as Rh,Wa as eo,X as Oh,Y as xh,Z as Zn,_ as Ph,bb as og,cb as ig,db as ag,eb as sg,fb as cg,g as eh,gb as lg,h as th,ha as Lh,hb as Sa,ib as hl,ja as Mh,jb as dg,ka as fl,kb as gl,lb as tr,ma as Fh,mb as mg,na as Dh,nb as pg,oa as _l,ob as ug,pb as fg,qb as _g,rb as to,sb as Ea,tb as hg,ub as gg,vb as nr,wb as yl,xb as yg,z as ch,za as jh}from"./chunk-BE2GK2G7.js";import{h as yt,i as hn,m as tg}from"./chunk-U7HWWEJ2.js";import{a as Zr,b as lh,c as ya,h as ph,i as uh}from"./chunk-HTMQDNVC.js";import{c as dl}from"./chunk-IDAYTYNN.js";import{A as pa,B as z_,C as H_,D as sl,E as Vr,F as ua,G as Xn,H as B_,I as cl,J as be,K as ll,L as ye,M as W_,N as V_,O as fa,P as Y_,Q as _a,R as J_,a as ia,b as Hr,c as aa,d as Pe,e as sa,f as L_,g as ca,h as la,i as Br,j as N_,k as da,l as ma,m as ht,n as M_,o as F_,p as D_,q as Wr,r as U_,s as j_,t as gt,u as v,v as G_,w as q_,y as Ge,z as K_}from"./chunk-WK773UVA.js";import{e as Mu,g as Fu,h as Du,k as Gu,q as Ku}from"./chunk-3DWNH72D.js";import{M as pf,N as Mc,O as uf,P as Ri,Q as Fc,R as ff,S as _f,Z as Dc,a as Sp,b as Ep,ba as hf,c as Ap,d as Tp,f as Cp}from"./chunk-NZQYHPUN.js";import{a as ih,b as ah,c as Ta,d as Ca,e as Ia}from"./chunk-67M7E2Z3.js";import{K as Uh,b as sh}from"./chunk-QHGGO7SY.js";import{A as Og,Ea as kl,Ga as xg,Va as oo,Xa as Pg,Ya as $g,b as oh,e as ml,g as pl,i as ul,j as no,l as Sg,m as Eg,n as wl,sa as vl,v as Ag,w as Tg,x as Cg,xa as ro,y as Ig,z as Rg,za as bl}from"./chunk-QCHCEFTO.js";import{A as wa,F as er,h as ha,k as Q_,l as Yr,o as Z_,w as $t,y as nh,z as rh}from"./chunk-2Y4H4LIX.js";import{a as Qr,b as fn,d as eg}from"./chunk-LY3JXL25.js";import{$ as If,$a as na,A as Pi,B as jc,C as et,D as kf,E as Gc,F as Sf,G as de,I as It,J as Ef,K as $i,L as Bt,M as he,N as zn,O as qc,P as Pr,Q as Kc,R as Li,S as Rt,T as Af,U as Ni,V as Mi,W as Fi,X as Di,Xa as qr,Y as Ui,Z as Tf,Za as y_,_ as Cf,_a as w_,ab as ra,bb as v_,c as $u,da as ji,ea as Gi,f as Lu,g as Nu,ha as Vi,i as wi,ia as Yi,j as Kt,ja as Qf,k as Dn,ka as Ji,l as Bu,la as Xi,m as Wu,ma as Yt,n as wf,oa as el,p as pt,pa as Qi,pb as Jn,q as ut,qb as b_,r as vf,ra as Zf,rb as ol,s as Uc,sa as e_,sb as k_,t as bf,ta as Ur,tb as S_,u as Ht,ub as E_,v as qn,w as Oi,x as Kn,xb as il,y as xi,yb as A_,z as ue}from"./chunk-56MIAFEN.js";import{$ as Vp,$a as ui,A as Sc,Aa as yu,B as Ec,C as $p,Ca as wu,D as Mn,Da as vu,E as Wo,Ea as bu,F as Vo,Fa as ku,G as Lp,Ga as Su,H as Np,Ha as Eu,I as Mp,Ia as ni,J as Fp,Ja as ri,K as Dp,Ka as oi,L as Yo,La as Au,M as Up,Ma as Tu,N as jp,Na as ii,O as Gp,Oa as Cu,P as Jo,Pa as Iu,Q as qp,Qa as Ru,R as Kp,Ra as ai,S as zp,Sa as si,T as Hp,Ta as ci,U as Xo,Ua as li,V as Qo,Va as Ir,W as Bp,Wa as Ou,X as Zo,Xa as di,Ya as Rr,Z as Wp,Za as mi,_ as Tr,_a as pi,aa as Yp,ab as fi,b as Ip,ba as Jp,bb as xu,c as Rp,ca as Xp,cb as qt,d as Op,da as Qp,db as _i,ea as Zp,eb as hi,fa as eu,fb as gi,ga as tu,gb as yi,h as vc,ha as nu,ia as ru,ja as ou,jb as Pu,ka as iu,la as au,lb as De,ma as su,mb as M,n as bc,na as cu,o as xp,oa as Cr,pa as lu,qa as du,r as Bo,ra as ei,s as kc,sa as ti,t as dn,ta as mu,ua as pu,v as Pp,va as uu,wa as fu,xa as _u,ya as hu,za as gu}from"./chunk-LWMPQRJT.js";import{A as Nh,a as Jr,b as Xr,c as Qn,d as rt,i as ga}from"./chunk-RFMKS7VD.js";import{d as X_}from"./chunk-PAGW6A2X.js";import{C as s_,E as c_,H as l_,M as d_,N as m_,O as ea,U as Jt,W as Xt,Y as q,Z as ne,_ as f_,aa as ge,b as Ze,ba as __,c as Go,ca as ta,d as qo,da as nt,e as xe,ea as h_,f as Yf,fa as Yn,g as Jf,ga as fe,h as Vt,ha as g_,ia as rl,j as je,k as Dr,l as Bn,m as o_,n as Wn,na as Kr,o as Vn,p as i_,v as Gr,x as a_}from"./chunk-WJHDUON5.js";import{A as Pf,Aa as Gf,Ab as O,B as qi,Ba as qf,Ca as Yc,E as Ki,Fa as Jc,G as Bc,Ha as Kf,Ia as zf,J as se,Ja as Hf,K as pn,Ka as Bf,L as ce,La as Wf,N as $f,O as Lf,P as Nf,Pa as Ue,Q as Wc,Qa as Wt,R as Mf,Ra as Xc,S as ft,Sa as Lr,T as xt,Ta as Nr,Ua as Qc,Va as _t,Wa as Mr,Xa as Fr,a as ju,c as At,ca as zi,cb as Vf,da as Df,e as bi,ea as Uf,eb as Zc,f as Tt,fa as $r,g as zt,ga as Hi,h as qu,hb as Xf,ib as Wi,j as D,jb as tt,k as Ct,l as Je,lb as Zi,n as Fn,nb as t_,ob as jr,qa as Vc,qb as n_,r as Ot,rb as Pt,sb as tl,tb as nl,u as Rf,ua as Hn,ub as r_,v as zc,va as I,vb as S,w as Of,wa as jf,wb as Ie,x as Hc,xa as Bi,y as xf,yb as p_,zb as u_}from"./chunk-ZBOCYFBE.js";import{a as Ii,b as mf}from"./chunk-C3O6JJPO.js";import{$a as B,$b as Ar,$d as of,A as sc,Aa as ie,B as cc,Ba as Et,Bc as Ce,C as lc,D as dc,Da as Ye,E as mc,Ea as Ho,F as pc,Fb as fp,Fc as Ti,Ga as cn,Gb as _p,Ha as ae,Hb as hp,He as df,Ib as gp,Ic as Yu,J as Jm,Jb as yp,Jc as N,Ka as Nn,Kb as wp,Kc as Ju,Lb as vp,Lc as dt,Mc as Xu,Nb as Sr,Pb as bp,Pd as E,Q as Xm,Qc as Qu,S as Qm,Sb as kp,Td as Ci,U as Zm,Ue as Ff,Vc as Nc,Vd as te,W as ep,X as tp,Za as Te,Zb as Er,_b as wc,a as Gm,bb as ln,bc as Vu,ce as mt,de as xr,ea as lt,fb as op,g as rc,ga as np,gb as ip,hb as ap,hc as Cc,i as oc,ia as fc,ib as sp,j as ic,ja as vr,jb as cp,jc as Ic,je as af,kb as lp,kc as Rc,lb as hc,lc as Oc,ma as _c,mb as dp,mc as xc,n as Uo,na as br,nc as Pc,nd as Zu,o as kt,oa as Re,ob as mp,oc as $c,od as ef,p as yr,pb as pp,pc as Lc,q as wr,qc as R,r as ac,ra as x,rd as tf,re as sf,sa as Ae,sb as gc,sc as Un,sd as nf,se as cf,t as qm,ta as Ko,tb as up,tc as mn,u as Km,ua as Ln,ub as yc,uc as J,ud as rf,v as zm,va as kr,vc as Ei,ve as Gn,w as Hm,wa as rp,wc as jn,xa as A,y as Bm,ya as zo,z as Wm,za as Oe,zc as Ai,ze as lf}from"./chunk-2SQUWQP3.js";import{a as mh}from"./chunk-EGN2HFRU.js";import{b as dh}from"./chunk-FOA7XKWP.js";import{A as d,C as H,D as St,E as Fe,F as ee,I as oe,K as $n,m as jo,s as uc,u as Vm,x as sn,y as Ym,z as m}from"./chunk-G6ERMFJ5.js";import{readFile as wE}from"node:fs/promises";import vE 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]="20a3a324-d176-5918-8167-5e548be4abc9")}catch{}})();var Sl="context-intents.json";function Ra(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bE(e,t,n){if(!Ra(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 Ng(e,t){let n=Array.isArray(e)?e:Ra(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)=>bE(r,t,o))}async function kE(e){let t=vE.join(e,Sl),n;try{n=await wE(t,"utf8")}catch(o){if(St(o))return[];throw await u_(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Sl}: ${i}`,{cause:o})}return Ng(r,Sl)}function SE(e){if(!Ra(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Ra(n)?n.contextIntents??n.context_intents:void 0}function EE(e){return e.flatMap(t=>{let n=SE(t.module);return n===void 0?[]:Ng(n,`package ${t.name}`)})}async function AE(e){let t=await kE(e.pmRoot),n=EE(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Oa(e,t){let n=await AE(e);return await cf(n,t)}import{readFile as TE}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]="9c3ae5d4-5437-543d-90a3-67e92b073c18")}catch{}})();function Pa(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,de(e,t)}function jg(e){return Object.prototype.toString.call(e)==="[object Object]"}function CE(e,t,n,r){let o=E();if(!jg(e))return{...r({created_at:o,author:n,text:t}),text:t,edited_at:o};let i=a=>typeof a=="string"&&a!=="";return{...e,...i(e.created_at)?{}:{created_at:o},...i(e.author)?{}:{author:n},text:t,edited_at:o}}function Mg(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new d(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function El(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function gn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function rr(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let o=ue(n,"--add");return Object.keys(o).map(i=>i.trim().toLowerCase()).some(i=>i!=="text")?n:o.text?.trim()||n}catch{return n}}function Al(e){return typeof e=="object"&&e!==null&&"code"in e}function ao(e,t){if(!It(e))throw new d(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function IE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new d(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let n=Bt(),r=It(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return ao(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let o=e.file.trim();if(!o)throw new d("--file path cannot be empty",m.USAGE);if(o==="-")return ao(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await TE(o,"utf8"),emptyFlag:"--file"}}catch(i){if(Al(i)&&St(i))throw new d(`--file path not found: ${o}. Use --file - to read stdin.`,m.USAGE);let a=i instanceof Error?i.message:String(i);throw new d(`Failed to read --file path "${o}": ${a}. Use --file - to read stdin.`,m.USAGE)}}async function $a(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new d("Specify only one of --edit or --delete",m.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new d("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new d("--delete must be a positive integer",m.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new d("--edit must be a positive integer",m.USAGE);let n=await IE(e,t);if(e.edit!==void 0){if(!n)throw new d("--edit requires replacement text from --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function io(e,t){throw e instanceof d&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new d(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Gg(e){return e==="comments"?"--stdin":"--add -"}function RE(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function OE(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function xE(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=OE(t),o=Gg(e.collectionKey),i=e.retryArgs===void 0?{}:{field:e.textFlag,recovery:{suggested_flags:[t],suggested_retry:N(e.retryArgs),suggested_retry_args:[...e.retryArgs]}};if(r!==void 0){let a=r.split(/[ =]/,1)[0],s=a==="--file"?"that file":"stdin",c=e.conflictingOperand===void 0?"":` "${e.conflictingOperand}" was read as positional text, which ${a} cannot be combined with: drop it, or pass it as the text without ${a}.`;return new d(`${e.textFlag} value "${t}" looks like an option, not annotation text: ${e.textFlag} took ${a} as its value. Drop ${e.textFlag} and pass ${r} on its own.${c}`,m.USAGE,{code:"annotation_flag_like_value",required:`Drop ${e.textFlag}: ${r} reads the ${n} text from ${s} by itself. Use ${e.textFlag} text=${t} only when the text really is "${t}".`,examples:[`${e.commandPrefix} ${r}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...i})}return new d(`${e.textFlag} value "${t}" looks like an option, not annotation text. Use ${o} to read stdin, or use text=${t} for literal dash-leading text.`,m.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${t} when the text really starts with "-".`,examples:[`${e.commandPrefix} ${o}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...i})}function PE(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!RE(e)))throw xE({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function $E(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new d(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,m.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(LE(e,t),e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new d(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,m.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> ${Gg(e.collectionKey)}`]})}function LE(e,t){if(t.expectAt!==void 0){if(e.input.mode!=="edit"&&e.input.mode!=="delete")throw new d(`--expect-at guards an --edit or --delete of one ${e.collectionKey.replace(/s$/,"")}`,m.USAGE,{code:"annotation_expectation_without_target",required:"Combine --expect-at with --edit <index> or --delete <index>; omit it for list and append operations.",examples:[`pm ${e.collectionKey} <id> --edit <index> --expect-at <created_at> --add "<text>"`,`pm ${e.collectionKey} <id> --delete <index> --expect-at <created_at>`]});if(typeof t.expectAt!="string"||t.expectAt.trim().length===0)throw new d("--expect-at must be the non-empty created_at timestamp of the entry you read",m.USAGE,{code:"annotation_expectation_invalid",required:"Pass the created_at value of the row you read at that index, as a string."})}}function Fg(e,t,n,r,o){if(o===void 0)return;let i=t[n]?.created_at,a=typeof i=="string"?i:null;if(a===o)return;let s=t.flatMap((f,h)=>f?.created_at===o?[h+1]:[]),c=r.collectionKey.replace(/s$/,""),l=r.input.mode==="delete"?"--delete":"--edit",p=n+1,u=s.length===1?` The ${c} created at ${o} is at index ${s[0]}.`:s.length>1?` ${s.length} ${r.collectionKey} were created at ${o}: indexes ${s.join(", ")}.`:` No ${c} on ${e} was created at ${o}.`;throw new d(`${c.charAt(0).toUpperCase()}${c.slice(1)} ${p} on ${e} was created at ${a||"an unrecorded time (malformed entry)"}, not ${o}; refusing ${l} of an entry the caller did not read. Nothing was written.${u}`,m.CONFLICT,{code:"annotation_entry_mismatch",item_id:e,details:{collection:r.collectionKey,entry_index:p,expected_created_at:o,actual_created_at:a,matching_indexes:s},required:`Address the ${c} by the index its listing row reports and keep --expect-at set to that row's created_at. When several indexes share the timestamp, inspect those rows before retrying, because the guard compares timestamps, not entry identities.`,why:"A listing page's position or count is not an entry address; only the row's index is, and the expectation checks that the entry at that index still carries the created_at that was read.",examples:[`pm ${r.collectionKey} ${e} --limit 5`,`pm ${r.collectionKey} ${e} ${l} ${s.length===1?s[0]:"<index>"} --expect-at ${o}${l==="--edit"?' --add "<text>"':""}`]})}function NE(e,t,n,r,o,i){let a=gn(e.metadata,t),s=o?a.findIndex(c=>jg(c)&&c.author===n&&c.text===r):-1;return s>=0?{changedFields:[],written:a,position:s}:(a.push(i({created_at:E(),author:n,text:r})),e.metadata[t]=a,{changedFields:[t],written:a,position:a.length-1})}function Dg(e,t,n){return $f.has(e)?t.map((r,o)=>o).sort((r,o)=>Lf(t[r],t[o])||r-o).indexOf(n)+1:n+1}async function or(e,t,n,r){$E(r,t);let o=A(process.cwd(),n.path);await O(o);let i=await S(o),a=x(i,R()),s=Ur(t.limit);if(r.input.mode==="list"){let _=await q(o,e,i.id_prefix,i.item_format,a.type_to_folder);if(!_)throw new d(`Item ${e} not found`,m.NOT_FOUND);let g=await ne(_,{schema:i.schema}),y=gn(g.document.metadata,r.collectionKey);return xa(_.id,r.collectionKey,y,s,t.includeMeta===!0)}let c=I(t.author,i.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,g;try{g=await fe({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=gn(w.metadata,r.collectionKey),k=Ug(r.input.index,b.length,r.collectionKey);return Fg(e,b,k,r,t.expectAt),Mg(b[k],"deleted"),b.splice(k,1),w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){io(w,r.conflictGuidance)}let y=gn(g.item,r.collectionKey);return xa(g.item.id,r.collectionKey,y,s,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let l=r.input.rawValue??r.input.value??"";PE(l,r);let p=r.parseText(r.input.value??"");if(!p.trim())throw new d(`${r.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(r.input.mode==="edit"){let _=r.editOp??r.op,g,y=0;try{g=await fe({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(k){let C=gn(k.metadata,r.collectionKey),T=Ug(r.input.index,C.length,r.collectionKey);Fg(e,C,T,r,t.expectAt);let $=C[T];return Mg($,"edited"),C[T]=CE($,p,c,r.createEntry),y=Dg(r.collectionKey,C,T),k.metadata[r.collectionKey]=C,{changedFields:[r.collectionKey]}}})}catch(k){io(k,r.conflictGuidance)}let w=gn(g.item,r.collectionKey),b=y;return xa(g.item.id,r.collectionKey,w,s,t.includeMeta===!0,{action:"edit",entryIndex:b,entry:w[b-1]},t.fullHistory===!0)}let u,f=0;try{u=await fe({pmRoot:o,settings:i,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(_){let g=NE(_,r.collectionKey,c,p,t.ifAbsent===!0,r.createEntry);return f=Dg(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(_){io(_,r.conflictGuidance)}let h=gn(u.item,r.collectionKey);return xa(u.item.id,r.collectionKey,h,s,t.includeMeta===!0,{action:"add",entryIndex:f,entry:h[f-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Ug(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)}`,i=t===1?`1 ${r}`:`${t} ${n}`;throw new d(`${o} index ${e??"(missing)"} out of range (item has ${i})`,m.USAGE)}return e-1}function ME(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 qg(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function FE(e,t){let n=e.length-t.length;return t.map((r,o)=>qg(r,n+o+1))}function xa(e,t,n,r,o,i,a=!1){let s=i===void 0||a?FE(n,El(n,i!==void 0&&a?void 0:r)):i.entry===void 0?[]:[qg(i.entry,i.entryIndex)],c=i!==void 0&&s.length<n.length;return{id:e,[t]:s,count:s.length,...i?.changedCount===void 0?{}:{changed:i.changedCount===1},...[o,i!==void 0].includes(!0)?{total_count:n.length,returned_count:s.length,has_more:c||s.length<n.length,...r!==void 0?{limit:r}:{}}:{},...ME(t,i,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]="146c927e-4db7-5a69-a715-c6996983f5f8")}catch{}})();function DE(e){return e===void 0?"unknown":e==="claim"?"claim":"assignment"}async function Kg(e,t,n){let r=[...await Promise.resolve().then(()=>Bi(Ye(e,t),t)).catch(()=>[])].reverse().find(s=>s.patch.some(c=>c.path==="/metadata/assignee")),o=r?.patch.find(s=>s.path==="/metadata/assignee"),i=o!==void 0&&typeof o.value=="string"&&o.value.trim()===n.trim()?r:void 0,a=DE(i?.op);return{phrase:a==="claim"?`claimed by ${n}`:`assigned to ${n}`,holder:n,source:a,since:i?.ts??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]="4790c318-c305-53d4-895c-e9ac90665376")}catch{}})();function ir(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Bu({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Ct(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Ct(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Wu(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new d(o,m.USAGE);return`workflow_transition_not_allowed: ${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]="e32c9f13-2e6a-5ac6-a1ce-9c839121441a")}catch{}})();function La(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new d("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",m.USAGE);let n=typeof e.handoff=="string"?Ct(e.handoff,t):void 0;if(n===void 0||Fn(n,t)||n===t.in_progress_status)throw new d("--handoff must name a configured non-terminal status distinct from the in-progress status. Inspect pm schema statuses or add a project queue with pm schema add-status <queue> --role active.",m.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new d("--handoff requires --message with implementation evidence and the next verification step.",m.USAGE);return n}function zg(e,t,n,r,o){if(Fn(e.status,r)||!e.assignee?.trim())throw new d("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",m.CONFLICT);let i=n.governance.workflow_enforcement??"off",a=ir({enforcement:i,typeWorkflows:i==="off"?[]:Dn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),s={from_status:e.status,to_status:t,message:o},c=e.status===t?[]:["status"];return e.status=t,{receipt:s,warnings:a?[a]:[],changedFields:c}}import{AsyncLocalStorage as UE}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]="f4c54507-c8b1-5f19-b58a-61186c79c8b0")}catch{}})();function Lt(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:Ct("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]="a49a1fae-4705-55b4-b4d7-8aa2b4fbfe89")}catch{}})();var jE="strict",Na="start_blocked_by_open_dependency";function Hg(e,t,n){if(t===void 0)return!1;let r=pn(Lt(n),n);return pn(t,n)===r&&pn(e??"",n)!==r}function Tl(e,t,n){let r=o=>je(o.trim(),n).toLowerCase();return r(e)===r(t)}function GE(e,t,n){let r=e.dependencies??[],o=r.filter(a=>a.kind==="blocked_by");if(r.some(a=>a.kind!=="blocked_by"&&Zm(a.kind)==="blocked_by"&&Tl(a.id,t,n)))return N(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&Tl(e.blocked_by,t,n))){let a=o.filter(s=>Tl(s.id,t,n));return a.length===1&&a.every(s=>s.id===Qn(s.id,n,void 0))?N(["update",e.id,"--dep-remove",`id=${a[0].id},kind=blocked_by`]):N(["get",e.id,"--fields","blocked_by,dependencies"])}let i=a=>a.trim().toLowerCase();return o.every(a=>i(a.id)===i(String(e.blocked_by)))?N(["update",e.id,"--unset","blocked_by"]):N(["get",e.id,"--fields","blocked_by,dependencies"])}var qE=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function KE(e,t){try{return(await eg(e)).filter(n=>!n.resolved)}catch(n){let r=Kr(n)?n.context.code:void 0;if(!t||typeof r!="string"||!qE.has(r))throw n;return r}}async function Bg(e){let t=e.settings.governance.start_blocker_enforcement??jE;if(t==="off")return[];let n=x(e.settings,R()).type_to_folder,r=e.metadata.id,o=await KE({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n,metadata:e.metadata},t==="warn"||e.force===!0);if(typeof o=="string")return[`start_blocker_unverifiable:${r}:${o}`];if(o.length===0)return[];let i=o.map(a=>a.id).join(",");if(t==="warn")return[`start_with_open_blockers:${r}:${i}`];if(e.force===!0)return[`start_blocker_override:${r}:${i}`];throw new d(`Cannot start ${r}: ${o.length===1?"its blocker":`${o.length} of its blockers`} ${i} ${o.length===1?"is":"are"} still open.`,m.CONFLICT,{code:"start_blocked_by_open_dependency",item_id:r,required:`Finish or close the open blocker${o.length===1?"":"s"} first, remove the blocked_by edge if it no longer applies, or start anyway with --force.`,why:"Starting work that a declared blocker still gates would leave an in-progress item that validate reports as non_blocked_status_has_blocked_by. governance.start_blocker_enforcement (strict by default) governs this check.",nextSteps:[...o.filter(a=>a.external!==!0).slice(0,3).map(a=>N(["get",a.id])),GE(e.metadata,o[0].id,e.settings.id_prefix),"pm next"],details:{enforcement:t,open_blockers:o.map(a=>({id:a.id,title:a.title,status:a.status,external:a.external===!0}))}})}async function Ma(e){if(e.requested===!1||!Hg(e.fromStatus,e.metadata.status,e.registry))return[];let t=await Bg(e),n=Cl.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var Cl=new UE;function Wg(e){return Cl.run({warnings:new Set},e)}async function Vg(e){let t=Cl.getStore();if(t===void 0)return[];let n=Hg(e.metadata.status,Lt(e.registry),e.registry)?await Bg(e):[];for(let r of n)t.warnings.add(r);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]="8893eba1-595b-5f31-9496-e8debc63a27c")}catch{}})();var Yg="no_available_next_item";function Jg(e,t){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let n=e.context;return typeof n=="object"&&n!==null&&"code"in n&&n.code===t}function zE(e){return Jg(e,"already_claimed_by")}async function so(e,t,n,r={}){let o=A(process.cwd(),n.path);await O(o);let i=await S(o),a=D(i.schema),s=I(r.author,i.author_default),c=Hn(s),l=null,p=!1,u={},f=[],h=await fe({pmRoot:o,settings:i,id:e,op:"claim",author:s,message:r.message,force:t,skipNoop:!0,async mutate(_){let g=_.metadata.assignee??"",y=_.metadata.claim_principal?.trim()||g;if(l=g.trim().length>0?g:null,Fn(_.metadata.status,a)&&!t)throw new d(`Cannot claim terminal item ${_.metadata.id} without --force`,m.CONFLICT);if(l!==null&&y!==c){if(r.ifAvailable===!0)return p=!0,f.push(`claim_skipped_held_by:${l}`),{changedFields:[]};if(!t){let P=await Kg(o,_.metadata.id,g);throw new d(`Item ${_.metadata.id} is already ${P.phrase}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",item_id:_.metadata.id,claimed_by:P.holder,claimed_at:P.since,claim_source:P.source,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."]})}f.push(`claim_takeover:${l}->${s}`)}let w={assignee:s,claim_principal:c},b=["assignee","claim_principal"].filter(P=>_.metadata[P]!==w[P]);Object.assign(_.metadata,w);let k=_.metadata.status,{changedFields:C,warnings:T,...$}=VE(_.metadata,r.start===!0,i,a);return T.push(...await WE({pmRoot:o,settings:i,metadata:_.metadata,fromStatus:k,registry:a,force:t,start:r.start===!0})),u=$,f.push(...T),{changedFields:[...b,...C],warnings:f}}});return p||f.push(...await BE({pmRoot:o,settings:i,principal:c,itemId:h.item.id})),{item:h.item,changed_fields:h.changedFields,claimed_by:p&&l!==null?l:s,previous_assignee:l,forced:t,...p?{skipped:!0}:{},...f.length>0?{warnings:f}:{},...u}}var HE="claim_semantic_attribution_unrecorded";async function BE(e){try{return await Sg(e),[]}catch{return[HE]}}function Xg(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new d(n?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",m.USAGE,{code:"missing_required_argument",field:"id",required:"Pass an item id, or --next to select the next available item.",nextSteps:[`Retry as pm claim <id>${r}, or pm claim --next${r}.`]});if(t&&e)throw new d("Specify either an item id or --next, not both",m.USAGE,{code:"ambiguous_option_combination",required:"Pass either an item id or --next.",nextSteps:[`Retry as pm claim ${e}${r} to claim that item, or drop the id to select with --next.`]})}async function WE(e){return e.start?Ma(e):Vg(e)}function VE(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(Fn(e.status,r))throw new d(`Cannot start terminal item ${e.id}; reopen it with pm item reopen before starting it`,m.CONFLICT,{code:"terminal_state_conflict",item_id:e.id,why:"Starting work moves an active item into progress; a terminal item must be reopened so its recurrence evidence is recorded.",nextSteps:[`Run pm item reopen ${e.id} "<reason>", then pm claim ${e.id} --start.`]});let o=Lt(r),i=n.governance.workflow_enforcement??"off",a=ir({enforcement:i,typeWorkflows:i==="off"?[]:Dn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:o}),s={from_status:e.status,to_status:o},c=e.status===o?[]:["status"];return e.status=o,{start:s,changedFields:c,warnings:a?[a]:[]}}async function Qg(e,t,n={},r={}){let o=YE(n.maxAttempts),i=await S(A(process.cwd(),t.path)),a={...n,author:I(n.author,i.author_default)},s=await ro({...r,callerAuthor:a.author,limit:String(o)},t),c=[s.recommended,...s.ready].filter(l=>l!==null).map(l=>({...l,reasons:"reasons"in l?l.reasons:["ranked ready candidate"]}));return JE(c.slice(0,o),e,t,a)}function YE(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new d("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function JE(e,t,n,r={},o=so){let i=0,a=[],s=()=>a.length>0?{start_refused:[...a]}:{};for(let c of e){i+=1;try{let l=await o(c.id,t,n,r),p={...l,recommendation:c,attempts:i,available:!0,...s()};if(!l.skipped)return p}catch(l){if(Jg(l,Na)){a.push(c.id);continue}if(!zE(l))throw l}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:I(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:i,...s(),warnings:[Yg]};throw XE(i,a,r.start===!0)}function XE(e,t,n){let r=e===0,o="Every ranked candidate was claimed by another agent before this atomic selection completed.";return r?o="No ready items matched the specified filters or selection criteria.":t.length>0&&(o=`${t.length} of ${e} attempted candidates refused their start because a declared blocker is open (${t.join(", ")}), and nothing was written to them; ${t.length===e?"no other candidate was attempted":"every other attempted candidate was claimed by another agent"}.`),new d(r?"No actionable items matched the selection filters":"No actionable item remained available to claim",r?m.NOT_FOUND:m.CONFLICT,{code:Yg,why:o,nextSteps:[r?"Verify the filters or run pm next to inspect all ready work.":`Run pm claim --next${n?" --start":""} again, with the same filters, to refresh the ranked candidate set.`],...t.length>0?{details:{start_refused:[...t]}}:{}})}async function sr(e,t,n,r={}){let o=A(process.cwd(),n.path);await O(o);let i=await S(o),a=I(r.author,i.author_default),s=Hn(a),c=r.ownershipReleaseBypass===!0,l=null,p=D(i.schema),u=La(r,p);if(u!==void 0&&c)throw new d("Ownership-release bypass only clears ownership; it cannot change a handoff status.",m.USAGE);let f,h;try{h=await fe({pmRoot:o,settings:i,id:e,op:"release",author:a,message:r.message,force:t,bypassAssigneeConflict:c,mutate(g){l=g.metadata.assignee??null;let y=u===void 0?void 0:zg(g.metadata,u,i,p,r.message);return f=y?.receipt,!l&&!g.metadata.claim_principal?{changedFields:[]}:(delete g.metadata.assignee,delete g.metadata.claim_principal,{changedFields:["assignee","claim_principal",...y?.changedFields??[]],warnings:y?.warnings})}})}catch(g){io(g,{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 Eg({pmRoot:o,principal:s,itemId:h.item.id});let _=pn(h.item.status,p)===pn(p.in_progress_status,p);return{item:h.item,released_by:a,changed_fields:h.changedFields,previous_assignee:l,forced:t,...f===void 0?{}:{handoff:f},...h.warnings.length>0||_?{warnings:[...h.warnings,..._?["released_unclaimed_in_progress"]:[]]}:{},..._?{suggestions:[`${h.item.id} remains ${h.item.status} and unclaimed. If work is paused, run pm release ${h.item.id} --pause 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]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function QE(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 ZE(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 eA(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 Zg(e=Hi,t=$r){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 TG(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 ey(e,t=$r,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let i of t){let a=`${o.agent_harness}\0${i}`,s=r.get(a)??{harness:o.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1;let c=o.agent_provenance?.[i];c!=null&&c.value.length>0?s.observed+=1:c===null?s.unavailable+=1:s.legacy_missing+=1,r.set(a,s)}return[...r.values()].map(o=>{let i=o.observed+o.unavailable;return{...o,coverage:i===0?null:o.observed/i,inert:i>=n&&o.observed===0}}).sort((o,i)=>o.harness.localeCompare(i.harness)||o.dimension.localeCompare(i.dimension))}function CG(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 l of["role","topic"]){let p=`${c.agent_harness}\0${l}`,u=o.get(p)??{harness:c.agent_harness,dimension:l,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let f=c.agent_provenance?.[l];f?.value&&(u.observed+=1,u.by_source[f.source]=(u.by_source[f.source]??0)+1),o.set(p,u)}let i=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([l],[p])=>l.localeCompare(p)))})).sort((c,l)=>c.harness.localeCompare(l.harness)||c.dimension.localeCompare(l.dimension)),a=i.filter(c=>c.entries>=r),s=a.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:a.length>0&&s.length===0,minimum_coverage:n,minimum_entries:r,rows:i,failures:s}}function IG(e){let t=[...e].sort((i,a)=>i.ts.localeCompare(a.ts)||i.author.localeCompare(a.author)||i.op.localeCompare(a.op)||i.before_hash.localeCompare(a.before_hash)||i.after_hash.localeCompare(a.after_hash)),n=new Map,r=new Map;for(let i of t){let a=i.agent_episode,s=QE(i),c=`${s.source}:${s.id}`,l=n.get(c);if(l){l.entries.push(i);continue}let p={id:s.id,...a?.label===void 0?{}:{label:a.label},...a?.parent_id===void 0?{}:{parent_id:a.parent_id},source:s.source,entries:[i],children:[]};n.set(c,p),a!==void 0&&r.set(s.id,p)}let o=[];for(let i of n.values()){let a=i.parent_id?r.get(i.parent_id):void 0;a&&ZE(i,a,r)?a.children.push(i):o.push(i)}return eA(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]="2661c74e-3e73-50f5-80a2-f103ff0cf2d4")}catch{}})();var ty=100;function cr(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new d(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function tA(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=ty?t:`${t.slice(0,ty-3)}...`}function ny(e){return e.map((t,n)=>`${n+1}. ${tA(t)}`).join("; ")}function nA(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 rA(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function ry(e,t){let n=nA(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,i)=>i+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new d(`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.`,m.USAGE);let r=n[0];if(e.length===0)throw new d(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new d("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let i=[],a=[];for(let s=0;s<e.length;s+=1)rA(e[s],o)&&(a.push(e[s]),i.push(s+1));if(a.length===0)throw new d(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${ny(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:a,selected_indexes:i,selected_count:a.length,skipped_count:e.length-a.length}}if(r==="only-index"){let o=cr(t.onlyIndex);if(o>e.length)throw new d(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${ny(e)}`,m.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]="1ce8c06c-cdc7-57bb-b4c3-477b2e07d71c")}catch{}})();var vn=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",Zr,lh,"FORCE_COLOR"]),Ua=/^[A-Za-z_][A-Za-z0-9_]*$/,wn=["schema","tracker","auto","none"],oy=["source","isolated","snapshot"];function co(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 d(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${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`,m.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1);if(!Ua.test(a))throw new d(`${t} env_set key "${a}" is invalid`,m.USAGE);if(vn.has(a.toUpperCase()))throw new d(`${t} env_set key "${a}" is reserved for sandbox safety`,m.USAGE);r[a]=s}return Object.keys(r).length>0?r:void 0}function lo(e,t){if(!e)return;let n=Jn(e,{separators:/[;,\n]/});if(n.length===0)throw new d(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let r of n){if(!Ua.test(r))throw new d(`${t} env_clear key "${r}" is invalid`,m.USAGE);if(vn.has(r.toUpperCase()))throw new d(`${t} env_clear key "${r}" is reserved for sandbox safety`,m.USAGE)}return n}function ja(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 d(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function Ga(e,t){if(!e)return;let n=e.trim().toLowerCase();if(wn.includes(n))return n;throw new d(`${t} pm_context_mode must be one of: ${wn.join(", ")}`,m.USAGE)}function bn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(oy.includes(n))return n;throw new d(`${t} workspace_context_mode must be one of: ${oy.join(", ")}`,m.USAGE)}function kn(e){if(!e)return;let t=Jn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function lr(e,t,n){let r=kn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(i){throw new d(`${t} ${n} includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`,m.USAGE)}return r}}function qa(e,t){if(!e)return;let n=he(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new d(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function Ka(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 d(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0||s.length===0)throw new d(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);r[a]=s}return Object.keys(r).length>0?r:void 0}function za(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 d(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0||s.length===0)throw new d(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(s);if(!Number.isFinite(c))throw new d(`${t} assert_json_field_gte value for "${a}" must be numeric`,m.USAGE);r[a]=c}return Object.keys(r).length>0?r:void 0}var oA=new Set(Rt);function Ha(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function iA(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let a=o.toLowerCase();if(!oA.has(a)){r.push(o);continue}if(Object.hasOwn(n,a))throw t(`provides key "${o}" more than once after case normalization`);n[a]=i}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${Rt.join(", ")}.`);return n}function yn(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 Fa(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(a=>typeof a!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=o.filter(a=>a.length>0);return i.length>0?i:void 0}function iy(e,t,n){let r=Fa(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(i){throw n(`field "${t}" includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`)}return r}}function Da(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 aA(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:Da(n,"timeout_seconds",t),i=r===void 0?void 0:Da(r,"timeout",t);if(o!==void 0&&i!==void 0&&o!==i)throw t("timeout and timeout_seconds must match when both are provided");let a=o??i;if(!Number.isInteger(a)||a<=0)throw t("timeout_seconds must be a positive integer");return a}function sA(e,t){let n=yn(e,"scope",t);if(n===void 0)return"project";if(!kt.includes(n))throw t(`field "scope" must be one of: ${kt.join(", ")}`);return n}function cA(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Ha(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,i]of Object.entries(n)){if(typeof i!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Ua.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(vn.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=i}return Object.keys(r).length>0?r:void 0}function lA(e,t){let n=Fa(e,"env_clear",t);if(n){for(let r of n){if(!Ua.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(vn.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function dA(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 mA(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=Da(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 pA(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Ha(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,i]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 i!="string"&&typeof i!="number"&&typeof i!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(i)}return Object.keys(r).length>0?r:void 0}function uA(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Ha(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,i]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]=Da(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function fA(e,t,n){let r=f=>new d(`${n} ${t} ${f}`,m.USAGE);if(!Ha(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Rt.join(", ")}.`);let o=iA(e,r),i=yn(o,"command",r),a=yn(o,"cmd",r);if(i!==void 0&&a!==void 0&&i!==a)throw r("command and cmd must match when both are provided");let s=i??a;if(s===void 0||s.trim().length===0)throw r('requires a non-empty "command" string');let c=yn(o,"path",r),l=yn(o,"pm_context_mode",r);if(l!==void 0&&!wn.includes(l))throw r(`field "pm_context_mode" must be one of: ${wn.join(", ")}`);let p=bn(yn(o,"workspace_context_mode",r),`${n} ${t}`),u=yn(o,"note",r);return{command:s,path:c!==void 0&&c.length>0?c:void 0,scope:sA(o,r),timeout_seconds:aA(o,r),pm_context_mode:l,workspace_context_mode:p,env_set:cA(o,r),env_clear:lA(o,r),shared_host_safe:dA(o,"shared_host_safe",r),assert_stdout_contains:Fa(o,"assert_stdout_contains",r),assert_stdout_regex:iy(o,"assert_stdout_regex",r),assert_stderr_contains:Fa(o,"assert_stderr_contains",r),assert_stderr_regex:iy(o,"assert_stderr_regex",r),assert_stdout_min_lines:mA(o,r),assert_json_field_equals:pA(o,r),assert_json_field_gte:uA(o,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function mo(e,t){let n=e.trim();if(n.length===0)throw new d(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let r;try{r=JSON.parse(n)}catch(i){throw new d(`${t} value is not valid JSON: ${i instanceof Error?i.message:String(i)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,m.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new d(`${t} array must include at least one linked-test entry object`,m.USAGE);return o.map((i,a)=>fA(i,o.length>1?`entry ${a+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]="f75d72fe-b7f5-576d-b6c1-1cd94e3288b3")}catch{}})();var Il=["command","cmd"],po=Object.freeze(Rt.filter(e=>!["command","cmd","timeout"].includes(e)));function ay(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new d("Use exactly one --update or --update-index with --set-json",m.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new d("--set-json must contain a JSON object with explicit linked-test metadata fields",m.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:cr(e.updateIndex,"--update-index")},patch:t};let n=e.update,r=/^(command|path)=/u.exec(n);return{selector:r?.[1]==="path"?{path:n.slice(r[0].length)}:{command:r?n.slice(r[0].length):n},patch:t}}function sy(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new d("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",m.USAGE)}function _A(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("Select one linked test by index, command, or path",m.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new d("Select one linked test by index, command, or path",m.USAGE);if("index"in t){let r=cr(t.index,"--update-index");if(r<=e.length)return r-1}else{let r="command"in t?"command":"path",o="command"in t?t.command:t.path;if(typeof o!="string"||o.trim().length===0)throw new d("Linked-test selector must be a non-empty command or path",m.USAGE);let i=e.flatMap((a,s)=>a[r]===o?[s]:[]);if(i.length===1)return i[0];if(i.length>1)throw new d(`Linked-test selector is ambiguous; matching indexes: ${i.map(a=>a+1).join(", ")}`,m.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new d("No linked test matched the update selector",m.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function cy(e,t){let n=Object.keys(e),r=n.filter(o=>!po.includes(o));if(n.length===0&&!t||r.length>0)throw new d("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",m.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...r.length>0?{field:r[0]}:{},required:`Patch at least one editable field: ${po.join(", ")}.`,recovery:{allowed_values:[...po]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new d("scope is required and cannot be cleared",m.USAGE)}function hA(e,t,n){let r={};for(let o of po){let i=t[o]!==void 0?t[o]:e[o];i!=null&&(r[o]=i)}return{command:n,...r}}function Ba(e){return{field:e,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function gA(e,t,n){let r=Il.filter(i=>Object.hasOwn(e,i)).map(i=>e[i]),o=typeof e[t]=="string"?e[t].trim():"";if(r.length>1&&r.some(i=>typeof i!="string"||i.trim()!==o))throw new d("--set-json sets command and cmd to different values; send one command",m.USAGE,{code:"linked_test_command_immutable",...Ba(t),nextSteps:["Send the replacement command once, as command."]});if(o.length===0||o===n.command)throw new d(o.length===0?`--set-json cannot set ${t}: a linked test's command is its immutable identity`:`--set-json ${t} repeats the selected entry's command; omit it to edit only metadata`,m.USAGE,{code:"linked_test_command_immutable",...Ba(t),nextSteps:[`Patch only editable fields: ${po.join(", ")}.`]});return to(o),o}function yA(e){let{id:t,tests:n,index:r,identityKey:o,otherFields:i,requested:a,global:s}=e;cy(i,!0);let c=hA(n[r],i,a),l=mo(JSON.stringify(c),"--add-json")[0];Kc(l);let p=n.findIndex((u,f)=>f!==r&&Li(u,l));if(p>=0)throw new d(`--set-json cannot change ${o}: linked test ${p+1} already has the requested identity, so a replacement would merge into it`,m.USAGE,{code:"linked_test_command_immutable",...Ba(o),nextSteps:[`Edit linked test ${p+1} instead: ${N([...dt(s),"test",t,"--update-index",String(p+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${N([...dt(s),"test",t,"--remove-index",String(r+1)])}`]});return c}function wA(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function vA(e){let{id:t,tests:n,index:r,patch:o,global:i,controls:a}=e;if(typeof o!="object"||o===null||Array.isArray(o))return;let s=o,c=Il.find(g=>Object.hasOwn(s,g));if(c===void 0)return;let l=n[r],p=gA(s,c,l),u=Object.fromEntries(Object.entries(s).filter(([g])=>!Il.includes(g))),f=yA({id:t,tests:n,index:r,identityKey:c,otherFields:u,requested:p,global:i}),h=l.command!==void 0&&n.filter(g=>g.command===l.command).length===1?["--remove",`command=${l.command}`]:["--remove-index",String(r+1)],_=[...dt(i),"test",t,...h,"--add-json",JSON.stringify(f),...wA(a)];throw new d(`--set-json cannot change ${c}: a linked test's command is its immutable identity; replace the entry instead`,m.USAGE,{code:"linked_test_command_immutable",...Ba(c),recovery:{suggested_retry:N(_),suggested_retry_args:_},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(t)}, { ${h[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function bA(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("Linked-test metadata patch must be a JSON object",m.USAGE);let n=Object.keys(t);cy(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([s])=>Rt.includes(s))),o=Nf(mo(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([s,c])=>[s,c===null?void 0:c]))}),"--set-json")[0]);Kc(o);let i=n.filter(s=>!ae(e[s],o[s])),a={...e};for(let s of i){let c=o[s];Object.assign(a,{[s]:c}),c===void 0&&delete a[s]}if(!a.command?.trim()&&!a.path?.trim())throw new d("Linked-test entry must retain a command or path",m.USAGE);return{test:a,fields:i}}async function ly(e,t,n={}){let r=A(process.cwd(),n.path);await O(r);let o=await S(r),i=I(t.author,o.author_default),a=x(o,R()),s=0,c=[],l=await Yn({pmRoot:r,settings:o,id:e,author:i,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:a.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:s,fields:c}}),mutate(u){let f=u.metadata.tests??[],h=_A(f,t.selector);vA({id:u.metadata.id,tests:f,index:h,patch:t.patch,global:n,controls:t});let _=bA(f[h],t.patch);return s=h+1,c=_.fields,_.fields.length===0?{changedFields:[]}:(u.metadata.tests=f.map((g,y)=>y===h?{..._.test,updated_by:i,updated_at:E()}:g),{changedFields:["tests"]})}}),p=l.item.tests;return{ok:!0,id:l.item.id,tests:p,count:p.length,changed:l.changedFields.length>0,updated_index:s,updated_fields: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]="0f06f072-47a7-560e-9291-72e47225a73c")}catch{}})();function kA(){return{metadata:{},body:""}}import{AsyncLocalStorage as ij}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]="78b20f7a-4ae7-5811-9ab7-049a07d844e5")}catch{}})();var SA=Dc("list").properties.outputSession,EA={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:{...SA},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},dy={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},my={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},me={type:"string",description:"pm item id, for example pm-abc1."},AA=`Operation name (one of): ${yc.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,TA={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."}},CA={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 j(e,t=[]){return{...my,properties:{...my.properties,...e},required:t}}var IA=[{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:j({action:{type:"string",enum:[...yc],description:AA},id:me,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."},...EA},["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:j({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:j({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:j({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 (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), 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:j({query:{type:"string"},options:{type:"object"},...CA},["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:j({options:{type:"object"},...TA})},{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:j({id:me,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:j({verify:{type:"boolean",description:"Verify complete selected authoritative history chains."},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:j({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, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:j({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:me,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"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},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"}},["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:j({id:me,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:j({id:me,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:j({id:me,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:j({id:me,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:j({id:me,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:j({id:me,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:j({id:me,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 return the newest comments that fit the output budget, with total_count/has_more metadata and a next_cursor that pages back to older comments through outputCursor; without options.limit or outputLimit, outputBudget "unbounded" returns the complete listing at once. Pass options.limit=N for only the newest N comments (next_cursor pages within that window when the budget trims it; has_more reports older comments beyond it without a cursor) or options.limit=0 for summary-only metadata; options.full=true returns the complete history after a write. Rows carry their absolute index; pair edit/delete with options.expectAt to refuse a different entry.',inputSchema:j({id:me,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:j({id:me,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:j({id:me,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; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:j({id:me,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; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:j({id:me,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:j({id:me,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:j({subcommand:{type:"string",enum:[...dp]},id:me,target:me,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:j({id:me,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:j({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:j({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:j({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. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:j({...dy,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",...Nn],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},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:[...ic]},description:`Lifecycle roles for add-status: ${ic.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.",properties:dy}},["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:j({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:j({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:j({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."}})}],RA={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"},OA=IA.map(e=>{let t=RA[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Dc(t,{properties:n,required:r})}});function py(){return OA.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]="29d30fe0-03b7-533b-a468-151d3db90ccb")}catch{}})();var uy=new Map([["activity",["--limit","--after","--full"]],["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"]]]),xA=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Sy=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Va=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"]),Sn=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),Ey=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["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"],["normalize","governance-audit"],["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"]]),Ay=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"]]),Ty=new Map([...Ay.entries()].flatMap(([e,t])=>Nt(t).map(n=>[n,e]))),Cy=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],xl=new Map(Cy.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),PA=10,$A=20,fy=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["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 items."],["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 workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),Iy=[["init",Wp],["install",Yp],["uninstall",Jp],["explore",Xp],["manage",ru],["describe",Qp],["reload",ou],["doctor",iu],["catalog",au],["adopt",su],["adopt-all",Zp],["activate",eu],["deactivate",tu],["migrate",nu]],LA=[...Iy.map(([e,t])=>e==="init"?[e,Vp]:[e,t]),["upgrade",Cr]],NA=[...Iy.map(([e,t])=>[`extension ${e}`,t]),...LA.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Qo],["config",Bp],["extension",Zo],["package",Tr],["packages",Tr],["install",cu],["create",ii],["item mutate",Cu],["item complete",Iu],["item reopen",Ru],["copy",ai],["focus",si],["update",ci],["update-many",li],["upgrade",Cr],["calendar",Ir],["cal",Ir],["context",Rr],["ctx",Rr],["get",mi],["search",hi],["eval",xu],["events",di],["workspace",qt],["workspace position",[]],["workspace snapshot",qt],["workspace snapshot create",qt],["workspace snapshot list",qt],["workspace snapshot inspect",qt],["workspace snapshot restore",qt],["workspace snapshot delete",qt],["next",_i],["aggregate",Vo],["deps",ui],["graph",fi],["guide",pi],["reindex",lu],["history",Yo],["history-compact",qp],["history-attest",Kp],["history-redact",jp],["history-repair",Gp],["history-author-acknowledge",Jo],["merge",Up],["schema",zp],["profile",Hp],["plan",Xo],["restore",pu],["delete",uu],["close",du],["close-many",ei],["append",ti],["claim",mu],["release",fu],["start-task",_u],["pause-task",hu],["close-task",gu],["comments",Lp],["notes",Np],["learnings",Mp],["files",Fp],["docs",Dp],["test",vu],["test-runs-worker",[]],["test-all",bu],["telemetry",ku],["test-runs",Su],["gc",Eu],["stats",ni],["ops",[]],["duplicates",ri],["validate",Au],["health",oi],["assurance",Tu],...Pu,["contracts",gi],["completion",yi],["activity",Ou],...[...Sy].map(e=>[e,Wo])],uo=new Map(NA);for(let{alias:e,canonical:t}of Te){let n=uo.get(e);n!==void 0&&uo.set(t,n)}function MA(e){return Ty.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function _y(e){let t=Te.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:hc.includes(e)?ke(e):e.startsWith("extension-")?ke(`extension ${e.slice(10)}`):e.startsWith("package-")?ke(`package ${e.slice(8)}`):e.startsWith("item-")?ke(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ke(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ke(`templates ${e.slice(10)}`):Va.has(e)?Ay.get(e)??ke(e):null}function FA(e,t){let n=B(t);return n!==t||Te.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:Nt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function Nt(e){return e.split("|").map(t=>ke(t)).filter(t=>t.length>0)}function DA(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let i of Nt(o.command_path)){let a=i.split(" ").filter(s=>s.length>0);if(a.length!==0)for(let s=a.length;s>0;s-=1){let c=a.slice(0,s).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function Wa(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function fo(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function UA(e,t){if(!t)return{...e};let n=fo(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:n}}function Rl(e,t){let n=fo(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:n}}function ke(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Ry(e){return e.replace(/\s+/g,"-")}function Zt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function hy(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=Zt(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function Ol(e,t,n){n&&(e[t]=!0)}function gy(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?Jm(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function jA(e){let t=gy(e.long,"long"),n=gy(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),Ol(o,"required",e.required===!0),Ol(o,"repeatable",e.repeatable===!0),Ol(o,"list",e.list===!0),e.default!==void 0&&(o.default=e.default);let i=Zt(e.description);i&&(o.description=i);let a=bp(e);o.value_arity=a.value_arity;let s=Zt(e.value_name)??a.value_name;s&&(o.value_name=s);let c=a.value_type??(a.value_name?"string":null);return c&&(o.value_type=c),o}function Oy(e){let t=new Map;for(let r of e){let o=ke(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},a=`${r.layer}:${r.name}`;i.sourceDedupe.has(a)||(i.sourceDedupe.add(a),i.sources.push({layer:r.layer,name:r.name}));for(let s of r.flags){let c=jA(s);if(!c)continue;let l=`${c.flag}|${c.short??""}`;i.dedupe.has(l)||(i.dedupe.add(l),i.flags.push(c))}t.set(o,i)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((i,a)=>{let s=i.layer.localeCompare(a.layer);return s!==0?s:(i.name??"").localeCompare(a.name??"")})});return n}function GA(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...Ec.filter(({flag:n})=>n.startsWith("--output-"))]}}function qA(e){let t=Oy(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let a=ke(i.command);if(a.length===0)continue;let s=Zt(i.action)??Ry(a),c=Array.isArray(i.arguments)?i.arguments.map(l=>{let p=Zt(l.name);return p?{name:p,required:l.required===!0,variadic:l.variadic===!0,description:Zt(l.description)}:null}).filter(l=>l!==null):[];n.set(a,{...i.tier===void 0?{}:{tier:i.tier},...GA(i,t.get(a)?.flags??[]),command:a,action:s,source:{layer:i.layer,name:i.name},description:Zt(i.description),intent:Zt(i.intent),arguments:c,examples:hy(i.examples),failure_hints:hy(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(ke(i));for(let i of n.keys())r.add(i);for(let i of t.keys())r.add(i);let o=[];for(let i of[...r].sort((a,s)=>a.localeCompare(s))){let a=n.get(i);o.push(KA(i,a,t.get(i)?.flags??[]))}return o}function KA(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Ry(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function zA(e){let t=e.flag.startsWith("--")?e.flag:void 0,n=al({long:t,short:t===void 0?e.flag:void 0});return n!==null&&/[a-z0-9]/iu.test(n)?n:null}function HA(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 BA(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}}:{},...e.default!==void 0?{default:e.default}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function WA(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]=HA(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=zA(o);!i||n[i]!==void 0||(n[i]=Ec.some(a=>a.flag===o.flag&&a.flag.startsWith("--output-"))?pf[i]:BA(o,e.action),o.required===!0&&r.push(i))}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 VA(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 YA(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((i,a)=>i.localeCompare(a)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(i=>`${i.flag}|${i.short??""}`));for(let i of n.flags){let a=`${i.flag}|${i.short??""}`;if(!o.has(a))o.add(a),r.flags.push(i);else{let s=r.flags.find(c=>`${c.flag}|${c.short??""}`===a);s&&VA(s,i)}}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 JA(e,t=S){let n={mode:sn.extensions.policy.mode,trust_mode:sn.extensions.policy.trust_mode,default_sandbox_profile:sn.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=A(process.cwd(),e.path);if(!await H(ie(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await Er({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),a=await Ar({...i,loaded:i.loaded});return{handlers:new Set(a.commands.handlers.map(s=>ke(s.command))),disabledReason:null,commandDefinitions:a.registrations.commands,flagRegistrations:a.registrations.flags,registrations:a.registrations,policyState:{mode:i.policy.mode,trust_mode:i.policy.trust_mode,default_sandbox_profile:i.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function XA(e,t={}){let n=new Map;for(let r of gc){let o=Va.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=_y(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of Va)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:_y(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:Te.find(o=>o.alias===r.command)?.canonical??ke(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function QA(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&&(!Sn.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?Nt(e.command_path):[],r=n.some(a=>t.handlers.has(a)||t.handlers.has(B(a))),o=n.map(a=>Ey.get(B(a))).find(a=>typeof a=="string"),i=t.disabledReason===null&&r;return{action:e.action,invocable:i,available:i,requires_extension:!0,provider:"extension",disabled_reason:i?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){let t=uo.get(e)??Mn,n=De(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function ZA(e){return Sn.has(B(e))?!1:uo.has(e)}function eT(e){return Sy.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function yy(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function tT(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function nT(e){let t=new Map;for(let r of e.definitions){let o=yy(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(s=>tT(s)).find(s=>s!==null),a=r.cli_aliases.map(s=>yy(s)).filter(s=>s!==null&&s!==o);for(let s of r.commands){let c=t.get(s)??{flags:[],seen:new Set},l=i?{flag:o,short:i}:{flag:o},p=`${l.flag}|${l.short??""}`;c.seen.has(p)||(c.seen.add(p),c.flags.push(l));for(let u of a){let f=`${u}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:u}))}t.set(s,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,Sc(o.flags));return n}function wy(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let i=`${o.flag}|${o.short??""}`;r.has(i)||(r.add(i),n.push(o))}return Sc(n)}function rT(e){let t=al(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function oT(e,t,n,r){let o=(n??[]).map(rT),i=t==="extension"&&(n!==void 0||iT(e,r));return{flags:o,inherited:i?{inherited_flags:$p({readOutput:aT(e,r)})}:{}}}function Py(e,t){let n=B(e);return t.find(r=>B(r.command)===n)}function iT(e,t){return Py(e,t)!==void 0}function aT(e,t){return Py(e,t)?.read_output!==void 0}function sT(e,t,n,r,o){let i=new Map(t);for(let{alias:a,canonical:s}of Te){let c=t.get(s)??t.get(a);c&&(i.set(a,c),i.set(s,c))}return e.map(a=>{let s=ZA(a),c=s?xy(a):[],l=n.get(eT(a))??[],p=i.get(a),u=wy(c,l),f=c.length>0&&(p?.flags.length??0)>0?"mixed":s?"core":"extension",h=oT(a,f,p?.flags,o),_=wy(u,h.flags);return{command:a,flags:_,...h.inherited,...r?{canonical_command:Ly(a),visibility:$y(a,o),positionals:xp(a)?.slots??[],flag_invocations:zr(a,_)}:{},provider:f,extension_sources:p?.sources}}).sort((a,s)=>a.command.localeCompare(s.command))}function cT(e,t=ln){let n=new Set(e),r=new Map;for(let o of Cy){let i=o.aliases.filter(a=>n.has(a));r.set(o.canonical,{canonical:o.canonical,aliases:i,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let i=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};i.aliases.includes(o.alias)||i.aliases.push(o.alias),i.contracts.push(o),r.set(o.canonical,i)}return[...r.values()].map(({contracts:o,...i})=>o.length===0?i:{...i,contracts:o}).sort((o,i)=>o.canonical.localeCompare(i.canonical))}function lT(){return{create_string_options:uf,create_repeatable_options:Ri,update_string_options:ff,update_repeatable_options:_f,list_string_options:Sp,search_string_options:Ep,calendar_string_options:Ap,context_string_options:Tp,activity_string_options:Cp}}function vy(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let s of e.required_create_fields)n.add(s);for(let s of e.required_create_repeatables)n.add(s)}let r=Ln(e,"create",n),o=[...new Set(r.required)].sort((s,c)=>s.localeCompare(c)),i=[...new Set(o.map(s=>Re("create",s)))].sort((s,c)=>s.localeCompare(c)),a=[...new Set(e.options.filter(s=>s.required===!0).map(s=>s.key))].sort((s,c)=>s.localeCompare(c));return{required_option_keys:o,required_flags:i,required_type_options:a,policy_errors:[...new Set(r.errors)].sort((s,c)=>s.localeCompare(c))}}function dT(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){let o=e.by_type[r];t[r]=vy(o,"strict"),n[r]=vy(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function mT(e,t){let n=fo(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let a=i.properties;if(typeof a!="object"||a===null)return i;let s=a.action;return typeof s!="object"||s===null||s.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function pT(e){let t=Wa(e.action)!==void 0||Wa(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,i=e.flagsOnly===!0,a=e.availabilityOnly===!0,s=e.runtimeOnly===!0,c=e.full===!0,l=Wa(e.action),p=Wa(e.command),u=!r&&!c&&!o&&!i&&!a&&!l&&!p;return{selectedAction:l,selectedCommand:p,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:a,runtimeOnly:s,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||p!==void 0&&!c}}function uT(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new d("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function fT(e,t=S){try{return await t(e)}catch{return structuredClone(sn)}}async function _T(e,t,n){let r=await fT(t),o=await JA(e),i=x(r,o.registrations??R()),a=Je(r.schema),s=qA(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:D(r.schema),runtimeFieldRegistry:a,runtimeFieldFlagMap:nT(a),createRequiredOptionContracts:dT(i),extensionContracts:s,mergedExtensionContracts:YA(s.filter(c=>Ya(n,c.command,s))),extensionFlagMap:Oy(o.flagRegistrations)}}function by(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Va.has(e.selectedAction)||e.selectedCommand!==void 0&&Sn.has(B(e.selectedCommand)))}function hT(e,t){let n=XA(t,{includePackageOwnedActions:by(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(up);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(i=>i.action===o.action)?.tier??oa(o.action))!=="internal"))}return by(e)&&e.selectedCommand!==void 0&&Sn.has(B(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:MA(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function gT(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new d(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function yT(e,t){return[...new Set([...hc.filter(n=>!Sn.has(B(n))),...[...uo.keys()].filter(n=>!Sn.has(B(n))),...e.flatMap(n=>n.command_path?Nt(n.command_path).filter(r=>n.provider==="extension"||!Sn.has(B(r))||t.some(o=>o.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let o=Te.find(i=>i.alias===r||i.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>ke(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function wT(e,t){let n=t.slice(0,PA),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,$A),a=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),s=t[0];return new d(`Command "${e}" is a command namespace. Choose a concrete child command: ${o}.`,m.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:a,nextSteps:[`Retry with a child command, for example: ${a[0]}`],recovery:{suggested_retry:`pm contracts --command "${s}" --flags-only --json`,fallback_candidates:i.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function vT(e,t){return new d(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm package install ${t} --project" and retry.`,m.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 package install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm package install ${t} --project`],recovery:{suggested_retry:`pm package install ${t} --project`}})}function bT(e){return new d(`Unknown command: "${e}".`,m.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 kT(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(o=>o.startsWith(`${e.selectedCommand} `));if(n.length>0)throw wT(e.selectedCommand,n);let r=Ey.get(B(e.selectedCommand));throw r?vT(e.selectedCommand,r):bT(e.selectedCommand)}function ST(e,t){let n=hT(e,t.mergedExtensionContracts);gT(e,n);let r=yT(n,t.mergedExtensionContracts);kT(e,r);let o=e.selectedCommand?Ty.get(B(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(l=>o?l.action===o:FA(l,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.some(l=>l.action===e.selectedAction))throw new d(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let a=e.selectedAction?i.filter(l=>l.action===e.selectedAction):i,s=[...new Map(a.map(l=>QA(l,t.runtimeProbe)).map(l=>[o?l.action:`${l.action}|${l.command_path??""}`,l])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?s.filter(l=>l.invocable):s;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:i,scopedActionDescriptors:a,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(l=>l.action))]}}function ET(e){return new Set(fo(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 AT(e){let t=hf,n=fo(t),r=ET(t),o=e.filter(i=>!r.has(i.action)).map(i=>WA(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function ky(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?UA(n,e.selectedAction):e.selectedCommand?Rl(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):Rl(n,r);return e.runtimeOnly&&!e.selectedAction?Rl(o,new Set(t.actions)):o}function TT(e,t,n){let r=AT(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?mT(ky(e,n,r),t.createRequiredOptionContracts):ky(e,n,r);return{mergedSchema:r,filteredSchema:o}}function CT(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?DA(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function $y(e,t){return t.find(n=>B(n.command)===B(e))?.tier??oa(e)}function Ya(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||$y(t,n)!=="internal"}function IT(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(ln.filter(o=>o.hidden&&(o.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(o=>o.alias));if(e.summary&&!e.fullOutput)for(let o of xl.keys())r.add(o);return t.filter(o=>!r.has(o)&&Ya(e,o,n))}function Ly(e){let t=Te.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":xl.get(n)??n}var RT=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"]]),OT=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function xT(e,t){let n=fy.get(B(e))??(e.includes(" ")?void 0:fy.get(Ly(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(l=>Nt(l.command).some(p=>B(p)===B(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(" "),i=o.at(-1),a=o.slice(0,-1).join(" "),s=RT.get(i),c=OT.get(e)??a;return{intent:s===void 0||a.length===0?`Run ${e}.`:`${s} ${c}.`,intent_source:"generated"}}function PT(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(ke))].filter(i=>i.length>0).sort((i,a)=>i.localeCompare(a)).map(i=>{let a=Nc(i,{generateFallback:!0}),s=i.split(" ")[0],c=xl.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),l=new Set([...xy(i).map(f=>f.flag),...t.filter(f=>Nt(f.command).some(h=>B(h)===B(i))).flatMap(f=>f.flags.map(h=>h.flag))]),p=(uy.get(B(i))??uy.get(c)??xA).filter(f=>l.has(f)),u=xT(i,t);return{command:i,intent:u.intent,...o||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...p.length>0?{flags:p}:{},default_max_estimated_tokens:a.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...a.default_max_estimated_tokens_by_format}}:{}}})}function $T(e){return e.map(t=>({budget:Nc(t,{generateFallback:!0}),envelope:$_(t)}))}function LT(e){let t=new Map;for(let n of e){let r=R_(n),o=r===void 0?[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED]:r.exit_codes,i=o.join(","),a=t.get(i)??{commands:[],exit_codes:o};a.commands.push(n),t.set(i,a)}return[...t.values()]}function NT(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>Nt(r.command).some(o=>B(o)===B(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>Nt(o.command).some(i=>r.has(i)))}return t.extensionContracts.filter(r=>Ya(e,r.command,t.extensionContracts))}function MT(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 FT(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=Ff);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,i])=>[o,[...new Set(i.map(a=>`--${a.cli_flag}`))].sort((a,s)=>a.localeCompare(s))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...op],services:[...ip],policy_modes:[...ap],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...lp],trust_modes:[...sp],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...cp],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...qm],create_modes:[...Km],close_validation_modes:[...zm],workflow_enforcement_modes:[...Hm]},e.relationship_kind_contracts=[...Xm,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,i)=>o.kind.localeCompare(i.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function DT(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 UT(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=sT(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(Op).filter(([a])=>i.has(a)).map(([a,s])=>({command:a,default:s,brief_fields:[...Rp,"priority"],compact_fields:[...Ip]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:a})=>({canonical:i,aliases:a})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function jT(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=lT();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function GT(e,t,n,r){e.command_summaries=PT(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Xu],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(ke))].filter(o=>ef(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...nf(o).keys()]}))}:{}},e.grammar_contracts={nouns:dn.nouns,shared_verbs:dn.shared_verbs,scope_before_verb:dn.scope_before_verb,visible_top_level_ceiling:dn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:dn.ceiling_raise_requires_pm_item,positional_shape_budget:dn.positional_shape_budget,positional_shape_count:new Set(kc.map(({slots:o})=>Pp(o))).size,positional_action_count:bc.length,positional_action_parents:[...new Set(bc.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:kc}:{}}}async function Pl(e,t){let n=pT(e);uT(n);let r=A(process.cwd(),t.path),o=await _T(t,r,n),i=ST(n,o),a=TT(n,o,i),s=CT(n,i),c=IT(n,s,o.extensionContracts),l=MT(n,a,i,c),p=NT(n,o,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&GT(l,c,p,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return l;let f=cT(i.commandCatalog.filter(h=>Ya(n,h,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||FT(l,o,n),DT(l,n,a,p),UT(l,n,o,c,f),jT(l,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(l.assurance_contracts={measurement_source_kinds:[...th],gate_triggers:[...eh]}),n.fullOutput&&l.grammar_contracts&&(l.grammar_contracts.destinations=Bo.map(h=>({...h,reason:h.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(l.mcp_tools=py(),l.context_intents=sf(),l.read_output_dimensions=Zu,l.error_codes=O_,l.command_output_contracts=$T(c),l.diagnostic_output_contracts=Qu,l.command_exit_contracts={vocabulary:I_,command_sets:LT(c)}),l}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a4abc17-0fcb-573f-8f89-6e505e112261")}catch{}})();async function Ny(e,t,n=af){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(i=>typeof i=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as qT}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]="971103f5-a101-5e45-a607-ebebbaafe7f5")}catch{}})();function $l(e){let t=Qm();for(let n of e)t.register(n);return t}function KT(e,t,n=[]){if(n.length===0)return e;let r=JSON.parse(e),o=JSON.parse(nl(t));for(let i of n){let a=i.split("."),s=o;for(let p of a){let u=fc(s);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(p)||["constructor","prototype","__proto__"].includes(p)||u===null||!Object.hasOwn(u,p))throw new d(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,m.USAGE);s=u[p]}if(fc(s)===null)throw new d(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,m.USAGE);let c=r,l=o;for(let p of a.slice(0,-1)){let u=c[p];l=l[p],u===void 0&&Object.defineProperty(c,p,{value:structuredClone(l),enumerable:!0,writable:!0,configurable:!0}),c=c[p]}Object.defineProperty(c,a.at(-1),{value:s,enumerable:!0,writable:!0,configurable:!0})}return ae(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
1
+ import{A as al,B as T_,C as C_,n as Uu,o as vi,p as zu,q as Hu,r as ki,s as Or,t as Ac,u as Tc,v as Si,y as gf,z as yf}from"./chunk-VVGXPF4W.js";import{a as I_,f as R_,h as un,m as O_,o as zr,r as oa,s as x_,t as P_,x as $_}from"./chunk-DW5S67LO.js";import{$ as $h,Aa as Gh,Ab as Aa,Ba as qh,Ca as Kh,Da as zh,Ea as Hh,Fa as Bh,Ga as _n,H as fh,Ha as Wh,Hb as wg,I as _h,Ia as Vh,Ib as vg,J as hh,Ja as Yh,Jb as bg,K as gh,Ka as va,L as yh,La as Jh,M as wh,Ma as Xh,N as vh,Na as Qh,Nb as kg,O as bh,Oa as Zh,Ob as Lg,P as kh,Pa as ng,Q as Sh,Qa as ba,R as Eh,Ra as Qt,S as Ah,Sa as rg,T as Th,Ta as ka,U as Ch,V as Ih,W as Rh,Wa as eo,X as Oh,Y as xh,Z as Zn,_ as Ph,bb as og,cb as ig,db as ag,eb as sg,fb as cg,g as eh,gb as lg,h as th,ha as Lh,hb as Sa,ib as hl,ja as Mh,jb as dg,ka as fl,kb as gl,lb as tr,ma as Fh,mb as mg,na as Dh,nb as pg,oa as _l,ob as ug,pb as fg,qb as _g,rb as to,sb as Ea,tb as hg,ub as gg,vb as nr,wb as yl,xb as yg,z as ch,za as jh}from"./chunk-3A6XMQZJ.js";import{h as yt,i as hn,m as tg}from"./chunk-M5FZTPFA.js";import{a as Zr,b as lh,c as ya,h as ph,i as uh}from"./chunk-GBW2EAAG.js";import{c as dl}from"./chunk-IDAYTYNN.js";import{A as pa,B as z_,C as H_,D as sl,E as Vr,F as ua,G as Xn,H as B_,I as cl,J as be,K as ll,L as ye,M as W_,N as V_,O as fa,P as Y_,Q as _a,R as J_,a as ia,b as Hr,c as aa,d as Pe,e as sa,f as L_,g as ca,h as la,i as Br,j as N_,k as da,l as ma,m as ht,n as M_,o as F_,p as D_,q as Wr,r as U_,s as j_,t as gt,u as v,v as G_,w as q_,y as Ge,z as K_}from"./chunk-2ZS3I5ZP.js";import{e as Mu,g as Fu,h as Du,k as Gu,q as Ku}from"./chunk-3SH3L3DB.js";import{M as pf,N as Mc,O as uf,P as Ri,Q as Fc,R as ff,S as _f,Z as Dc,a as Sp,b as Ep,ba as hf,c as Ap,d as Tp,f as Cp}from"./chunk-V27M5UQH.js";import{a as ih,b as ah,c as Ta,d as Ca,e as Ia}from"./chunk-P6KYUJD4.js";import{K as Uh,b as sh}from"./chunk-AXPRCCYM.js";import{A as Og,Ea as kl,Ga as xg,Va as oo,Xa as Pg,Ya as $g,b as oh,e as ml,g as pl,i as ul,j as no,l as Sg,m as Eg,n as wl,sa as vl,v as Ag,w as Tg,x as Cg,xa as ro,y as Ig,z as Rg,za as bl}from"./chunk-JYWVRXLD.js";import{A as wa,F as er,h as ha,k as Q_,l as Yr,o as Z_,w as $t,y as nh,z as rh}from"./chunk-NMU3QFAU.js";import{a as Qr,b as fn,d as eg}from"./chunk-NP5C2TQM.js";import{$ as If,$a as na,A as Pi,B as jc,C as et,D as kf,E as Gc,F as Sf,G as de,I as It,J as Ef,K as $i,L as Bt,M as he,N as zn,O as qc,P as Pr,Q as Kc,R as Li,S as Rt,T as Af,U as Ni,V as Mi,W as Fi,X as Di,Xa as qr,Y as Ui,Z as Tf,Za as y_,_ as Cf,_a as w_,ab as ra,bb as v_,c as $u,da as ji,ea as Gi,f as Lu,g as Nu,ha as Vi,i as wi,ia as Yi,j as Kt,ja as Qf,k as Dn,ka as Ji,l as Bu,la as Xi,m as Wu,ma as Yt,n as wf,oa as el,p as pt,pa as Qi,pb as Jn,q as ut,qb as b_,r as vf,ra as Zf,rb as ol,s as Uc,sa as e_,sb as k_,t as bf,ta as Ur,tb as S_,u as Ht,ub as E_,v as qn,w as Oi,x as Kn,xb as il,y as xi,yb as A_,z as ue}from"./chunk-33EK522E.js";import{$ as Vp,$a as ui,A as Sc,Aa as yu,B as Ec,C as $p,Ca as wu,D as Mn,Da as vu,E as Wo,Ea as bu,F as Vo,Fa as ku,G as Lp,Ga as Su,H as Np,Ha as Eu,I as Mp,Ia as ni,J as Fp,Ja as ri,K as Dp,Ka as oi,L as Yo,La as Au,M as Up,Ma as Tu,N as jp,Na as ii,O as Gp,Oa as Cu,P as Jo,Pa as Iu,Q as qp,Qa as Ru,R as Kp,Ra as ai,S as zp,Sa as si,T as Hp,Ta as ci,U as Xo,Ua as li,V as Qo,Va as Ir,W as Bp,Wa as Ou,X as Zo,Xa as di,Ya as Rr,Z as Wp,Za as mi,_ as Tr,_a as pi,aa as Yp,ab as fi,b as Ip,ba as Jp,bb as xu,c as Rp,ca as Xp,cb as qt,d as Op,da as Qp,db as _i,ea as Zp,eb as hi,fa as eu,fb as gi,ga as tu,gb as yi,h as vc,ha as nu,ia as ru,ja as ou,jb as Pu,ka as iu,la as au,lb as De,ma as su,mb as M,n as bc,na as cu,o as xp,oa as Cr,pa as lu,qa as du,r as Bo,ra as ei,s as kc,sa as ti,t as dn,ta as mu,ua as pu,v as Pp,va as uu,wa as fu,xa as _u,ya as hu,za as gu}from"./chunk-UCUESVFW.js";import{A as Nh,a as Jr,b as Xr,c as Qn,d as rt,i as ga}from"./chunk-NSOXVVQX.js";import{d as X_}from"./chunk-3FN4ON2Z.js";import{C as s_,E as c_,H as l_,M as d_,N as m_,O as ea,U as Jt,W as Xt,Y as q,Z as ne,_ as f_,aa as ge,b as Ze,ba as __,c as Go,ca as ta,d as qo,da as nt,e as xe,ea as h_,f as Yf,fa as Yn,g as Jf,ga as fe,h as Vt,ha as g_,ia as rl,j as je,k as Dr,l as Bn,m as o_,n as Wn,na as Kr,o as Vn,p as i_,v as Gr,x as a_}from"./chunk-NY65XTX7.js";import{A as Pf,Aa as Gf,Ab as O,B as qi,Ba as qf,Ca as Yc,E as Ki,Fa as Jc,G as Bc,Ha as Kf,Ia as zf,J as se,Ja as Hf,K as pn,Ka as Bf,L as ce,La as Wf,N as $f,O as Lf,P as Nf,Pa as Ue,Q as Wc,Qa as Wt,R as Mf,Ra as Xc,S as ft,Sa as Lr,T as xt,Ta as Nr,Ua as Qc,Va as _t,Wa as Mr,Xa as Fr,a as ju,c as At,ca as zi,cb as Vf,da as Df,e as bi,ea as Uf,eb as Zc,f as Tt,fa as $r,g as zt,ga as Hi,h as qu,hb as Xf,ib as Wi,j as D,jb as tt,k as Ct,l as Je,lb as Zi,n as Fn,nb as t_,ob as jr,qa as Vc,qb as n_,r as Ot,rb as Pt,sb as tl,tb as nl,u as Rf,ua as Hn,ub as r_,v as zc,va as I,vb as S,w as Of,wa as jf,wb as Ie,x as Hc,xa as Bi,y as xf,yb as p_,zb as u_}from"./chunk-HIKZYZ26.js";import{a as Ii,b as mf}from"./chunk-C3O6JJPO.js";import{$a as B,$b as Ar,A as sc,Aa as ie,B as cc,Ba as Et,Bc as Ce,C as lc,Ce as lf,D as dc,Da as Ye,E as mc,Ea as Ho,F as pc,Fb as fp,Fc as Ti,Ga as cn,Gb as _p,Ha as ae,Hb as hp,Ib as gp,Ic as Yu,J as Jm,Jb as yp,Jc as N,Ka as Nn,Kb as wp,Ke as df,Lb as vp,Nb as Sr,Nc as Ju,Oc as dt,Pb as bp,Pc as Xu,Q as Xm,S as Qm,Sb as kp,Sd as E,Tc as Qu,U as Zm,W as ep,Wd as Ci,X as tp,Xe as Ff,Yc as Nc,Yd as te,Za as Te,Zb as Er,_b as wc,a as Gm,bb as ln,bc as Vu,ce as of,ea as lt,fb as op,fe as mt,g as rc,ga as np,gb as ip,ge as xr,hb as ap,hc as Cc,i as oc,ia as fc,ib as sp,j as ic,ja as vr,jb as cp,jc as Ic,kb as lp,kc as Rc,lb as hc,lc as Oc,ma as _c,mb as dp,mc as xc,me as af,n as Uo,na as br,nc as Pc,o as kt,oa as Re,ob as mp,oc as $c,p as yr,pb as pp,pc as Lc,q as wr,qc as R,qd as Zu,r as ac,ra as x,rd as ef,sa as Ae,sb as gc,sc as Un,t as qm,ta as Ko,tb as up,tc as mn,u as Km,ua as Ln,ub as yc,uc as J,ud as tf,ue as sf,v as zm,va as kr,vc as Ei,vd as nf,ve as cf,w as Hm,wa as rp,wc as jn,xa as A,xd as rf,y as Bm,ya as zo,ye as Gn,z as Wm,za as Oe,zc as Ai}from"./chunk-MK7UQEE5.js";import{a as mh}from"./chunk-EGN2HFRU.js";import{b as dh}from"./chunk-FOA7XKWP.js";import{A as d,C as H,D as St,E as Fe,F as ee,I as oe,K as $n,m as jo,s as uc,u as Vm,x as sn,y as Ym,z as m}from"./chunk-G6ERMFJ5.js";import{readFile as wE}from"node:fs/promises";import vE 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]="20a3a324-d176-5918-8167-5e548be4abc9")}catch{}})();var Sl="context-intents.json";function Ra(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bE(e,t,n){if(!Ra(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 Ng(e,t){let n=Array.isArray(e)?e:Ra(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)=>bE(r,t,o))}async function kE(e){let t=vE.join(e,Sl),n;try{n=await wE(t,"utf8")}catch(o){if(St(o))return[];throw await u_(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Sl}: ${i}`,{cause:o})}return Ng(r,Sl)}function SE(e){if(!Ra(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Ra(n)?n.contextIntents??n.context_intents:void 0}function EE(e){return e.flatMap(t=>{let n=SE(t.module);return n===void 0?[]:Ng(n,`package ${t.name}`)})}async function AE(e){let t=await kE(e.pmRoot),n=EE(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Oa(e,t){let n=await AE(e);return await cf(n,t)}import{readFile as TE}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]="9c3ae5d4-5437-543d-90a3-67e92b073c18")}catch{}})();function Pa(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,de(e,t)}function jg(e){return Object.prototype.toString.call(e)==="[object Object]"}function CE(e,t,n,r){let o=E();if(!jg(e))return{...r({created_at:o,author:n,text:t}),text:t,edited_at:o};let i=a=>typeof a=="string"&&a!=="";return{...e,...i(e.created_at)?{}:{created_at:o},...i(e.author)?{}:{author:n},text:t,edited_at:o}}function Mg(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new d(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function El(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function gn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function rr(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let o=ue(n,"--add");return Object.keys(o).map(i=>i.trim().toLowerCase()).some(i=>i!=="text")?n:o.text?.trim()||n}catch{return n}}function Al(e){return typeof e=="object"&&e!==null&&"code"in e}function ao(e,t){if(!It(e))throw new d(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function IE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new d(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let n=Bt(),r=It(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return ao(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let o=e.file.trim();if(!o)throw new d("--file path cannot be empty",m.USAGE);if(o==="-")return ao(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await TE(o,"utf8"),emptyFlag:"--file"}}catch(i){if(Al(i)&&St(i))throw new d(`--file path not found: ${o}. Use --file - to read stdin.`,m.USAGE);let a=i instanceof Error?i.message:String(i);throw new d(`Failed to read --file path "${o}": ${a}. Use --file - to read stdin.`,m.USAGE)}}async function $a(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new d("Specify only one of --edit or --delete",m.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new d("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new d("--delete must be a positive integer",m.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new d("--edit must be a positive integer",m.USAGE);let n=await IE(e,t);if(e.edit!==void 0){if(!n)throw new d("--edit requires replacement text from --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function io(e,t){throw e instanceof d&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new d(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Gg(e){return e==="comments"?"--stdin":"--add -"}function RE(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function OE(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function xE(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=OE(t),o=Gg(e.collectionKey),i=e.retryArgs===void 0?{}:{field:e.textFlag,recovery:{suggested_flags:[t],suggested_retry:N(e.retryArgs),suggested_retry_args:[...e.retryArgs]}};if(r!==void 0){let a=r.split(/[ =]/,1)[0],s=a==="--file"?"that file":"stdin",c=e.conflictingOperand===void 0?"":` "${e.conflictingOperand}" was read as positional text, which ${a} cannot be combined with: drop it, or pass it as the text without ${a}.`;return new d(`${e.textFlag} value "${t}" looks like an option, not annotation text: ${e.textFlag} took ${a} as its value. Drop ${e.textFlag} and pass ${r} on its own.${c}`,m.USAGE,{code:"annotation_flag_like_value",required:`Drop ${e.textFlag}: ${r} reads the ${n} text from ${s} by itself. Use ${e.textFlag} text=${t} only when the text really is "${t}".`,examples:[`${e.commandPrefix} ${r}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...i})}return new d(`${e.textFlag} value "${t}" looks like an option, not annotation text. Use ${o} to read stdin, or use text=${t} for literal dash-leading text.`,m.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${t} when the text really starts with "-".`,examples:[`${e.commandPrefix} ${o}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...i})}function PE(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!RE(e)))throw xE({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function $E(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new d(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,m.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(LE(e,t),e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new d(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,m.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> ${Gg(e.collectionKey)}`]})}function LE(e,t){if(t.expectAt!==void 0){if(e.input.mode!=="edit"&&e.input.mode!=="delete")throw new d(`--expect-at guards an --edit or --delete of one ${e.collectionKey.replace(/s$/,"")}`,m.USAGE,{code:"annotation_expectation_without_target",required:"Combine --expect-at with --edit <index> or --delete <index>; omit it for list and append operations.",examples:[`pm ${e.collectionKey} <id> --edit <index> --expect-at <created_at> --add "<text>"`,`pm ${e.collectionKey} <id> --delete <index> --expect-at <created_at>`]});if(typeof t.expectAt!="string"||t.expectAt.trim().length===0)throw new d("--expect-at must be the non-empty created_at timestamp of the entry you read",m.USAGE,{code:"annotation_expectation_invalid",required:"Pass the created_at value of the row you read at that index, as a string."})}}function Fg(e,t,n,r,o){if(o===void 0)return;let i=t[n]?.created_at,a=typeof i=="string"?i:null;if(a===o)return;let s=t.flatMap((f,h)=>f?.created_at===o?[h+1]:[]),c=r.collectionKey.replace(/s$/,""),l=r.input.mode==="delete"?"--delete":"--edit",p=n+1,u=s.length===1?` The ${c} created at ${o} is at index ${s[0]}.`:s.length>1?` ${s.length} ${r.collectionKey} were created at ${o}: indexes ${s.join(", ")}.`:` No ${c} on ${e} was created at ${o}.`;throw new d(`${c.charAt(0).toUpperCase()}${c.slice(1)} ${p} on ${e} was created at ${a||"an unrecorded time (malformed entry)"}, not ${o}; refusing ${l} of an entry the caller did not read. Nothing was written.${u}`,m.CONFLICT,{code:"annotation_entry_mismatch",item_id:e,details:{collection:r.collectionKey,entry_index:p,expected_created_at:o,actual_created_at:a,matching_indexes:s},required:`Address the ${c} by the index its listing row reports and keep --expect-at set to that row's created_at. When several indexes share the timestamp, inspect those rows before retrying, because the guard compares timestamps, not entry identities.`,why:"A listing page's position or count is not an entry address; only the row's index is, and the expectation checks that the entry at that index still carries the created_at that was read.",examples:[`pm ${r.collectionKey} ${e} --limit 5`,`pm ${r.collectionKey} ${e} ${l} ${s.length===1?s[0]:"<index>"} --expect-at ${o}${l==="--edit"?' --add "<text>"':""}`]})}function NE(e,t,n,r,o,i){let a=gn(e.metadata,t),s=o?a.findIndex(c=>jg(c)&&c.author===n&&c.text===r):-1;return s>=0?{changedFields:[],written:a,position:s}:(a.push(i({created_at:E(),author:n,text:r})),e.metadata[t]=a,{changedFields:[t],written:a,position:a.length-1})}function Dg(e,t,n){return $f.has(e)?t.map((r,o)=>o).sort((r,o)=>Lf(t[r],t[o])||r-o).indexOf(n)+1:n+1}async function or(e,t,n,r){$E(r,t);let o=A(process.cwd(),n.path);await O(o);let i=await S(o),a=x(i,R()),s=Ur(t.limit);if(r.input.mode==="list"){let _=await q(o,e,i.id_prefix,i.item_format,a.type_to_folder);if(!_)throw new d(`Item ${e} not found`,m.NOT_FOUND);let g=await ne(_,{schema:i.schema}),y=gn(g.document.metadata,r.collectionKey);return xa(_.id,r.collectionKey,y,s,t.includeMeta===!0)}let c=I(t.author,i.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,g;try{g=await fe({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let b=gn(w.metadata,r.collectionKey),k=Ug(r.input.index,b.length,r.collectionKey);return Fg(e,b,k,r,t.expectAt),Mg(b[k],"deleted"),b.splice(k,1),w.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(w){io(w,r.conflictGuidance)}let y=gn(g.item,r.collectionKey);return xa(g.item.id,r.collectionKey,y,s,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let l=r.input.rawValue??r.input.value??"";PE(l,r);let p=r.parseText(r.input.value??"");if(!p.trim())throw new d(`${r.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(r.input.mode==="edit"){let _=r.editOp??r.op,g,y=0;try{g=await fe({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(k){let C=gn(k.metadata,r.collectionKey),T=Ug(r.input.index,C.length,r.collectionKey);Fg(e,C,T,r,t.expectAt);let $=C[T];return Mg($,"edited"),C[T]=CE($,p,c,r.createEntry),y=Dg(r.collectionKey,C,T),k.metadata[r.collectionKey]=C,{changedFields:[r.collectionKey]}}})}catch(k){io(k,r.conflictGuidance)}let w=gn(g.item,r.collectionKey),b=y;return xa(g.item.id,r.collectionKey,w,s,t.includeMeta===!0,{action:"edit",entryIndex:b,entry:w[b-1]},t.fullHistory===!0)}let u,f=0;try{u=await fe({pmRoot:o,settings:i,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(_){let g=NE(_,r.collectionKey,c,p,t.ifAbsent===!0,r.createEntry);return f=Dg(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(_){io(_,r.conflictGuidance)}let h=gn(u.item,r.collectionKey);return xa(u.item.id,r.collectionKey,h,s,t.includeMeta===!0,{action:"add",entryIndex:f,entry:h[f-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Ug(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)}`,i=t===1?`1 ${r}`:`${t} ${n}`;throw new d(`${o} index ${e??"(missing)"} out of range (item has ${i})`,m.USAGE)}return e-1}function ME(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 qg(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function FE(e,t){let n=e.length-t.length;return t.map((r,o)=>qg(r,n+o+1))}function xa(e,t,n,r,o,i,a=!1){let s=i===void 0||a?FE(n,El(n,i!==void 0&&a?void 0:r)):i.entry===void 0?[]:[qg(i.entry,i.entryIndex)],c=i!==void 0&&s.length<n.length;return{id:e,[t]:s,count:s.length,...i?.changedCount===void 0?{}:{changed:i.changedCount===1},...[o,i!==void 0].includes(!0)?{total_count:n.length,returned_count:s.length,has_more:c||s.length<n.length,...r!==void 0?{limit:r}:{}}:{},...ME(t,i,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]="146c927e-4db7-5a69-a715-c6996983f5f8")}catch{}})();function DE(e){return e===void 0?"unknown":e==="claim"?"claim":"assignment"}async function Kg(e,t,n){let r=[...await Promise.resolve().then(()=>Bi(Ye(e,t),t)).catch(()=>[])].reverse().find(s=>s.patch.some(c=>c.path==="/metadata/assignee")),o=r?.patch.find(s=>s.path==="/metadata/assignee"),i=o!==void 0&&typeof o.value=="string"&&o.value.trim()===n.trim()?r:void 0,a=DE(i?.op);return{phrase:a==="claim"?`claimed by ${n}`:`assigned to ${n}`,holder:n,source:a,since:i?.ts??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]="4790c318-c305-53d4-895c-e9ac90665376")}catch{}})();function ir(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Bu({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Ct(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Ct(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Wu(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new d(o,m.USAGE);return`workflow_transition_not_allowed: ${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]="e32c9f13-2e6a-5ac6-a1ce-9c839121441a")}catch{}})();function La(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new d("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",m.USAGE);let n=typeof e.handoff=="string"?Ct(e.handoff,t):void 0;if(n===void 0||Fn(n,t)||n===t.in_progress_status)throw new d("--handoff must name a configured non-terminal status distinct from the in-progress status. Inspect pm schema statuses or add a project queue with pm schema add-status <queue> --role active.",m.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new d("--handoff requires --message with implementation evidence and the next verification step.",m.USAGE);return n}function zg(e,t,n,r,o){if(Fn(e.status,r)||!e.assignee?.trim())throw new d("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",m.CONFLICT);let i=n.governance.workflow_enforcement??"off",a=ir({enforcement:i,typeWorkflows:i==="off"?[]:Dn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),s={from_status:e.status,to_status:t,message:o},c=e.status===t?[]:["status"];return e.status=t,{receipt:s,warnings:a?[a]:[],changedFields:c}}import{AsyncLocalStorage as UE}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]="f4c54507-c8b1-5f19-b58a-61186c79c8b0")}catch{}})();function Lt(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:Ct("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]="a49a1fae-4705-55b4-b4d7-8aa2b4fbfe89")}catch{}})();var jE="strict",Na="start_blocked_by_open_dependency";function Hg(e,t,n){if(t===void 0)return!1;let r=pn(Lt(n),n);return pn(t,n)===r&&pn(e??"",n)!==r}function Tl(e,t,n){let r=o=>je(o.trim(),n).toLowerCase();return r(e)===r(t)}function GE(e,t,n){let r=e.dependencies??[],o=r.filter(a=>a.kind==="blocked_by");if(r.some(a=>a.kind!=="blocked_by"&&Zm(a.kind)==="blocked_by"&&Tl(a.id,t,n)))return N(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&Tl(e.blocked_by,t,n))){let a=o.filter(s=>Tl(s.id,t,n));return a.length===1&&a.every(s=>s.id===Qn(s.id,n,void 0))?N(["update",e.id,"--dep-remove",`id=${a[0].id},kind=blocked_by`]):N(["get",e.id,"--fields","blocked_by,dependencies"])}let i=a=>a.trim().toLowerCase();return o.every(a=>i(a.id)===i(String(e.blocked_by)))?N(["update",e.id,"--unset","blocked_by"]):N(["get",e.id,"--fields","blocked_by,dependencies"])}var qE=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function KE(e,t){try{return(await eg(e)).filter(n=>!n.resolved)}catch(n){let r=Kr(n)?n.context.code:void 0;if(!t||typeof r!="string"||!qE.has(r))throw n;return r}}async function Bg(e){let t=e.settings.governance.start_blocker_enforcement??jE;if(t==="off")return[];let n=x(e.settings,R()).type_to_folder,r=e.metadata.id,o=await KE({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n,metadata:e.metadata},t==="warn"||e.force===!0);if(typeof o=="string")return[`start_blocker_unverifiable:${r}:${o}`];if(o.length===0)return[];let i=o.map(a=>a.id).join(",");if(t==="warn")return[`start_with_open_blockers:${r}:${i}`];if(e.force===!0)return[`start_blocker_override:${r}:${i}`];throw new d(`Cannot start ${r}: ${o.length===1?"its blocker":`${o.length} of its blockers`} ${i} ${o.length===1?"is":"are"} still open.`,m.CONFLICT,{code:"start_blocked_by_open_dependency",item_id:r,required:`Finish or close the open blocker${o.length===1?"":"s"} first, remove the blocked_by edge if it no longer applies, or start anyway with --force.`,why:"Starting work that a declared blocker still gates would leave an in-progress item that validate reports as non_blocked_status_has_blocked_by. governance.start_blocker_enforcement (strict by default) governs this check.",nextSteps:[...o.filter(a=>a.external!==!0).slice(0,3).map(a=>N(["get",a.id])),GE(e.metadata,o[0].id,e.settings.id_prefix),"pm next"],details:{enforcement:t,open_blockers:o.map(a=>({id:a.id,title:a.title,status:a.status,external:a.external===!0}))}})}async function Ma(e){if(e.requested===!1||!Hg(e.fromStatus,e.metadata.status,e.registry))return[];let t=await Bg(e),n=Cl.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var Cl=new UE;function Wg(e){return Cl.run({warnings:new Set},e)}async function Vg(e){let t=Cl.getStore();if(t===void 0)return[];let n=Hg(e.metadata.status,Lt(e.registry),e.registry)?await Bg(e):[];for(let r of n)t.warnings.add(r);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]="8893eba1-595b-5f31-9496-e8debc63a27c")}catch{}})();var Yg="no_available_next_item";function Jg(e,t){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let n=e.context;return typeof n=="object"&&n!==null&&"code"in n&&n.code===t}function zE(e){return Jg(e,"already_claimed_by")}async function so(e,t,n,r={}){let o=A(process.cwd(),n.path);await O(o);let i=await S(o),a=D(i.schema),s=I(r.author,i.author_default),c=Hn(s),l=null,p=!1,u={},f=[],h=await fe({pmRoot:o,settings:i,id:e,op:"claim",author:s,message:r.message,force:t,skipNoop:!0,async mutate(_){let g=_.metadata.assignee??"",y=_.metadata.claim_principal?.trim()||g;if(l=g.trim().length>0?g:null,Fn(_.metadata.status,a)&&!t)throw new d(`Cannot claim terminal item ${_.metadata.id} without --force`,m.CONFLICT);if(l!==null&&y!==c){if(r.ifAvailable===!0)return p=!0,f.push(`claim_skipped_held_by:${l}`),{changedFields:[]};if(!t){let P=await Kg(o,_.metadata.id,g);throw new d(`Item ${_.metadata.id} is already ${P.phrase}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",item_id:_.metadata.id,claimed_by:P.holder,claimed_at:P.since,claim_source:P.source,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."]})}f.push(`claim_takeover:${l}->${s}`)}let w={assignee:s,claim_principal:c},b=["assignee","claim_principal"].filter(P=>_.metadata[P]!==w[P]);Object.assign(_.metadata,w);let k=_.metadata.status,{changedFields:C,warnings:T,...$}=VE(_.metadata,r.start===!0,i,a);return T.push(...await WE({pmRoot:o,settings:i,metadata:_.metadata,fromStatus:k,registry:a,force:t,start:r.start===!0})),u=$,f.push(...T),{changedFields:[...b,...C],warnings:f}}});return p||f.push(...await BE({pmRoot:o,settings:i,principal:c,itemId:h.item.id})),{item:h.item,changed_fields:h.changedFields,claimed_by:p&&l!==null?l:s,previous_assignee:l,forced:t,...p?{skipped:!0}:{},...f.length>0?{warnings:f}:{},...u}}var HE="claim_semantic_attribution_unrecorded";async function BE(e){try{return await Sg(e),[]}catch{return[HE]}}function Xg(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new d(n?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",m.USAGE,{code:"missing_required_argument",field:"id",required:"Pass an item id, or --next to select the next available item.",nextSteps:[`Retry as pm claim <id>${r}, or pm claim --next${r}.`]});if(t&&e)throw new d("Specify either an item id or --next, not both",m.USAGE,{code:"ambiguous_option_combination",required:"Pass either an item id or --next.",nextSteps:[`Retry as pm claim ${e}${r} to claim that item, or drop the id to select with --next.`]})}async function WE(e){return e.start?Ma(e):Vg(e)}function VE(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(Fn(e.status,r))throw new d(`Cannot start terminal item ${e.id}; reopen it with pm item reopen before starting it`,m.CONFLICT,{code:"terminal_state_conflict",item_id:e.id,why:"Starting work moves an active item into progress; a terminal item must be reopened so its recurrence evidence is recorded.",nextSteps:[`Run pm item reopen ${e.id} "<reason>", then pm claim ${e.id} --start.`]});let o=Lt(r),i=n.governance.workflow_enforcement??"off",a=ir({enforcement:i,typeWorkflows:i==="off"?[]:Dn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:o}),s={from_status:e.status,to_status:o},c=e.status===o?[]:["status"];return e.status=o,{start:s,changedFields:c,warnings:a?[a]:[]}}async function Qg(e,t,n={},r={}){let o=YE(n.maxAttempts),i=await S(A(process.cwd(),t.path)),a={...n,author:I(n.author,i.author_default)},s=await ro({...r,callerAuthor:a.author,limit:String(o)},t),c=[s.recommended,...s.ready].filter(l=>l!==null).map(l=>({...l,reasons:"reasons"in l?l.reasons:["ranked ready candidate"]}));return JE(c.slice(0,o),e,t,a)}function YE(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new d("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function JE(e,t,n,r={},o=so){let i=0,a=[],s=()=>a.length>0?{start_refused:[...a]}:{};for(let c of e){i+=1;try{let l=await o(c.id,t,n,r),p={...l,recommendation:c,attempts:i,available:!0,...s()};if(!l.skipped)return p}catch(l){if(Jg(l,Na)){a.push(c.id);continue}if(!zE(l))throw l}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:I(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:i,...s(),warnings:[Yg]};throw XE(i,a,r.start===!0)}function XE(e,t,n){let r=e===0,o="Every ranked candidate was claimed by another agent before this atomic selection completed.";return r?o="No ready items matched the specified filters or selection criteria.":t.length>0&&(o=`${t.length} of ${e} attempted candidates refused their start because a declared blocker is open (${t.join(", ")}), and nothing was written to them; ${t.length===e?"no other candidate was attempted":"every other attempted candidate was claimed by another agent"}.`),new d(r?"No actionable items matched the selection filters":"No actionable item remained available to claim",r?m.NOT_FOUND:m.CONFLICT,{code:Yg,why:o,nextSteps:[r?"Verify the filters or run pm next to inspect all ready work.":`Run pm claim --next${n?" --start":""} again, with the same filters, to refresh the ranked candidate set.`],...t.length>0?{details:{start_refused:[...t]}}:{}})}async function sr(e,t,n,r={}){let o=A(process.cwd(),n.path);await O(o);let i=await S(o),a=I(r.author,i.author_default),s=Hn(a),c=r.ownershipReleaseBypass===!0,l=null,p=D(i.schema),u=La(r,p);if(u!==void 0&&c)throw new d("Ownership-release bypass only clears ownership; it cannot change a handoff status.",m.USAGE);let f,h;try{h=await fe({pmRoot:o,settings:i,id:e,op:"release",author:a,message:r.message,force:t,bypassAssigneeConflict:c,mutate(g){l=g.metadata.assignee??null;let y=u===void 0?void 0:zg(g.metadata,u,i,p,r.message);return f=y?.receipt,!l&&!g.metadata.claim_principal?{changedFields:[]}:(delete g.metadata.assignee,delete g.metadata.claim_principal,{changedFields:["assignee","claim_principal",...y?.changedFields??[]],warnings:y?.warnings})}})}catch(g){io(g,{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 Eg({pmRoot:o,principal:s,itemId:h.item.id});let _=pn(h.item.status,p)===pn(p.in_progress_status,p);return{item:h.item,released_by:a,changed_fields:h.changedFields,previous_assignee:l,forced:t,...f===void 0?{}:{handoff:f},...h.warnings.length>0||_?{warnings:[...h.warnings,..._?["released_unclaimed_in_progress"]:[]]}:{},..._?{suggestions:[`${h.item.id} remains ${h.item.status} and unclaimed. If work is paused, run pm release ${h.item.id} --pause 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]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function QE(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 ZE(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 eA(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 Zg(e=Hi,t=$r){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 TG(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 ey(e,t=$r,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let i of t){let a=`${o.agent_harness}\0${i}`,s=r.get(a)??{harness:o.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1;let c=o.agent_provenance?.[i];c!=null&&c.value.length>0?s.observed+=1:c===null?s.unavailable+=1:s.legacy_missing+=1,r.set(a,s)}return[...r.values()].map(o=>{let i=o.observed+o.unavailable;return{...o,coverage:i===0?null:o.observed/i,inert:i>=n&&o.observed===0}}).sort((o,i)=>o.harness.localeCompare(i.harness)||o.dimension.localeCompare(i.dimension))}function CG(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 l of["role","topic"]){let p=`${c.agent_harness}\0${l}`,u=o.get(p)??{harness:c.agent_harness,dimension:l,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let f=c.agent_provenance?.[l];f?.value&&(u.observed+=1,u.by_source[f.source]=(u.by_source[f.source]??0)+1),o.set(p,u)}let i=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([l],[p])=>l.localeCompare(p)))})).sort((c,l)=>c.harness.localeCompare(l.harness)||c.dimension.localeCompare(l.dimension)),a=i.filter(c=>c.entries>=r),s=a.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:a.length>0&&s.length===0,minimum_coverage:n,minimum_entries:r,rows:i,failures:s}}function IG(e){let t=[...e].sort((i,a)=>i.ts.localeCompare(a.ts)||i.author.localeCompare(a.author)||i.op.localeCompare(a.op)||i.before_hash.localeCompare(a.before_hash)||i.after_hash.localeCompare(a.after_hash)),n=new Map,r=new Map;for(let i of t){let a=i.agent_episode,s=QE(i),c=`${s.source}:${s.id}`,l=n.get(c);if(l){l.entries.push(i);continue}let p={id:s.id,...a?.label===void 0?{}:{label:a.label},...a?.parent_id===void 0?{}:{parent_id:a.parent_id},source:s.source,entries:[i],children:[]};n.set(c,p),a!==void 0&&r.set(s.id,p)}let o=[];for(let i of n.values()){let a=i.parent_id?r.get(i.parent_id):void 0;a&&ZE(i,a,r)?a.children.push(i):o.push(i)}return eA(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]="2661c74e-3e73-50f5-80a2-f103ff0cf2d4")}catch{}})();var ty=100;function cr(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new d(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function tA(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=ty?t:`${t.slice(0,ty-3)}...`}function ny(e){return e.map((t,n)=>`${n+1}. ${tA(t)}`).join("; ")}function nA(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 rA(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function ry(e,t){let n=nA(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,i)=>i+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new d(`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.`,m.USAGE);let r=n[0];if(e.length===0)throw new d(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new d("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let i=[],a=[];for(let s=0;s<e.length;s+=1)rA(e[s],o)&&(a.push(e[s]),i.push(s+1));if(a.length===0)throw new d(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${ny(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:a,selected_indexes:i,selected_count:a.length,skipped_count:e.length-a.length}}if(r==="only-index"){let o=cr(t.onlyIndex);if(o>e.length)throw new d(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${ny(e)}`,m.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]="1ce8c06c-cdc7-57bb-b4c3-477b2e07d71c")}catch{}})();var vn=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",Zr,lh,"FORCE_COLOR"]),Ua=/^[A-Za-z_][A-Za-z0-9_]*$/,wn=["schema","tracker","auto","none"],oy=["source","isolated","snapshot"];function co(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 d(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${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`,m.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1);if(!Ua.test(a))throw new d(`${t} env_set key "${a}" is invalid`,m.USAGE);if(vn.has(a.toUpperCase()))throw new d(`${t} env_set key "${a}" is reserved for sandbox safety`,m.USAGE);r[a]=s}return Object.keys(r).length>0?r:void 0}function lo(e,t){if(!e)return;let n=Jn(e,{separators:/[;,\n]/});if(n.length===0)throw new d(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let r of n){if(!Ua.test(r))throw new d(`${t} env_clear key "${r}" is invalid`,m.USAGE);if(vn.has(r.toUpperCase()))throw new d(`${t} env_clear key "${r}" is reserved for sandbox safety`,m.USAGE)}return n}function ja(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 d(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function Ga(e,t){if(!e)return;let n=e.trim().toLowerCase();if(wn.includes(n))return n;throw new d(`${t} pm_context_mode must be one of: ${wn.join(", ")}`,m.USAGE)}function bn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(oy.includes(n))return n;throw new d(`${t} workspace_context_mode must be one of: ${oy.join(", ")}`,m.USAGE)}function kn(e){if(!e)return;let t=Jn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function lr(e,t,n){let r=kn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(i){throw new d(`${t} ${n} includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`,m.USAGE)}return r}}function qa(e,t){if(!e)return;let n=he(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new d(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function Ka(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 d(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0||s.length===0)throw new d(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);r[a]=s}return Object.keys(r).length>0?r:void 0}function za(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 d(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0||s.length===0)throw new d(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(s);if(!Number.isFinite(c))throw new d(`${t} assert_json_field_gte value for "${a}" must be numeric`,m.USAGE);r[a]=c}return Object.keys(r).length>0?r:void 0}var oA=new Set(Rt);function Ha(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function iA(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let a=o.toLowerCase();if(!oA.has(a)){r.push(o);continue}if(Object.hasOwn(n,a))throw t(`provides key "${o}" more than once after case normalization`);n[a]=i}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${Rt.join(", ")}.`);return n}function yn(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 Fa(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(a=>typeof a!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=o.filter(a=>a.length>0);return i.length>0?i:void 0}function iy(e,t,n){let r=Fa(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(i){throw n(`field "${t}" includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`)}return r}}function Da(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 aA(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:Da(n,"timeout_seconds",t),i=r===void 0?void 0:Da(r,"timeout",t);if(o!==void 0&&i!==void 0&&o!==i)throw t("timeout and timeout_seconds must match when both are provided");let a=o??i;if(!Number.isInteger(a)||a<=0)throw t("timeout_seconds must be a positive integer");return a}function sA(e,t){let n=yn(e,"scope",t);if(n===void 0)return"project";if(!kt.includes(n))throw t(`field "scope" must be one of: ${kt.join(", ")}`);return n}function cA(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Ha(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,i]of Object.entries(n)){if(typeof i!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Ua.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(vn.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=i}return Object.keys(r).length>0?r:void 0}function lA(e,t){let n=Fa(e,"env_clear",t);if(n){for(let r of n){if(!Ua.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(vn.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function dA(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 mA(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=Da(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 pA(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Ha(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,i]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 i!="string"&&typeof i!="number"&&typeof i!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(i)}return Object.keys(r).length>0?r:void 0}function uA(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Ha(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,i]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]=Da(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function fA(e,t,n){let r=f=>new d(`${n} ${t} ${f}`,m.USAGE);if(!Ha(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Rt.join(", ")}.`);let o=iA(e,r),i=yn(o,"command",r),a=yn(o,"cmd",r);if(i!==void 0&&a!==void 0&&i!==a)throw r("command and cmd must match when both are provided");let s=i??a;if(s===void 0||s.trim().length===0)throw r('requires a non-empty "command" string');let c=yn(o,"path",r),l=yn(o,"pm_context_mode",r);if(l!==void 0&&!wn.includes(l))throw r(`field "pm_context_mode" must be one of: ${wn.join(", ")}`);let p=bn(yn(o,"workspace_context_mode",r),`${n} ${t}`),u=yn(o,"note",r);return{command:s,path:c!==void 0&&c.length>0?c:void 0,scope:sA(o,r),timeout_seconds:aA(o,r),pm_context_mode:l,workspace_context_mode:p,env_set:cA(o,r),env_clear:lA(o,r),shared_host_safe:dA(o,"shared_host_safe",r),assert_stdout_contains:Fa(o,"assert_stdout_contains",r),assert_stdout_regex:iy(o,"assert_stdout_regex",r),assert_stderr_contains:Fa(o,"assert_stderr_contains",r),assert_stderr_regex:iy(o,"assert_stderr_regex",r),assert_stdout_min_lines:mA(o,r),assert_json_field_equals:pA(o,r),assert_json_field_gte:uA(o,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function mo(e,t){let n=e.trim();if(n.length===0)throw new d(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let r;try{r=JSON.parse(n)}catch(i){throw new d(`${t} value is not valid JSON: ${i instanceof Error?i.message:String(i)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,m.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new d(`${t} array must include at least one linked-test entry object`,m.USAGE);return o.map((i,a)=>fA(i,o.length>1?`entry ${a+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]="f75d72fe-b7f5-576d-b6c1-1cd94e3288b3")}catch{}})();var Il=["command","cmd"],po=Object.freeze(Rt.filter(e=>!["command","cmd","timeout"].includes(e)));function ay(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new d("Use exactly one --update or --update-index with --set-json",m.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new d("--set-json must contain a JSON object with explicit linked-test metadata fields",m.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:cr(e.updateIndex,"--update-index")},patch:t};let n=e.update,r=/^(command|path)=/u.exec(n);return{selector:r?.[1]==="path"?{path:n.slice(r[0].length)}:{command:r?n.slice(r[0].length):n},patch:t}}function sy(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new d("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",m.USAGE)}function _A(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("Select one linked test by index, command, or path",m.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new d("Select one linked test by index, command, or path",m.USAGE);if("index"in t){let r=cr(t.index,"--update-index");if(r<=e.length)return r-1}else{let r="command"in t?"command":"path",o="command"in t?t.command:t.path;if(typeof o!="string"||o.trim().length===0)throw new d("Linked-test selector must be a non-empty command or path",m.USAGE);let i=e.flatMap((a,s)=>a[r]===o?[s]:[]);if(i.length===1)return i[0];if(i.length>1)throw new d(`Linked-test selector is ambiguous; matching indexes: ${i.map(a=>a+1).join(", ")}`,m.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new d("No linked test matched the update selector",m.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function cy(e,t){let n=Object.keys(e),r=n.filter(o=>!po.includes(o));if(n.length===0&&!t||r.length>0)throw new d("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",m.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...r.length>0?{field:r[0]}:{},required:`Patch at least one editable field: ${po.join(", ")}.`,recovery:{allowed_values:[...po]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new d("scope is required and cannot be cleared",m.USAGE)}function hA(e,t,n){let r={};for(let o of po){let i=t[o]!==void 0?t[o]:e[o];i!=null&&(r[o]=i)}return{command:n,...r}}function Ba(e){return{field:e,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function gA(e,t,n){let r=Il.filter(i=>Object.hasOwn(e,i)).map(i=>e[i]),o=typeof e[t]=="string"?e[t].trim():"";if(r.length>1&&r.some(i=>typeof i!="string"||i.trim()!==o))throw new d("--set-json sets command and cmd to different values; send one command",m.USAGE,{code:"linked_test_command_immutable",...Ba(t),nextSteps:["Send the replacement command once, as command."]});if(o.length===0||o===n.command)throw new d(o.length===0?`--set-json cannot set ${t}: a linked test's command is its immutable identity`:`--set-json ${t} repeats the selected entry's command; omit it to edit only metadata`,m.USAGE,{code:"linked_test_command_immutable",...Ba(t),nextSteps:[`Patch only editable fields: ${po.join(", ")}.`]});return to(o),o}function yA(e){let{id:t,tests:n,index:r,identityKey:o,otherFields:i,requested:a,global:s}=e;cy(i,!0);let c=hA(n[r],i,a),l=mo(JSON.stringify(c),"--add-json")[0];Kc(l);let p=n.findIndex((u,f)=>f!==r&&Li(u,l));if(p>=0)throw new d(`--set-json cannot change ${o}: linked test ${p+1} already has the requested identity, so a replacement would merge into it`,m.USAGE,{code:"linked_test_command_immutable",...Ba(o),nextSteps:[`Edit linked test ${p+1} instead: ${N([...dt(s),"test",t,"--update-index",String(p+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${N([...dt(s),"test",t,"--remove-index",String(r+1)])}`]});return c}function wA(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function vA(e){let{id:t,tests:n,index:r,patch:o,global:i,controls:a}=e;if(typeof o!="object"||o===null||Array.isArray(o))return;let s=o,c=Il.find(g=>Object.hasOwn(s,g));if(c===void 0)return;let l=n[r],p=gA(s,c,l),u=Object.fromEntries(Object.entries(s).filter(([g])=>!Il.includes(g))),f=yA({id:t,tests:n,index:r,identityKey:c,otherFields:u,requested:p,global:i}),h=l.command!==void 0&&n.filter(g=>g.command===l.command).length===1?["--remove",`command=${l.command}`]:["--remove-index",String(r+1)],_=[...dt(i),"test",t,...h,"--add-json",JSON.stringify(f),...wA(a)];throw new d(`--set-json cannot change ${c}: a linked test's command is its immutable identity; replace the entry instead`,m.USAGE,{code:"linked_test_command_immutable",...Ba(c),recovery:{suggested_retry:N(_),suggested_retry_args:_},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(t)}, { ${h[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function bA(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("Linked-test metadata patch must be a JSON object",m.USAGE);let n=Object.keys(t);cy(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([s])=>Rt.includes(s))),o=Nf(mo(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([s,c])=>[s,c===null?void 0:c]))}),"--set-json")[0]);Kc(o);let i=n.filter(s=>!ae(e[s],o[s])),a={...e};for(let s of i){let c=o[s];Object.assign(a,{[s]:c}),c===void 0&&delete a[s]}if(!a.command?.trim()&&!a.path?.trim())throw new d("Linked-test entry must retain a command or path",m.USAGE);return{test:a,fields:i}}async function ly(e,t,n={}){let r=A(process.cwd(),n.path);await O(r);let o=await S(r),i=I(t.author,o.author_default),a=x(o,R()),s=0,c=[],l=await Yn({pmRoot:r,settings:o,id:e,author:i,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:a.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:s,fields:c}}),mutate(u){let f=u.metadata.tests??[],h=_A(f,t.selector);vA({id:u.metadata.id,tests:f,index:h,patch:t.patch,global:n,controls:t});let _=bA(f[h],t.patch);return s=h+1,c=_.fields,_.fields.length===0?{changedFields:[]}:(u.metadata.tests=f.map((g,y)=>y===h?{..._.test,updated_by:i,updated_at:E()}:g),{changedFields:["tests"]})}}),p=l.item.tests;return{ok:!0,id:l.item.id,tests:p,count:p.length,changed:l.changedFields.length>0,updated_index:s,updated_fields: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]="0f06f072-47a7-560e-9291-72e47225a73c")}catch{}})();function kA(){return{metadata:{},body:""}}import{AsyncLocalStorage as ij}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]="78b20f7a-4ae7-5811-9ab7-049a07d844e5")}catch{}})();var SA=Dc("list").properties.outputSession,EA={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:{...SA},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},dy={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},my={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},me={type:"string",description:"pm item id, for example pm-abc1."},AA=`Operation name (one of): ${yc.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,TA={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."}},CA={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 j(e,t=[]){return{...my,properties:{...my.properties,...e},required:t}}var IA=[{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:j({action:{type:"string",enum:[...yc],description:AA},id:me,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."},...EA},["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:j({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:j({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:j({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 (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), 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:j({query:{type:"string"},options:{type:"object"},...CA},["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:j({options:{type:"object"},...TA})},{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:j({id:me,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:j({verify:{type:"boolean",description:"Verify complete selected authoritative history chains."},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:j({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, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:j({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:me,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"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},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"}},["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:j({id:me,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:j({id:me,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:j({id:me,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:j({id:me,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:j({id:me,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:j({id:me,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:j({id:me,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 return the newest comments that fit the output budget, with total_count/has_more metadata and a next_cursor that pages back to older comments through outputCursor; without options.limit or outputLimit, outputBudget "unbounded" returns the complete listing at once. Pass options.limit=N for only the newest N comments (next_cursor pages within that window when the budget trims it; has_more reports older comments beyond it without a cursor) or options.limit=0 for summary-only metadata; options.full=true returns the complete history after a write. Rows carry their absolute index; pair edit/delete with options.expectAt to refuse a different entry.',inputSchema:j({id:me,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:j({id:me,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:j({id:me,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; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:j({id:me,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; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:j({id:me,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:j({id:me,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:j({subcommand:{type:"string",enum:[...dp]},id:me,target:me,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:j({id:me,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:j({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:j({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:j({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. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:j({...dy,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",...Nn],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},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:[...ic]},description:`Lifecycle roles for add-status: ${ic.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.",properties:dy}},["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:j({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:j({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:j({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."}})}],RA={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"},OA=IA.map(e=>{let t=RA[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Dc(t,{properties:n,required:r})}});function py(){return OA.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]="29d30fe0-03b7-533b-a468-151d3db90ccb")}catch{}})();var uy=new Map([["activity",["--limit","--after","--full"]],["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"]]]),xA=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Sy=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Va=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"]),Sn=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),Ey=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["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"],["normalize","governance-audit"],["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"]]),Ay=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"]]),Ty=new Map([...Ay.entries()].flatMap(([e,t])=>Nt(t).map(n=>[n,e]))),Cy=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],xl=new Map(Cy.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),PA=10,$A=20,fy=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["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 items."],["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 workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),Iy=[["init",Wp],["install",Yp],["uninstall",Jp],["explore",Xp],["manage",ru],["describe",Qp],["reload",ou],["doctor",iu],["catalog",au],["adopt",su],["adopt-all",Zp],["activate",eu],["deactivate",tu],["migrate",nu]],LA=[...Iy.map(([e,t])=>e==="init"?[e,Vp]:[e,t]),["upgrade",Cr]],NA=[...Iy.map(([e,t])=>[`extension ${e}`,t]),...LA.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Qo],["config",Bp],["extension",Zo],["package",Tr],["packages",Tr],["install",cu],["create",ii],["item mutate",Cu],["item complete",Iu],["item reopen",Ru],["copy",ai],["focus",si],["update",ci],["update-many",li],["upgrade",Cr],["calendar",Ir],["cal",Ir],["context",Rr],["ctx",Rr],["get",mi],["search",hi],["eval",xu],["events",di],["workspace",qt],["workspace position",[]],["workspace snapshot",qt],["workspace snapshot create",qt],["workspace snapshot list",qt],["workspace snapshot inspect",qt],["workspace snapshot restore",qt],["workspace snapshot delete",qt],["next",_i],["aggregate",Vo],["deps",ui],["graph",fi],["guide",pi],["reindex",lu],["history",Yo],["history-compact",qp],["history-attest",Kp],["history-redact",jp],["history-repair",Gp],["history-author-acknowledge",Jo],["merge",Up],["schema",zp],["profile",Hp],["plan",Xo],["restore",pu],["delete",uu],["close",du],["close-many",ei],["append",ti],["claim",mu],["release",fu],["start-task",_u],["pause-task",hu],["close-task",gu],["comments",Lp],["notes",Np],["learnings",Mp],["files",Fp],["docs",Dp],["test",vu],["test-runs-worker",[]],["test-all",bu],["telemetry",ku],["test-runs",Su],["gc",Eu],["stats",ni],["ops",[]],["duplicates",ri],["validate",Au],["health",oi],["assurance",Tu],...Pu,["contracts",gi],["completion",yi],["activity",Ou],...[...Sy].map(e=>[e,Wo])],uo=new Map(NA);for(let{alias:e,canonical:t}of Te){let n=uo.get(e);n!==void 0&&uo.set(t,n)}function MA(e){return Ty.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function _y(e){let t=Te.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:hc.includes(e)?ke(e):e.startsWith("extension-")?ke(`extension ${e.slice(10)}`):e.startsWith("package-")?ke(`package ${e.slice(8)}`):e.startsWith("item-")?ke(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ke(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ke(`templates ${e.slice(10)}`):Va.has(e)?Ay.get(e)??ke(e):null}function FA(e,t){let n=B(t);return n!==t||Te.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:Nt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function Nt(e){return e.split("|").map(t=>ke(t)).filter(t=>t.length>0)}function DA(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let i of Nt(o.command_path)){let a=i.split(" ").filter(s=>s.length>0);if(a.length!==0)for(let s=a.length;s>0;s-=1){let c=a.slice(0,s).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function Wa(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function fo(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function UA(e,t){if(!t)return{...e};let n=fo(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:n}}function Rl(e,t){let n=fo(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:n}}function ke(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Ry(e){return e.replace(/\s+/g,"-")}function Zt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function hy(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=Zt(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function Ol(e,t,n){n&&(e[t]=!0)}function gy(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?Jm(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function jA(e){let t=gy(e.long,"long"),n=gy(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),Ol(o,"required",e.required===!0),Ol(o,"repeatable",e.repeatable===!0),Ol(o,"list",e.list===!0),e.default!==void 0&&(o.default=e.default);let i=Zt(e.description);i&&(o.description=i);let a=bp(e);o.value_arity=a.value_arity;let s=Zt(e.value_name)??a.value_name;s&&(o.value_name=s);let c=a.value_type??(a.value_name?"string":null);return c&&(o.value_type=c),o}function Oy(e){let t=new Map;for(let r of e){let o=ke(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},a=`${r.layer}:${r.name}`;i.sourceDedupe.has(a)||(i.sourceDedupe.add(a),i.sources.push({layer:r.layer,name:r.name}));for(let s of r.flags){let c=jA(s);if(!c)continue;let l=`${c.flag}|${c.short??""}`;i.dedupe.has(l)||(i.dedupe.add(l),i.flags.push(c))}t.set(o,i)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((i,a)=>{let s=i.layer.localeCompare(a.layer);return s!==0?s:(i.name??"").localeCompare(a.name??"")})});return n}function GA(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...Ec.filter(({flag:n})=>n.startsWith("--output-"))]}}function qA(e){let t=Oy(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let a=ke(i.command);if(a.length===0)continue;let s=Zt(i.action)??Ry(a),c=Array.isArray(i.arguments)?i.arguments.map(l=>{let p=Zt(l.name);return p?{name:p,required:l.required===!0,variadic:l.variadic===!0,description:Zt(l.description)}:null}).filter(l=>l!==null):[];n.set(a,{...i.tier===void 0?{}:{tier:i.tier},...GA(i,t.get(a)?.flags??[]),command:a,action:s,source:{layer:i.layer,name:i.name},description:Zt(i.description),intent:Zt(i.intent),arguments:c,examples:hy(i.examples),failure_hints:hy(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(ke(i));for(let i of n.keys())r.add(i);for(let i of t.keys())r.add(i);let o=[];for(let i of[...r].sort((a,s)=>a.localeCompare(s))){let a=n.get(i);o.push(KA(i,a,t.get(i)?.flags??[]))}return o}function KA(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Ry(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function zA(e){let t=e.flag.startsWith("--")?e.flag:void 0,n=al({long:t,short:t===void 0?e.flag:void 0});return n!==null&&/[a-z0-9]/iu.test(n)?n:null}function HA(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 BA(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}}:{},...e.default!==void 0?{default:e.default}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function WA(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]=HA(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=zA(o);!i||n[i]!==void 0||(n[i]=Ec.some(a=>a.flag===o.flag&&a.flag.startsWith("--output-"))?pf[i]:BA(o,e.action),o.required===!0&&r.push(i))}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 VA(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 YA(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((i,a)=>i.localeCompare(a)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(i=>`${i.flag}|${i.short??""}`));for(let i of n.flags){let a=`${i.flag}|${i.short??""}`;if(!o.has(a))o.add(a),r.flags.push(i);else{let s=r.flags.find(c=>`${c.flag}|${c.short??""}`===a);s&&VA(s,i)}}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 JA(e,t=S){let n={mode:sn.extensions.policy.mode,trust_mode:sn.extensions.policy.trust_mode,default_sandbox_profile:sn.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=A(process.cwd(),e.path);if(!await H(ie(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await Er({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),a=await Ar({...i,loaded:i.loaded});return{handlers:new Set(a.commands.handlers.map(s=>ke(s.command))),disabledReason:null,commandDefinitions:a.registrations.commands,flagRegistrations:a.registrations.flags,registrations:a.registrations,policyState:{mode:i.policy.mode,trust_mode:i.policy.trust_mode,default_sandbox_profile:i.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function XA(e,t={}){let n=new Map;for(let r of gc){let o=Va.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=_y(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of Va)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:_y(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:Te.find(o=>o.alias===r.command)?.canonical??ke(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function QA(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&&(!Sn.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?Nt(e.command_path):[],r=n.some(a=>t.handlers.has(a)||t.handlers.has(B(a))),o=n.map(a=>Ey.get(B(a))).find(a=>typeof a=="string"),i=t.disabledReason===null&&r;return{action:e.action,invocable:i,available:i,requires_extension:!0,provider:"extension",disabled_reason:i?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){let t=uo.get(e)??Mn,n=De(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function ZA(e){return Sn.has(B(e))?!1:uo.has(e)}function eT(e){return Sy.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function yy(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function tT(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function nT(e){let t=new Map;for(let r of e.definitions){let o=yy(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(s=>tT(s)).find(s=>s!==null),a=r.cli_aliases.map(s=>yy(s)).filter(s=>s!==null&&s!==o);for(let s of r.commands){let c=t.get(s)??{flags:[],seen:new Set},l=i?{flag:o,short:i}:{flag:o},p=`${l.flag}|${l.short??""}`;c.seen.has(p)||(c.seen.add(p),c.flags.push(l));for(let u of a){let f=`${u}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:u}))}t.set(s,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,Sc(o.flags));return n}function wy(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let i=`${o.flag}|${o.short??""}`;r.has(i)||(r.add(i),n.push(o))}return Sc(n)}function rT(e){let t=al(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function oT(e,t,n,r){let o=(n??[]).map(rT),i=t==="extension"&&(n!==void 0||iT(e,r));return{flags:o,inherited:i?{inherited_flags:$p({readOutput:aT(e,r)})}:{}}}function Py(e,t){let n=B(e);return t.find(r=>B(r.command)===n)}function iT(e,t){return Py(e,t)!==void 0}function aT(e,t){return Py(e,t)?.read_output!==void 0}function sT(e,t,n,r,o){let i=new Map(t);for(let{alias:a,canonical:s}of Te){let c=t.get(s)??t.get(a);c&&(i.set(a,c),i.set(s,c))}return e.map(a=>{let s=ZA(a),c=s?xy(a):[],l=n.get(eT(a))??[],p=i.get(a),u=wy(c,l),f=c.length>0&&(p?.flags.length??0)>0?"mixed":s?"core":"extension",h=oT(a,f,p?.flags,o),_=wy(u,h.flags);return{command:a,flags:_,...h.inherited,...r?{canonical_command:Ly(a),visibility:$y(a,o),positionals:xp(a)?.slots??[],flag_invocations:zr(a,_)}:{},provider:f,extension_sources:p?.sources}}).sort((a,s)=>a.command.localeCompare(s.command))}function cT(e,t=ln){let n=new Set(e),r=new Map;for(let o of Cy){let i=o.aliases.filter(a=>n.has(a));r.set(o.canonical,{canonical:o.canonical,aliases:i,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let i=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};i.aliases.includes(o.alias)||i.aliases.push(o.alias),i.contracts.push(o),r.set(o.canonical,i)}return[...r.values()].map(({contracts:o,...i})=>o.length===0?i:{...i,contracts:o}).sort((o,i)=>o.canonical.localeCompare(i.canonical))}function lT(){return{create_string_options:uf,create_repeatable_options:Ri,update_string_options:ff,update_repeatable_options:_f,list_string_options:Sp,search_string_options:Ep,calendar_string_options:Ap,context_string_options:Tp,activity_string_options:Cp}}function vy(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let s of e.required_create_fields)n.add(s);for(let s of e.required_create_repeatables)n.add(s)}let r=Ln(e,"create",n),o=[...new Set(r.required)].sort((s,c)=>s.localeCompare(c)),i=[...new Set(o.map(s=>Re("create",s)))].sort((s,c)=>s.localeCompare(c)),a=[...new Set(e.options.filter(s=>s.required===!0).map(s=>s.key))].sort((s,c)=>s.localeCompare(c));return{required_option_keys:o,required_flags:i,required_type_options:a,policy_errors:[...new Set(r.errors)].sort((s,c)=>s.localeCompare(c))}}function dT(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){let o=e.by_type[r];t[r]=vy(o,"strict"),n[r]=vy(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function mT(e,t){let n=fo(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let a=i.properties;if(typeof a!="object"||a===null)return i;let s=a.action;return typeof s!="object"||s===null||s.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function pT(e){let t=Wa(e.action)!==void 0||Wa(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,i=e.flagsOnly===!0,a=e.availabilityOnly===!0,s=e.runtimeOnly===!0,c=e.full===!0,l=Wa(e.action),p=Wa(e.command),u=!r&&!c&&!o&&!i&&!a&&!l&&!p;return{selectedAction:l,selectedCommand:p,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:a,runtimeOnly:s,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||p!==void 0&&!c}}function uT(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new d("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function fT(e,t=S){try{return await t(e)}catch{return structuredClone(sn)}}async function _T(e,t,n){let r=await fT(t),o=await JA(e),i=x(r,o.registrations??R()),a=Je(r.schema),s=qA(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:D(r.schema),runtimeFieldRegistry:a,runtimeFieldFlagMap:nT(a),createRequiredOptionContracts:dT(i),extensionContracts:s,mergedExtensionContracts:YA(s.filter(c=>Ya(n,c.command,s))),extensionFlagMap:Oy(o.flagRegistrations)}}function by(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Va.has(e.selectedAction)||e.selectedCommand!==void 0&&Sn.has(B(e.selectedCommand)))}function hT(e,t){let n=XA(t,{includePackageOwnedActions:by(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(up);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(i=>i.action===o.action)?.tier??oa(o.action))!=="internal"))}return by(e)&&e.selectedCommand!==void 0&&Sn.has(B(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:MA(B(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function gT(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new d(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function yT(e,t){return[...new Set([...hc.filter(n=>!Sn.has(B(n))),...[...uo.keys()].filter(n=>!Sn.has(B(n))),...e.flatMap(n=>n.command_path?Nt(n.command_path).filter(r=>n.provider==="extension"||!Sn.has(B(r))||t.some(o=>o.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let o=Te.find(i=>i.alias===r||i.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>ke(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function wT(e,t){let n=t.slice(0,PA),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,$A),a=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),s=t[0];return new d(`Command "${e}" is a command namespace. Choose a concrete child command: ${o}.`,m.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:a,nextSteps:[`Retry with a child command, for example: ${a[0]}`],recovery:{suggested_retry:`pm contracts --command "${s}" --flags-only --json`,fallback_candidates:i.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function vT(e,t){return new d(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm package install ${t} --project" and retry.`,m.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 package install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm package install ${t} --project`],recovery:{suggested_retry:`pm package install ${t} --project`}})}function bT(e){return new d(`Unknown command: "${e}".`,m.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 kT(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(o=>o.startsWith(`${e.selectedCommand} `));if(n.length>0)throw wT(e.selectedCommand,n);let r=Ey.get(B(e.selectedCommand));throw r?vT(e.selectedCommand,r):bT(e.selectedCommand)}function ST(e,t){let n=hT(e,t.mergedExtensionContracts);gT(e,n);let r=yT(n,t.mergedExtensionContracts);kT(e,r);let o=e.selectedCommand?Ty.get(B(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(l=>o?l.action===o:FA(l,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.some(l=>l.action===e.selectedAction))throw new d(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let a=e.selectedAction?i.filter(l=>l.action===e.selectedAction):i,s=[...new Map(a.map(l=>QA(l,t.runtimeProbe)).map(l=>[o?l.action:`${l.action}|${l.command_path??""}`,l])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?s.filter(l=>l.invocable):s;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:i,scopedActionDescriptors:a,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(l=>l.action))]}}function ET(e){return new Set(fo(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 AT(e){let t=hf,n=fo(t),r=ET(t),o=e.filter(i=>!r.has(i.action)).map(i=>WA(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function ky(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?UA(n,e.selectedAction):e.selectedCommand?Rl(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):Rl(n,r);return e.runtimeOnly&&!e.selectedAction?Rl(o,new Set(t.actions)):o}function TT(e,t,n){let r=AT(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?mT(ky(e,n,r),t.createRequiredOptionContracts):ky(e,n,r);return{mergedSchema:r,filteredSchema:o}}function CT(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?DA(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function $y(e,t){return t.find(n=>B(n.command)===B(e))?.tier??oa(e)}function Ya(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||$y(t,n)!=="internal"}function IT(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(ln.filter(o=>o.hidden&&(o.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(o=>o.alias));if(e.summary&&!e.fullOutput)for(let o of xl.keys())r.add(o);return t.filter(o=>!r.has(o)&&Ya(e,o,n))}function Ly(e){let t=Te.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":xl.get(n)??n}var RT=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"]]),OT=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function xT(e,t){let n=fy.get(B(e))??(e.includes(" ")?void 0:fy.get(Ly(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(l=>Nt(l.command).some(p=>B(p)===B(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(" "),i=o.at(-1),a=o.slice(0,-1).join(" "),s=RT.get(i),c=OT.get(e)??a;return{intent:s===void 0||a.length===0?`Run ${e}.`:`${s} ${c}.`,intent_source:"generated"}}function PT(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(ke))].filter(i=>i.length>0).sort((i,a)=>i.localeCompare(a)).map(i=>{let a=Nc(i,{generateFallback:!0}),s=i.split(" ")[0],c=xl.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),l=new Set([...xy(i).map(f=>f.flag),...t.filter(f=>Nt(f.command).some(h=>B(h)===B(i))).flatMap(f=>f.flags.map(h=>h.flag))]),p=(uy.get(B(i))??uy.get(c)??xA).filter(f=>l.has(f)),u=xT(i,t);return{command:i,intent:u.intent,...o||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...p.length>0?{flags:p}:{},default_max_estimated_tokens:a.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...a.default_max_estimated_tokens_by_format}}:{}}})}function $T(e){return e.map(t=>({budget:Nc(t,{generateFallback:!0}),envelope:$_(t)}))}function LT(e){let t=new Map;for(let n of e){let r=R_(n),o=r===void 0?[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED]:r.exit_codes,i=o.join(","),a=t.get(i)??{commands:[],exit_codes:o};a.commands.push(n),t.set(i,a)}return[...t.values()]}function NT(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>Nt(r.command).some(o=>B(o)===B(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>Nt(o.command).some(i=>r.has(i)))}return t.extensionContracts.filter(r=>Ya(e,r.command,t.extensionContracts))}function MT(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 FT(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=Ff);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,i])=>[o,[...new Set(i.map(a=>`--${a.cli_flag}`))].sort((a,s)=>a.localeCompare(s))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...op],services:[...ip],policy_modes:[...ap],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...lp],trust_modes:[...sp],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...cp],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...qm],create_modes:[...Km],close_validation_modes:[...zm],workflow_enforcement_modes:[...Hm]},e.relationship_kind_contracts=[...Xm,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,i)=>o.kind.localeCompare(i.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function DT(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 UT(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=sT(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(Op).filter(([a])=>i.has(a)).map(([a,s])=>({command:a,default:s,brief_fields:[...Rp,"priority"],compact_fields:[...Ip]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:a})=>({canonical:i,aliases:a})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function jT(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=lT();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function GT(e,t,n,r){e.command_summaries=PT(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Xu],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(ke))].filter(o=>ef(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...nf(o).keys()]}))}:{}},e.grammar_contracts={nouns:dn.nouns,shared_verbs:dn.shared_verbs,scope_before_verb:dn.scope_before_verb,visible_top_level_ceiling:dn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:dn.ceiling_raise_requires_pm_item,positional_shape_budget:dn.positional_shape_budget,positional_shape_count:new Set(kc.map(({slots:o})=>Pp(o))).size,positional_action_count:bc.length,positional_action_parents:[...new Set(bc.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:kc}:{}}}async function Pl(e,t){let n=pT(e);uT(n);let r=A(process.cwd(),t.path),o=await _T(t,r,n),i=ST(n,o),a=TT(n,o,i),s=CT(n,i),c=IT(n,s,o.extensionContracts),l=MT(n,a,i,c),p=NT(n,o,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&GT(l,c,p,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return l;let f=cT(i.commandCatalog.filter(h=>Ya(n,h,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||FT(l,o,n),DT(l,n,a,p),UT(l,n,o,c,f),jT(l,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(l.assurance_contracts={measurement_source_kinds:[...th],gate_triggers:[...eh]}),n.fullOutput&&l.grammar_contracts&&(l.grammar_contracts.destinations=Bo.map(h=>({...h,reason:h.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(l.mcp_tools=py(),l.context_intents=sf(),l.read_output_dimensions=Zu,l.error_codes=O_,l.command_output_contracts=$T(c),l.diagnostic_output_contracts=Qu,l.command_exit_contracts={vocabulary:I_,command_sets:LT(c)}),l}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a4abc17-0fcb-573f-8f89-6e505e112261")}catch{}})();async function Ny(e,t,n=af){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(i=>typeof i=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as qT}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]="971103f5-a101-5e45-a607-ebebbaafe7f5")}catch{}})();function $l(e){let t=Qm();for(let n of e)t.register(n);return t}function KT(e,t,n=[]){if(n.length===0)return e;let r=JSON.parse(e),o=JSON.parse(nl(t));for(let i of n){let a=i.split("."),s=o;for(let p of a){let u=fc(s);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(p)||["constructor","prototype","__proto__"].includes(p)||u===null||!Object.hasOwn(u,p))throw new d(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,m.USAGE);s=u[p]}if(fc(s)===null)throw new d(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,m.USAGE);let c=r,l=o;for(let p of a.slice(0,-1)){let u=c[p];l=l[p],u===void 0&&Object.defineProperty(c,p,{value:structuredClone(l),enumerable:!0,writable:!0,configurable:!0}),c=c[p]}Object.defineProperty(c,a.at(-1),{value:s,enumerable:!0,writable:!0,configurable:!0})}return ae(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
2
2
  `}function My(e,t,n,r){return{fitOutputEnvelope:oh,client:t,isItemNotFoundError:o=>Kr(o)&&o.exitCode===m.NOT_FOUND,getItemAt:(o,i)=>rh(o,i,{pmRoot:e}),readSettingsSection:(o,i)=>S_(e,o,i),writeSettingsSection:(o,i,a)=>E_(e,o,i,{author:n,...a}),openRelationshipEventStore:o=>ah.open({pmRoot:e,nodes:o.nodes,registry:$l(o.definitions),...o.relativePath===void 0?{}:{relativePath:o.relativePath}}),createRelationshipGraph:o=>new tp(o.nodes,o.edges,$l(o.definitions)),analyzeRelationshipImpact:(o,i,a)=>sh(o,i,a),validateRelationshipEvents:o=>{let i=new ih(o.nodes,{registry:$l(o.definitions)});return o.events.map(a=>i.append({...a,expectedVersion:i.version}))},commitWorkspaceTransaction:o=>ch({...o,pmRoot:e}),mutateWorkspaceSettings:async o=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(o.operationId))throw new d("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",m.USAGE);let i=o.dryRun===!0?await jr(e,()=>S(e)):await S(e);try{let a=await Wi({pmRoot:e,filePath:ie(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${qT("sha256").update(r).digest("hex").slice(0,16)}:${o.operationId}`,author:I(n,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!1,dryRun:o.dryRun===!0,mutate:async s=>{let c=s===null?null:JSON.parse(s),l=Zi(c);if(!l.success)throw new d("Workspace settings mutation requires a valid initialized settings.json.",m.USAGE);let p=tl(l.data),u=await o.mutate(structuredClone(p));if(!Zi(u).success)throw new d("Workspace settings mutation returned invalid settings.json.",m.USAGE);let f=ae(p,u)?s:nl(u,{source:{raw:c,validated:l.data}});f=KT(f,u,o.replaceSubtrees);let h=Zi(JSON.parse(f));if(!h.success)throw new d("Workspace settings mutation serialized invalid settings.json.",m.USAGE);return{raw:f,result:o.includePreview===!0?tl(h.data):void 0}}});return a.changed&&o.dryRun!==!0&&await J({path:ie(e),scope:"project",op:"extension:pm:settings"}),{changed:a.changed,dry_run:o.dryRun===!0,replayed:a.replayed===!0,...a.result===void 0?{}:{preview:a.result}}}finally{t_(e)}}}}import zT from"node:fs/promises";import X from"node:path";import HT from"node:readline/promises";import{stdin as BT,stdout as qe}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]="0bfdfae5-a153-5cc1-9946-aa2ef215aa85")}catch{}})();var Nl=Symbol.for("pm.sdk.init-invocation-cwd");var WT=()=>HT.createInterface({input:BT,output:qe});function VT(){return structuredClone(sn)}var YT=["minimal","default","strict"];function Dy(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new d("--preset must not be empty",m.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new d(`Invalid --preset value "${e}". Allowed: ${YT.join(", ")}`,m.USAGE)}function JT(e){if(e!==void 0){if(e.trim().length===0)throw new d("--type-preset must not be empty",m.USAGE);try{return Fu(e)}catch{throw new d(`Invalid --type-preset value "${e}". Allowed: ${Mu.join(", ")}`,m.USAGE)}}}function XT(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new d("--author must not be empty",m.USAGE);return t}function Ll(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:X.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function QT(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new d("--workspace must not be empty",m.USAGE);if(o!==void 0){if(t.path!==void 0||Ll(n))throw new d("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",m.USAGE);let l=X.resolve(e,o),p=X.join(l,".agents","pm");return{pmRoot:p,prefixArg:n,target:{mode:"workspace-path",tracker_root:p,workspace_root:l}}}if(t.path===void 0&&Ll(n)){let l=X.resolve(e,n.trim());return{pmRoot:l,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:l}}}let i=A(e,t.path),a=X.join(X.resolve(e),".agents","pm"),s=X.dirname(X.dirname(i)),c=X.resolve(i)===a?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:c,requested_cwd:X.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function ZT(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new d("--id-prefix must not be empty",m.USAGE);if(Ll(t))throw new d(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,m.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&&Vt(e)!==Vt(t))throw new d(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,m.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Vt(e)}`,`pm init --id-prefix ${Vt(t)}`]});return t}function eC(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new d("--agent-guidance must not be empty",m.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new d(`Invalid --agent-guidance value "${e}". Allowed: ${Ph.join(", ")}`,m.USAGE)}function tC(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Uy(e,t){let n=Vm[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function nC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rC(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(nC).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function oC(e,t,n){let r=bi(t.schema),o=Tt(e,r.files.types,At.types),i=Lu(await ee(o)),a=[],s=[];for(let c of Du(n)){let l=Nu(i,c);i=l.file,(l.replaced?s:a).push(l.definition.name)}return await tt({pmRoot:e,filePath:o,raw:wi(i),op:"init:type-preset",author:I(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:s,file:o}}async function iC(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",X.join(".agents","pm")];for(let n of t)if(await H(X.join(e,n)))return!0;return!1}async function aC(e,t,n){if(!t||n||await H(X.join(e,"settings.json"))||!await iC(e))return;let r=X.join(e,".agents","pm");throw new d(`Refusing to initialize tracker files directly in workspace root "${e}".`,m.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 jy(e,t){let n=[],r=[];for(let o of t){let i=o?X.join(e,o):e,a=await H(i);await zT.mkdir(i,{recursive:!0}),a?r.push(`already_exists:${i}`):n.push(i),r.push(...await J({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function sC(e,t){let n=WT(),r=t===void 0?2:3;try{qe.write(`pm init setup wizard (agent-optimized)
3
3
  `),qe.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
4
4
 
@@ -26,7 +26,7 @@ import{A as al,B as T_,C as C_,n as Uu,o as vi,p as zu,q as Hu,r as ki,s as Or,t
26
26
  ${r(t.oursRaw)}||||||| pm base
27
27
  ${r(t.baseRaw)}=======
28
28
  ${r(t.theirsRaw)}>>>>>>> pm theirs
29
- `,"utf8"),new d(`Unresolved identity for ${t.itemPath}: both snapshots remain in conflict markers. ${n.message}`,n.exitCode,{...n.context,recovery:{suggested_retry:"git status --short"},nextSteps:["Preserve both source snapshots and establish item identity before resolving. Do not stage conflict markers as a completed merge; pm health and storage validation reject them."]})}throw n}}async function bb(e,t){let n=pL(e.artifact),r=uL(e.prefer),o=mL.resolve(e.outputPath??e.oursPath),[i,a,s]=await Promise.all([Bd(e.basePath,"base"),Bd(e.oursPath,"ours"),Bd(e.theirsPath,"theirs")]),c,l,p=[],u={},f={baseRaw:i,oursRaw:a,theirsRaw:s,outputPath:o,itemPath:e.itemPath??o};if(n==="history"){let _=await wb(()=>Gh(i,a,s),f);c=_.merged,u.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 _=qh(i,a,s);c=_.merged,u.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 fL(t),g=_L(e.itemPath??o,_),y=Ze(R()),w=await wb(()=>Kh(i,a,s,{format:g,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"}),f);if(c=w.merged,p.push(...w.conflict_fields),u.item={fields_from_theirs:w.fields_from_theirs,union_fields:w.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let b=Mf(c,{format:g,schema:_?.schema,extensionFieldNames:y}),k=b.metadata,C=[...new Set([...w.fields_from_theirs,...w.union_fields,...w.conflict_decisions.map(T=>T.field)])];l={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:w.fields_from_theirs,unionFields:w.union_fields,mergedFieldHashes:Object.fromEntries(C.map(T=>[T,jh(T==="body"?b.body:k[T])])),decisions:w.conflict_decisions,operation:await Hh(process.cwd(),e.itemPath,a)}}}else{let _=zh(i,a,s,{preferred:r});c=_.merged,p.push(..._.conflict_paths),u.json={paths_from_theirs:_.paths_from_theirs}}if(await vb(o,c,"utf8"),l!==void 0){let _=await Wh(l);_!==null&&(u.receipt=_n(_))}let h=[];if(p.length>0){let _=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;h.push(`Both branches changed ${p.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"&&u.history?.reanchored&&h.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:p.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:p,...u,guidance:h,generated_at: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]="3fe6f853-6742-5305-b722-0cc74547f367")}catch{}})();async function kb(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await Bh(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Qt(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Qt(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:r,message:e.message??`Settle ${n.operation.kind} receipt after exact original Git state restoration`,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{..._n(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await va(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as hL}from"node:fs/promises";import gL 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]="4d506b3c-f1c1-5642-a258-45d93ba64d81")}catch{}})();var yL=4;function Sb(e){let t=e.checks.find(s=>s.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,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,a=Array.isArray(o)?o.flatMap(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return[];let c=s;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:i,coordinates:a}}async function wL(e,t){let n=[];for(let r of t){let o;try{o=await hL(gL.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let i=o.split(/\r?\n/)[r.history_line-1];if(i===void 0||i.trim().length===0)continue;let a;try{a=JSON.parse(i)}catch{continue}let s=Zh(a,r.item_id).find(c=>c.receiptId===r.receipt_id);s===void 0||!Qh(s)||s.eventTimestamp===void 0||Ci(s.eventTimestamp,Xh)>=0||n.push({...r,original_event_ts:s.eventTimestamp})}return n}async function vL(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 Qt(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 bL(e){try{return{status:"fulfilled",value:await Qt(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 kL(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 SL(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=>va(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}function EL(e,t){if(!(e===0||t))return'If receipt proof is unavailable or competing values were discarded, first review receipts.summaries and repair.streams and re-apply intended values. Only with explicit authority to accept that review, run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>". This appends an audit event; it does not restore missing evidence or discarded values.'}async function AL(e,t){if(e.force===!0)throw new d("Automatic staging cannot accept forced reconciliation.",m.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let n={...e,stage:!1},{stageLosslessMergeReconciliation:r,resolveMergeSettlementGlobal:o}=await import("./stage-KPK2UHVO.js"),i=await o(t),a=await vs({...n,dryRun:!0},i);return r({preview:a,dryRun:e.dryRun===!0,global:i,apply:()=>vs({...n,dryRun:!1},i)})}async function vs(e,t){return e.stage===!0?AL(e,t):TL(e,t)}async function TL(e,t){let n=e.dryRun===!0,r=A(process.cwd(),t.path),o=await eo(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=Sb(o),a=await wL(r,i.coordinates),s=await ya(r),c=s??r,l=await Vh(c,{includeLossless:!0,pmRoot:r});if(l.invalid_evidence_count>0)throw new d(`Merge reconciliation refused ${l.invalid_evidence_count} invalid receipt evidence file(s).`,m.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"}});Yh(l.receipts.map(G=>G.id),l,n);let p=await vL({candidates:a,options:e,global:t}),u=l.receipts,f=await kb({cwd:s,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),h=new Set(f),_=new Map;for(let G of u.filter(_e=>!h.has(_e.id))){let _e=_.get(G.item_id)??[];_e.push(G),_.set(G.item_id,_e)}let g=Object.fromEntries([..._].map(([G,_e])=>[G,{merge:{receipts:_e.map(_n)}}])),y=Object.fromEntries([..._].map(([G,_e])=>[G,{gitWorkspaceRoot:s,receipts:_e}])),w=await ka({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(w.streams.map(G=>G.id)),k=[..._.keys()].filter(G=>!b.has(G)),C=await xh(k,yL,G=>bL({id:G,dryRun:n,options:e,global:t,auditContext:g[G],mergeReceiptProof:y[G]}));kL({receiptOnlyIds:k,results:C,repair:w});let T=await SL({dryRun:n,pendingReceipts:u,repair:w,receiptWorkspaceRoot:c}),$=await Aa({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),P=p===0?o:await eo(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),F=Sb(P),Q=$.checks.every(G=>G.status==="ok"),W=n?u.length===0:T+f.length===u.length,re=[w.totals.failed===0,Q,W,F.count===0,!F.truncated].every(Boolean),ve=i.truncated||F.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,Me=EL(u.length,re),ct=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",ve,Me,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:re?["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.",ve,Me,...a.length>0&&p===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(G=>G!==void 0);return{ok:re,dry_run:n,repair:w,receipts:{pending_before:u.length,reconciled:T,abandoned:f.length,summaries:u.map(_n),unstaged_durable_receipt_ids:l.unstaged_durable_receipt_ids,missing_history_references_before:i.count,legacy_disposition_eligible:a.length,legacy_disposition_recorded:p,missing_history_references_after:F.count},validation:$,guidance:ct,generated_at:$.generated_at}}import{createHash as CL}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]="c583f859-9204-565b-b143-59aba53c3e9c")}catch{}})();var Cb=1,Ib=/^[A-Za-z0-9_-]+$/,IL=100,Eb=1e3;var y5=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function st(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 RL(e){return CL("sha256").update(cn({type:st(e.type),author:st(e.author),item:st(e.item),harness:st(e.harness),agent_instance:st(e.agentInstance),provenance:st(e.provenanceFilter)})).digest("hex").slice(0,24)}function Ab(e,t){let n={version:Cb,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 OL(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Cb,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 xL(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Ib.test(n))throw new d("Invalid mutation event cursor.",m.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new d("Invalid mutation event cursor.",m.USAGE,{code:"invalid_event_cursor"})}if(!OL(r,t))throw new d("Mutation event cursor does not match this query.",m.USAGE,{code:"event_cursor_query_mismatch"});return r}function PL(e){let t=e??IL;if(!Number.isSafeInteger(t)||t<0||t>Eb)throw new d(`Mutation event limit must be an integer from 0 to ${Eb}.`,m.USAGE,{code:"invalid_event_limit"});return t}function $L(e,t){let n=e?.trim();if(!n)return{};if(Ib.test(n))return{cursor:xL(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new d("Mutation event --since must be an event cursor or ISO timestamp.",m.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function LL(e,t){if(t.verify)return Tb(e,t);let n=await Yc(e,t),r=n.result;if(r===null&&n.repair_needed)try{await Gf(e,{lockWaitMs:0})&&(r=(await Yc(e,t)).result)}catch{}return r===null?Tb(e,t):{...r,source:"derived_index"}}async function Tb(e,t){try{return{...await qf(e,t),source:"authoritative_history"}}catch(n){throw n instanceof d?n:new d("Mutation events are unavailable because authoritative history could not be read.",m.GENERIC_FAILURE,{code:"event_index_unavailable",why:lt(n)})}}function NL(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new d("Mutation event cursor mode must be batch or row.",m.USAGE,{code:"invalid_event_cursor_mode"});return t}async function bs(e={}){let t=A(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=PL(e.limit),r=NL(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new d("Mutation event projections are mutually exclusive. Use --provenance or --full.",m.USAGE);let o=await S(t),i=o.agent_identity.identity_vocabulary,a=Ag(o.agent_identity.harness_signals),s=Tg({provenance:e.provenanceFilter},a),c=st(e.harness),l=RL(e),{cursor:p,sinceTimestamp:u}=$L(e.since,l),f={verify:e.verify===!0,...p?{after_ts:p.ts,after_stream_id:p.stream_id,after_stream_offset:p.stream_offset}:u?{since_ts:u}:{},ops:st(e.type),authors:st(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,g])=>c.includes(g)).map(([g])=>g):void 0,agent_instances:st(e.agentInstance),provenance:[...s].map(([g,y])=>({dimension:g,values:[...y]})),stream_ids:st(e.item),limit:n},h=await LL(t,f),_=h.events.map(g=>({...r==="row"?{cursor:Ab(g,l)}:{},item_id:g.stream_id,version:g.stream_offset+1,ts:g.entry.ts,author:g.entry.author,type:g.entry.op,...g.entry.message===void 0?{}:{message:g.entry.message},patch_count:g.entry.patch.length,...e.full===!0?{entry:structuredClone(g.recorded_entry??g.entry)}:{},...e.provenance===!0?{provenance:Cg(g.entry,i,{itemId:g.stream_id,version:g.stream_offset+1})}:{}}));return{integrity:e.verify===!0?"verified":"unverified",...h.verified_streams===void 0?{}:{verified_streams:h.verified_streams},events:_,count:_.length,has_more:h.has_more,cursor_mode:r,...h.events.length===0?{}:{next_cursor:Ab(h.events[h.events.length-1],l)},source:h.source,...e.provenanceSummary===!0?{provenance_summary:Ig(h.events.map(g=>g.entry),i,a)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e3b8e8c-5c05-5c68-bfe2-cb3ca0a17a20")}catch{}})();var ML="1h",FL="now",DL="+1d";function rn(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Rb(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,inheritFocus:n.inheritFocus,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return de(n,r)}async function Ob(e,t,n,r){let o=Rb(e,t,n),i=[];return rn(i,"start",n.start??FL),n.end!==void 0?rn(i,"end",n.end):rn(i,"duration",n.duration??ML),rn(i,"location",n.location),rn(i,"timezone",n.timezone),n.allDay===!0&&rn(i,"all_day","true"),o.event=[i.join(",")],tn(o,r)}function xb(e,t,n){return Ob("Meeting",e,t,n)}function Pb(e,t,n){return Ob("Event",e,t,n)}function $b(e,t,n){let r=Rb("Reminder",e,t),o=[];return rn(o,"at",t.at??DL),rn(o,"text",t.text??e),r.reminder=[o.join(",")],tn(r,n)}import bo from"node:crypto";import{cp as Lb,lstat as UL,mkdir as On,readFile as _r,readdir as Vd,rename as Fb,rm as Jd,writeFile as ks}from"node:fs/promises";import U 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]="62b04ebf-f842-5a88-8817-ed9b17350034")}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]="66cb8c82-3760-5628-a1de-69e417cf0292")}catch{}})();var Db="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var Ub=U.join("runtime","workspace-snapshots"),jL=new Set(["checkpoints","locks","runtime","search","transactions"]),GL=/^[a-z0-9][a-z0-9._-]*$/,fr="sdk-workspace-transaction",Wd={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},jb={renameEntry:Fb,removeEntry:async e=>{await Jd(e,{recursive:!0,force:!0})}},Yd=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=await of(this.lockPath,fr);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await _r(this.lockPath,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Workspace writer lock has invalid structure");let r=n;if(r.id!==fr||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await oe(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
29
+ `,"utf8"),new d(`Unresolved identity for ${t.itemPath}: both snapshots remain in conflict markers. ${n.message}`,n.exitCode,{...n.context,recovery:{suggested_retry:"git status --short"},nextSteps:["Preserve both source snapshots and establish item identity before resolving. Do not stage conflict markers as a completed merge; pm health and storage validation reject them."]})}throw n}}async function bb(e,t){let n=pL(e.artifact),r=uL(e.prefer),o=mL.resolve(e.outputPath??e.oursPath),[i,a,s]=await Promise.all([Bd(e.basePath,"base"),Bd(e.oursPath,"ours"),Bd(e.theirsPath,"theirs")]),c,l,p=[],u={},f={baseRaw:i,oursRaw:a,theirsRaw:s,outputPath:o,itemPath:e.itemPath??o};if(n==="history"){let _=await wb(()=>Gh(i,a,s),f);c=_.merged,u.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 _=qh(i,a,s);c=_.merged,u.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 fL(t),g=_L(e.itemPath??o,_),y=Ze(R()),w=await wb(()=>Kh(i,a,s,{format:g,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"}),f);if(c=w.merged,p.push(...w.conflict_fields),u.item={fields_from_theirs:w.fields_from_theirs,union_fields:w.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let b=Mf(c,{format:g,schema:_?.schema,extensionFieldNames:y}),k=b.metadata,C=[...new Set([...w.fields_from_theirs,...w.union_fields,...w.conflict_decisions.map(T=>T.field)])];l={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:w.fields_from_theirs,unionFields:w.union_fields,mergedFieldHashes:Object.fromEntries(C.map(T=>[T,jh(T==="body"?b.body:k[T])])),decisions:w.conflict_decisions,operation:await Hh(process.cwd(),e.itemPath,a)}}}else{let _=zh(i,a,s,{preferred:r});c=_.merged,p.push(..._.conflict_paths),u.json={paths_from_theirs:_.paths_from_theirs}}if(await vb(o,c,"utf8"),l!==void 0){let _=await Wh(l);_!==null&&(u.receipt=_n(_))}let h=[];if(p.length>0){let _=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;h.push(`Both branches changed ${p.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"&&u.history?.reanchored&&h.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:p.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:p,...u,guidance:h,generated_at: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]="3fe6f853-6742-5305-b722-0cc74547f367")}catch{}})();async function kb(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await Bh(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Qt(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Qt(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:r,message:e.message??`Settle ${n.operation.kind} receipt after exact original Git state restoration`,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{..._n(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await va(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as hL}from"node:fs/promises";import gL 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]="4d506b3c-f1c1-5642-a258-45d93ba64d81")}catch{}})();var yL=4;function Sb(e){let t=e.checks.find(s=>s.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,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,a=Array.isArray(o)?o.flatMap(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return[];let c=s;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:i,coordinates:a}}async function wL(e,t){let n=[];for(let r of t){let o;try{o=await hL(gL.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let i=o.split(/\r?\n/)[r.history_line-1];if(i===void 0||i.trim().length===0)continue;let a;try{a=JSON.parse(i)}catch{continue}let s=Zh(a,r.item_id).find(c=>c.receiptId===r.receipt_id);s===void 0||!Qh(s)||s.eventTimestamp===void 0||Ci(s.eventTimestamp,Xh)>=0||n.push({...r,original_event_ts:s.eventTimestamp})}return n}async function vL(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 Qt(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 bL(e){try{return{status:"fulfilled",value:await Qt(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 kL(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 SL(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=>va(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}function EL(e,t){if(!(e===0||t))return'If receipt proof is unavailable or competing values were discarded, first review receipts.summaries and repair.streams and re-apply intended values. Only with explicit authority to accept that review, run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>". This appends an audit event; it does not restore missing evidence or discarded values.'}async function AL(e,t){if(e.force===!0)throw new d("Automatic staging cannot accept forced reconciliation.",m.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let n={...e,stage:!1},{stageLosslessMergeReconciliation:r,resolveMergeSettlementGlobal:o}=await import("./stage-EKYWEU2Y.js"),i=await o(t),a=await vs({...n,dryRun:!0},i);return r({preview:a,dryRun:e.dryRun===!0,global:i,apply:()=>vs({...n,dryRun:!1},i)})}async function vs(e,t){return e.stage===!0?AL(e,t):TL(e,t)}async function TL(e,t){let n=e.dryRun===!0,r=A(process.cwd(),t.path),o=await eo(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=Sb(o),a=await wL(r,i.coordinates),s=await ya(r),c=s??r,l=await Vh(c,{includeLossless:!0,pmRoot:r});if(l.invalid_evidence_count>0)throw new d(`Merge reconciliation refused ${l.invalid_evidence_count} invalid receipt evidence file(s).`,m.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"}});Yh(l.receipts.map(G=>G.id),l,n);let p=await vL({candidates:a,options:e,global:t}),u=l.receipts,f=await kb({cwd:s,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),h=new Set(f),_=new Map;for(let G of u.filter(_e=>!h.has(_e.id))){let _e=_.get(G.item_id)??[];_e.push(G),_.set(G.item_id,_e)}let g=Object.fromEntries([..._].map(([G,_e])=>[G,{merge:{receipts:_e.map(_n)}}])),y=Object.fromEntries([..._].map(([G,_e])=>[G,{gitWorkspaceRoot:s,receipts:_e}])),w=await ka({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(w.streams.map(G=>G.id)),k=[..._.keys()].filter(G=>!b.has(G)),C=await xh(k,yL,G=>bL({id:G,dryRun:n,options:e,global:t,auditContext:g[G],mergeReceiptProof:y[G]}));kL({receiptOnlyIds:k,results:C,repair:w});let T=await SL({dryRun:n,pendingReceipts:u,repair:w,receiptWorkspaceRoot:c}),$=await Aa({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),P=p===0?o:await eo(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),F=Sb(P),Q=$.checks.every(G=>G.status==="ok"),W=n?u.length===0:T+f.length===u.length,re=[w.totals.failed===0,Q,W,F.count===0,!F.truncated].every(Boolean),ve=i.truncated||F.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,Me=EL(u.length,re),ct=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",ve,Me,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:re?["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.",ve,Me,...a.length>0&&p===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(G=>G!==void 0);return{ok:re,dry_run:n,repair:w,receipts:{pending_before:u.length,reconciled:T,abandoned:f.length,summaries:u.map(_n),unstaged_durable_receipt_ids:l.unstaged_durable_receipt_ids,missing_history_references_before:i.count,legacy_disposition_eligible:a.length,legacy_disposition_recorded:p,missing_history_references_after:F.count},validation:$,guidance:ct,generated_at:$.generated_at}}import{createHash as CL}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]="c583f859-9204-565b-b143-59aba53c3e9c")}catch{}})();var Cb=1,Ib=/^[A-Za-z0-9_-]+$/,IL=100,Eb=1e3;var y5=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function st(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 RL(e){return CL("sha256").update(cn({type:st(e.type),author:st(e.author),item:st(e.item),harness:st(e.harness),agent_instance:st(e.agentInstance),provenance:st(e.provenanceFilter)})).digest("hex").slice(0,24)}function Ab(e,t){let n={version:Cb,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 OL(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Cb,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 xL(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Ib.test(n))throw new d("Invalid mutation event cursor.",m.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new d("Invalid mutation event cursor.",m.USAGE,{code:"invalid_event_cursor"})}if(!OL(r,t))throw new d("Mutation event cursor does not match this query.",m.USAGE,{code:"event_cursor_query_mismatch"});return r}function PL(e){let t=e??IL;if(!Number.isSafeInteger(t)||t<0||t>Eb)throw new d(`Mutation event limit must be an integer from 0 to ${Eb}.`,m.USAGE,{code:"invalid_event_limit"});return t}function $L(e,t){let n=e?.trim();if(!n)return{};if(Ib.test(n))return{cursor:xL(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new d("Mutation event --since must be an event cursor or ISO timestamp.",m.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function LL(e,t){if(t.verify)return Tb(e,t);let n=await Yc(e,t),r=n.result;if(r===null&&n.repair_needed)try{await Gf(e,{lockWaitMs:0})&&(r=(await Yc(e,t)).result)}catch{}return r===null?Tb(e,t):{...r,source:"derived_index"}}async function Tb(e,t){try{return{...await qf(e,t),source:"authoritative_history"}}catch(n){throw n instanceof d?n:new d("Mutation events are unavailable because authoritative history could not be read.",m.GENERIC_FAILURE,{code:"event_index_unavailable",why:lt(n)})}}function NL(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new d("Mutation event cursor mode must be batch or row.",m.USAGE,{code:"invalid_event_cursor_mode"});return t}async function bs(e={}){let t=A(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=PL(e.limit),r=NL(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new d("Mutation event projections are mutually exclusive. Use --provenance or --full.",m.USAGE);let o=await S(t),i=o.agent_identity.identity_vocabulary,a=Ag(o.agent_identity.harness_signals),s=Tg({provenance:e.provenanceFilter},a),c=st(e.harness),l=RL(e),{cursor:p,sinceTimestamp:u}=$L(e.since,l),f={verify:e.verify===!0,...p?{after_ts:p.ts,after_stream_id:p.stream_id,after_stream_offset:p.stream_offset}:u?{since_ts:u}:{},ops:st(e.type),authors:st(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,g])=>c.includes(g)).map(([g])=>g):void 0,agent_instances:st(e.agentInstance),provenance:[...s].map(([g,y])=>({dimension:g,values:[...y]})),stream_ids:st(e.item),limit:n},h=await LL(t,f),_=h.events.map(g=>({...r==="row"?{cursor:Ab(g,l)}:{},item_id:g.stream_id,version:g.stream_offset+1,ts:g.entry.ts,author:g.entry.author,type:g.entry.op,...g.entry.message===void 0?{}:{message:g.entry.message},patch_count:g.entry.patch.length,...e.full===!0?{entry:structuredClone(g.recorded_entry??g.entry)}:{},...e.provenance===!0?{provenance:Cg(g.entry,i,{itemId:g.stream_id,version:g.stream_offset+1})}:{}}));return{integrity:e.verify===!0?"verified":"unverified",...h.verified_streams===void 0?{}:{verified_streams:h.verified_streams},events:_,count:_.length,has_more:h.has_more,cursor_mode:r,...h.events.length===0?{}:{next_cursor:Ab(h.events[h.events.length-1],l)},source:h.source,...e.provenanceSummary===!0?{provenance_summary:Ig(h.events.map(g=>g.entry),i,a)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e3b8e8c-5c05-5c68-bfe2-cb3ca0a17a20")}catch{}})();var ML="1h",FL="now",DL="+1d";function rn(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Rb(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,inheritFocus:n.inheritFocus,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return de(n,r)}async function Ob(e,t,n,r){let o=Rb(e,t,n),i=[];return rn(i,"start",n.start??FL),n.end!==void 0?rn(i,"end",n.end):rn(i,"duration",n.duration??ML),rn(i,"location",n.location),rn(i,"timezone",n.timezone),n.allDay===!0&&rn(i,"all_day","true"),o.event=[i.join(",")],tn(o,r)}function xb(e,t,n){return Ob("Meeting",e,t,n)}function Pb(e,t,n){return Ob("Event",e,t,n)}function $b(e,t,n){let r=Rb("Reminder",e,t),o=[];return rn(o,"at",t.at??DL),rn(o,"text",t.text??e),r.reminder=[o.join(",")],tn(r,n)}import bo from"node:crypto";import{cp as Lb,lstat as UL,mkdir as On,readFile as _r,readdir as Vd,rename as Fb,rm as Jd,writeFile as ks}from"node:fs/promises";import U 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]="62b04ebf-f842-5a88-8817-ed9b17350034")}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]="66cb8c82-3760-5628-a1de-69e417cf0292")}catch{}})();var Db="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var Ub=U.join("runtime","workspace-snapshots"),jL=new Set(["checkpoints","locks","runtime","search","transactions"]),GL=/^[a-z0-9][a-z0-9._-]*$/,fr="sdk-workspace-transaction",Wd={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},jb={renameEntry:Fb,removeEntry:async e=>{await Jd(e,{recursive:!0,force:!0})}},Yd=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=await of(this.lockPath,fr);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await _r(this.lockPath,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Workspace writer lock has invalid structure");let r=n;if(r.id!==fr||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await oe(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
30
30
  `)}finally{await t()}}};async function Gb(e,t=""){let n=await Vd(U.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((i,a)=>i.name.localeCompare(a.name))){if(t.length===0&&jL.has(o.name))continue;let i=U.posix.join(t.replaceAll(U.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${i}`);if(o.isDirectory())r.push(...await Gb(e,i));else if(o.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function qb(e){let t=await Gb(e),n=bo.createHash("sha256"),r=[],o=0;for(let a of t){let s=await _r(U.join(e,a));r.push(s),o+=s.byteLength,n.update(a),n.update("\0"),n.update(String(s.byteLength)),n.update("\0"),n.update(s)}let i=n.digest("hex");return{manifest:{schema:Db,fingerprint:i,files:t,bytes:o},contents:r}}function Nb(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
31
31
  `).filter(t=>t.trim().length>0).length}async function qL(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),i=await Promise.all(o.map(async a=>[a,await _r(U.join(e,a))]));for(let[a,s]of i)n.set(a,s)}return n}function Xd(e){if(!GL.test(e))throw new d("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",m.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 Kb(e,t){return Sr(`workspace_snapshot_${e}`,t,{codes:{capacity:Wd.capacity.code,permission:Wd.permission.code,resource:Wd.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 xn(e){return U.join(e,Ub)}function zb(e){return new d(`Unknown workspace snapshot: ${e}`,m.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 Hb(e,t){try{return JSON.parse(await _r(e,"utf8"))}catch(n){throw Fe(n)?zb(t):n}}async function Mb(e,t,n){try{await Jd(e,{recursive:n})}catch(r){throw Fe(r)?zb(t):r}}async function KL(e,t,n=jb){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 zL(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(i){throw await r.renameEntry(n,t),await r.removeEntry(e),i}await r.removeEntry(n)}async function HL(e,t){return Xd(t),/^[a-f0-9]{64}$/.test(t)?t:(await Hb(U.join(xn(e),"refs",`${t}.json`),t)).fingerprint}async function Qd(e,t={}){if(t.name!==void 0&&(Xd(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new d("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",m.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 qb(e),o=xn(e),i=U.join(o,"objects",n.fingerprint),a=!1;try{a=(await UL(i)).isDirectory()}catch(s){if(!(s instanceof Error&&"code"in s&&Fe(s)))throw s}if(!a){let s=U.join(o,"objects",`.create-${process.pid}-${bo.randomUUID()}`);await Kb("create_object",async()=>{await On(U.join(s,"files"),{recursive:!0});for(let[c,l]of n.files.entries()){let p=U.join(s,"files",l);await On(U.dirname(p),{recursive:!0}),await ks(p,r[c])}await ks(U.join(s,"manifest.json"),`${JSON.stringify(n,null,2)}
32
32
  `,"utf8"),await On(U.dirname(i),{recursive:!0})}),a=await KL(s,i)}if(t.name!==void 0){let s={name:t.name,fingerprint:n.fingerprint},c=U.join(o,"refs");await On(c,{recursive:!0});let l=U.join(c,`.ref-${process.pid}-${bo.randomUUID()}`);await ks(l,`${JSON.stringify(s,null,2)}
@@ -40,5 +40,5 @@ ${t}`;for(let r of sM)if(r.regex.test(n))return{code:r.code};return null}functio
40
40
  [pm linked-test output truncated at ${Ls} bytes per stream; the child process continued to completion]
41
41
  `:"";!_&&await Fk(e,{exitCode:b,stderr:T.text},n,i)&&(_="Linked test executable was not found. Install the tool or update the linked command before retrying.");let F={stdout:`${C.text}${P}`,stderr:T.text,exitCode:b,signal:k,timedOut:w,maxBufferExceeded:!1,outputTruncated:$,spawnError:_};return mF(r,F,a,o),F}finally{await Ro(s,{recursive:!0,force:!0})}}function gF(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Ls} 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 yF(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
42
42
  `);return UM.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>jM.test(n)&&GM.test(n))}function wF(e){return yF(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function vF(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function Oo(e){let t=vF();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}function zk(e,t){for(let[n,r]of Object.entries(t.env_set))vn.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)vn.has(n.toUpperCase())||delete e[n]}function bF(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 kF(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 mS(e,t,n){return{env_set:XM(e,"--env-set"),env_clear:QM(t,"--env-clear"),shared_host_safe:n===!0}}async function Io(e,t,n=!1,r=_m){if(await H(e))try{await Sr("seed_linked_test",async()=>{if(await r(le.dirname(t),{recursive:!0}),n){await Uk(e,t,{recursive:!0,force:!0});return}await Uk(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&&Fe(o))return;throw o}}async function Hk(e,t,n,r=!1){for(let[o,i]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let a=await ee(ie(o));if(a!==null){let s=await S(i);await tt({pmRoot:i,filePath:ie(i),raw:a,op:"settings:write",author:I(void 0,s.author_default),lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Io(ie(o),ie(i));await Io(le.join(n.projectPmRoot,"extensions"),le.join(e,"extensions"),!0),await Io(le.join(n.globalPmRoot,"extensions"),le.join(t,"extensions"),!0)}async function Bk(e,t){if(!await H(e))return;let n=await um(e,{withFileTypes:!0});for(let r of n){if(FM.has(r.name))continue;let o=le.join(e,r.name),i=le.join(t,r.name);if(r.isDirectory()){await Io(o,i,!0);continue}r.isFile()&&await Io(o,i)}}async function Wk(e,t){let n=await ee(ie(e));if(n===null||await H(Zc(e)))return;let r=await S(t);await Ro(Zc(t),{force:!0}),await Ro(ie(t),{force:!0}),await tt({pmRoot:t,filePath:ie(t),raw:n,op:"settings:write",author:I(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 gr(e){if(!await H(e))return 0;let t=0,n=await um(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||DM.has(r.name))continue;let o=le.join(e,r.name),i;try{i=await um(o,{withFileTypes:!0})}catch{continue}for(let a of i)a.isFile()&&rp.some(s=>a.name.toLowerCase().endsWith(s))&&(t+=1)}return t}function SF(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function EF(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 AF(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?ae(e,t):Object.is(e,t)}function TF(e,t,n){let r=[];r.push(...Vk("stdout",t,e.assert_stdout_contains)),r.push(...Yk("stdout",t,e.assert_stdout_regex)),r.push(...Vk("stderr",n,e.assert_stderr_contains)),r.push(...Yk("stderr",n,e.assert_stderr_regex)),r.push(...CF(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},i=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(i).length>0))return r;let a;try{a=JSON.parse(t)}catch(s){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${s instanceof Error?s.message:String(s)}`),r}for(let[s,c]of Object.entries(o)){let l=sm(a,s);if(!l.found){r.push(`assert_json_field_equals missing path "${s}"`);continue}let p=EF(c);AF(l.value,p)||r.push(`assert_json_field_equals mismatch at "${s}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(l.value)})`)}for(let[s,c]of Object.entries(i)){let l=sm(a,s);if(!l.found){r.push(`assert_json_field_gte missing path "${s}"`);continue}if(typeof l.value!="number"||!Number.isFinite(l.value)){r.push(`assert_json_field_gte path "${s}" resolved to non-numeric value`);continue}l.value<c&&r.push(`assert_json_field_gte failed at "${s}" (expected >= ${c}, actual ${l.value})`)}return r}function Vk(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function Yk(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(i){r.push(`${e} regex assertion is invalid: /${o}/ (${i instanceof Error?i.message:String(i)})`)}return r}function CF(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}`]:[]}function Jk(e){let t=Ea(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Sa(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&cS(n))}function IF(e){return{root:e,schemaProjectPmPath:le.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:le.join(e,"schema","global"),trackerProjectPmPath:le.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:le.join(e,"tracker","global"),workspaceSnapshotRoot:le.join(e,"workspace","project"),workspaceIsolatedRoot:le.join(e,"workspace","isolated")}}function RF(e,t,n){return e.some(r=>oS(r,t,n)==="snapshot")}async function OF(e,t){let n=le.join(e,".agents"),r=le.join(n,"pm");await _m(n,{recursive:!0}),await Ro(r,{recursive:!0,force:!0}),await $M(t,r,process.platform==="win32"?"junction":"dir")}async function xF(e,t=_o,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 PF(e,t,n){t&&(await Hk(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await Hk(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Bk(t.projectPmRoot,e.trackerProjectPmPath),await Bk(t.globalPmRoot,e.trackerGlobalPmPath),await Wk(t.projectPmRoot,e.trackerProjectPmPath),await Wk(t.globalPmRoot,e.trackerGlobalPmPath)))}function $F(e,t,n){return e.some(r=>{let o=r.command??"",i=o.length>0&&sS(o),a=n?.autoPmContext===!0&&i?"auto":iS(r,t,n?.overrideLinkedPmContext===!0);return aS(a,i)==="tracker"})}async function LF(e,t){return{sourceProjectItemCount:t?await gr(t.projectPmRoot):0,sourceGlobalItemCount:t?await gr(t.globalPmRoot):0,schemaProjectItemCount:await gr(e.schemaProjectPmPath),schemaGlobalItemCount:await gr(e.schemaGlobalPmPath),trackerProjectItemCount:await gr(e.trackerProjectPmPath),trackerGlobalItemCount:await gr(e.trackerGlobalPmPath)}}function NF(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,i=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,a=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,s=e.workspaceContextMode==="isolated"?"":a;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:i,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==i),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:a,source_workspace_root:s,trust:e.trust}}async function MF(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Ms(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?ZM(n):!1,o=r&&n?sS(n):!1,i=e.options?.autoPmContext===!0&&o,a=i?"auto":iS(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),s=aS(a,o),c=s==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await OF(e.layout.workspaceSnapshotRoot,c);let l=e.options?.pmRoot?await yl(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await yl(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:NF({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:a,effectivePmContextMode:s,autoPmContextApplied:i,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:l})}}function Xk(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function FF(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 DF(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 UF(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 DF(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 jF(e){if(!e.linkedTest.command)return Xk(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=nF(e.linkedTest.command);return t?Xk(e.linkedTest,e.executionContext,t):null}function GF(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Ns(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?Ns(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function Ns(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function qF(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=JM({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Ns(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function KF(e){return jF(e)||UF(e)||GF(e)||qF(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!YM(e.linkedTest)?Ns(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function zF(e){let t=kF(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return zk(n,e.runtimeDirectives),zk(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&bF(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Zr]):(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[Zr]="read_only"),n}function HF(e,t,n,r){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...r?{execution_receipt:r}:{}}}function Qk(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 BF(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:SF(e.execution),failure_category:wF(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:gF(e.execution,e.timeoutMs)}}function WF(e){let t=Ik(e.execution.stdout,e.execution.stderr);if(e.options?.failOnEmptyTestRun===!0||Jk(e.linkedTest.command??"")){let r=Is(e.execution.stdout,e.execution.stderr);if(r)return Qk({...e,emptyRunSignal:r});if(Jk(e.linkedTest.command??"")&&!t)return Qk({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let n=TF(e.linkedTest,e.execution.stdout,e.execution.stderr);return n.length>0?FF(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${n.join("; ")}`,e.execution):HF(e.linkedTest,e.executionContext,e.execution,t)}async function VF(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await hF(t,n,zF(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?WF({...e,execution:r}):BF({...e,execution:r,timeoutMs:n})}async function ym(e,t,n){for(let g of e)Pr(g.command);let r=[],o=await tS(le.join(nS(),"pm-linked-test-")),i=IF(o),a=Ms(n?.pmContext),s=rS(n?.workspaceContext),c=n?.progress===!0?"always":"auto",l=mS(n?.envSet,n?.envClear,n?.sharedHostSafe),p=n?.sourceRoots,u=gg(),f=$F(e,a,n),h=RF(e,s,n?.overrideLinkedWorkspaceContext===!0),_=await hg(u);try{await xF(i,_o,f),await _m(i.workspaceIsolatedRoot,{recursive:!0}),await PF(i,p,f),h&&await Lk(u,i.workspaceSnapshotRoot,p?.projectPmRoot,f);let g=await LF(i,p);for(let y=0;y<e.length;y+=1){let w=e[y],b=oS(w,s,n?.overrideLinkedWorkspaceContext===!0),k=await MF({linkedTest:w,layout:i,counts:g,sourceRoots:p,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:s,workspaceContextMode:b,currentSourceRef:_,sourceWorkspaceRoot:u}),C=KF({linkedTest:w,executionContext:k.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:k.linkedOverridePmContextMode,options:n});if(C){r.push(C);continue}r.push(await VF({linkedTest:w,index:y,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:l,progressMode:c,executionContext:k.executionContext,options:n}))}}finally{await Ro(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function YF(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,i=await q(n,t,r.id_prefix,r.item_format,o);if(!i)throw new d(`Item ${t} not found`,m.NOT_FOUND);let a=await ne(i,{schema:r.schema});return{itemId:i.id,tests:a.document.metadata.tests??[],testRuns:a.document.metadata.test_runs??[],changed:!1,removed:0}}function JF(e,t){let n=[...e];for(let r of t)n.some(o=>Li(o,r))||n.push(r);return n}function XF(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((i,a)=>r.has(a+1)?!1:!t.some(s=>s.kind==="command"?i.command===s.value:s.kind==="path"?i.path===s.value:i.command===s.value||i.path===s.value));return{tests:o,removed:e.length-o.length}}function QF(e,t,n,r){return XF(JF(e,t),n,r)}function ZF(e){return[e.timeout!==void 0,e.progress===!0,(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 pS(e){if(ZF(e)&&e.run!==!0)throw new d("--timeout, --progress, --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",m.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new d("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",m.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new d("--match, --only-index, and --only-last require --run",m.USAGE)}async function eD(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:i,adds:a,removes:s,removeIndexes:c}=e;if(a.length===0&&s.length===0&&c.length===0)return YF({id:t,pmRoot:r,settings:o,typeToFolder:i});let l=0,p=await fe({pmRoot:r,settings:o,id:t,op:a.length>0?"tests_add":"tests_remove",author:I(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let f=u.metadata.tests??[],h=QF(f,a,s,c);if(qc(()=>uS(n,h.tests)),l=h.removed,(s.length>0||c.length>0)&&l===0)throw new d("No linked tests matched the requested removal selector",m.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...s.map(_=>`${_.kind}=${_.value}`),...c.map(_=>`index=${_}`)],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 u.metadata.tests=h.tests,{changedFields:ae(f,h.tests)?[]:["tests"]}}});return{itemId:p.item.id,tests:p.item.tests??[],testRuns:p.item.test_runs??[],changed:p.changedFields.length>0,removed:l}}function uS(e,t){let n=Ms(e.pmContext);rS(e.workspaceContext),mS(e.envSet,e.envClear,e.sharedHostSafe);let r={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:cr(e.onlyIndex),onlyLast:e.onlyLast},o=e.timeout===void 0?void 0:he(e.timeout,"--timeout");if(o!==void 0&&o<=0)throw new d(`--timeout must be a positive number (got "${e.timeout}")`,m.USAGE);pS(e);let i=e.run===!0?ry(t,r):void 0;if(i)for(let a of i.selected)Pr(a.command);return{defaultTimeoutSeconds:o,pmContextMode:n,runSelection:i,testsToRun:i?.selected??t}}async function tD(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await ym(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===!0||(t.measure?.length??0)>0,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:Oe(process.cwd())}})}function nD(e,t){let n=[];if(e.run===!0&&e.checkContext===!0){let r=gm(t);n.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}`)}return n}function rD(e){let t=WM(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=E(),i=Ao(e.options.measure,o);return{run_id:BM("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:i.length>0?i:void 0,executions:e.runResults.filter(a=>a.command?.trim()).slice(0,32).map(a=>({command:a.command.trim(),requested_pm_context_mode:a.execution_context?.requested_pm_context_mode,pm_context_mode:a.execution_context?.pm_context_mode,workspace_context_mode:a.execution_context?.workspace_context_mode,trust_reason:a.execution_context?.trust.reason}))}}async function oD(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:i,runResults:a,failOnSkippedTriggered:s,warnings:c}=e;if(t.run!==!0||!i)return;let l=rD({options:t,runStartedAt:i,runResults:a,failOnSkippedTriggered:s});if(r.testing.record_results_to_items!==!0)return{entry:l,receipt:{recorded:!1,reason:"tracking_disabled",run_id:l.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Cs({pmRoot:n,settings:r,itemId:o,author:I(t.author,r.author_default),message:`Track test run summary (${l.run_id})`,entry:l}),{entry:l,receipt:{recorded:!0,reason:"recorded",run_id:l.run_id}}}catch(p){if(hn(p))throw p;return c.push(`test_result_tracking_failed:${o}:${p instanceof Error?p.message:String(p)}`),{entry:l,receipt:{recorded:!1,reason:"write_failed",run_id:l.run_id}}}}function Zk(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),i=e.metricBelow.slice(0,o).trim(),a=e.metricBelow.slice(o+1).trim(),s=Number(a);if(o<=0||i.length===0||a.length===0||!Number.isFinite(s))throw new d("--metric-below must use name=value",m.USAGE);r=uk(t,i,s)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:fk(t,e.metricDiff)}}async function iD(e,t,n){if(e.acknowledgeLinkedTests===!0)return yg(t,n,E())}function aD(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:i,warnings:a,recording:s,measurementProjection:c,restoreScope:l}=e,p=o!==void 0&&o.selector!==null&&o.skipped_count>0,u=Ok(t.itemId,l);return{ok:n.every(f=>f.status!=="failed"&&f.status!=="refused")&&i!==!0,id:t.itemId,tests:p?o.selected:t.tests,...p?{tests_omitted:{count:t.tests.length-o.selected.length,restore_with:u}}:{},run_results:n,failure_categories:r,selection:o?{selector:o.selector,requested:o.requested,selected_indexes:o.selected_indexes,selected_count:o.selected_count,skipped_count:o.skipped_count}:void 0,fail_on_skipped_triggered:i?!0:void 0,warnings:a.length>0?a:void 0,changed:t.changed||s?.receipt.recorded===!0,...s?{evidence_recording:s.receipt}:{},count:t.tests.length,...t.removed>0?{removed:t.removed}:{},...c}}async function Fs(e,t,n){let r=ay(t);if(r)return sy(t),pS(t),mm(e,t,n,A(process.cwd(),n.path)),{...await ly(e,{...r,author:t.author,message:t.message,force:t.force},n),run_results:[],failure_categories:Oo([])};let o=Bt(),i=A(process.cwd(),n.path);await O(i);let a=await S(i);mm(e,t,n,i),Ao(t.measure,"validation"),Zk(t,[],void 0);let s=x(a,R()),c=await o.resolveList(t.add,"--add"),l=await o.resolveList(t.addJson,"--add-json"),p=await o.resolveList(t.remove,"--remove"),u=[...rF(c),...aF(l)],f=await nr(u,I(t.author,a.author_default),E())??[],h=sF(p),_=cF(t.removeIndex),g=await eD({id:e,options:t,pmRoot:i,settings:a,typeToFolder:s.type_to_folder,adds:f,removes:h,removeIndexes:_}),y=qc(()=>uS(t,g.tests)),w=await iD(t,i,g.tests),b=t.run===!0?E():void 0,k=await tD({options:t,runOptions:y,pmRoot:i,untrustedLinkedTestsPolicyEnabled:a.testing.allow_untrusted_linked_tests});Dk(e,t,n,i,k);let C=Oo(k),T=t.run===!0&&t.failOnSkipped===!0&&k.some(W=>W.status==="skipped"),$=nD(t,k);w&&$.push(`linked_test_trust_acknowledged:${w.acknowledged}`);let P=await oD({options:t,pmRoot:i,settings:a,itemId:g.itemId,runStartedAt:b,runResults:k,failOnSkippedTriggered:T,warnings:$}),F=P?.receipt.recorded?am([...g.testRuns,P.entry]):g.testRuns,Q=Zk(t,F,P?.entry);return aD({item:g,runResults:k,failureCategories:C,runSelection:y.runSelection,failOnSkippedTriggered:T,warnings:$,recording:P,measurementProjection:Q,restoreScope:Rk(n,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]="22944f9f-02a6-5fb4-b13e-d034ec4cfa7d")}catch{}})();var sD=(e,t)=>{if(e===void 0)return;let n=se(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new d(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE)}return n},cD=e=>{if(e===void 0)return;let t=he(e,"timeout");if(t<=0)throw new d("timeout must be a positive number",m.USAGE);return t},fS=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new d(`${t} must be a non-negative integer`,m.USAGE);return n},lD=e=>e instanceof Error?e.message:String(e),dD=()=>{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)}`},mD=e=>e.trim().replaceAll(/\s+/g," "),pD=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),uD=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),fD=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},_D=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Ds=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),_S=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),hD=e=>typeof e=="number"?e:void 0,gD=e=>{let t={assert_stdout_contains:Ds(e.assert_stdout_contains),assert_stdout_regex:Ds(e.assert_stdout_regex),assert_stderr_contains:Ds(e.assert_stderr_contains),assert_stderr_regex:Ds(e.assert_stderr_regex),assert_stdout_min_lines:hD(e.assert_stdout_min_lines),assert_json_field_equals:_S(e.assert_json_field_equals),assert_json_field_gte:_S(e.assert_json_field_gte)};return JSON.stringify(t)},yD=e=>{let t=wm(e.command);return t!==void 0?`command:${e.scope}:${mD(t)}`:`path:${e.scope}:${wm(e.path)??""}`},hS=e=>{let t=pD(e.env_set),n=uD(e.env_clear),r=fD(e.pm_context_mode),o=_D(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",a=gD(e);return`${yD(e)}:${t}:${n}:${r}:${o}:${i}:${a}`},wD=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,vD=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"||o.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},bD=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Us=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
43
- `)}catch{}},kD=async(e,t,n)=>{let r=[],o=0;for(let i of e){let a=await Fs(i.id,{run:!1},{...t,path:n});o+=a.tests.length,r.push({item:i,tests:a.tests})}return{itemTests:r,linkedTests:o}},SD=async e=>{let t=D(e.settings.schema),n=x(e.settings,R()),r=sD(e.options.status,t),o=fS(e.options.limit,"--limit"),i=fS(e.options.offset,"--offset")??0,a=(await ge(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(s=>r?s.status===r:!0).sort((s,c)=>s.id.localeCompare(c.id));return{filteredItems:o===void 0?a.slice(i):a.slice(i,i+o),statusFilter:r,limitFilter:o,offsetFilter:i}},ED=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=hS(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,wD(t.get(o),r.timeout_seconds))}return t};function AD(e,t){try{Pr(e.command);return}catch(n){if(!(n instanceof d)||n.code!=="linked_test_command_not_executable")throw n;return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Linked test refused for ${t}: ${n.message}`}}}var TD=async(e,t)=>{let n=[],r=e.tests.map(p=>{let u=hS(p),f=AD(p,e.item.id);if(f)return{test:p,key:u,duplicate:!1,refusal:f};let h=t.seenTestKeys.has(u);if(!h){t.seenTestKeys.add(u);let _=t.effectiveTimeoutByKey.get(u);n.push(_===void 0?p:{...p,timeout_seconds:_})}return{test:p,key:u,duplicate:h,refusal:f}}),o=n.length>0?await ym(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}):[],i=0,a=r.map(({test:p,key:u,duplicate:f,refusal:h})=>{if(h)return h;if(!f){let _=o[i];return i+=1,_}return{command:p.command,path:p.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),s=vD(a),c=Oo(a),l=await RD(e,s,a,t);return{passed:s.passed,failed:s.failed,skipped:s.skipped,trackingWarnings:l,failureCategories:c,result:{ok:s.failed===0&&!(t.options.failOnSkipped===!0&&s.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:s.passed,failed:s.failed,skipped:s.skipped,run_results:a,failure_categories:c}}},CD=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),ID=e=>e?!0:void 0,RD=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=CD(t,r.options);await Cs({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:E(),recorded_at:E(),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:ID(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.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}))}})}catch(o){return hn(o)?(r.revisionConflicts.push(o),[]):[`test_result_tracking_failed:${e.item.id}:${lD(o)}`]}return[]},OD=()=>{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},wm=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},xD=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:Oe(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:ED(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:I(e.options.author,e.settings.author_default),trackingRunId:dD(),trackingAttempt:OD(),trackingResumedFrom:wm(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),PD=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:Oo([]),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}},$D=async(e,t,n)=>{for(let[o,i]of e.entries()){Us(t.options,`item ${o+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let a=await TD(i,t);bD(n.failureCategories,a.failureCategories),n.passed+=a.passed,n.failed+=a.failed,n.skipped+=a.skipped,n.trackingWarnings.push(...a.trackingWarnings),n.results.push(a.result),Us(t.options,`item ${o+1}/${e.length} end id=${i.item.id} status=${a.failed===0?"passed":"failed"} passed=${a.passed} failed=${a.failed} skipped=${a.skipped}`)}let[r]=t.revisionConflicts;if(r!==void 0)throw r},LD=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=gm(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}`)},ND=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}),MD=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(" "),FD=async(e,t)=>{let n=A(process.cwd(),t.path);await O(n);let r=await S(n),o=await SD({pmRoot:n,settings:r,options:e}),i=cD(e.timeout),a=E(),s=await kD(o.filteredItems,t,n);return Us(e,MD({...o,linkedTests:s.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:s.itemTests,linkedTests:s.linkedTests,defaultTimeoutSeconds:i,runStartedAt:a}},DD=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}},gS=async(e,t)=>{let n=await FD(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=PD(e,n.linkedTests,n.filteredItems),i=xD({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await $D(n.itemTests,i,r),LD(e,r);let a=DD({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Us(e,`end status=${a.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),ND({ok:a.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:a.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]="920b5725-710a-5839-86e3-dbdbc8a602a8")}catch{}})();function yS(e,t,n){let r;if(typeof e.lines=="string")r=fl(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=fl(`${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]="09fa5b5c-d44a-55e4-9365-a08702d8a952")}catch{}})();function Ne(e,t){let n=v(e,t);if(!n)throw new d(`Missing required argument: ${t}`,64);return n}function Pn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]: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]="9a4dbe8d-9341-55f1-8c4a-d476c2b338e5")}catch{}})();function UD(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:v(e.args,"name")??v(e.options,"name"),author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:be(n)}}function jD(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=Pn({list:()=>kh(t.global),show:()=>Sh(r,t.global),"show-status":()=>Eh(r,t.global),"list-fields":()=>Ch(t.global),"show-field":()=>Ih(r,t.global),"remove-type":()=>yh(r,{author:o,force:i},t.global),"remove-field":()=>Th(r,{author:o,force:i},t.global),"remove-status":()=>bh(r,{author:o,force:i},t.global),"apply-preset":()=>Rh(v(t.args,"typePreset")??v(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function GD(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,a=t.args.commands??t.options.commands,s=t.args.requiredTypes??t.options.requiredTypes;return Ah(n,{type:v(t.args,"fieldType")??v(t.options,"fieldType"),commands:a===void 0?void 0:be(a),description:v(t.args,"description")??v(t.options,"description"),cliFlag:v(t.args,"cliFlag")??v(t.options,"cliFlag"),alias:i,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:s===void 0?void 0:be(s),author:r,force:o},t.global)}function qD(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,a=t.args.role??t.options.role;return vh(n,{role:a===void 0?void 0:be(a),alias:i,description:v(t.args,"description")??v(t.options,"description"),order:Ge(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function KD(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return gh(n,{description:v(t.args,"description")??v(t.options,"description"),defaultStatus:v(t.args,"defaultStatus")??v(t.args,"default_status")??v(t.options,"defaultStatus")??v(t.options,"default_status"),folder:v(t.args,"folder")??v(t.options,"folder"),alias:i,author:r,force:o},t.global)}function zD(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=v(t.args,"to")??Ne(t.options,"to"),s=v(t.args,"migrationId")??v(t.args,"migration_id")??v(t.options,"migrationId")??v(t.options,"migration_id"),c=v(t.args,"fieldTypeScope")??v(t.options,"fieldTypeScope")??v(t.args,"type")??v(t.options,"type"),l=n==="rename-type"?{kind:"rename-type",from:r??"",to:a}:n==="rename-field"?{kind:"rename-field",from:r??"",to:a,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:a};return _h(l,{migrationId:s,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function wS(e){let t=UD(e);wf(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Nn.find(o=>o===t.subcommand);if(n)return fh(n,t.name,{definition:e.args.definition??e.options.definition,policy:v(e.args,"policy")??v(e.options,"policy"),message:v(e.args,"message")??v(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=jD(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return zD(t);if(t.subcommand==="add-field")return GD(t);if(t.subcommand==="add-status")return qD(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Oh({minCount:Ge(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):KD(t);throw xe({command_path:"schema",token:t.subcommand,allowed:hh,exit_code:64})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="99e0fe28-8c78-52d7-8cec-11ed8079bc7c")}catch{}})();function js(e){return v(e.args,"target")??v(e.options,"target")}function Ee(e,t=e.options){return e.id??Ne(t,"id")}async function HD(e){let t=Gn("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),Ml(await $t(v(e.args,"status")??v(t,"status"),t,e.global),t)}async function BD(e){let t=v(e.args,"query")??v(e.args,"keywords")??Ne(e.args,"query"),n=Gn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Ml(await oo(t,n,e.global),n)}async function WD(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ye(e.args,e.options);return Ce(await tn(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function VD(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ye(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 Ce(await Zl(Ee(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function YD(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ye(e.args,e.options);return Ce(await it(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function JD(e){let t=Pa(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),By(Ee(e),t,e.global)}function vS(e,t){return Dh(yS(e.options,t,Ge),e.global)}function XD(e){let t=be(e.options.lookupPath);if(t&&t.length>0)return vS(e,t);let n=Ee(e);return e.options.discover===!0?_l(n,ua(e.options),e.global):Fh(n,Vr(e.options),e.global)}function QD(e){return Ak({subcommand:v(e.args,"subcommand")??v(e.options,"subcommand"),limit:K_(e.args,e.options)},e.global)}function ZD(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),eo(e.global,t)}function eU(e){let t=v(e.args,"configAction")??v(e.options,"configAction")??v(e.options,"action");if(t===void 0)throw new d("Missing required argument: configAction",64);let n=v(e.args,"value")??v(e.options,"value"),r=v(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options,o=v(e.args,"key")??v(e.options,"key");return uw(v(e.args,"scope")??v(e.options,"scope")??If(o),t,o,r,e.global,v(e.options,"policy")===void 0?n:void 0)}function tU(e){let t=e.options;return Og(Rg(t),e.global)}function nU(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new d(`${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 d(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new d(`${t} must be a finite integer.`,64);return r}}async function rU(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=ye(e.args,e.options),i=await Hv({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:oU(e),reorderTo:nU(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&j_(e.args)&&(i.mutation_receipt=hs(i,void 0)),t==="show"?i:Ce(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function oU(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function iU(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=t.trim().toLowerCase(),r=v(e.args,"name")??v(e.options,"name"),o=Pn({list:()=>lb(),show:()=>db(r),lint:()=>mb(r),apply:()=>pb(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!o)throw xe({command_path:"profile",token:t,allowed:cb,exit_code:64});return o()}async function aU(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ye(e.args,e.options);return Ce(await Tw(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function sU(e){let{changedFields:t,runnerOptions:n}=ye(e.args,e.options);return Ce(await Qv(_a(n),e.global),{changedFields:t})}async function cU(e){let{changedFields:t,runnerOptions:n}=ye(e.args,e.options),r=v(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),Ce(await Nw(fa(o),e.global),{changedFields:t})}async function lU(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ye(e.args,e.options),o=v(r,"target")??Ne(e.args,"target");return Ce(await Fd(Ee(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function dU(e){let t={...e.args,...e.options};return Uh(Ne(t,"subcommand"),v(t,"id")??e.id,v(t,"target"),V_(t),e.global)}function mU(e){return Lh(A(process.cwd(),e.global.path),{...e.args,...e.options})}var bS={init:e=>_o(v(e.args,"prefix"),e.global,e.options),context:e=>vl(Gn("context",e.options),e.global),next:e=>ro(Gn("next",e.options),e.global),eval:Vb,events:Yb,merge:Jb,workspace:Xb,meet:Ss,event:Ss,remind:Ss,list:HD,get:e=>{let t=Ee(e);return kl(t,e.global,Gn("get",e.options,[t]))},search:BD,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:be(e.options.status);return ul(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:v(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Ge(e.options.limit,"limit")})},create:WD,copy:VD,focus:e=>ld(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:YD,"item-reopen":$v,restore:lU,claim:Ov,release:Pv,"start-task":e=>Cn(e,"start_task"),"pause-task":e=>Cn(e,"pause_task"),"close-task":e=>Cn(e,"close_task"),close:xv,comments:JD,notes:e=>eb(Ee(e),Pa(e.options),e.global),learnings:e=>Aw(Ee(e),Pa(e.options),e.global),files:XD,docs:e=>Mh(Ee(e),Vr(e.options),e.global),test:e=>Fs(Ee(e),e.options,e.global),"test-all":e=>gS(e.options,e.global),telemetry:QD,validate:e=>Aa(e.options,e.global,{runUpdate:(t,n,r)=>it(t,n,r)}),health:ZD,assurance:e=>wg(e.args,e.options,e.global),contracts:e=>Pl(e.options,e.global),config:eU,activity:tU,aggregate:e=>bl(e.options,e.global),extension:e=>Zn(js(e),e.options,e.global),package:e=>Zn(js(e),e.options,e.global),install:e=>Zn(js(e),{...e.options,install:!0},e.global),upgrade:e=>bg(js(e),e.options,e.global),delete:e=>cd(Ee(e),e.options,e.global),deps:e=>Nh(Ee(e),e.options,e.global),graph:dU,"files-discover":e=>_l(Ee(e),e.options,e.global),"files-lookup":e=>vS(e,be(e.options.paths)),history:e=>xg(Ee(e),{...e.options,compact:e.options.full===!0||e.options.provenance===!0?!1:e.options.compact!==!1},e.global),"history-redact":e=>Ew(Ee(e),e.options,e.global),"history-repair":ww,"history-compact":vw,"history-attest":e=>kg(e.options,e.global),"history-author-acknowledge":mU,plan:rU,schema:wS,profile:iU,stats:e=>nm(e.global,Qb(e.options)),append:aU,"update-many":sU,"close-many":cU,gc:e=>vg(e.global,e.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]="96234a42-d25c-5221-a12b-a992925a13ba")}catch{}})();var pU=new Map;function vm(){pU.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]="69f9c792-7ee1-5e4b-9900-38e1c887c4d4")}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]="5417c092-2e52-5b18-bcb6-da34f07f595f")}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]="ba66cac9-25d6-559e-95d1-71db5c404807")}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]="5917df84-25e1-5ce2-9203-746f92bb4037")}catch{}})();var SS=[{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:P_().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 workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","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>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --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> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --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 package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --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:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],kS=new Map;for(let e of SS){kS.set(e.id,e);for(let t of e.aliases)kS.set(t,e)}function bm(){return SS.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]="b11b0e04-bad1-5090-8df9-d922568db013")}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]="ebe25271-7465-5536-a4d8-ee402b0b3848")}catch{}})();var z9=[...rc],H9=[...oc],km=new Set(ln.filter(e=>e.hidden).map(e=>e.alias)),ES=x_("full").filter(e=>!e.includes(" ")&&!km.has(e)),uU=M(Wo),fU=M(Vo),_U=M(ti),hU=M(ai),AS=zr("restore",De("restore")),TS=zr("history-attest",De("history-attest")),gU=M(si),yU=M(yu),wU=M(wu),vU=M(ii),bU=M(mi),kU=M(ci),SU=M(li),EU=M(ei),Sm=[...new Set(Te.map(e=>e.canonical_argv[0]))],CS=[...new Set(Te.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],B9=new Set(Bo.filter(e=>e.disposition==="package_owned").map(e=>B(e.command))),IS=Te.filter(e=>e.canonical_argv[0]==="history"),AU=IS.map(e=>e.canonical_argv[1]).join(" ");var TU=IS.map(e=>({...e,flags:M(De(e.alias))})),CU=M(Yo),IU=M(Jo,!1),RU=M(di),OU=M(Ir),xU=M(Rr),PU=M(_i),$U=M(ui),LU=M(ri),NU=M(fi),MU=M(pi),FU=M(hi),DU=M(ni),UU=M(oi),jU=M(Qo),GU=M(gi),qU=M(Xo),Em=`${Nn.join(" ")} list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status`;var KU=M(yi),zU=`${KU} bash zsh fish`,Am=qs(bm()),Gs="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",Tm=`${Gs} upgrade`,HU=M(Zo),BU=M(Tr),WU=M(Cr);var VU=M(De("close")),YU=M(De("close-task")),JU=M(De("release")),XU=M(De("claim"));var RS=Mn.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),Cm=[...Ti].join("|"),Im=[...Ti].map(e=>`${e}=*`).join("|"),Rm=[...RS.split(" ").filter(e=>!Ti.has(e)),"-h","-V"].join("|");function qs(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]="dd896f8b-8a4a-54b2-854b-3a8653ed4d18")}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]="c87dfc55-d79e-5210-b74b-8afb6280770c")}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]="bb5fead2-4f62-5056-a07b-30efc42af0dd")}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]="a7cfbd72-3010-53e7-946b-e65842ee4ceb")}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]="7a7096c6-a9c3-5d8e-96e4-ed1b0218234e")}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]="8e9a2374-d190-52e1-8afd-14e1954863f0")}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]="20ef5759-1314-513e-8225-347796637494")}catch{}})();var xo=Symbol("pm.active-extension-host-context");function He(e){return{fullChangedFields:!0,options:e}}var z=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[xo]=!0,n}run(t,n={}){return pj({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}async withItemTransactionContext(t,n=!1){let r=A(this.defaults.cwd??process.cwd(),this.defaults.path),o=async()=>{let a=await jr(r,()=>S(r));return t({pmRoot:r,author:I(this.defaults.author,a.author_default)})};if(this.defaults[xo]===!0||zs.getStore()===!0)return o();let i=()=>aj({...this.defaults,path:r},o);return n?jr(r,i):i()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-CVGK4RJP.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-CVGK4RJP.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,r)=>this.withItemTransactionContext(async o=>(await import("./item-transaction-CVGK4RJP.js")).abandonItemTransaction({...r,...o,transactionId:n}));return{status:n=>this.withItemTransactionContext(async r=>(await import("./item-transaction-CVGK4RJP.js")).readItemTransaction(r.pmRoot,n),!0),abandon:t,supersede:(n,r,o)=>t(n,{...o,supersededBy:r})}}readItemRevision(t){return this.withItemTransactionContext(async({pmRoot:n})=>(await import("./item-revision-XC4ZJ7MY.js")).readItemRevision(t,{pmRoot:n}))}async withExpectedItemRevisions(t,n){let r=await import("./item-revision-XC4ZJ7MY.js"),o="",i=await this.withItemTransactionContext(({pmRoot:s})=>(o=s,r.bindExpectedItemRevisions(t,{pmRoot:s}))),a=this.defaults.noExtensions===!0&&this.defaults[xo]!==!0;return r.runWithBoundItemRevisionScope(i,n,{scopeArgs:["--pm-path",o,...a?["--no-extensions"]:[]]})}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return qy(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return pl(await this.list(ml(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})}async append(t,n,r={}){return M_(r,"append"),await this.runTyped("append",{id:t,...He(gt(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,i={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,r={}){return this.runTyped("schema",{name:n,options:{...r,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={}){let{type:r,...o}=n;return this.runTyped("schema",{name:t,options:{...o,fieldType:r,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}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}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,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...i===void 0?{}:{reorderTo:i},options:gt(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",He(t))}update(t,n={}){return this.runTyped("update",{id:t,...He(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,...He(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...He(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...He(t)})}release(t,n={}){return this.runTyped("release",{id:t,...He(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...He(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...He(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},...He(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...He(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...He(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...He(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 BX(e={},t={}){return new z(t).context(e)}function WX(e={},t={}){return new z(t).list(e)}function VX(e={},t={}){return new z(t).listAllComplete(e)}function YX(e,t={},n={}){return new z(n).search(e,t)}function JX(e,t={},n={}){return new z(n).get(e,t)}function XX(e={},t={}){return new z(t).next(e)}function QX(e={},t={}){return new z(t).aggregate(e)}function ZX(e,t={},n={}){return new z(n).comments(e,t)}function eQ(e,t={},n={}){return new z(n).notes(e,t)}function tQ(e,t={},n={}){return new z(n).learnings(e,t)}function nQ(e,t={},n={}){return new z(n).files(e,t)}function rQ(e,t={},n={}){return new z(n).filesDiscover(e,t)}function oQ(e,t={},n={}){return new z(n).docs(e,t)}function iQ(e,t={},n={}){return new z(n).deps(e,t)}function aQ(e,t={},n={},r={}){return new z(r).graph(e,t,n)}function sQ(e,t,n={},r={}){return new z(r).append(e,t,n)}function cQ(e={},t={}){return new z(t).create(e)}function lQ(e,t={},n={}){return new z(n).update(e,t)}function dQ(e,t,n={},r={}){return new z(r).reopen(e,t,n)}function mQ(e,t,n={},r={}){return new z(r).close(e,t,n)}function pQ(e,t={},n={}){return new z(n).claim(e,t)}function uQ(e={},t={}){return new z(t).claimNext(e)}function fQ(e,t={},n={}){return new z(n).release(e,t)}function _Q(e,t={},n={}){return new z(n).copy(e,t)}function hQ(e,t={},n={}){return new z(n).delete(e,t)}function gQ(e,t,n={},r={}){return new z(r).restore(e,t,n)}function yQ(e,t={},n={}){return new z(n).focus(e,t)}var $S=Vu(),zs=new ij;function Ks(){Ic(fp()),Rc(_p()),Oc(hp()),xc(gp()),Pc(yp()),$c(wp()),Lc(vp())}async function MS(e,t,n,r){return Cc(()=>t===void 0?$S.read(()=>LS(e,n,r)):$S.write(()=>lj(t,()=>LS(e,n,r))))}async function aj(e,t){let n=e.cwd;if(zs.getStore()===!0&&n===void 0&&e.noExtensions===!0){let o=A(process.cwd(),e.path);return Cc(()=>Oa({pmRoot:o},t))}let r=n??process.cwd();return MS(pa({path:e.path,noExtensions:e.noExtensions}),n,r,()=>zs.run(!0,t))}function sj(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:v_(e);return typeof n=="string"?n:"Unknown failure"}catch{return"Unknown failure"}}async function LS(e,t,n){let r=A(t,e.path);if(e.noExtensions)return Ks(),Oa({pmRoot:r},()=>n(null));if(!await H(ie(r)))return Ks(),n(null);let o=null,i;try{let a=await S(r),s=await Er({pmRoot:r,settings:a,cwd:t,noExtensions:!1}),c=await Ar({...s,loaded:s.loaded});i={loadResult:s,activationResult:c},Ic(c.hooks),Rc(c.commands),Oc(c.parsers),xc(c.preflight),Pc(c.services),$c(c.renderers),Lc(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:s.loaded}}catch(a){Ks(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",sj(a))}try{return await Oa({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Ks(),i&&await wc(i.loadResult,i.activationResult).catch(()=>{})}}function FS(e,t){let n=Xn(e);return t?.registrations.commands.find(r=>Xn(r.action)===n)?.command??t?.commands.handlers.find(r=>Xn(r.command)===n)?.command}async function cj(e,t,n,r,o){if(!o)throw new d(`Unsupported native pm action: ${e}`,m.USAGE);let i=FS(e,o);if(!i)throw new d(`Unsupported native pm action: ${e}`,m.USAGE);let a=typeof n.author=="string"?n.author:r.author,s=cl(i),c=C_(ll(t,n),T_(o.registrations,s),s),l=await Ai({command:s,args:be(n.args??t.args),options:c,global:{...r,author:a},pm_root:o.pmRoot,sdk:My(o.pmRoot,z.forActiveExtensionHost({pmRoot:o.pmRoot,author:a}),a,s)});if(!l.handled){if(Object.hasOwn(l,"cause"))throw ra(i,l);let p=l.warnings.length>0?` (${l.warnings.join(", ")})`:"";throw new d(`Unsupported native pm action: ${e}${p}`,m.USAGE)}return l.result}async function lj(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function dj(e){let t=Ne(e,"action"),n=Xn(t),r=Pn(zy,n),o=r?.action??n,i={...e,action:o};return r?.options!==void 0&&(i.options={...r.options,...vr(e.options)}),o==="package"&&(i.options={...vr(i.options),vocabulary:"package"}),{action:o,args:i}}function mj(e,t,n,r){let o=e[xo]===!0,i=t.noExtensions===!0&&!o?["--no-extensions"]:[];if(n!==void 0)return["--pm-path",A(r,t.path),...i];let a=dt(t,r);return[...t.noExtensions===!0?a.slice(0,-1):a,...i]}async function pj(e){let t=dj(e),n=pa(t.args);Ju(n);let r=B_(t.action),o=v(t.args,"cwd"),i=o??process.cwd();t.action==="init"&&(n[Nl]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=A(i,n.path));let{expectHash:a,dispatchArgs:s}=J_(t.args),c=async l=>{if(a===void 0)return NS(t.action,s,n,l);let{dispatchWithExpectedItemRevisions:p}=await import("./item-revision-XC4ZJ7MY.js");return p({action:t.action,expectHash:a,defaultId:v(s,"id")??v(vr(s.options),"id"),options:vr(s.options),background:s.background,pmRoot:A(i,n.path),invocation:{scopeArgs:mj(e,n,o,i),...n.outputFormat===void 0?{}:{outputArgs:["--output-format",n.outputFormat]}},run:()=>NS(t.action,s,n,l)})};try{return t.action==="history-attest"?await c(null):e[xo]===!0||zs.getStore()===!0?await c(null):await MS(n,o,i,l=>c(l))}finally{r&&vm()}}async function NS(e,t,n,r){let o=sl(t,e);if(e==="create"||e==="update"){let{assertNativeMutationOptions:p}=await import("./mutation-admission-N27D5H64.js");await p(e,t,o,n.path,z_[e])}let i=Pn(bS,e),a=i?void 0:FS(e,r),s=a===void 0?e:`extension:${a}`;tf(s,o),rf(s,o);let c={action:e,args:t,options:o,id:v(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},l=i?await i(c):await cj(e,t,o,n,r);if(e==="history-attest")return l;{let p=lf(s,o,l);return await Ny(A(process.cwd(),n.path),p),p}}var uj={closeManyOptionsFromFlat:fa,extensionOptionsFromArgs:ll,globalOptions:pa,mutationListOptions:W_,normalizeActionName:Xn,normalizeCommandPath:cl,normalizeMcpUpdateOptions:Y_,normalizeMcpOptionsArrays:H_,optionsWithAuthor:sl,readRequiredString:Ne,readScalarString:G_,readScalarStringAllowBlank:q_,readStringArray:be,updateManyOptionsFromFlat:_a,withAddNoteOption:Vr,withFilesDiscoveryOptions:ua,withMutationCompaction:ye};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=uj);export{Sl as a,zE as b,QE as c,Zg as d,TG as e,ey as f,CG as g,IG as h,ly as i,kA as j,z as k,BX as l,WX as m,VX as n,YX as o,JX as p,XX as q,QX as r,ZX as s,eQ as t,tQ as u,nQ as v,rQ as w,oQ as x,iQ as y,aQ as z,sQ as A,cQ as B,lQ as C,dQ as D,mQ as E,pQ as F,uQ as G,fQ as H,_Q as I,hQ as J,gQ as K,yQ as L,aj as M,pj as N};
44
- //# sourceMappingURL=chunk-QK7FX4O5.js.map
43
+ `)}catch{}},kD=async(e,t,n)=>{let r=[],o=0;for(let i of e){let a=await Fs(i.id,{run:!1},{...t,path:n});o+=a.tests.length,r.push({item:i,tests:a.tests})}return{itemTests:r,linkedTests:o}},SD=async e=>{let t=D(e.settings.schema),n=x(e.settings,R()),r=sD(e.options.status,t),o=fS(e.options.limit,"--limit"),i=fS(e.options.offset,"--offset")??0,a=(await ge(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(s=>r?s.status===r:!0).sort((s,c)=>s.id.localeCompare(c.id));return{filteredItems:o===void 0?a.slice(i):a.slice(i,i+o),statusFilter:r,limitFilter:o,offsetFilter:i}},ED=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=hS(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,wD(t.get(o),r.timeout_seconds))}return t};function AD(e,t){try{Pr(e.command);return}catch(n){if(!(n instanceof d)||n.code!=="linked_test_command_not_executable")throw n;return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Linked test refused for ${t}: ${n.message}`}}}var TD=async(e,t)=>{let n=[],r=e.tests.map(p=>{let u=hS(p),f=AD(p,e.item.id);if(f)return{test:p,key:u,duplicate:!1,refusal:f};let h=t.seenTestKeys.has(u);if(!h){t.seenTestKeys.add(u);let _=t.effectiveTimeoutByKey.get(u);n.push(_===void 0?p:{...p,timeout_seconds:_})}return{test:p,key:u,duplicate:h,refusal:f}}),o=n.length>0?await ym(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}):[],i=0,a=r.map(({test:p,key:u,duplicate:f,refusal:h})=>{if(h)return h;if(!f){let _=o[i];return i+=1,_}return{command:p.command,path:p.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),s=vD(a),c=Oo(a),l=await RD(e,s,a,t);return{passed:s.passed,failed:s.failed,skipped:s.skipped,trackingWarnings:l,failureCategories:c,result:{ok:s.failed===0&&!(t.options.failOnSkipped===!0&&s.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:s.passed,failed:s.failed,skipped:s.skipped,run_results:a,failure_categories:c}}},CD=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),ID=e=>e?!0:void 0,RD=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=CD(t,r.options);await Cs({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:E(),recorded_at:E(),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:ID(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.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}))}})}catch(o){return hn(o)?(r.revisionConflicts.push(o),[]):[`test_result_tracking_failed:${e.item.id}:${lD(o)}`]}return[]},OD=()=>{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},wm=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},xD=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:Oe(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:ED(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:I(e.options.author,e.settings.author_default),trackingRunId:dD(),trackingAttempt:OD(),trackingResumedFrom:wm(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),PD=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:Oo([]),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}},$D=async(e,t,n)=>{for(let[o,i]of e.entries()){Us(t.options,`item ${o+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let a=await TD(i,t);bD(n.failureCategories,a.failureCategories),n.passed+=a.passed,n.failed+=a.failed,n.skipped+=a.skipped,n.trackingWarnings.push(...a.trackingWarnings),n.results.push(a.result),Us(t.options,`item ${o+1}/${e.length} end id=${i.item.id} status=${a.failed===0?"passed":"failed"} passed=${a.passed} failed=${a.failed} skipped=${a.skipped}`)}let[r]=t.revisionConflicts;if(r!==void 0)throw r},LD=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=gm(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}`)},ND=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}),MD=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(" "),FD=async(e,t)=>{let n=A(process.cwd(),t.path);await O(n);let r=await S(n),o=await SD({pmRoot:n,settings:r,options:e}),i=cD(e.timeout),a=E(),s=await kD(o.filteredItems,t,n);return Us(e,MD({...o,linkedTests:s.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:s.itemTests,linkedTests:s.linkedTests,defaultTimeoutSeconds:i,runStartedAt:a}},DD=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}},gS=async(e,t)=>{let n=await FD(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=PD(e,n.linkedTests,n.filteredItems),i=xD({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await $D(n.itemTests,i,r),LD(e,r);let a=DD({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Us(e,`end status=${a.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),ND({ok:a.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:a.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]="920b5725-710a-5839-86e3-dbdbc8a602a8")}catch{}})();function yS(e,t,n){let r;if(typeof e.lines=="string")r=fl(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=fl(`${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]="09fa5b5c-d44a-55e4-9365-a08702d8a952")}catch{}})();function Ne(e,t){let n=v(e,t);if(!n)throw new d(`Missing required argument: ${t}`,64);return n}function Pn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]: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]="9a4dbe8d-9341-55f1-8c4a-d476c2b338e5")}catch{}})();function UD(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:v(e.args,"name")??v(e.options,"name"),author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:be(n)}}function jD(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=Pn({list:()=>kh(t.global),show:()=>Sh(r,t.global),"show-status":()=>Eh(r,t.global),"list-fields":()=>Ch(t.global),"show-field":()=>Ih(r,t.global),"remove-type":()=>yh(r,{author:o,force:i},t.global),"remove-field":()=>Th(r,{author:o,force:i},t.global),"remove-status":()=>bh(r,{author:o,force:i},t.global),"apply-preset":()=>Rh(v(t.args,"typePreset")??v(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function GD(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,a=t.args.commands??t.options.commands,s=t.args.requiredTypes??t.options.requiredTypes;return Ah(n,{type:v(t.args,"fieldType")??v(t.options,"fieldType"),commands:a===void 0?void 0:be(a),description:v(t.args,"description")??v(t.options,"description"),cliFlag:v(t.args,"cliFlag")??v(t.options,"cliFlag"),alias:i,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:s===void 0?void 0:be(s),author:r,force:o},t.global)}function qD(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,a=t.args.role??t.options.role;return vh(n,{role:a===void 0?void 0:be(a),alias:i,description:v(t.args,"description")??v(t.options,"description"),order:Ge(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function KD(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return gh(n,{description:v(t.args,"description")??v(t.options,"description"),defaultStatus:v(t.args,"defaultStatus")??v(t.args,"default_status")??v(t.options,"defaultStatus")??v(t.options,"default_status"),folder:v(t.args,"folder")??v(t.options,"folder"),alias:i,author:r,force:o},t.global)}function zD(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=v(t.args,"to")??Ne(t.options,"to"),s=v(t.args,"migrationId")??v(t.args,"migration_id")??v(t.options,"migrationId")??v(t.options,"migration_id"),c=v(t.args,"fieldTypeScope")??v(t.options,"fieldTypeScope")??v(t.args,"type")??v(t.options,"type"),l=n==="rename-type"?{kind:"rename-type",from:r??"",to:a}:n==="rename-field"?{kind:"rename-field",from:r??"",to:a,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:a};return _h(l,{migrationId:s,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function wS(e){let t=UD(e);wf(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Nn.find(o=>o===t.subcommand);if(n)return fh(n,t.name,{definition:e.args.definition??e.options.definition,policy:v(e.args,"policy")??v(e.options,"policy"),message:v(e.args,"message")??v(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=jD(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return zD(t);if(t.subcommand==="add-field")return GD(t);if(t.subcommand==="add-status")return qD(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Oh({minCount:Ge(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):KD(t);throw xe({command_path:"schema",token:t.subcommand,allowed:hh,exit_code:64})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="99e0fe28-8c78-52d7-8cec-11ed8079bc7c")}catch{}})();function js(e){return v(e.args,"target")??v(e.options,"target")}function Ee(e,t=e.options){return e.id??Ne(t,"id")}async function HD(e){let t=Gn("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),Ml(await $t(v(e.args,"status")??v(t,"status"),t,e.global),t)}async function BD(e){let t=v(e.args,"query")??v(e.args,"keywords")??Ne(e.args,"query"),n=Gn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Ml(await oo(t,n,e.global),n)}async function WD(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ye(e.args,e.options);return Ce(await tn(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function VD(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ye(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 Ce(await Zl(Ee(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function YD(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ye(e.args,e.options);return Ce(await it(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function JD(e){let t=Pa(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),By(Ee(e),t,e.global)}function vS(e,t){return Dh(yS(e.options,t,Ge),e.global)}function XD(e){let t=be(e.options.lookupPath);if(t&&t.length>0)return vS(e,t);let n=Ee(e);return e.options.discover===!0?_l(n,ua(e.options),e.global):Fh(n,Vr(e.options),e.global)}function QD(e){return Ak({subcommand:v(e.args,"subcommand")??v(e.options,"subcommand"),limit:K_(e.args,e.options)},e.global)}function ZD(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),eo(e.global,t)}function eU(e){let t=v(e.args,"configAction")??v(e.options,"configAction")??v(e.options,"action");if(t===void 0)throw new d("Missing required argument: configAction",64);let n=v(e.args,"value")??v(e.options,"value"),r=v(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options,o=v(e.args,"key")??v(e.options,"key");return uw(v(e.args,"scope")??v(e.options,"scope")??If(o),t,o,r,e.global,v(e.options,"policy")===void 0?n:void 0)}function tU(e){let t=e.options;return Og(Rg(t),e.global)}function nU(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new d(`${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 d(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new d(`${t} must be a finite integer.`,64);return r}}async function rU(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=ye(e.args,e.options),i=await Hv({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:oU(e),reorderTo:nU(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&j_(e.args)&&(i.mutation_receipt=hs(i,void 0)),t==="show"?i:Ce(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function oU(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function iU(e){let t=v(e.args,"subcommand")??Ne(e.options,"subcommand"),n=t.trim().toLowerCase(),r=v(e.args,"name")??v(e.options,"name"),o=Pn({list:()=>lb(),show:()=>db(r),lint:()=>mb(r),apply:()=>pb(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:v(e.args,"author")??v(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!o)throw xe({command_path:"profile",token:t,allowed:cb,exit_code:64});return o()}async function aU(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ye(e.args,e.options);return Ce(await Tw(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function sU(e){let{changedFields:t,runnerOptions:n}=ye(e.args,e.options);return Ce(await Qv(_a(n),e.global),{changedFields:t})}async function cU(e){let{changedFields:t,runnerOptions:n}=ye(e.args,e.options),r=v(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),Ce(await Nw(fa(o),e.global),{changedFields:t})}async function lU(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ye(e.args,e.options),o=v(r,"target")??Ne(e.args,"target");return Ce(await Fd(Ee(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function dU(e){let t={...e.args,...e.options};return Uh(Ne(t,"subcommand"),v(t,"id")??e.id,v(t,"target"),V_(t),e.global)}function mU(e){return Lh(A(process.cwd(),e.global.path),{...e.args,...e.options})}var bS={init:e=>_o(v(e.args,"prefix"),e.global,e.options),context:e=>vl(Gn("context",e.options),e.global),next:e=>ro(Gn("next",e.options),e.global),eval:Vb,events:Yb,merge:Jb,workspace:Xb,meet:Ss,event:Ss,remind:Ss,list:HD,get:e=>{let t=Ee(e);return kl(t,e.global,Gn("get",e.options,[t]))},search:BD,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:be(e.options.status);return ul(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:v(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Ge(e.options.limit,"limit")})},create:WD,copy:VD,focus:e=>ld(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:YD,"item-reopen":$v,restore:lU,claim:Ov,release:Pv,"start-task":e=>Cn(e,"start_task"),"pause-task":e=>Cn(e,"pause_task"),"close-task":e=>Cn(e,"close_task"),close:xv,comments:JD,notes:e=>eb(Ee(e),Pa(e.options),e.global),learnings:e=>Aw(Ee(e),Pa(e.options),e.global),files:XD,docs:e=>Mh(Ee(e),Vr(e.options),e.global),test:e=>Fs(Ee(e),e.options,e.global),"test-all":e=>gS(e.options,e.global),telemetry:QD,validate:e=>Aa(e.options,e.global,{runUpdate:(t,n,r)=>it(t,n,r)}),health:ZD,assurance:e=>wg(e.args,e.options,e.global),contracts:e=>Pl(e.options,e.global),config:eU,activity:tU,aggregate:e=>bl(e.options,e.global),extension:e=>Zn(js(e),e.options,e.global),package:e=>Zn(js(e),e.options,e.global),install:e=>Zn(js(e),{...e.options,install:!0},e.global),upgrade:e=>bg(js(e),e.options,e.global),delete:e=>cd(Ee(e),e.options,e.global),deps:e=>Nh(Ee(e),e.options,e.global),graph:dU,"files-discover":e=>_l(Ee(e),e.options,e.global),"files-lookup":e=>vS(e,be(e.options.paths)),history:e=>xg(Ee(e),{...e.options,compact:e.options.full===!0||e.options.provenance===!0?!1:e.options.compact!==!1},e.global),"history-redact":e=>Ew(Ee(e),e.options,e.global),"history-repair":ww,"history-compact":vw,"history-attest":e=>kg(e.options,e.global),"history-author-acknowledge":mU,plan:rU,schema:wS,profile:iU,stats:e=>nm(e.global,Qb(e.options)),append:aU,"update-many":sU,"close-many":cU,gc:e=>vg(e.global,e.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]="96234a42-d25c-5221-a12b-a992925a13ba")}catch{}})();var pU=new Map;function vm(){pU.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]="69f9c792-7ee1-5e4b-9900-38e1c887c4d4")}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]="5417c092-2e52-5b18-bcb6-da34f07f595f")}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]="ba66cac9-25d6-559e-95d1-71db5c404807")}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]="5917df84-25e1-5ce2-9203-746f92bb4037")}catch{}})();var SS=[{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:P_().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 workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","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>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --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> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --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 package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --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:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],kS=new Map;for(let e of SS){kS.set(e.id,e);for(let t of e.aliases)kS.set(t,e)}function bm(){return SS.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]="b11b0e04-bad1-5090-8df9-d922568db013")}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]="ebe25271-7465-5536-a4d8-ee402b0b3848")}catch{}})();var z9=[...rc],H9=[...oc],km=new Set(ln.filter(e=>e.hidden).map(e=>e.alias)),ES=x_("full").filter(e=>!e.includes(" ")&&!km.has(e)),uU=M(Wo),fU=M(Vo),_U=M(ti),hU=M(ai),AS=zr("restore",De("restore")),TS=zr("history-attest",De("history-attest")),gU=M(si),yU=M(yu),wU=M(wu),vU=M(ii),bU=M(mi),kU=M(ci),SU=M(li),EU=M(ei),Sm=[...new Set(Te.map(e=>e.canonical_argv[0]))],CS=[...new Set(Te.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],B9=new Set(Bo.filter(e=>e.disposition==="package_owned").map(e=>B(e.command))),IS=Te.filter(e=>e.canonical_argv[0]==="history"),AU=IS.map(e=>e.canonical_argv[1]).join(" ");var TU=IS.map(e=>({...e,flags:M(De(e.alias))})),CU=M(Yo),IU=M(Jo,!1),RU=M(di),OU=M(Ir),xU=M(Rr),PU=M(_i),$U=M(ui),LU=M(ri),NU=M(fi),MU=M(pi),FU=M(hi),DU=M(ni),UU=M(oi),jU=M(Qo),GU=M(gi),qU=M(Xo),Em=`${Nn.join(" ")} list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status`;var KU=M(yi),zU=`${KU} bash zsh fish`,Am=qs(bm()),Gs="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",Tm=`${Gs} upgrade`,HU=M(Zo),BU=M(Tr),WU=M(Cr);var VU=M(De("close")),YU=M(De("close-task")),JU=M(De("release")),XU=M(De("claim"));var RS=Mn.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),Cm=[...Ti].join("|"),Im=[...Ti].map(e=>`${e}=*`).join("|"),Rm=[...RS.split(" ").filter(e=>!Ti.has(e)),"-h","-V"].join("|");function qs(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]="dd896f8b-8a4a-54b2-854b-3a8653ed4d18")}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]="c87dfc55-d79e-5210-b74b-8afb6280770c")}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]="bb5fead2-4f62-5056-a07b-30efc42af0dd")}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]="a7cfbd72-3010-53e7-946b-e65842ee4ceb")}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]="7a7096c6-a9c3-5d8e-96e4-ed1b0218234e")}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]="8e9a2374-d190-52e1-8afd-14e1954863f0")}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]="20ef5759-1314-513e-8225-347796637494")}catch{}})();var xo=Symbol("pm.active-extension-host-context");function He(e){return{fullChangedFields:!0,options:e}}var z=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[xo]=!0,n}run(t,n={}){return pj({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}async withItemTransactionContext(t,n=!1){let r=A(this.defaults.cwd??process.cwd(),this.defaults.path),o=async()=>{let a=await jr(r,()=>S(r));return t({pmRoot:r,author:I(this.defaults.author,a.author_default)})};if(this.defaults[xo]===!0||zs.getStore()===!0)return o();let i=()=>aj({...this.defaults,path:r},o);return n?jr(r,i):i()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-4JDWOXNB.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-4JDWOXNB.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,r)=>this.withItemTransactionContext(async o=>(await import("./item-transaction-4JDWOXNB.js")).abandonItemTransaction({...r,...o,transactionId:n}));return{status:n=>this.withItemTransactionContext(async r=>(await import("./item-transaction-4JDWOXNB.js")).readItemTransaction(r.pmRoot,n),!0),abandon:t,supersede:(n,r,o)=>t(n,{...o,supersededBy:r})}}readItemRevision(t){return this.withItemTransactionContext(async({pmRoot:n})=>(await import("./item-revision-B3BIG66B.js")).readItemRevision(t,{pmRoot:n}))}async withExpectedItemRevisions(t,n){let r=await import("./item-revision-B3BIG66B.js"),o="",i=await this.withItemTransactionContext(({pmRoot:s})=>(o=s,r.bindExpectedItemRevisions(t,{pmRoot:s}))),a=this.defaults.noExtensions===!0&&this.defaults[xo]!==!0;return r.runWithBoundItemRevisionScope(i,n,{scopeArgs:["--pm-path",o,...a?["--no-extensions"]:[]]})}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return qy(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return pl(await this.list(ml(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})}async append(t,n,r={}){return M_(r,"append"),await this.runTyped("append",{id:t,...He(gt(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,i={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,r={}){return this.runTyped("schema",{name:n,options:{...r,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={}){let{type:r,...o}=n;return this.runTyped("schema",{name:t,options:{...o,fieldType:r,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}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}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,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...i===void 0?{}:{reorderTo:i},options:gt(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",He(t))}update(t,n={}){return this.runTyped("update",{id:t,...He(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,...He(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...He(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...He(t)})}release(t,n={}){return this.runTyped("release",{id:t,...He(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...He(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...He(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},...He(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...He(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...He(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...He(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 BX(e={},t={}){return new z(t).context(e)}function WX(e={},t={}){return new z(t).list(e)}function VX(e={},t={}){return new z(t).listAllComplete(e)}function YX(e,t={},n={}){return new z(n).search(e,t)}function JX(e,t={},n={}){return new z(n).get(e,t)}function XX(e={},t={}){return new z(t).next(e)}function QX(e={},t={}){return new z(t).aggregate(e)}function ZX(e,t={},n={}){return new z(n).comments(e,t)}function eQ(e,t={},n={}){return new z(n).notes(e,t)}function tQ(e,t={},n={}){return new z(n).learnings(e,t)}function nQ(e,t={},n={}){return new z(n).files(e,t)}function rQ(e,t={},n={}){return new z(n).filesDiscover(e,t)}function oQ(e,t={},n={}){return new z(n).docs(e,t)}function iQ(e,t={},n={}){return new z(n).deps(e,t)}function aQ(e,t={},n={},r={}){return new z(r).graph(e,t,n)}function sQ(e,t,n={},r={}){return new z(r).append(e,t,n)}function cQ(e={},t={}){return new z(t).create(e)}function lQ(e,t={},n={}){return new z(n).update(e,t)}function dQ(e,t,n={},r={}){return new z(r).reopen(e,t,n)}function mQ(e,t,n={},r={}){return new z(r).close(e,t,n)}function pQ(e,t={},n={}){return new z(n).claim(e,t)}function uQ(e={},t={}){return new z(t).claimNext(e)}function fQ(e,t={},n={}){return new z(n).release(e,t)}function _Q(e,t={},n={}){return new z(n).copy(e,t)}function hQ(e,t={},n={}){return new z(n).delete(e,t)}function gQ(e,t,n={},r={}){return new z(r).restore(e,t,n)}function yQ(e,t={},n={}){return new z(n).focus(e,t)}var $S=Vu(),zs=new ij;function Ks(){Ic(fp()),Rc(_p()),Oc(hp()),xc(gp()),Pc(yp()),$c(wp()),Lc(vp())}async function MS(e,t,n,r){return Cc(()=>t===void 0?$S.read(()=>LS(e,n,r)):$S.write(()=>lj(t,()=>LS(e,n,r))))}async function aj(e,t){let n=e.cwd;if(zs.getStore()===!0&&n===void 0&&e.noExtensions===!0){let o=A(process.cwd(),e.path);return Cc(()=>Oa({pmRoot:o},t))}let r=n??process.cwd();return MS(pa({path:e.path,noExtensions:e.noExtensions}),n,r,()=>zs.run(!0,t))}function sj(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:v_(e);return typeof n=="string"?n:"Unknown failure"}catch{return"Unknown failure"}}async function LS(e,t,n){let r=A(t,e.path);if(e.noExtensions)return Ks(),Oa({pmRoot:r},()=>n(null));if(!await H(ie(r)))return Ks(),n(null);let o=null,i;try{let a=await S(r),s=await Er({pmRoot:r,settings:a,cwd:t,noExtensions:!1}),c=await Ar({...s,loaded:s.loaded});i={loadResult:s,activationResult:c},Ic(c.hooks),Rc(c.commands),Oc(c.parsers),xc(c.preflight),Pc(c.services),$c(c.renderers),Lc(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:s.loaded}}catch(a){Ks(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",sj(a))}try{return await Oa({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Ks(),i&&await wc(i.loadResult,i.activationResult).catch(()=>{})}}function FS(e,t){let n=Xn(e);return t?.registrations.commands.find(r=>Xn(r.action)===n)?.command??t?.commands.handlers.find(r=>Xn(r.command)===n)?.command}async function cj(e,t,n,r,o){if(!o)throw new d(`Unsupported native pm action: ${e}`,m.USAGE);let i=FS(e,o);if(!i)throw new d(`Unsupported native pm action: ${e}`,m.USAGE);let a=typeof n.author=="string"?n.author:r.author,s=cl(i),c=C_(ll(t,n),T_(o.registrations,s),s),l=await Ai({command:s,args:be(n.args??t.args),options:c,global:{...r,author:a},pm_root:o.pmRoot,sdk:My(o.pmRoot,z.forActiveExtensionHost({pmRoot:o.pmRoot,author:a}),a,s)});if(!l.handled){if(Object.hasOwn(l,"cause"))throw ra(i,l);let p=l.warnings.length>0?` (${l.warnings.join(", ")})`:"";throw new d(`Unsupported native pm action: ${e}${p}`,m.USAGE)}return l.result}async function lj(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function dj(e){let t=Ne(e,"action"),n=Xn(t),r=Pn(zy,n),o=r?.action??n,i={...e,action:o};return r?.options!==void 0&&(i.options={...r.options,...vr(e.options)}),o==="package"&&(i.options={...vr(i.options),vocabulary:"package"}),{action:o,args:i}}function mj(e,t,n,r){let o=e[xo]===!0,i=t.noExtensions===!0&&!o?["--no-extensions"]:[];if(n!==void 0)return["--pm-path",A(r,t.path),...i];let a=dt(t,r);return[...t.noExtensions===!0?a.slice(0,-1):a,...i]}async function pj(e){let t=dj(e),n=pa(t.args);Ju(n);let r=B_(t.action),o=v(t.args,"cwd"),i=o??process.cwd();t.action==="init"&&(n[Nl]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=A(i,n.path));let{expectHash:a,dispatchArgs:s}=J_(t.args),c=async l=>{if(a===void 0)return NS(t.action,s,n,l);let{dispatchWithExpectedItemRevisions:p}=await import("./item-revision-B3BIG66B.js");return p({action:t.action,expectHash:a,defaultId:v(s,"id")??v(vr(s.options),"id"),options:vr(s.options),background:s.background,pmRoot:A(i,n.path),invocation:{scopeArgs:mj(e,n,o,i),...n.outputFormat===void 0?{}:{outputArgs:["--output-format",n.outputFormat]}},run:()=>NS(t.action,s,n,l)})};try{return t.action==="history-attest"?await c(null):e[xo]===!0||zs.getStore()===!0?await c(null):await MS(n,o,i,l=>c(l))}finally{r&&vm()}}async function NS(e,t,n,r){let o=sl(t,e);if(e==="create"||e==="update"){let{assertNativeMutationOptions:p}=await import("./mutation-admission-577MXOGD.js");await p(e,t,o,n.path,z_[e])}let i=Pn(bS,e),a=i?void 0:FS(e,r),s=a===void 0?e:`extension:${a}`;tf(s,o),rf(s,o);let c={action:e,args:t,options:o,id:v(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},l=i?await i(c):await cj(e,t,o,n,r);if(e==="history-attest")return l;{let p=lf(s,o,l);return await Ny(A(process.cwd(),n.path),p),p}}var uj={closeManyOptionsFromFlat:fa,extensionOptionsFromArgs:ll,globalOptions:pa,mutationListOptions:W_,normalizeActionName:Xn,normalizeCommandPath:cl,normalizeMcpUpdateOptions:Y_,normalizeMcpOptionsArrays:H_,optionsWithAuthor:sl,readRequiredString:Ne,readScalarString:G_,readScalarStringAllowBlank:q_,readStringArray:be,updateManyOptionsFromFlat:_a,withAddNoteOption:Vr,withFilesDiscoveryOptions:ua,withMutationCompaction:ye};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=uj);export{Sl as a,zE as b,QE as c,Zg as d,TG as e,ey as f,CG as g,IG as h,ly as i,kA as j,z as k,BX as l,WX as m,VX as n,YX as o,JX as p,XX as q,QX as r,ZX as s,eQ as t,tQ as u,nQ as v,rQ as w,oQ as x,iQ as y,aQ as z,sQ as A,cQ as B,lQ as C,dQ as D,mQ as E,pQ as F,uQ as G,fQ as H,_Q as I,hQ as J,gQ as K,yQ as L,aj as M,pj as N};
44
+ //# sourceMappingURL=chunk-6TJXTKZD.js.map