@unbrained/pm-cli 2026.11.26 → 2026.11.27

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 (112) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli-bundle/bundle-manifest.json +1 -1
  3. package/dist/cli-bundle/chunks/{chunk-LNZKNVMT.js → chunk-5CMR4R5V.js} +2 -2
  4. package/dist/cli-bundle/chunks/{chunk-7F3UFYZA.js → chunk-5M7UTO2G.js} +2 -2
  5. package/dist/cli-bundle/chunks/{chunk-B2GM6KOM.js → chunk-63AVXDZS.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-NDS4MXZX.js → chunk-66TNCHHG.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-5AAIRHNE.js → chunk-6NJ3BONB.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-HTGN24XM.js → chunk-AVHRMUXJ.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-KCRRTJ4X.js → chunk-HTT52JL3.js} +37 -37
  10. package/dist/cli-bundle/chunks/{chunk-GQXK4KKH.js → chunk-J25DZRYJ.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-QMM46SJM.js → chunk-J6TFG34A.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-IGW3RVJC.js → chunk-JX475QVU.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-MNFCJNQA.js → chunk-KP75JTTO.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-T3GJPXIZ.js → chunk-KS47NGMQ.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-PQSEEVOA.js → chunk-O23KTJL6.js} +5 -5
  16. package/dist/cli-bundle/chunks/{chunk-KES4VHU4.js → chunk-OFX2VA5Z.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-HOLQZ56F.js → chunk-QVDEZBSV.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-BITDGTAX.js → chunk-SIRZ4VMT.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-XRCE4QNL.js → chunk-VC4BJIA7.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-FWBR3OW7.js → chunk-W7SPEGSP.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-WY7467RY.js +3 -0
  22. package/dist/cli-bundle/chunks/{chunk-5FY2VHRF.js → chunk-X6TE47CS.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-5BPDT7G2.js → chunk-XB6QEVUK.js} +2 -2
  24. package/dist/cli-bundle/chunks/chunk-XYX4CXFR.js +2 -0
  25. package/dist/cli-bundle/chunks/{chunk-ZDL45VTB.js → chunk-Y5U7QCNX.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-CBBKXTJG.js → chunk-YGK6SA7P.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-DYL2N3OC.js → chunk-ZGV4ZXDS.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-WZOJSHJT.js → chunk-ZILIHDDY.js} +41 -41
  29. package/dist/cli-bundle/chunks/{field-option-collisions-CGRJEAPQ.js → field-option-collisions-UL6BIPAK.js} +2 -2
  30. package/dist/cli-bundle/chunks/{item-revision-FGDR5NSF.js → item-revision-WNUDY5DM.js} +2 -2
  31. package/dist/cli-bundle/chunks/item-transaction-ER3OWOPV.js +2 -0
  32. package/dist/cli-bundle/chunks/{mutation-actor-HGG47KXV.js → mutation-actor-SFYTD2ZB.js} +2 -2
  33. package/dist/cli-bundle/chunks/{mutation-admission-LLHIRY6O.js → mutation-admission-AVOOT3KH.js} +2 -2
  34. package/dist/cli-bundle/chunks/{register-list-query-EKSCZWEZ.js → register-list-query-Q7UW2EPV.js} +2 -2
  35. package/dist/cli-bundle/chunks/{register-mutation-ZIAOKKUJ.js → register-mutation-YNW7E3T4.js} +2 -2
  36. package/dist/cli-bundle/chunks/{register-operations-ECVBZ5FM.js → register-operations-DAUTQCIO.js} +2 -2
  37. package/dist/cli-bundle/chunks/{register-setup-3QYD5H4H.js → register-setup-VSURGF7V.js} +2 -2
  38. package/dist/cli-bundle/chunks/{stage-RSCSUYEJ.js → stage-N5GDBS5A.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-AAB3ZR7Z.js → chunk-24W63UPP.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-AVLB4L7M.js → chunk-2XGHBYDA.js} +5 -5
  41. package/dist/cli-bundle/focused-chunks/{chunk-JUG3BAZZ.js → chunk-3QRMY6KF.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-RDELKGLS.js → chunk-4HLZOOZI.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/chunk-52PHSTGP.js +27 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-QNWNUQSJ.js → chunk-7FKGIJEB.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-QSRXF6XS.js → chunk-7GZMOLQY.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-GQBWI4KA.js → chunk-AL47ODFZ.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-KEZ4VXYD.js → chunk-AN4NFFLL.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-FW5Q26HA.js → chunk-B2HJI6KA.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-YNRW2FWB.js → chunk-C2HW7BSE.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-IWEGGRRD.js → chunk-GISZWMBS.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-3GQRWIT5.js → chunk-GUAT4OAC.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-3BR5NWQI.js → chunk-H4JBS477.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-NSFS3VWP.js → chunk-HGJ4MILN.js} +37 -37
  54. package/dist/cli-bundle/focused-chunks/{chunk-NXUFVQ33.js → chunk-HSWL6L2O.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-RMJKVQYE.js → chunk-I4GY7HAP.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-UA2JNKMY.js → chunk-KMG4O2IU.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-YSZZSV6M.js → chunk-N7ZAMULP.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-TNVLDU7Z.js → chunk-REORRDPH.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{chunk-WHHFPATO.js → chunk-SXWUKNTY.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-FQWKESMI.js → chunk-UGQ2EXTU.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/chunk-YPOATPTX.js +3 -0
  62. package/dist/cli-bundle/focused-chunks/{chunk-VV2QF5IE.js → chunk-ZZYJS74B.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{field-option-collisions-WV6GPYYP.js → field-option-collisions-BP7ILGQK.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{item-revision-RPTXN7WW.js → item-revision-NOHVIOQQ.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{item-transaction-A6MVNPT7.js → item-transaction-O26COBOJ.js} +2 -2
  66. package/dist/cli-bundle/focused-chunks/{mutation-actor-6ZVW6OME.js → mutation-actor-HVJV5S76.js} +2 -2
  67. package/dist/cli-bundle/focused-chunks/{mutation-admission-2DA4CINP.js → mutation-admission-JRICEVYN.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{stage-RG3PKST7.js → stage-NSX6ASBZ.js} +2 -2
  69. package/dist/cli-bundle/main.js +2 -2
  70. package/dist/cli-bundle/sdk-authoring.js +1 -1
  71. package/dist/cli-bundle/sdk-contracts.js +1 -1
  72. package/dist/cli-bundle/sdk-core.js +1 -1
  73. package/dist/cli-bundle/sdk-governance.js +1 -1
  74. package/dist/cli-bundle/sdk-graph.js +1 -1
  75. package/dist/cli-bundle/sdk-merge.js +51 -51
  76. package/dist/cli-bundle/sdk-query.js +1 -1
  77. package/dist/cli-bundle/sdk-runtime.js +1 -1
  78. package/dist/cli-bundle/sdk-testing.js +1 -1
  79. package/dist/cli-bundle/sdk.js +1 -1
  80. package/dist/core/extensions/index.js +1 -1
  81. package/dist/core/shared/command-line.d.ts +2 -2
  82. package/dist/core/shared/command-line.js +1 -1
  83. package/dist/core/shared/secret-rules.js +5 -5
  84. package/docs/CONFIGURATION.md +1 -1
  85. package/docs/MUTATION_INTEGRITY.md +47 -0
  86. package/docs/SDK.md +3 -1
  87. package/marketplace.json +1 -1
  88. package/package.json +1 -1
  89. package/packages/pm-beads/package.json +1 -1
  90. package/packages/pm-calendar/package.json +1 -1
  91. package/packages/pm-command-kit/package.json +1 -1
  92. package/packages/pm-digital-twin/package.json +1 -1
  93. package/packages/pm-governance-audit/package.json +1 -1
  94. package/packages/pm-guide-shell/package.json +1 -1
  95. package/packages/pm-kanban/package.json +1 -1
  96. package/packages/pm-lifecycle-hooks/package.json +1 -1
  97. package/packages/pm-linked-test-adapters/package.json +1 -1
  98. package/packages/pm-search-advanced/package.json +1 -1
  99. package/packages/pm-templates/package.json +1 -1
  100. package/packages/pm-todos/package.json +1 -1
  101. package/packages/pm-vcs/package.json +1 -1
  102. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  103. package/plugins/pm-claude/package.json +1 -1
  104. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  105. package/plugins/pm-codex/package.json +1 -1
  106. package/plugins/pm-codex/plugin.json +1 -1
  107. package/runtime-dependencies.json +1 -1
  108. package/dist/cli-bundle/chunks/chunk-DUJSME77.js +0 -3
  109. package/dist/cli-bundle/chunks/chunk-RFK3ERYX.js +0 -2
  110. package/dist/cli-bundle/chunks/item-transaction-C3KAMEYO.js +0 -2
  111. package/dist/cli-bundle/focused-chunks/chunk-R6QFPHWW.js +0 -3
  112. package/dist/cli-bundle/focused-chunks/chunk-RFJ3MEFP.js +0 -27
@@ -1,5 +1,5 @@
1
- import{A as Ad,B as Ch,C as Th,n as Tf,o as Mi,p as Pf,q as Lf,r as Ui,s as Wr,t as Mc,u as Dc,v as ji,y as G_,z as q_}from"./chunk-RDELKGLS.js";import{a as Rh,f as xh,h as kn,m as Ih,o as ao,r as ws,s as Oh,t as $h,x as Ph}from"./chunk-KEZ4VXYD.js";import{$ as $g,A as dg,Ab as gy,Bb as yy,Cb as fr,Db as qd,Eb as wy,Ga as Gg,Ha as qg,Hb as Fs,I as _g,Ia as Kg,J as hg,Ja as zg,K as gg,Ka as Hg,L as yg,La as Bg,M as wg,Ma as Wg,N as vg,Na as An,O as bg,Oa as Vg,Ob as vy,P as kg,Pa as Yg,Pb as by,Q as Sg,Qa as Jg,Qb as ky,R as Ag,Ra as Os,S as Eg,Sa as Xg,T as Cg,Ta as Qg,U as Tg,Ua as Zg,Ub as Sy,V as Rg,Va as ey,Vb as Fy,W as xg,Wa as ry,X as Ig,Xa as $s,Y as Og,Ya as en,Z as $d,Za as oy,_ as mr,_a as Ps,aa as Pg,bb as wo,g as tg,h as ng,ia as Lg,ib as iy,jb as sy,ka as Fg,kb as ay,la as Nd,lb as cy,ma as Fd,mb as dy,na as Mg,nb as ly,oa as Dd,ob as Ls,pb as jd,qa as Dg,qb as my,ra as Ug,rb as Gd,sa as Ud,sb as pr,tb as uy,ub as py,vb as fy,wb as _y,xb as hy,yb as vo,zb as Ns}from"./chunk-FQWKESMI.js";import{a as ug}from"./chunk-IIP6LZ5E.js";import{h as vt,i as En,m as ny}from"./chunk-IWEGGRRD.js";import{a as yo,b as lg,c as xs,h as pg,i as fg}from"./chunk-YSZZSV6M.js";import{c as Od}from"./chunk-4SX2BN4V.js";import{c as mg}from"./chunk-AIDL2ZNT.js";import{A as zh,B as uo,C as Hh,D as Bh,E as Rd,F as po,G as As,H as dr,I as Wh,J as xd,K as Se,L as Id,M as ve,N as Vh,O as Yh,P as Es,R as Jh,S as Cs,T as Xh,a as vs,b as co,c as bs,d as Ne,e as ks,f as Lh,g as Nh,h as Ss,i as lo,j as Fh,k as Mh,l as Ed,m as Cd,n as yt,o as Dh,p as Uh,q as jh,r as mo,s as Gh,t as Td,u as wt,v as b,w as qh,x as Kh,z as Ke}from"./chunk-QNWNUQSJ.js";import{e as Af,g as Ef,h as Cf,l as $f}from"./chunk-3GQRWIT5.js";import{a as xf,c as If,m as j_}from"./chunk-RMJKVQYE.js";import{S as N_,T as cd,U as F_,V as Xi,W as dd,X as M_,Y as D_,a as lp,b as mp,c as up,d as pp,da as ld,f as fp,ha as U_}from"./chunk-TNVLDU7Z.js";import{a as sg,b as ag,c as Ms,d as Ds,e as Us}from"./chunk-NXUFVQ33.js";import{K as jg,b as cg}from"./chunk-JUG3BAZZ.js";import{$a as Ny,A as Iy,Aa as ko,B as Oy,C as $y,Ca as Bd,Ha as Wd,Ja as Py,Ya as So,_a as Ly,b as ig,e as Pd,g as Ld,i as Md,j as bo,l as Ay,m as Ey,n as Kd,q as Cy,r as zd,va as Hd,x as Ty,y as Ry,z as xy}from"./chunk-QSRXF6XS.js";import{T as Is,Y as ur,h as Ts,k as Zh,l as fo,o as eg,w as Lt,y as rg,z as og}from"./chunk-UA2JNKMY.js";import{a as go,b as Sn,d as ty}from"./chunk-FW5Q26HA.js";import{$ as J_,$a as hh,A as _e,B as es,Bb as wh,C as ud,D as rt,E as H_,F as pd,Fb as vh,G as B_,H as ue,J as Ot,Jb as cr,K as W_,Kb as bh,L as ts,Lb as kd,M as Vt,Mb as kh,N as ge,Nb as Sh,O as or,Ob as Ah,P as fd,Q as to,R as _d,Rb as Sd,S as no,Sb as Eh,T as $t,U as V_,V as ns,W as rs,X as os,Y as is,Ya as io,Z as ss,_ as Y_,_a as _h,aa as X_,ab as gs,bb as ys,c as bf,cb as gh,ea as as,f as kf,fa as cs,g as Sf,i as Fi,ia as ls,j as zt,ja as ms,k as Jn,ka as th,l as Nf,la as us,m as Ff,ma as ps,n as K_,na as Jt,p as ht,pa as gd,q as gt,qa as fs,r as tr,rb as yh,s as md,sa as nh,t as z_,ta as rh,u as Wt,ua as oo,v as nr,w as Qi,x as rr,y as Zi}from"./chunk-RFJ3MEFP.js";import{$ as qr,$a as Ri,Aa as rf,B as Nc,Ba as of,C as Fc,Ca as sf,D as vp,E as Vn,Ea as af,F as li,Fa as cf,G as mi,Ga as df,H as bp,Ha as lf,I as kp,Ia as mf,J as Sp,Ja as uf,K as Ap,Ka as wi,L as Ep,La as vi,M as ui,Ma as bi,N as Cp,Na as pf,O as Tp,Oa as ff,P as Rp,Pa as ki,Q as pi,Qa as _f,R as xp,Ra as hf,S as Ip,Sa as gf,T as Op,Ta as Si,U as $p,Ua as Ai,V as fi,Va as Ei,W as _i,Wa as Ci,X as Pp,Xa as Hr,Y as hi,Ya as yf,Za as Ti,_ as Lp,_a as Br,aa as Np,ab as xi,b as _p,ba as Fp,bb as Ii,c as hp,ca as Mp,cb as Oi,d as gp,da as Dp,db as wf,ea as Kr,eb as Kt,fa as Up,fb as $i,ga as jp,gb as Pi,ha as Gp,hb as Li,i as $c,ia as qp,ib as Ni,ja as Kp,ka as zp,la as Hp,lb as vf,ma as Bp,na as Wp,nb as Ge,o as Pc,oa as Vp,ob as M,p as yp,pa as Yp,qa as zr,ra as Jp,s as di,sa as Xp,t as Lc,ta as gi,u as pn,ua as yi,va as Qp,w as wp,wa as Zp,xa as ef,ya as tf,za as nf}from"./chunk-GQBWI4KA.js";import{A as Ng,a as _o,b as ho,c as lr,d as st,i as Rs}from"./chunk-YNRW2FWB.js";import{d as Qh}from"./chunk-3BR5NWQI.js";import{D as Xt,F as Qt,H as j,I as te,J as mh,L as ye,M as uh,N as bn,O as it,P as ph,Q as Zt,R as we,S as fh,T as bd,Y as so,b as Ue,c as oi,d as ii,e as Pe,f as Q_,g as Z_,h as Yt,j as Le,k as ro,l as wn,m as ah,n as sr,o as ar,p as ch,v as vn,x as hs}from"./chunk-VV2QF5IE.js";import{b as hd,e as eh,f as ds,g as ot,i as _s,k as oh,l as ir,n as ih,o as Pt,p as yd,q as wd,r as sh,s as A,t as xe,v as dh,w as vd,x as lh,y as O}from"./chunk-WHHFPATO.js";import{a as Ji,b as L_}from"./chunk-X6CXWWNB.js";import{$a as cp,$f as er,Ad as qe,Ba as xc,Bb as qc,Bd as Bt,Be as Yi,Ca as Zu,Cd as Wi,Da as Ic,E as mt,Eb as de,Ee as b_,F as qu,Fb as _n,Fc as hn,Fe as ke,Gb as le,Gc as R,Ge as k_,H as Cc,Hb as Kc,Hc as t_,Hd as f_,I as Fr,Ib as zc,Jb as Hc,Jd as __,Ke as S_,L as Tc,Lb as Wf,Lc as n_,M as Mr,Md as h_,N as Oe,Nb as Bc,Oa as ep,Pa as tp,Pb as Vf,Pe as ad,Pf as x_,Q as $,Qa as np,Qb as Yf,Qc as r_,R as Ce,Ra as rp,Rb as Jf,Rc as Yc,Rd as g_,S as si,Sa as op,Sb as Wc,Sc as Xr,Sd as y_,T as Bn,Ta as ip,Tb as Xf,Tc as Qr,U as Dr,Ua as sp,Ub as ut,Uc as Jc,Ud as w_,V as Ku,Vb as pt,Vc as _t,W as E,Wa as Ur,Wc as Zr,Wd as v_,X as ai,Xc as eo,Xf as I_,Y as $e,Ya as ap,Yf as O_,Z as ce,_ as Et,_c as o_,a as Tu,aa as Ze,ab as dp,ac as Qf,ae as Zc,ba as ci,cd as i_,ce as ed,da as Wn,dc as Yr,de as td,dg as $_,ec as ft,ee as nd,fe as rd,gd as s_,ge as od,h as Fu,hb as jr,he as id,hf as A_,ib as Oc,ie as sd,if as E_,jb as Gr,jd as a_,je as I,kd as c_,kg as P_,lc as Hi,ld as Xc,le as Qn,mc as Zf,me as gn,nc as e_,ne as Z,nf as C_,o as Mu,oa as zu,ob as Mf,oc as Jr,od as Qc,of as T_,pa as Hu,pc as Bi,q as Du,qa as Bu,qd as d_,qe as yn,qf as R_,ra as Wu,re as Zn,s as Uu,sa as Vu,sd as l_,ta as Yu,td as m_,u as ju,ua as Rc,v as Gu,va as Ju,vb as It,vd as u_,ve as Vi,wd as p_,xa as Xu,xe as Re,ya as Qu,zb as zi,zc as Vc}from"./chunk-NSFS3VWP.js";import{A as se,B as Df,C as P,F as fn,G as Uc,H as Uf,I as Xn,J as jf,K as Vr,L as Gf,O as qf,P as jc,Q as Kf,R as Gc,S as zf,T as qi,V as Hf,W as Bf,X as Ki,c as Ct,d as ie,k as Te,m as V,o as un,u as C,y as Gi}from"./chunk-R6QFPHWW.js";import{C as Rf,F as Tt,J as Di,K as Rt,L as Ht,M as Of,O as D,P as xt,Q as et,S as Yn,a as _c,c as hc,d as gc,h as ni,i as St,j as Lr,k as Nr,l as yc,n as Ru,o as xu,p as Iu,q as Ou,s as $u,t as Pu,u as wc,v as vc,w as bc,x as kc,y as Sc,z as Ac}from"./chunk-OCKKIECS.js";import{A as l,C as W,D as At,E as je,F as oe,I as ae,K as Hn,m as ri,s as Ec,u as Lu,x as mn,y as Nu,z as m}from"./chunk-NGFDPEP7.js";import{readFile as LE}from"node:fs/promises";import NE from"node:path";var Vd="context-intents.json";function js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function FE(e,t,n){if(!js(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 My(e,t){let n=Array.isArray(e)?e:js(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)=>FE(r,t,o))}async function ME(e){let t=NE.join(e,Vd),n;try{n=await LE(t,"utf8")}catch(o){if(At(o))return[];throw await lh(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Vd}: ${i}`,{cause:o})}return My(r,Vd)}function DE(e){if(!js(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return js(n)?n.contextIntents??n.context_intents:void 0}function UE(e){return e.flatMap(t=>{let n=DE(t.module);return n===void 0?[]:My(n,`package ${t.name}`)})}async function jE(e){let t=await ME(e.pmRoot),n=UE(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Yd(e,t){let n=await jE(e);return await O_(n,t)}import{createHash as sC}from"node:crypto";import{readFileSync as aC}from"node:fs";import{readFile as GE}from"node:fs/promises";function Tn(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,ue(e,t)}function qy(e){return Object.prototype.toString.call(e)==="[object Object]"}function qE(e,t,n,r){let o=C();if(!qy(e))return{...r({created_at:o,author:n,text:t}),text:t,edited_at:o};let i=s=>typeof s=="string"&&s!=="";return{...e,...i(e.created_at)?{}:{created_at:o},...i(e.author)?{}:{author:n},text:t,edited_at:o}}function Dy(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function Jd(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Cn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function _r(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 i=_e(n,"--add");return Object.keys(i).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:i.text?.trim()||n}catch{return n}}function Xd(e){return typeof e=="object"&&e!==null&&"code"in e}function Eo(e,t){if(!Ot(e))throw new l(`${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 KE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let r=Vt(),o=Ot(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",o)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return Eo(e,"--stdin"),{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",m.USAGE);if(i==="-")return Eo(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await GE(i,"utf8"),emptyFlag:"--file"}}catch(s){if(Xd(s)&&At(s))throw new l(`--file path not found: ${i}. Use --file - to read stdin.`,m.USAGE);let a=s instanceof Error?s.message:String(s);throw new l(`Failed to read --file path "${i}": ${a}. Use --file - to read stdin.`,m.USAGE)}}async function qs(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("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 l("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--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 l("--edit must be a positive integer",m.USAGE);let n=await KE(e,t);if(e.edit!==void 0){if(!n)throw new l("--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 Ao(e,t){throw e instanceof l&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Ky(e){return e==="comments"?"--stdin":"--add -"}function zE(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function HE(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function BE(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=HE(t),o=Ky(e.collectionKey),i=e.retryArgs===void 0?{}:{field:e.textFlag,recovery:{suggested_flags:[t],suggested_retry:P(e.retryArgs),suggested_retry_args:[...e.retryArgs]}};if(r!==void 0){let s=r.split(/[ =]/,1)[0],a=s==="--file"?"that file":"stdin",c=e.conflictingOperand===void 0?"":` "${e.conflictingOperand}" was read as positional text, which ${s} cannot be combined with: drop it, or pass it as the text without ${s}.`;return new l(`${e.textFlag} value "${t}" looks like an option, not annotation text: ${e.textFlag} took ${s} 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 ${a} 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 l(`${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 WE(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!zE(e)))throw BE({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function VE(e,t,n,r,o){if(n.input.mode!=="edit")return;let i=dp(t);if(i===void 0)return;let s=n.collectionKey.replace(/s$/,""),a=n.input.index,c=ke(r)[0]==="--pm-path"?["--pm-path",o]:[];throw new l(`Replacement text for ${s} ${a} on ${e} ends with the read-output compaction marker, so it was copied from a compacted read that left out ${i} characters. Nothing was written.`,m.USAGE,{code:"annotation_text_compacted",item_id:e,details:{collection:n.collectionKey,entry_index:a,omitted_characters:i},required:`Read the whole ${s} with --output-budget unbounded, apply the change to the full text, and retry the edit without the trailing marker.`,why:"A budgeted read shortens long entries to a prefix plus a marker naming how many characters it left out; editing from that text would replace the stored entry with the shortened prefix.",examples:[P([...c,n.collectionKey,e,"--output-budget","unbounded","--json"]),`${P([...c,n.collectionKey,e,"--edit",String(a),"--file"])} <full-text-file>`]})}function YE(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new l(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,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(JE(e,t),e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,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> ${Ky(e.collectionKey)}`]})}function JE(e,t){if(t.expectAt!==void 0){if(e.input.mode!=="edit"&&e.input.mode!=="delete")throw new l(`--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 l("--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 Uy(e,t,n,r,o){if(o===void 0)return;let i=t[n]?.created_at,s=typeof i=="string"?i:null;if(s===o)return;let a=t.flatMap((f,h)=>f?.created_at===o?[h+1]:[]),c=r.collectionKey.replace(/s$/,""),d=r.input.mode==="delete"?"--delete":"--edit",u=n+1,p=a.length===1?` The ${c} created at ${o} is at index ${a[0]}.`:a.length>1?` ${a.length} ${r.collectionKey} were created at ${o}: indexes ${a.join(", ")}.`:` No ${c} on ${e} was created at ${o}.`;throw new l(`${c.charAt(0).toUpperCase()}${c.slice(1)} ${u} on ${e} was created at ${s||"an unrecorded time (malformed entry)"}, not ${o}; refusing ${d} of an entry the caller did not read. Nothing was written.${p}`,m.CONFLICT,{code:"annotation_entry_mismatch",item_id:e,details:{collection:r.collectionKey,entry_index:u,expected_created_at:o,actual_created_at:s,matching_indexes:a},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} ${d} ${a.length===1?a[0]:"<index>"} --expect-at ${o}${d==="--edit"?' --add "<text>"':""}`]})}function XE(e,t,n,r,o,i){let s=Cn(e.metadata,t),a=o?s.findIndex(c=>qy(c)&&c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],written:s,position:a}:(s.push(i({created_at:C(),author:n,text:r})),e.metadata[t]=s,{changedFields:[t],written:s,position:s.length-1})}function jy(e,t,n){return Vf.has(e)?t.map((o,i)=>i).sort((o,i)=>Yf(t[o],t[i])||o-i).indexOf(n)+1:n+1}async function hr(e,t,n,r){YE(r,t);let o=E(process.cwd(),n.path);await O(o);let i=await A(o),s=$(i,I()),a=oo(t.limit);if(r.input.mode==="list"){let _=await j(o,e,i.id_prefix,i.item_format,s.type_to_folder);if(!_)throw new l(`Item ${e} not found`,m.NOT_FOUND);let g=await te(_,{schema:i.schema}),y=Cn(g.document.metadata,r.collectionKey);return Gs(_.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=R(t.author,i.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,g;try{g=await we({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let v=Cn(w.metadata,r.collectionKey),k=Gy(r.input.index,v.length,r.collectionKey);return Uy(e,v,k,r,t.expectAt),Dy(v[k],"deleted"),v.splice(k,1),w.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(w){Ao(w,r.conflictGuidance)}let y=Cn(g.item,r.collectionKey);return Gs(g.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let d=r.input.rawValue??r.input.value??"";WE(d,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(VE(e,u,r,n,o),r.input.mode==="edit"){let _=r.editOp??r.op,g,y=0;try{g=await we({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(k){let S=Cn(k.metadata,r.collectionKey),T=Gy(r.input.index,S.length,r.collectionKey);Uy(e,S,T,r,t.expectAt);let x=S[T];return Dy(x,"edited"),S[T]=qE(x,u,c,r.createEntry),y=jy(r.collectionKey,S,T),k.metadata[r.collectionKey]=S,{changedFields:[r.collectionKey]}}})}catch(k){Ao(k,r.conflictGuidance)}let w=Cn(g.item,r.collectionKey),v=y;return Gs(g.item.id,r.collectionKey,w,a,t.includeMeta===!0,{action:"edit",entryIndex:v,entry:w[v-1]},t.fullHistory===!0)}let p,f=0;try{p=await we({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=XE(_,r.collectionKey,c,u,t.ifAbsent===!0,r.createEntry);return f=jy(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(_){Ao(_,r.conflictGuidance)}let h=Cn(p.item,r.collectionKey);return Gs(p.item.id,r.collectionKey,h,a,t.includeMeta===!0,{action:"add",entryIndex:f,entry:h[f-1],changedCount:t.ifAbsent===!0?Math.min(p.changedFields.length,1):void 0},t.fullHistory===!0)}function Gy(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 l(`${o} index ${e??"(missing)"} out of range (item has ${i})`,m.USAGE)}return e-1}function QE(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 zy(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function ZE(e,t){let n=e.length-t.length;return t.map((r,o)=>zy(r,n+o+1))}function Gs(e,t,n,r,o,i,s=!1){let a=i===void 0||s?ZE(n,Jd(n,i!==void 0&&s?void 0:r)):i.entry===void 0?[]:[zy(i.entry,i.entryIndex)],c=i!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...i?.changedCount===void 0?{}:{changed:i.changedCount===1},...[o,i!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...QE(t,i,c)}}function gr(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Nf({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=xt(e.fromStatus,e.statusRegistry)??e.fromStatus,r=xt(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Ff(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,m.USAGE);return`workflow_transition_not_allowed: ${o}`}function Ks(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new l("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",m.USAGE);let n=typeof e.handoff=="string"?xt(e.handoff,t):void 0;if(n===void 0||Yn(n,t)||n===t.in_progress_status)throw new l("--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 l("--handoff requires --message with implementation evidence and the next verification step.",m.USAGE);return n}function Hy(e,t,n,r,o){if(Yn(e.status,r)||!e.assignee?.trim())throw new l("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",s=gr({enforcement:i,typeWorkflows:i==="off"?[]:Jn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),a={from_status:e.status,to_status:t,message:o},c=e.status===t?[]:["status"];return e.status=t,{receipt:a,warnings:s?[s]:[],changedFields:c}}import{AsyncLocalStorage as eC}from"node:async_hooks";function Nt(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:xt("in_progress",e)??e.open_status}var tC="strict",Hs="start_blocked_by_open_dependency";function By(e,t,n){if(t===void 0)return!1;let r=_n(Nt(n),n);return _n(t,n)===r&&_n(e??"",n)!==r}function zs(e,t,n){let r=o=>Le(o.trim(),n).toLowerCase();return r(e)===r(t)}var nC=new Set(["cli:create:blocked_by","cli:update:blocked_by"]);function Qd(e,t,n){if(e.kind!=="blocked_by"||typeof t!="string"||t.trim().length===0)return!1;let r=e.id.trim().toLowerCase();return r===t.trim().toLowerCase()?!0:r===Le(t.trim(),n).toLowerCase()&&nC.has(e.source_kind?.trim().toLowerCase()??"")}function rC(e,t,n){let r=e.dependencies??[],o=r.filter(s=>s.kind==="blocked_by");if(r.some(s=>s.kind!=="blocked_by"&&Uu(s.kind)==="blocked_by"&&zs(s.id,t,n)))return P(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&zs(e.blocked_by,t,n))){let s=o.filter(a=>zs(a.id,t,n));return s.length===1&&s.every(a=>a.id===lr(a.id,n,void 0))?P(["update",e.id,"--dep-remove",`id=${s[0].id},kind=blocked_by`]):P(["get",e.id,"--fields","blocked_by,dependencies"])}return o.filter(s=>zs(s.id,t,n)).every(s=>Qd(s,e.blocked_by,n))?P(["update",e.id,"--unset","blocked_by"]):P(["get",e.id,"--fields","blocked_by,dependencies"])}var oC=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function iC(e,t){try{return(await ty(e)).filter(n=>!n.resolved)}catch(n){let r=so(n)?n.context.code:void 0;if(!t||typeof r!="string"||!oC.has(r))throw n;return r}}async function Wy(e){let t=e.settings.governance.start_blocker_enforcement??tC;if(t==="off")return[];let n=$(e.settings,I()).type_to_folder,r=e.metadata.id,o=await iC({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(s=>s.id).join(",");if(t==="warn")return[`start_with_open_blockers:${r}:${i}`];if(e.force===!0)return[`start_blocker_override:${r}:${i}`];throw new l(`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(s=>s.external!==!0).slice(0,3).map(s=>P(["get",s.id])),rC(e.metadata,o[0].id,e.settings.id_prefix),"pm next"],details:{enforcement:t,open_blockers:o.map(s=>({id:s.id,title:s.title,status:s.status,external:s.external===!0}))}})}async function Bs(e){if(e.requested===!1||!By(e.fromStatus,e.metadata.status,e.registry))return[];let t=await Wy(e),n=Zd.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var Zd=new eC;function Vy(e){return Zd.run({warnings:new Set},e)}async function Yy(e){let t=Zd.getStore();if(t===void 0)return[];let n=By(e.metadata.status,Nt(e.registry),e.registry)?await Wy(e):[];for(let r of n)t.warnings.add(r);return n}var Qy="no_available_next_item";function Zy(e){if(!(e instanceof Error)||e.name!=="PmCliError")return;let t=e.context;if(typeof t!="object"||t===null)return;let n=t.code;return typeof n=="string"?n:void 0}function ew(e,t){return Zy(e)===t}function cC(e){return ew(e,"already_claimed_by")}async function Co(e,t,n,r={}){let o=E(process.cwd(),n.path);await O(o);let i=await A(o),s=D(i.schema),a=R(r.author,i.author_default),c=hn(a),d=r.takeoverStale===!0;lC(d,t);let u=null,p=!1,f={},h,_=[],g=await Zt({pmRoot:o,settings:i,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,resolveHistoryContext:()=>h===void 0?void 0:{stale_claim_takeover:h},async mutate(w,v){let S=w.metadata.assignee??"",T=w.metadata.claim_principal?.trim()||S;if(u=S.trim().length>0?S:null,Yn(w.metadata.status,s)&&!t)throw new l(`Cannot claim terminal item ${w.metadata.id} without --force`,m.CONFLICT);if(u!==null&&T!==c){let J=await dC({pmRoot:o,storageId:v.storageId,metadata:w.metadata,holder:S,author:a,thresholdHours:i.mutation_guard.stale_in_progress_hours,force:t,ifAvailable:r.ifAvailable===!0,takeoverStale:d});if(J.kind==="skip")return p=!0,_.push(`claim_skipped_held_by:${Vr(S)}`),{changedFields:[]};h=J.takeover,_.push(J.warning)}let F={assignee:a,claim_principal:c},L=["assignee","claim_principal"].filter(J=>w.metadata[J]!==F[J]);Object.assign(w.metadata,F);let H=w.metadata.status,{changedFields:B,warnings:Y,...re}=yC(w.metadata,r.start===!0,i,s);return Y.push(...await gC({pmRoot:o,settings:i,metadata:w.metadata,fromStatus:H,registry:s,force:t,start:r.start===!0})),f=re,_.push(...Y),{changedFields:[...L,...B],warnings:_}}}),y=tw(await nw("claim",g.item.id,n,p,()=>Ay({pmRoot:o,settings:i,principal:c,itemId:g.item.id})));return _.push(...y.warnings),{item:Uc(g.item),changed_fields:g.changedFields,claimed_by:p&&u!==null?fn(u):a,previous_assignee:u===null?null:fn(u),forced:t,...p?{skipped:!0}:{},..._.length>0?{warnings:_}:{},...el("suggestions",y.suggestions),...f,...h===void 0?{}:{takeover:h}}}async function dC(e){if(e.ifAvailable&&!e.takeoverStale)return{kind:"skip"};if(e.force)return{kind:"take",warning:`claim_takeover:${Vr(e.holder)}->${e.author}`};let t=await Cy(e.pmRoot,e.storageId,e.holder,{updated_at:e.metadata.updated_at,threshold_hours:e.thresholdHours}),n=e.takeoverStale?mC(t,e.author):void 0;if(n!==void 0)return{kind:"take",warning:`claim_stale_takeover:${n.previous_holder}->${e.author}:idle_hours=${n.idle_hours}`,takeover:n};if(e.takeoverStale&&e.ifAvailable)return{kind:"skip"};throw fC(e.metadata.id,t,e.takeoverStale)}function lC(e,t){if(!(!e||!t))throw new l("--takeover-stale cannot be combined with --force",m.USAGE,{code:"ambiguous_option_combination",required:"Pass --takeover-stale to take over only an idle claim, or --force for a coordinated unconditional takeover.",nextSteps:["Drop --force to let the stale-work policy decide, or drop --takeover-stale for a coordinated override."]})}function mC(e,t){let n=e.activity;if(n.stale_policy.stale)return{previous_holder:e.holder,new_holder:t,claimed_at:e.since,last_activity_at:n.last_activity_at,idle_hours:n.idle_hours,threshold_hours:n.stale_policy.threshold_hours,policy:n.stale_policy.setting}}var uC={claim_record_unavailable:"no original history record shows when the holder took it",discarded_history_tail:"a history salvage after the claim discarded a record whose time is unknown",rewritten_history:"a history repair, redaction or merge reconcile after the claim rewrote its records",workspace_restored:"a workspace snapshot restore at or after the claim may have replaced the holder's work"};function pC(e,t){return t.history_unreadable===!0?{reason:"its history stream could not be read, so idleness cannot be established",nextStep:`Repair the history stream of ${e} (pm history ${e} --verify), then retry --takeover-stale.`}:t.unproven_activity!==void 0?{reason:`${uC[t.unproven_activity]}, so idleness cannot be proven`,nextStep:`Ask the holder to release ${e} (pm release ${e}); a new claim starts a provable record.`}:t.stale_policy.eligible_at===null?{reason:t.idle_hours===null?"no valid activity time is recorded":`idle ${t.idle_hours}h of ${t.stale_policy.threshold_hours}h`,nextStep:`No eligibility time can be computed for ${e}; inspect pm history ${e}.`}:{reason:`idle ${t.idle_hours}h of ${t.stale_policy.threshold_hours}h`,nextStep:`Retry with --takeover-stale after ${t.stale_policy.eligible_at} if nothing else is recorded on ${e}.`}}function fC(e,t,n){let r=t.activity,o=r.stale_policy,i={item_id:e,claimed_by:t.holder,claimed_at:t.since,claim_source:t.source,claim_activity:r},s="Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",a="Re-run with --force only when taking over the item is coordinated.";if(n){let c=pC(e,r);return new l(`Item ${e} is ${t.phrase}, and its claim is not stale under ${o.setting} (${c.reason}).`,m.CONFLICT,{code:"stale_claim_takeover_refused",...i,required:`The claim must be idle for at least ${o.threshold_hours}h (${o.setting}) before --takeover-stale may take it.`,why:`${s} A stale takeover needs recorded evidence that the claim has been idle for the configured threshold, so an active claim is never taken over.`,nextSteps:[c.nextStep,"Run pm next to pick a different unclaimed item.",a]})}return new l(`Item ${e} is already ${t.phrase}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",...i,why:s,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.",...o.stale?[`Re-run with --takeover-stale: the claim has been idle ${r.idle_hours}h, past ${o.setting}=${o.threshold_hours}.`]:[],a]})}var _C="claim_semantic_attribution_unrecorded";function tw(e){return e?{warnings:[e.warning],suggestions:[e.suggestion]}:{warnings:[],suggestions:[]}}function el(e,t){return t.length>0?{[e]:t}:{}}var hC="release_semantic_attribution_unrecorded";async function nw(e,t,n,r,o){if(!r)try{await o();return}catch(i){let s=Zy(i)??"unexpected_error",a=ke(n);return{warning:e==="claim"?_C:hC,suggestion:`The ${e} of ${t} is saved, but the session attribution that names this agent's active work was not updated (${s}); nothing needs a retry. If ${P([...a,"health"])} reports a stale lock, remove it with ${P([...a,"gc","--scope","locks"])}.`}}}function rw(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new l(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 l("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 gC(e){return e.start?Bs(e):Yy(e)}function yC(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(Yn(e.status,r))throw new l(`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=Nt(r),i=n.governance.workflow_enforcement??"off",s=gr({enforcement:i,typeWorkflows:i==="off"?[]:Jn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:o}),a={from_status:e.status,to_status:o},c=e.status===o?[]:["status"];return e.status=o,{start:a,changedFields:c,warnings:s?[s]:[]}}async function ow(e,t,n={},r={}){if(n.takeoverStale===!0)throw new l("--takeover-stale cannot be combined with --next",m.USAGE,{code:"ambiguous_option_combination",required:"Pass an explicit item id with --takeover-stale; --next only selects work no other author holds.",nextSteps:["Retry as pm claim <id> --takeover-stale for the held item, or drop --takeover-stale to select with --next."]});let o=wC(n.maxAttempts),i=await A(E(process.cwd(),t.path)),s={...n,author:R(n.author,i.author_default)},a=await ko({...r,callerAuthor:s.author,limit:String(o)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return vC(c.slice(0,o),e,t,s)}function wC(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new l("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function vC(e,t,n,r={},o=Co){let i=0,s=[],a=()=>s.length>0?{start_refused:[...s]}:{};for(let c of e){i+=1;try{let d=await o(c.id,t,n,r),u={...d,recommendation:c,attempts:i,available:!0,...a()};if(!d.skipped)return u}catch(d){if(ew(d,Hs)){s.push(c.id);continue}if(!cC(d))throw d}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:R(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:i,...a(),warnings:[Qy]};throw bC(i,s,r.start===!0)}function bC(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 l(r?"No actionable items matched the selection filters":"No actionable item remained available to claim",r?m.NOT_FOUND:m.CONFLICT,{code:Qy,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]}}:{}})}function kC(e){if(e===void 0)return[];let t=e.trim();if(fn(t)===t)return t.startsWith("-")?[`--author=${t}`]:["--author",t]}var iw="release_claim_ended_by_close";function sw(e,t,n,r,o){let i=kC(o),s=i===void 0?void 0:P([...ke(r),"claim",e,"--force",...i]),a=s===void 0||Gf(s)!==s?"Take the item first with a coordinated pm claim --force as the same author only when that takeover is approved.":`Take the item first with a coordinated ${s} only when that takeover is approved.`;return new l(`A close of ${e} already ended your claim, and ${t} has claimed it since; ${n} cannot move or release another holder's claim.`,m.CONFLICT,{code:iw,item_id:e,claimed_by:t,required:`Only the current holder (${t}) can release or hand off ${e}.`,why:"A close ends its holder's claim, so that holder's later release must not change work another principal claimed after it.",nextSteps:[`Ask ${t} to release or hand off ${e}.`,a]})}function aw(e){let t=e.assignee?.trim();return t?e.claim_principal?.trim()||t:void 0}async function cw(e,t,n){let r=E(process.cwd(),t.path),o=await A(r),i=hn(R(n,o.author_default)),s=$(o,I()).type_to_folder,a=await j(r,e,o.id_prefix,o.item_format,s);if(!a)return h=>h();let c=Ze(r,a.id),d=Xy(c),{document:u}=await te(a,{schema:o.schema}),p=aw(u.metadata);if(p!==void 0&&p!==i&&await zd(r,a.id,i))throw sw(a.id,fn(u.metadata.assignee.trim()),"--pause",t,n);let f=Jy(u.metadata,d);return h=>Wi({pmRoot:r,id:a.id,validate:_=>{if(Jy(_.metadata,Xy(c))!==f)throw new l(`${a.id} changed while the pause was judged, so nothing was written.`,m.CONFLICT,{code:SC,item_id:a.id,nextSteps:[`Check the current holder with ${P([...ke(t),"get",a.id])}, reconfirm any override, then re-run the original pause command unchanged.`]})}},h)}var SC="pause_item_changed";function Jy(e,t){return JSON.stringify([aw(e)??null,e.status,e.updated_at,t])}function Xy(e){try{return sC("sha256").update(aC(e)).digest("hex")}catch{return"absent"}}async function wr(e,t,n,r={}){let o=E(process.cwd(),n.path);await O(o);let i=await A(o),s=R(r.author,i.author_default),a=hn(s),c=r.ownershipReleaseBypass===!0,d=null,u=D(i.schema),p=Ks(r,u);if(p!==void 0&&c)throw new l("Ownership-release bypass only clears ownership; it cannot change a handoff status.",m.USAGE);let f,h,_;try{_=await we({pmRoot:o,settings:i,id:e,op:"release",author:s,message:r.message,force:t,bypassAssigneeConflict:c,...c?{}:{callerClaimScope:({storageId:w,callerPrincipal:v})=>zd(o,w,v)},mutate(w,v){if(v.callerClaimScoped===!0){let S=fn(w.metadata.assignee.trim());if(p!==void 0)throw sw(w.metadata.id,S,"--handoff",n,r.author);return h=S,{changedFields:[],warnings:[`${iw}:${w.metadata.id}:${S}`]}}d=w.metadata.assignee??null;let k=p===void 0?void 0:Hy(w.metadata,p,i,u,r.message);return f=k?.receipt,!d&&!w.metadata.claim_principal?{changedFields:[]}:(delete w.metadata.assignee,delete w.metadata.claim_principal,{changedFields:["assignee","claim_principal",...k?.changedFields??[]],warnings:k?.warnings})}})}catch(w){Ao(w,{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."]})}let g=tw(await nw("release",_.item.id,n,!1,()=>Ey({pmRoot:o,principal:a,itemId:_.item.id}))),y=h===void 0?AC(_.item,u):{warnings:[],suggestions:[`A close of ${_.item.id} already ended your claim; ${h} claimed it afterwards and keeps it. The item was not changed.`]};return{item:Uc(_.item),released_by:s,changed_fields:_.changedFields,previous_assignee:d===null?null:fn(d),forced:t,...f===void 0?{}:{handoff:f},...el("warnings",[..._.warnings,...y.warnings,...g.warnings]),...el("suggestions",[...y.suggestions,...g.suggestions])}}function AC(e,t){return _n(e.status,t)===_n(t.in_progress_status,t)?{warnings:["released_unclaimed_in_progress"],suggestions:[`${e.id} remains ${e.status} and unclaimed. If work is paused, run pm release ${e.id} --pause to move it to ${t.open_status}.`]}:{warnings:[],suggestions:[]}}function EC(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 CC(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 TC(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 dw(e=Bi,t=Jr){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 wK(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 lw(e,t=Jr,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let i of t){let s=`${o.agent_harness}\0${i}`,a=r.get(s)??{harness:o.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=o.agent_provenance?.[i];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(s,a)}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 vK(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let u=`${c.agent_harness}\0${d}`,p=o.get(u)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[d];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),o.set(u,p)}let i=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[u])=>d.localeCompare(u)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),s=i.filter(c=>c.entries>=r),a=s.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:s.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:i,failures:a}}function bK(e){let t=[...e].sort((i,s)=>i.ts.localeCompare(s.ts)||i.author.localeCompare(s.author)||i.op.localeCompare(s.op)||i.before_hash.localeCompare(s.before_hash)||i.after_hash.localeCompare(s.after_hash)),n=new Map,r=new Map;for(let i of t){let s=i.agent_episode,a=EC(i),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(i);continue}let u={id:a.id,...s?.label===void 0?{}:{label:s.label},...s?.parent_id===void 0?{}:{parent_id:s.parent_id},source:a.source,entries:[i],children:[]};n.set(c,u),s!==void 0&&r.set(a.id,u)}let o=[];for(let i of n.values()){let s=i.parent_id?r.get(i.parent_id):void 0;s&&CC(i,s,r)?s.children.push(i):o.push(i)}return TC(o),o}var mw=100;function vr(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function RC(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=mw?n:`${n.slice(0,mw-3)}...`}function uw(e){return e.map((t,n)=>`${n+1}. ${RC(t)}`).join("; ")}function xC(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 IC(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function pw(e,t){let n=xC(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 l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,m.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let i=[],s=[];for(let a=0;a<e.length;a+=1)IC(e[a],o)&&(s.push(e[a]),i.push(a+1));if(s.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${uw(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:s,selected_indexes:i,selected_count:s.length,skipped_count:e.length-s.length}}if(r==="only-index"){let o=vr(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${uw(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}}var OC=["setup","test"];function Ie(e){return e.phase==="setup"}function br(e,t){if(e===void 0)return;let n=typeof e=="string"?e.trim().toLowerCase():e;if(n==="setup")return"setup";if(!(n==="test"||n===""))throw new l(`${t} field "phase" must be one of: ${OC.join(", ")}`,m.USAGE,{code:"invalid_argument_value",required:"Use phase=setup for a step that runs before the linked commands, or omit phase for a regular linked test.",examples:['pm test <id> --add "command=npm run build,phase=setup"']})}function Ws(e){return[...e.filter(Ie),...e.filter(t=>!Ie(t))]}function fw(e,t){if(!e.selected.some(i=>!Ie(i)))return e;let n=t.flatMap((i,s)=>Ie(i)?[s+1]:[]);if(n.length===0)return e;let r=e.selected_indexes.filter(i=>!Ie(t[i-1])),o=n.filter(i=>!e.selected_indexes.includes(i));return{...e,selected:[...n,...r].map(i=>t[i-1]),selected_indexes:[...n,...r],selected_count:n.length+r.length,skipped_count:t.length-n.length-r.length,...o.length>0?{setup_indexes:o}:{}}}function _w(e,t,n){if(!Ie(e))return;let r=[...n].filter(o=>o!==t).sort();if(r.length!==0)return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Setup entry runs in the ${t} workspace, but linked commands it prepares run in ${r.join(", ")}, so its output would not reach them. Set workspace_context_mode on the setup entry and the linked commands to one mode.`}}function To(){let e;return{blocked(t){if(e!==void 0)return{command:t.command,path:t.path,status:"skipped",...Ie(t)?{phase:"setup"}:{},error:`Skipped because setup entry "${e.label}" did not pass (${e.outcome}); no later linked command ran.`}},options(t,n){return!Ie(t)||n===void 0?n:{...n,failOnEmptyTestRun:!1,requireAssertionsForPm:!1}},record(t,n){if(!Ie(t))return n;if(n.status==="passed")return{...n,phase:"setup"};let o=n.status==="refused"||n.failure_category==="trust_refusal"||n.failure_category==="setup_failed"?{...n,phase:"setup"}:{...n,status:"failed",phase:"setup",failure_category:"setup_failed",...n.failure_category===void 0?{}:{setup_failure_cause:n.failure_category}};return e={label:t.command??t.path??"<no command>",outcome:o.failure_category??o.status},o}}}function $C(){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,setup_failed:0}}function kr(e){let t=$C();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}var In=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",yo,lg,"FORCE_COLOR"]),Js=/^[A-Za-z_][A-Za-z0-9_]*$/,xn=["schema","tracker","auto","none"],hw=["source","isolated","snapshot"];function Ro(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,m.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1);if(!Js.test(s))throw new l(`${t} env_set key "${s}" is invalid`,m.USAGE);if(In.has(s.toUpperCase()))throw new l(`${t} env_set key "${s}" is reserved for sandbox safety`,m.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function xo(e,t){if(!e)return;let n=cr(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let r of n){if(!Js.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,m.USAGE);if(In.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,m.USAGE)}return n}function Xs(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function Qs(e,t){if(!e)return;let n=e.trim().toLowerCase();if(xn.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${xn.join(", ")}`,m.USAGE)}function On(e,t){if(!e)return;let n=e.trim().toLowerCase();if(hw.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${hw.join(", ")}`,m.USAGE)}function $n(e){if(!e)return;let t=cr(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Sr(e,t,n){let r=$n(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(i){throw new l(`${t} ${n} includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`,m.USAGE)}return r}}function Zs(e,t){if(!e)return;let n=ge(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function ea(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0||a.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function ta(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0||a.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${s}" must be numeric`,m.USAGE);r[s]=c}return Object.keys(r).length>0?r:void 0}var PC=new Set($t);function na(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function LC(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!PC.has(s)){r.push(o);continue}if(Object.hasOwn(n,s))throw t(`provides key "${o}" more than once after case normalization`);n[s]=i}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${$t.join(", ")}.`);return n}function Rn(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 Vs(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(s=>typeof s!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=o.filter(s=>s.length>0);return i.length>0?i:void 0}function gw(e,t,n){let r=Vs(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 Ys(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 NC(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:Ys(n,"timeout_seconds",t),i=r===void 0?void 0:Ys(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 s=o??i;if(!Number.isInteger(s)||s<=0)throw t("timeout_seconds must be a positive integer");return s}function FC(e,t){let n=Rn(e,"scope",t);if(n===void 0)return"project";if(!St.includes(n))throw t(`field "scope" must be one of: ${St.join(", ")}`);return n}function MC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!na(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(!Js.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(In.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 DC(e,t){let n=Vs(e,"env_clear",t);if(n){for(let r of n){if(!Js.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(In.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function UC(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 jC(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=Ys(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 GC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!na(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 qC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!na(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]=Ys(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function KC(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,m.USAGE);if(!na(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${$t.join(", ")}.`);let o=LC(e,r),i=Rn(o,"command",r),s=Rn(o,"cmd",r);if(i!==void 0&&s!==void 0&&i!==s)throw r("command and cmd must match when both are provided");let a=i??s;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=Rn(o,"path",r),d=Rn(o,"pm_context_mode",r);if(d!==void 0&&!xn.includes(d))throw r(`field "pm_context_mode" must be one of: ${xn.join(", ")}`);let u=On(Rn(o,"workspace_context_mode",r),`${n} ${t}`),p=Rn(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:FC(o,r),timeout_seconds:NC(o,r),pm_context_mode:d,workspace_context_mode:u,env_set:MC(o,r),env_clear:DC(o,r),shared_host_safe:UC(o,"shared_host_safe",r),assert_stdout_contains:Vs(o,"assert_stdout_contains",r),assert_stdout_regex:gw(o,"assert_stdout_regex",r),assert_stderr_contains:Vs(o,"assert_stderr_contains",r),assert_stderr_regex:gw(o,"assert_stderr_regex",r),assert_stdout_min_lines:jC(o,r),assert_json_field_equals:GC(o,r),assert_json_field_gte:qC(o,r),note:p!==void 0&&p.trim().length>0?p.trim():void 0,phase:br(o.phase,`${n} ${t}`)}}function Io(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let r;try{r=JSON.parse(n)}catch(i){throw new l(`${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 l(`${t} array must include at least one linked-test entry object`,m.USAGE);return o.map((i,s)=>KC(i,o.length>1?`entry ${s+1}`:"entry",t))}var tl=["command","cmd"],Oo=Object.freeze($t.filter(e=>!["command","cmd","timeout"].includes(e)));function yw(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 l("Use exactly one --update or --update-index with --set-json",m.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new l("--set-json must contain a JSON object with explicit linked-test metadata fields",m.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:vr(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 ww(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 l("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",m.USAGE)}function zC(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("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 l("Select one linked test by index, command, or path",m.USAGE);if("index"in t){let r=vr(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 l("Linked-test selector must be a non-empty command or path",m.USAGE);let i=e.flatMap((s,a)=>s[r]===o?[a]:[]);if(i.length===1)return i[0];if(i.length>1)throw new l(`Linked-test selector is ambiguous; matching indexes: ${i.map(s=>s+1).join(", ")}`,m.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new l("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 vw(e,t){let n=Object.keys(e),r=n.filter(o=>!Oo.includes(o));if(n.length===0&&!t||r.length>0)throw new l("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: ${Oo.join(", ")}.`,recovery:{allowed_values:[...Oo]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new l("scope is required and cannot be cleared",m.USAGE)}function HC(e,t,n){let r={};for(let o of Oo){let i=t[o]!==void 0?t[o]:e[o];i!=null&&(r[o]=i)}return{command:n,...r}}function ra(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 BC(e,t,n){let r=tl.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 l("--set-json sets command and cmd to different values; send one command",m.USAGE,{code:"linked_test_command_immutable",...ra(t),nextSteps:["Send the replacement command once, as command."]});if(o.length===0||o===n.command)throw new l(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",...ra(t),nextSteps:[`Patch only editable fields: ${Oo.join(", ")}.`]});return vo(o),o}function WC(e){let{id:t,tests:n,index:r,identityKey:o,otherFields:i,requested:s,global:a}=e;vw(i,!0);let c=HC(n[r],i,s),d=Io(JSON.stringify(c),"--add-json")[0];_d(d);let u=n.findIndex((p,f)=>f!==r&&no(p,d));if(u>=0)throw new l(`--set-json cannot change ${o}: linked test ${u+1} already has the requested identity, so a replacement would merge into it`,m.USAGE,{code:"linked_test_command_immutable",...ra(o),nextSteps:[`Edit linked test ${u+1} instead: ${P([...ke(a),"test",t,"--update-index",String(u+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${P([...ke(a),"test",t,"--remove-index",String(r+1)])}`]});return c}function VC(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function YC(e){let{id:t,tests:n,index:r,patch:o,global:i,controls:s}=e;if(typeof o!="object"||o===null||Array.isArray(o))return;let a=o,c=tl.find(g=>Object.hasOwn(a,g));if(c===void 0)return;let d=n[r],u=BC(a,c,d),p=Object.fromEntries(Object.entries(a).filter(([g])=>!tl.includes(g))),f=WC({id:t,tests:n,index:r,identityKey:c,otherFields:p,requested:u,global:i}),h=d.command!==void 0&&n.filter(g=>g.command===d.command).length===1?["--remove",`command=${d.command}`]:["--remove-index",String(r+1)],_=[...ke(i),"test",t,...h,"--add-json",JSON.stringify(f),...VC(s)];throw new l(`--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",...ra(c),recovery:{suggested_retry:P(_),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 JC(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("Linked-test metadata patch must be a JSON object",m.USAGE);let n=Object.keys(t);vw(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([a])=>$t.includes(a))),o=Jf(Io(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([a,c])=>[a,c===null?void 0:c]))}),"--set-json")[0]);_d(o);let i=n.filter(a=>!ie(e[a],o[a])),s={...e};for(let a of i){let c=o[a];Object.assign(s,{[a]:c}),c===void 0&&delete s[a]}if(!s.command?.trim()&&!s.path?.trim())throw new l("Linked-test entry must retain a command or path",m.USAGE);return{test:s,fields:i}}async function bw(e,t,n={}){let r=E(process.cwd(),n.path);await O(r);let o=await A(r),i=R(t.author,o.author_default),s=$(o,I()),a=0,c=[],d=await Zt({pmRoot:r,settings:o,id:e,author:i,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:s.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:a,fields:c}}),mutate(p){let f=p.metadata.tests??[],h=zC(f,t.selector);YC({id:p.metadata.id,tests:f,index:h,patch:t.patch,global:n,controls:t});let _=JC(f[h],t.patch);return a=h+1,c=_.fields,_.fields.length===0?{changedFields:[]}:(p.metadata.tests=f.map((g,y)=>y===h?{..._.test,updated_by:i,updated_at:C()}:g),{changedFields:["tests"]})}}),u=d.item.tests;return{ok:!0,id:d.item.id,tests:u,count:u.length,changed:d.changedFields.length>0,updated_index:a,updated_fields:c}}function XC(){return{metadata:{},body:""}}import{AsyncLocalStorage as BG}from"node:async_hooks";import{realpathSync as WG}from"node:fs";import uu from"node:path";var QC=ld("list").properties.outputSession,ZC={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:{...QC},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},kw={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."}},Sw={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},pe={type:"string",description:"pm item id, for example pm-abc1."},eT=`Operation name (one of): ${Ic.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,tT={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."}},nT={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 q(e,t=[]){return{...Sw,properties:{...Sw.properties,...e},required:t}}var rT=[{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:q({action:{type:"string",enum:[...Ic],description:eT},id:pe,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."},...ZC},["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:q({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:q({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:q({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:q({query:{type:"string"},options:{type:"object"},...nT},["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:q({options:{type:"object"},...tT})},{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:q({id:pe,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:q({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:q({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:q({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:pe,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:q({id:pe,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:q({id:pe,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:q({id:pe,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:q({id:pe,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:q({id:pe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:q({id:pe,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:q({id:pe,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:q({id:pe,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:q({id:pe,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:q({id:pe,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:q({id:pe,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:q({id:pe,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:q({id:pe,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:q({subcommand:{type:"string",enum:[...Ju]},id:pe,target:pe,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:q({id:pe,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:q({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:q({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:q({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:q({...kw,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",...Wn],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:[...gc]},description:`Lifecycle roles for add-status: ${gc.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:kw}},["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:q({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:q({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:q({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."}})}],oT={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"},iT=rT.map(e=>{let t=oT[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:ld(t,{properties:n,required:r})}});function Aw(){return iT.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))}var Ew=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"]]]),sT=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Nw=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ia=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"]),Pn=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"]),Fw=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"]]),Mw=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"]]),Dw=new Map([...Mw.entries()].flatMap(([e,t])=>Ft(t).map(n=>[n,e]))),Uw=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],ol=new Map(Uw.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),aT=10,cT=20,Cw=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."]]),jw=[["init",Lp],["install",Fp],["uninstall",Mp],["explore",Dp],["inventory",Kr],["manage",zp],["describe",Up],["reload",Hp],["doctor",Bp],["catalog",Wp],["adopt",Vp],["adopt-all",jp],["activate",Gp],["deactivate",qp],["migrate",Kp]],dT=[...jw.map(([e,t])=>e==="init"?[e,Np]:[e,t]),["upgrade",zr]],lT=[...jw.map(([e,t])=>[`extension ${e}`,t]),...dT.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["package list",Kr],["packages list",Kr],["extension list",Kr],["init",_i],["config",Pp],["extension",hi],["package",qr],["packages",qr],["install",Yp],["create",ki],["item mutate",_f],["item complete",hf],["item reopen",gf],["copy",Si],["focus",Ai],["update",Ei],["update-many",Ci],["upgrade",zr],["calendar",Hr],["cal",Hr],["context",Br],["ctx",Br],["get",Ri],["search",Pi],["eval",wf],["events",Ti],["workspace",Kt],["workspace position",[]],["workspace snapshot",Kt],["workspace snapshot create",Kt],["workspace snapshot list",Kt],["workspace snapshot inspect",Kt],["workspace snapshot restore",Kt],["workspace snapshot delete",Kt],["next",$i],["aggregate",mi],["deps",Ii],["graph",Oi],["guide",xi],["reindex",Jp],["history",ui],["history-compact",xp],["history-attest",Ip],["history-redact",Tp],["history-repair",Rp],["history-author-acknowledge",pi],["merge",Cp],["schema",Op],["profile",$p],["plan",fi],["restore",Zp],["delete",ef],["close",Xp],["close-many",gi],["append",yi],["claim",Qp],["release",tf],["start-task",nf],["pause-task",rf],["close-task",of],["comments",bp],["notes",kp],["learnings",Sp],["files",Ap],["docs",Ep],["test",cf],["test-runs-worker",[]],["test-all",df],["telemetry",lf],["test-runs",mf],["gc",uf],["stats",wi],["ops",[]],["duplicates",vi],["validate",pf],["health",bi],["assurance",ff],...vf,["contracts",Li],["completion",Ni],["activity",yf],...[...Nw].map(e=>[e,li])],$o=new Map(lT);for(let{alias:e,canonical:t}of Te){let n=$o.get(e);n!==void 0&&$o.set(t,n)}function mT(e){let t=Dw.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Tw(e){let t=Te.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Rc.includes(e)?Ae(e):e.startsWith("extension-")?Ae(`extension ${e.slice(10)}`):e.startsWith("package-")?Ae(`package ${e.slice(8)}`):e.startsWith("item-")?Ae(`item ${e.slice(5)}`):e.startsWith("test-runs-")?Ae(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?Ae(`templates ${e.slice(10)}`):ia.has(e)?Mw.get(e)??Ae(e):null}function uT(e,t){let n=V(t);return n!==t||Te.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:Ft(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function Ft(e){return e.split("|").map(t=>Ae(t)).filter(t=>t.length>0)}function pT(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let i of Ft(o.command_path)){let s=i.split(" ").filter(a=>a.length>0);if(s.length!==0)for(let a=s.length;a>0;a-=1){let c=s.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function oa(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Po(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function fT(e,t){if(!t)return{...e};let r=Po(e).filter(o=>{let i=o.properties;if(typeof i!="object"||i===null)return!1;let s=i.action;return typeof s!="object"||s===null?!1:s.const===t});return{...e,oneOf:r}}function nl(e,t){let r=Po(e).filter(o=>{let i=o.properties;if(typeof i!="object"||i===null)return!1;let s=i.action;if(typeof s!="object"||s===null)return!1;let a=s.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function Ae(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Gw(e){return e.replace(/\s+/g,"-")}function tn(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Rw(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=tn(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function rl(e,t,n){n&&(e[t]=!0)}function xw(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?Fu(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function _T(e){let t=xw(e.long,"long"),n=xw(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),rl(o,"required",e.required===!0),rl(o,"repeatable",e.repeatable===!0),rl(o,"list",e.list===!0),e.default!==void 0&&(o.default=e.default);let i=tn(e.description);i&&(o.description=i);let s=ap(e);o.value_arity=s.value_arity;let a=tn(e.value_name)??s.value_name;a&&(o.value_name=a);let c=s.value_type??(s.value_name?"string":null);return c&&(o.value_type=c),o}function qw(e){let t=new Map;for(let r of e){let o=Ae(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},s=`${r.layer}:${r.name}`;i.sourceDedupe.has(s)||(i.sourceDedupe.add(s),i.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=_T(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;i.dedupe.has(d)||(i.dedupe.add(d),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,s)=>{let a=i.layer.localeCompare(s.layer);return a!==0?a:(i.name??"").localeCompare(s.name??"")})});return n}function hT(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...Fc.filter(({flag:n})=>n.startsWith("--output-"))]}}function gT(e){let t=qw(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let s=Ae(i.command);if(s.length===0)continue;let a=tn(i.action)??Gw(s),c=Array.isArray(i.arguments)?i.arguments.map(d=>{let u=tn(d.name);return u?{name:u,required:d.required===!0,variadic:d.variadic===!0,description:tn(d.description)}:null}).filter(d=>d!==null):[];n.set(s,{...i.tier===void 0?{}:{tier:i.tier},...hT(i,t.get(s)?.flags??[]),command:s,action:a,source:{layer:i.layer,name:i.name},description:tn(i.description),intent:tn(i.intent),arguments:c,examples:Rw(i.examples),failure_hints:Rw(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(Ae(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((s,a)=>s.localeCompare(a))){let s=n.get(i);o.push(yT(i,s,t.get(i)?.flags??[]))}return o}function yT(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Gw(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function wT(e){let t=e.flag.startsWith("--")?e.flag:void 0,n=Ad({long:t,short:t===void 0?e.flag:void 0});return n!==null&&/[a-z0-9]/iu.test(n)?n:null}function vT(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 bT(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 kT(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]=vT(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=wT(o);!i||n[i]!==void 0||(n[i]=Fc.some(s=>s.flag===o.flag&&s.flag.startsWith("--output-"))?N_[i]:bT(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 ST(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 AT(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,s)=>i.localeCompare(s)).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 s=`${i.flag}|${i.short??""}`;if(!o.has(s))o.add(s),r.flags.push(i);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===s);a&&ST(a,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 ET(e,t=A){let n={mode:mn.extensions.policy.mode,trust_mode:mn.extensions.policy.trust_mode,default_sandbox_profile:mn.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await W(ce(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await jr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),s=await Gr({...i,loaded:i.loaded});return{handlers:new Set(s.commands.handlers.map(c=>Ae(c.command))),disabledReason:null,commandDefinitions:s.registrations.commands,flagRegistrations:s.registrations.flags,registrations:s.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 CT(e,t={}){let n=new Map;for(let r of xc){let o=ia.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=Tw(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of ia)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Tw(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??Ae(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function TT(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&&(!Pn.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?Ft(e.command_path):[],r=n.some(s=>t.handlers.has(s)||t.handlers.has(V(s))),o=n.map(s=>Fw.get(V(s))).find(s=>typeof s=="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 Kw(e){let t=$o.get(e)??Vn,n=Ge(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function il(e){return Pn.has(V(e))?!1:$o.has(e)}function RT(e){return Nw.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Iw(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function xT(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function IT(e){let t=new Map;for(let r of e.definitions){let o=Iw(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(a=>xT(a)).find(a=>a!==null),s=r.cli_aliases.map(a=>Iw(a)).filter(a=>a!==null&&a!==o);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},d=i?{flag:o,short:i}:{flag:o},u=`${d.flag}|${d.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(d));for(let p of s){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,Nc(o.flags));return n}function Ow(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 Nc(n)}function OT(e){let t=Ad(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function $T(e,t,n,r){let o=(n??[]).map(OT),i=t==="extension"&&(n!==void 0||PT(e,r));return{flags:o,inherited:i?{inherited_flags:vp({readOutput:LT(e,r)})}:{}}}function zw(e,t){let n=V(e);return t.find(r=>V(r.command)===n)}function PT(e,t){return zw(e,t)!==void 0}function LT(e,t){return zw(e,t)?.read_output!==void 0}function NT(e,t,n,r,o){let i=new Map(t);for(let{alias:s,canonical:a}of Te){let c=t.get(a)??t.get(s);c&&(i.set(s,c),i.set(a,c))}return e.map(s=>{let a=il(s),c=a?Kw(s):[],d=n.get(RT(s))??[],u=i.get(s),p=Ow(c,d),f=c.length>0&&(u?.flags.length??0)>0?"mixed":a?"core":"extension",h=$T(s,f,u?.flags,o),_=Ow(p,h.flags);return{command:s,flags:_,...h.inherited,...r?{canonical_command:Bw(s),visibility:Hw(s,o),positionals:yp(s)?.slots??[],flag_invocations:ao(s,_)}:{},provider:f,extension_sources:u?.sources}}).sort((s,a)=>s.command.localeCompare(a.command))}function FT(e,t=un){let n=new Set(e),r=new Map;for(let o of Uw){let i=o.aliases.filter(s=>n.has(s));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 MT(){return{create_string_options:F_,create_repeatable_options:Xi,update_string_options:M_,update_repeatable_options:D_,list_string_options:lp,search_string_options:mp,calendar_string_options:up,context_string_options:pp,activity_string_options:fp}}function $w(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=Bn(e,"create",n),o=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),i=[...new Set(o.map(a=>Oe("create",a)))].sort((a,c)=>a.localeCompare(c)),s=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:o,required_flags:i,required_type_options:s,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.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]=$w(o,"strict"),n[r]=$w(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function UT(e,t){let n=Po(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let s=i.properties;if(typeof s!="object"||s===null)return i;let a=s.action;return typeof a!="object"||a===null||a.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function jT(e){let t=oa(e.action)!==void 0||oa(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,s=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=oa(e.action),u=oa(e.command),p=!r&&!c&&!o&&!i&&!s&&!d&&!u;return{selectedAction:d,selectedCommand:u,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:s,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function GT(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function qT(e,t=A){try{return await t(e)}catch{return structuredClone(mn)}}async function KT(e,t,n){let r=await qT(t),o=await ET(e),i=$(r,o.registrations??I()),s=et(r.schema),a=gT(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:D(r.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:IT(s),createRequiredOptionContracts:DT(i),extensionContracts:a,mergedExtensionContracts:AT(a.filter(c=>sa(n,c.command,a))),extensionFlagMap:qw(o.flagRegistrations)}}function Pw(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ia.has(e.selectedAction)||e.selectedCommand!==void 0&&Pn.has(V(e.selectedCommand)))}function zT(e,t){let n=CT(t,{includePackageOwnedActions:Pw(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Zu);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(i=>i.action===o.action)?.tier??ws(o.action))!=="internal"))}return Pw(e)&&e.selectedCommand!==void 0&&Pn.has(V(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:mT(V(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function HT(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new l(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function BT(e,t){return[...new Set([...Rc.filter(n=>!Pn.has(V(n))),...[...$o.keys()].filter(n=>!Pn.has(V(n))),...e.flatMap(n=>n.command_path?Ft(n.command_path).filter(r=>n.provider==="extension"||!Pn.has(V(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=>Ae(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function WT(e,t){let n=t.slice(0,aT),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,cT),s=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new l(`Command "${e}" is a command namespace. Choose a concrete child command: ${o}.`,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:s,nextSteps:[`Retry with a child command, for example: ${s[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --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 l(`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 YT(e){return new l(`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 JT(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(i=>i.startsWith(`${e.selectedCommand} `));if(r.length>0)throw WT(e.selectedCommand,r);let o=Fw.get(V(e.selectedCommand));throw o?VT(e.selectedCommand,o):YT(e.selectedCommand)}function XT(e,t){let n=zT(e,t.mergedExtensionContracts);HT(e,n);let r=BT(n,t.mergedExtensionContracts);JT(e,r);let o=e.selectedCommand?Dw.get(V(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(d=>o?d.action===o:uT(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.some(d=>d.action===e.selectedAction))throw new l(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let s=e.selectedAction?i.filter(d=>d.action===e.selectedAction):i,a=[...new Map(s.map(d=>TT(d,t.runtimeProbe)).map(d=>[o?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:i,scopedActionDescriptors:s,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function QT(e){return new Set(Po(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 ZT(e){let t=U_,n=Po(t),r=QT(t),o=e.filter(i=>!r.has(i.action)).map(i=>kT(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function Lw(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?fT(n,e.selectedAction):e.selectedCommand?nl(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):nl(n,r);return e.runtimeOnly&&!e.selectedAction?nl(o,new Set(t.actions)):o}function eR(e,t,n){let r=ZT(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?UT(Lw(e,n,r),t.createRequiredOptionContracts):Lw(e,n,r);return{mergedSchema:r,filteredSchema:i}}function tR(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?pT(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Hw(e,t){return t.find(n=>V(n.command)===V(e))?.tier??ws(e)}function sa(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||Hw(t,n)!=="internal"}function nR(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(un.filter(o=>o.hidden&&(o.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(o=>o.alias));if(e.summary&&!e.fullOutput)for(let o of ol.keys())r.add(o);return t.filter(o=>!r.has(o)&&sa(e,o,n))}function Bw(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":ol.get(n)??n}var rR=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"]]),oR=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function iR(e,t){let n=Cw.get(V(e))??(e.includes(" ")?void 0:Cw.get(Bw(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>Ft(d.command).some(u=>V(u)===V(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),s=o.slice(0,-1).join(" "),a=rR.get(i),c=oR.get(e)??s;return{intent:a===void 0||s.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function sR(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(Ae))].filter(i=>i.length>0).sort((i,s)=>i.localeCompare(s)).map(i=>{let s=ad(i,{generateFallback:!0}),a=i.split(" ")[0],c=ol.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...Kw(i).map(f=>f.flag),...t.filter(f=>Ft(f.command).some(h=>V(h)===V(i))).flatMap(f=>f.flags.map(h=>h.flag))]),u=(Ew.get(V(i))??Ew.get(c)??sT).filter(f=>d.has(f)),p=iR(i,t);return{command:i,intent:p.intent,...o||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:s.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...s.default_max_estimated_tokens_by_format}}:{}}})}function aR(e){return e.map(t=>({budget:ad(t,{generateFallback:!0}),envelope:Ph(t)}))}function cR(e){let t=new Map;for(let n of e){let r=xh(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(","),s=t.get(i)??{commands:[],exit_codes:o};s.commands.push(n),t.set(i,s)}return[...t.values()]}function dR(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>Ft(r.command).some(o=>V(o)===V(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>Ft(o.command).some(i=>r.has(i)))}return t.extensionContracts.filter(r=>sa(e,r.command,t.extensionContracts))}function lR(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 mR(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=Mf);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(s=>`--${s.cli_flag}`))].sort((s,a)=>s.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...zu],services:[...Hu],policy_modes:[...Bu],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Yu],trust_modes:[...Wu],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Vu],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Ru],create_modes:[...xu],close_validation_modes:[...Iu],workflow_enforcement_modes:[...Ou]},e.relationship_kind_contracts=[...Mu,...(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 uR(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 pR(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=NT(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(gp).filter(([s])=>i.has(s)).map(([s,a])=>({command:s,default:a,brief_fields:[...hp,"priority"],compact_fields:[..._p]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:s})=>({canonical:i,aliases:s})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function fR(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=MT();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function _R(e,t,n,r){e.command_summaries=sR(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...k_],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(Ae))].filter(o=>E_(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...T_(o).keys()]}))}:{}},e.grammar_contracts={nouns:pn.nouns,shared_verbs:pn.shared_verbs,scope_before_verb:pn.scope_before_verb,visible_top_level_ceiling:pn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:pn.ceiling_raise_requires_pm_item,positional_shape_budget:pn.positional_shape_budget,positional_shape_count:new Set(Lc.map(({slots:o})=>wp(o))).size,positional_action_count:Pc.length,positional_action_parents:[...new Set(Pc.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:Lc}:{}}}async function sl(e,t){let n=jT(e);GT(n);let r=E(process.cwd(),t.path),o=await KT(t,r,n),i=XT(n,o),s=eR(n,o,i),a=tR(n,i),c=nR(n,a,o.extensionContracts),d=lR(n,s,i,c),u=dR(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&_R(d,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return d;let f=FT(i.commandCatalog.filter(h=>sa(n,h,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||mR(d,o,n),uR(d,n,s,u),pR(d,n,o,c,f),fR(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...ng],gate_triggers:[...tg]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=di.map(h=>({...h,reason:h.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=Aw(),d.context_intents=I_(),d.read_output_dimensions=A_,d.error_codes=Ih,d.command_output_contracts=aR(c),d.diagnostic_output_contracts=S_,d.command_exit_contracts={vocabulary:Rh,command_sets:cR(c)}),d}async function Ww(e,t,n=x_){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 hR}from"node:crypto";function al(e){let t=Du();for(let n of e)t.register(n);return t}function gR(e,t,n=[]){if(n.length===0)return e;let r=JSON.parse(e),o=JSON.parse(wd(t));for(let i of n){let s=i.split("."),a=o;for(let u of s){let p=Cc(a);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(u)||["constructor","prototype","__proto__"].includes(u)||p===null||!Object.hasOwn(p,u))throw new l(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,m.USAGE);a=p[u]}if(Cc(a)===null)throw new l(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,m.USAGE);let c=r,d=o;for(let u of s.slice(0,-1)){let p=c[u];d=d[u],p===void 0&&Object.defineProperty(c,u,{value:structuredClone(d),enumerable:!0,writable:!0,configurable:!0}),c=c[u]}Object.defineProperty(c,s.at(-1),{value:a,enumerable:!0,writable:!0,configurable:!0})}return ie(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
2
- `}async function yR(e,t,n){let r=t.schema?.fields??[];if(r.length===0)return;let{normalizeCliToken:o,resolveRuntimeFieldRegistry:i}=await import("./runtime-schema-YXPYDD2C.js"),s=f=>i({fields:[f]}).definitions[0],a=f=>JSON.parse(JSON.stringify(f)),c=[...e.schema.fields,...Array.isArray(n)?n:[]].map(f=>({resolved:s(f),persisted:a(f)})),d=f=>[f.cli_flag,...Array.isArray(f.cli_aliases)?f.cli_aliases:[]].some(h=>typeof h=="string"&&o(h).length===0),u=r.filter(f=>{let h=s(f),_=c.some(g=>ie(g.persisted,a(f)));return h===void 0||d(f)?!_:!c.some(g=>ie(g.resolved,h))});if(u.length===0)return;let{assertFieldDefinitionOptionsAvailable:p}=await import("./field-option-collisions-WV6GPYYP.js");for(let f of u)p(f)}function Vw(e,t,n,r){return{fitOutputEnvelope:ig,client:t,isItemNotFoundError:o=>so(o)&&o.exitCode===m.NOT_FOUND,getItemAt:(o,i)=>og(o,i,{pmRoot:e}),readSettingsSection:(o,i)=>Sh(e,o,i),writeSettingsSection:(o,i,s)=>Ah(e,o,i,{author:n,...s}),openRelationshipEventStore:o=>ag.open({pmRoot:e,nodes:o.nodes,registry:al(o.definitions),...o.relativePath===void 0?{}:{relativePath:o.relativePath}}),createRelationshipGraph:o=>new Gu(o.nodes,o.edges,al(o.definitions)),analyzeRelationshipImpact:(o,i,s)=>cg(o,i,s),validateRelationshipEvents:o=>{let i=new sg(o.nodes,{registry:al(o.definitions)});return o.events.map(s=>i.append({...s,expectedVersion:i.version}))},commitWorkspaceTransaction:o=>dg({...o,pmRoot:e}),mutateWorkspaceSettings:async o=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(o.operationId))throw new l("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",m.USAGE);let i=o.dryRun===!0?await ir(e,()=>A(e)):await A(e);try{let s=await ds({pmRoot:e,filePath:ce(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${hR("sha256").update(r).digest("hex").slice(0,16)}:${o.operationId}`,author:R(n,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!1,dryRun:o.dryRun===!0,mutate:async a=>{let c=a===null?null:JSON.parse(a),d=_s(c);if(!d.success)throw new l("Workspace settings mutation requires a valid initialized settings.json.",m.USAGE);let u=yd(d.data),p=await o.mutate(structuredClone(u));if(!_s(p).success)throw new l("Workspace settings mutation returned invalid settings.json.",m.USAGE);await yR(u,p,c.schema?.fields);let f=ie(u,p)?a:wd(p,{source:{raw:c,validated:d.data}});f=gR(f,p,o.replaceSubtrees);let h=_s(JSON.parse(f));if(!h.success)throw new l("Workspace settings mutation serialized invalid settings.json.",m.USAGE);return{raw:f,result:o.includePreview===!0?yd(h.data):void 0}}});return s.changed&&o.dryRun!==!0&&await Z({path:ce(e),scope:"project",op:"extension:pm:settings"}),{changed:s.changed,dry_run:o.dryRun===!0,replayed:s.replayed===!0,...s.result===void 0?{}:{preview:s.result}}}finally{oh(e)}}}}function Yw(e){return{undeclaredKeys:il(e)?"pass":"refuse"}}import wR from"node:fs/promises";import ee from"node:path";import vR from"node:readline/promises";import{stdin as bR,stdout as ze}from"node:process";var dl=Symbol.for("pm.sdk.init-invocation-cwd");var kR=()=>vR.createInterface({input:bR,output:ze});function SR(){return structuredClone(mn)}var AR=["minimal","default","strict"];function Xw(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--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 l(`Invalid --preset value "${e}". Allowed: ${AR.join(", ")}`,m.USAGE)}function ER(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",m.USAGE);try{return Ef(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${Af.join(", ")}`,m.USAGE)}}}function CR(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new l("--author must not be empty",m.USAGE);return t}function cl(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:ee.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function TR(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new l("--workspace must not be empty",m.USAGE);if(o!==void 0){if(t.path!==void 0||cl(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",m.USAGE);let d=ee.resolve(e,o),u=ee.join(d,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:d}}}if(t.path===void 0&&cl(n)){let d=ee.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let i=E(e,t.path),s=ee.join(ee.resolve(e),".agents","pm"),a=ee.dirname(ee.dirname(i)),c=ee.resolve(i)===s?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:a,discovery:c,requested_cwd:ee.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:s}:{}}:{mode:"tracker-path",tracker_root:i}}}function RR(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new l("--id-prefix must not be empty",m.USAGE);if(cl(t))throw new l(`--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&&Yt(e)!==Yt(t))throw new l(`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 ${Yt(e)}`,`pm init --id-prefix ${Yt(t)}`]});return t}function xR(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--agent-guidance must not be empty",m.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new l(`Invalid --agent-guidance value "${e}". Allowed: ${$g.join(", ")}`,m.USAGE)}function IR(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Qw(e,t){let n=Lu[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function OR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $R(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(OR).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function PR(e,t,n){let r=Di(t.schema),o=Rt(e,r.files.types,Tt.types),s=kf(await oe(o)),a=[],c=[];for(let d of Cf(n)){let u=Sf(s,d);s=u.file,(u.replaced?c:a).push(u.definition.name)}return await ot({pmRoot:e,filePath:o,raw:Fi(s),op:"init:type-preset",author:R(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:o}}async function LR(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",ee.join(".agents","pm")];for(let n of t)if(await W(ee.join(e,n)))return!0;return!1}async function NR(e,t,n){if(!t||n||await W(ee.join(e,"settings.json"))||!await LR(e))return;let r=ee.join(e,".agents","pm");throw new l(`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 Zw(e,t){let n=[],r=[];for(let o of t){let i=o?ee.join(e,o):e,s=await W(i);await wR.mkdir(i,{recursive:!0}),s?r.push(`already_exists:${i}`):n.push(i),r.push(...await Z({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function FR(e,t){let n=kR(),r=t===void 0?2:3;try{ze.write(`pm init setup wizard (agent-optimized)
1
+ import{A as Ad,B as Ch,C as Th,n as Tf,o as Mi,p as Pf,q as Lf,r as Ui,s as Wr,t as Mc,u as Dc,v as ji,y as G_,z as q_}from"./chunk-4HLZOOZI.js";import{a as Rh,f as xh,h as kn,m as Ih,o as ao,r as ws,s as Oh,t as $h,x as Ph}from"./chunk-AN4NFFLL.js";import{$ as $g,A as dg,Ab as gy,Bb as yy,Cb as fr,Db as qd,Eb as wy,Ga as Gg,Ha as qg,Hb as Fs,I as _g,Ia as Kg,J as hg,Ja as zg,K as gg,Ka as Hg,L as yg,La as Bg,M as wg,Ma as Wg,N as vg,Na as An,O as bg,Oa as Vg,Ob as vy,P as kg,Pa as Yg,Pb as by,Q as Sg,Qa as Jg,Qb as ky,R as Ag,Ra as Os,S as Eg,Sa as Xg,T as Cg,Ta as Qg,U as Tg,Ua as Zg,Ub as Sy,V as Rg,Va as ey,Vb as Fy,W as xg,Wa as ry,X as Ig,Xa as $s,Y as Og,Ya as en,Z as $d,Za as oy,_ as mr,_a as Ps,aa as Pg,bb as wo,g as tg,h as ng,ia as Lg,ib as iy,jb as sy,ka as Fg,kb as ay,la as Nd,lb as cy,ma as Fd,mb as dy,na as Mg,nb as ly,oa as Dd,ob as Ls,pb as jd,qa as Dg,qb as my,ra as Ug,rb as Gd,sa as Ud,sb as pr,tb as uy,ub as py,vb as fy,wb as _y,xb as hy,yb as vo,zb as Ns}from"./chunk-UGQ2EXTU.js";import{a as ug}from"./chunk-IIP6LZ5E.js";import{h as vt,i as En,m as ny}from"./chunk-GISZWMBS.js";import{a as yo,b as lg,c as xs,h as pg,i as fg}from"./chunk-N7ZAMULP.js";import{c as Od}from"./chunk-4SX2BN4V.js";import{c as mg}from"./chunk-AIDL2ZNT.js";import{A as zh,B as uo,C as Hh,D as Bh,E as Rd,F as po,G as As,H as dr,I as Wh,J as xd,K as Se,L as Id,M as ve,N as Vh,O as Yh,P as Es,R as Jh,S as Cs,T as Xh,a as vs,b as co,c as bs,d as Ne,e as ks,f as Lh,g as Nh,h as Ss,i as lo,j as Fh,k as Mh,l as Ed,m as Cd,n as yt,o as Dh,p as Uh,q as jh,r as mo,s as Gh,t as Td,u as wt,v as b,w as qh,x as Kh,z as Ke}from"./chunk-7FKGIJEB.js";import{e as Af,g as Ef,h as Cf,l as $f}from"./chunk-GUAT4OAC.js";import{a as xf,c as If,m as j_}from"./chunk-I4GY7HAP.js";import{S as N_,T as cd,U as F_,V as Xi,W as dd,X as M_,Y as D_,a as lp,b as mp,c as up,d as pp,da as ld,f as fp,ha as U_}from"./chunk-REORRDPH.js";import{a as sg,b as ag,c as Ms,d as Ds,e as Us}from"./chunk-HSWL6L2O.js";import{K as jg,b as cg}from"./chunk-3QRMY6KF.js";import{$a as Ny,A as Iy,Aa as ko,B as Oy,C as $y,Ca as Bd,Ha as Wd,Ja as Py,Ya as So,_a as Ly,b as ig,e as Pd,g as Ld,i as Md,j as bo,l as Ay,m as Ey,n as Kd,q as Cy,r as zd,va as Hd,x as Ty,y as Ry,z as xy}from"./chunk-7GZMOLQY.js";import{T as Is,Y as ur,h as Ts,k as Zh,l as fo,o as eg,w as Lt,y as rg,z as og}from"./chunk-KMG4O2IU.js";import{a as go,b as Sn,d as ty}from"./chunk-B2HJI6KA.js";import{$ as J_,$a as hh,A as _e,B as es,Bb as wh,C as ud,D as rt,E as H_,F as pd,Fb as vh,G as B_,H as ue,J as Ot,Jb as cr,K as W_,Kb as bh,L as ts,Lb as kd,M as Vt,Mb as kh,N as ge,Nb as Sh,O as or,Ob as Ah,P as fd,Q as to,R as _d,Rb as Sd,S as no,Sb as Eh,T as $t,U as V_,V as ns,W as rs,X as os,Y as is,Ya as io,Z as ss,_ as Y_,_a as _h,aa as X_,ab as gs,bb as ys,c as bf,cb as gh,ea as as,f as kf,fa as cs,g as Sf,i as Fi,ia as ls,j as zt,ja as ms,k as Jn,ka as th,l as Nf,la as us,m as Ff,ma as ps,n as K_,na as Jt,p as ht,pa as gd,q as gt,qa as fs,r as tr,rb as yh,s as md,sa as nh,t as z_,ta as rh,u as Wt,ua as oo,v as nr,w as Qi,x as rr,y as Zi}from"./chunk-52PHSTGP.js";import{$ as qr,$a as Ri,Aa as rf,B as Nc,Ba as of,C as Fc,Ca as sf,D as vp,E as Vn,Ea as af,F as li,Fa as cf,G as mi,Ga as df,H as bp,Ha as lf,I as kp,Ia as mf,J as Sp,Ja as uf,K as Ap,Ka as wi,L as Ep,La as vi,M as ui,Ma as bi,N as Cp,Na as pf,O as Tp,Oa as ff,P as Rp,Pa as ki,Q as pi,Qa as _f,R as xp,Ra as hf,S as Ip,Sa as gf,T as Op,Ta as Si,U as $p,Ua as Ai,V as fi,Va as Ei,W as _i,Wa as Ci,X as Pp,Xa as Hr,Y as hi,Ya as yf,Za as Ti,_ as Lp,_a as Br,aa as Np,ab as xi,b as _p,ba as Fp,bb as Ii,c as hp,ca as Mp,cb as Oi,d as gp,da as Dp,db as wf,ea as Kr,eb as Kt,fa as Up,fb as $i,ga as jp,gb as Pi,ha as Gp,hb as Li,i as $c,ia as qp,ib as Ni,ja as Kp,ka as zp,la as Hp,lb as vf,ma as Bp,na as Wp,nb as Ge,o as Pc,oa as Vp,ob as M,p as yp,pa as Yp,qa as zr,ra as Jp,s as di,sa as Xp,t as Lc,ta as gi,u as pn,ua as yi,va as Qp,w as wp,wa as Zp,xa as ef,ya as tf,za as nf}from"./chunk-AL47ODFZ.js";import{A as Ng,a as _o,b as ho,c as lr,d as st,i as Rs}from"./chunk-C2HW7BSE.js";import{d as Qh}from"./chunk-H4JBS477.js";import{D as Xt,F as Qt,H as j,I as te,J as mh,L as ye,M as uh,N as bn,O as it,P as ph,Q as Zt,R as we,S as fh,T as bd,Y as so,b as Ue,c as oi,d as ii,e as Pe,f as Q_,g as Z_,h as Yt,j as Le,k as ro,l as wn,m as ah,n as sr,o as ar,p as ch,v as vn,x as hs}from"./chunk-ZZYJS74B.js";import{b as hd,e as eh,f as ds,g as ot,i as _s,k as oh,l as ir,n as ih,o as Pt,p as yd,q as wd,r as sh,s as A,t as xe,v as dh,w as vd,x as lh,y as O}from"./chunk-SXWUKNTY.js";import{a as Ji,b as L_}from"./chunk-X6CXWWNB.js";import{$a as cp,$f as er,Ad as qe,Ba as xc,Bb as qc,Bd as Bt,Be as Yi,Ca as Zu,Cd as Wi,Da as Ic,E as mt,Eb as de,Ee as b_,F as qu,Fb as _n,Fc as hn,Fe as ke,Gb as le,Gc as R,Ge as k_,H as Cc,Hb as Kc,Hc as t_,Hd as f_,I as Fr,Ib as zc,Jb as Hc,Jd as __,Ke as S_,L as Tc,Lb as Wf,Lc as n_,M as Mr,Md as h_,N as Oe,Nb as Bc,Oa as ep,Pa as tp,Pb as Vf,Pe as ad,Pf as x_,Q as $,Qa as np,Qb as Yf,Qc as r_,R as Ce,Ra as rp,Rb as Jf,Rc as Yc,Rd as g_,S as si,Sa as op,Sb as Wc,Sc as Xr,Sd as y_,T as Bn,Ta as ip,Tb as Xf,Tc as Qr,U as Dr,Ua as sp,Ub as ut,Uc as Jc,Ud as w_,V as Ku,Vb as pt,Vc as _t,W as E,Wa as Ur,Wc as Zr,Wd as v_,X as ai,Xc as eo,Xf as I_,Y as $e,Ya as ap,Yf as O_,Z as ce,_ as Et,_c as o_,a as Tu,aa as Ze,ab as dp,ac as Qf,ae as Zc,ba as ci,cd as i_,ce as ed,da as Wn,dc as Yr,de as td,dg as $_,ec as ft,ee as nd,fe as rd,gd as s_,ge as od,h as Fu,hb as jr,he as id,hf as A_,ib as Oc,ie as sd,if as E_,jb as Gr,jd as a_,je as I,kd as c_,kg as P_,lc as Hi,ld as Xc,le as Qn,mc as Zf,me as gn,nc as e_,ne as Z,nf as C_,o as Mu,oa as zu,ob as Mf,oc as Jr,od as Qc,of as T_,pa as Hu,pc as Bi,q as Du,qa as Bu,qd as d_,qe as yn,qf as R_,ra as Wu,re as Zn,s as Uu,sa as Vu,sd as l_,ta as Yu,td as m_,u as ju,ua as Rc,v as Gu,va as Ju,vb as It,vd as u_,ve as Vi,wd as p_,xa as Xu,xe as Re,ya as Qu,zb as zi,zc as Vc}from"./chunk-HGJ4MILN.js";import{A as se,B as Df,C as P,F as fn,G as Uc,H as Uf,I as Xn,J as jf,K as Vr,L as Gf,O as qf,P as jc,Q as Kf,R as Gc,S as zf,T as qi,V as Hf,W as Bf,X as Ki,c as Ct,d as ie,k as Te,m as V,o as un,u as C,y as Gi}from"./chunk-YPOATPTX.js";import{C as Rf,F as Tt,J as Di,K as Rt,L as Ht,M as Of,O as D,P as xt,Q as et,S as Yn,a as _c,c as hc,d as gc,h as ni,i as St,j as Lr,k as Nr,l as yc,n as Ru,o as xu,p as Iu,q as Ou,s as $u,t as Pu,u as wc,v as vc,w as bc,x as kc,y as Sc,z as Ac}from"./chunk-OCKKIECS.js";import{A as l,C as W,D as At,E as je,F as oe,I as ae,K as Hn,m as ri,s as Ec,u as Lu,x as mn,y as Nu,z as m}from"./chunk-NGFDPEP7.js";import{readFile as LE}from"node:fs/promises";import NE from"node:path";var Vd="context-intents.json";function js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function FE(e,t,n){if(!js(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 My(e,t){let n=Array.isArray(e)?e:js(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)=>FE(r,t,o))}async function ME(e){let t=NE.join(e,Vd),n;try{n=await LE(t,"utf8")}catch(o){if(At(o))return[];throw await lh(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Vd}: ${i}`,{cause:o})}return My(r,Vd)}function DE(e){if(!js(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return js(n)?n.contextIntents??n.context_intents:void 0}function UE(e){return e.flatMap(t=>{let n=DE(t.module);return n===void 0?[]:My(n,`package ${t.name}`)})}async function jE(e){let t=await ME(e.pmRoot),n=UE(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Yd(e,t){let n=await jE(e);return await O_(n,t)}import{createHash as sC}from"node:crypto";import{readFileSync as aC}from"node:fs";import{readFile as GE}from"node:fs/promises";function Tn(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,ue(e,t)}function qy(e){return Object.prototype.toString.call(e)==="[object Object]"}function qE(e,t,n,r){let o=C();if(!qy(e))return{...r({created_at:o,author:n,text:t}),text:t,edited_at:o};let i=s=>typeof s=="string"&&s!=="";return{...e,...i(e.created_at)?{}:{created_at:o},...i(e.author)?{}:{author:n},text:t,edited_at:o}}function Dy(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function Jd(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Cn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function _r(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 i=_e(n,"--add");return Object.keys(i).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:i.text?.trim()||n}catch{return n}}function Xd(e){return typeof e=="object"&&e!==null&&"code"in e}function Eo(e,t){if(!Ot(e))throw new l(`${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 KE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let r=Vt(),o=Ot(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",o)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return Eo(e,"--stdin"),{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",m.USAGE);if(i==="-")return Eo(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await GE(i,"utf8"),emptyFlag:"--file"}}catch(s){if(Xd(s)&&At(s))throw new l(`--file path not found: ${i}. Use --file - to read stdin.`,m.USAGE);let a=s instanceof Error?s.message:String(s);throw new l(`Failed to read --file path "${i}": ${a}. Use --file - to read stdin.`,m.USAGE)}}async function qs(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("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 l("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--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 l("--edit must be a positive integer",m.USAGE);let n=await KE(e,t);if(e.edit!==void 0){if(!n)throw new l("--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 Ao(e,t){throw e instanceof l&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Ky(e){return e==="comments"?"--stdin":"--add -"}function zE(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function HE(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function BE(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=HE(t),o=Ky(e.collectionKey),i=e.retryArgs===void 0?{}:{field:e.textFlag,recovery:{suggested_flags:[t],suggested_retry:P(e.retryArgs),suggested_retry_args:[...e.retryArgs]}};if(r!==void 0){let s=r.split(/[ =]/,1)[0],a=s==="--file"?"that file":"stdin",c=e.conflictingOperand===void 0?"":` "${e.conflictingOperand}" was read as positional text, which ${s} cannot be combined with: drop it, or pass it as the text without ${s}.`;return new l(`${e.textFlag} value "${t}" looks like an option, not annotation text: ${e.textFlag} took ${s} 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 ${a} 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 l(`${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 WE(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!zE(e)))throw BE({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function VE(e,t,n,r,o){if(n.input.mode!=="edit")return;let i=dp(t);if(i===void 0)return;let s=n.collectionKey.replace(/s$/,""),a=n.input.index,c=ke(r)[0]==="--pm-path"?["--pm-path",o]:[];throw new l(`Replacement text for ${s} ${a} on ${e} ends with the read-output compaction marker, so it was copied from a compacted read that left out ${i} characters. Nothing was written.`,m.USAGE,{code:"annotation_text_compacted",item_id:e,details:{collection:n.collectionKey,entry_index:a,omitted_characters:i},required:`Read the whole ${s} with --output-budget unbounded, apply the change to the full text, and retry the edit without the trailing marker.`,why:"A budgeted read shortens long entries to a prefix plus a marker naming how many characters it left out; editing from that text would replace the stored entry with the shortened prefix.",examples:[P([...c,n.collectionKey,e,"--output-budget","unbounded","--json"]),`${P([...c,n.collectionKey,e,"--edit",String(a),"--file"])} <full-text-file>`]})}function YE(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new l(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,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(JE(e,t),e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,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> ${Ky(e.collectionKey)}`]})}function JE(e,t){if(t.expectAt!==void 0){if(e.input.mode!=="edit"&&e.input.mode!=="delete")throw new l(`--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 l("--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 Uy(e,t,n,r,o){if(o===void 0)return;let i=t[n]?.created_at,s=typeof i=="string"?i:null;if(s===o)return;let a=t.flatMap((f,h)=>f?.created_at===o?[h+1]:[]),c=r.collectionKey.replace(/s$/,""),d=r.input.mode==="delete"?"--delete":"--edit",u=n+1,p=a.length===1?` The ${c} created at ${o} is at index ${a[0]}.`:a.length>1?` ${a.length} ${r.collectionKey} were created at ${o}: indexes ${a.join(", ")}.`:` No ${c} on ${e} was created at ${o}.`;throw new l(`${c.charAt(0).toUpperCase()}${c.slice(1)} ${u} on ${e} was created at ${s||"an unrecorded time (malformed entry)"}, not ${o}; refusing ${d} of an entry the caller did not read. Nothing was written.${p}`,m.CONFLICT,{code:"annotation_entry_mismatch",item_id:e,details:{collection:r.collectionKey,entry_index:u,expected_created_at:o,actual_created_at:s,matching_indexes:a},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} ${d} ${a.length===1?a[0]:"<index>"} --expect-at ${o}${d==="--edit"?' --add "<text>"':""}`]})}function XE(e,t,n,r,o,i){let s=Cn(e.metadata,t),a=o?s.findIndex(c=>qy(c)&&c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],written:s,position:a}:(s.push(i({created_at:C(),author:n,text:r})),e.metadata[t]=s,{changedFields:[t],written:s,position:s.length-1})}function jy(e,t,n){return Vf.has(e)?t.map((o,i)=>i).sort((o,i)=>Yf(t[o],t[i])||o-i).indexOf(n)+1:n+1}async function hr(e,t,n,r){YE(r,t);let o=E(process.cwd(),n.path);await O(o);let i=await A(o),s=$(i,I()),a=oo(t.limit);if(r.input.mode==="list"){let _=await j(o,e,i.id_prefix,i.item_format,s.type_to_folder);if(!_)throw new l(`Item ${e} not found`,m.NOT_FOUND);let g=await te(_,{schema:i.schema}),y=Cn(g.document.metadata,r.collectionKey);return Gs(_.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=R(t.author,i.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,g;try{g=await we({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let v=Cn(w.metadata,r.collectionKey),k=Gy(r.input.index,v.length,r.collectionKey);return Uy(e,v,k,r,t.expectAt),Dy(v[k],"deleted"),v.splice(k,1),w.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(w){Ao(w,r.conflictGuidance)}let y=Cn(g.item,r.collectionKey);return Gs(g.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let d=r.input.rawValue??r.input.value??"";WE(d,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(VE(e,u,r,n,o),r.input.mode==="edit"){let _=r.editOp??r.op,g,y=0;try{g=await we({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(k){let S=Cn(k.metadata,r.collectionKey),T=Gy(r.input.index,S.length,r.collectionKey);Uy(e,S,T,r,t.expectAt);let x=S[T];return Dy(x,"edited"),S[T]=qE(x,u,c,r.createEntry),y=jy(r.collectionKey,S,T),k.metadata[r.collectionKey]=S,{changedFields:[r.collectionKey]}}})}catch(k){Ao(k,r.conflictGuidance)}let w=Cn(g.item,r.collectionKey),v=y;return Gs(g.item.id,r.collectionKey,w,a,t.includeMeta===!0,{action:"edit",entryIndex:v,entry:w[v-1]},t.fullHistory===!0)}let p,f=0;try{p=await we({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=XE(_,r.collectionKey,c,u,t.ifAbsent===!0,r.createEntry);return f=jy(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(_){Ao(_,r.conflictGuidance)}let h=Cn(p.item,r.collectionKey);return Gs(p.item.id,r.collectionKey,h,a,t.includeMeta===!0,{action:"add",entryIndex:f,entry:h[f-1],changedCount:t.ifAbsent===!0?Math.min(p.changedFields.length,1):void 0},t.fullHistory===!0)}function Gy(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 l(`${o} index ${e??"(missing)"} out of range (item has ${i})`,m.USAGE)}return e-1}function QE(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 zy(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function ZE(e,t){let n=e.length-t.length;return t.map((r,o)=>zy(r,n+o+1))}function Gs(e,t,n,r,o,i,s=!1){let a=i===void 0||s?ZE(n,Jd(n,i!==void 0&&s?void 0:r)):i.entry===void 0?[]:[zy(i.entry,i.entryIndex)],c=i!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...i?.changedCount===void 0?{}:{changed:i.changedCount===1},...[o,i!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...QE(t,i,c)}}function gr(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Nf({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=xt(e.fromStatus,e.statusRegistry)??e.fromStatus,r=xt(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Ff(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,m.USAGE);return`workflow_transition_not_allowed: ${o}`}function Ks(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new l("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",m.USAGE);let n=typeof e.handoff=="string"?xt(e.handoff,t):void 0;if(n===void 0||Yn(n,t)||n===t.in_progress_status)throw new l("--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 l("--handoff requires --message with implementation evidence and the next verification step.",m.USAGE);return n}function Hy(e,t,n,r,o){if(Yn(e.status,r)||!e.assignee?.trim())throw new l("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",s=gr({enforcement:i,typeWorkflows:i==="off"?[]:Jn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),a={from_status:e.status,to_status:t,message:o},c=e.status===t?[]:["status"];return e.status=t,{receipt:a,warnings:s?[s]:[],changedFields:c}}import{AsyncLocalStorage as eC}from"node:async_hooks";function Nt(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:xt("in_progress",e)??e.open_status}var tC="strict",Hs="start_blocked_by_open_dependency";function By(e,t,n){if(t===void 0)return!1;let r=_n(Nt(n),n);return _n(t,n)===r&&_n(e??"",n)!==r}function zs(e,t,n){let r=o=>Le(o.trim(),n).toLowerCase();return r(e)===r(t)}var nC=new Set(["cli:create:blocked_by","cli:update:blocked_by"]);function Qd(e,t,n){if(e.kind!=="blocked_by"||typeof t!="string"||t.trim().length===0)return!1;let r=e.id.trim().toLowerCase();return r===t.trim().toLowerCase()?!0:r===Le(t.trim(),n).toLowerCase()&&nC.has(e.source_kind?.trim().toLowerCase()??"")}function rC(e,t,n){let r=e.dependencies??[],o=r.filter(s=>s.kind==="blocked_by");if(r.some(s=>s.kind!=="blocked_by"&&Uu(s.kind)==="blocked_by"&&zs(s.id,t,n)))return P(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&zs(e.blocked_by,t,n))){let s=o.filter(a=>zs(a.id,t,n));return s.length===1&&s.every(a=>a.id===lr(a.id,n,void 0))?P(["update",e.id,"--dep-remove",`id=${s[0].id},kind=blocked_by`]):P(["get",e.id,"--fields","blocked_by,dependencies"])}return o.filter(s=>zs(s.id,t,n)).every(s=>Qd(s,e.blocked_by,n))?P(["update",e.id,"--unset","blocked_by"]):P(["get",e.id,"--fields","blocked_by,dependencies"])}var oC=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function iC(e,t){try{return(await ty(e)).filter(n=>!n.resolved)}catch(n){let r=so(n)?n.context.code:void 0;if(!t||typeof r!="string"||!oC.has(r))throw n;return r}}async function Wy(e){let t=e.settings.governance.start_blocker_enforcement??tC;if(t==="off")return[];let n=$(e.settings,I()).type_to_folder,r=e.metadata.id,o=await iC({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(s=>s.id).join(",");if(t==="warn")return[`start_with_open_blockers:${r}:${i}`];if(e.force===!0)return[`start_blocker_override:${r}:${i}`];throw new l(`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(s=>s.external!==!0).slice(0,3).map(s=>P(["get",s.id])),rC(e.metadata,o[0].id,e.settings.id_prefix),"pm next"],details:{enforcement:t,open_blockers:o.map(s=>({id:s.id,title:s.title,status:s.status,external:s.external===!0}))}})}async function Bs(e){if(e.requested===!1||!By(e.fromStatus,e.metadata.status,e.registry))return[];let t=await Wy(e),n=Zd.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var Zd=new eC;function Vy(e){return Zd.run({warnings:new Set},e)}async function Yy(e){let t=Zd.getStore();if(t===void 0)return[];let n=By(e.metadata.status,Nt(e.registry),e.registry)?await Wy(e):[];for(let r of n)t.warnings.add(r);return n}var Qy="no_available_next_item";function Zy(e){if(!(e instanceof Error)||e.name!=="PmCliError")return;let t=e.context;if(typeof t!="object"||t===null)return;let n=t.code;return typeof n=="string"?n:void 0}function ew(e,t){return Zy(e)===t}function cC(e){return ew(e,"already_claimed_by")}async function Co(e,t,n,r={}){let o=E(process.cwd(),n.path);await O(o);let i=await A(o),s=D(i.schema),a=R(r.author,i.author_default),c=hn(a),d=r.takeoverStale===!0;lC(d,t);let u=null,p=!1,f={},h,_=[],g=await Zt({pmRoot:o,settings:i,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,resolveHistoryContext:()=>h===void 0?void 0:{stale_claim_takeover:h},async mutate(w,v){let S=w.metadata.assignee??"",T=w.metadata.claim_principal?.trim()||S;if(u=S.trim().length>0?S:null,Yn(w.metadata.status,s)&&!t)throw new l(`Cannot claim terminal item ${w.metadata.id} without --force`,m.CONFLICT);if(u!==null&&T!==c){let J=await dC({pmRoot:o,storageId:v.storageId,metadata:w.metadata,holder:S,author:a,thresholdHours:i.mutation_guard.stale_in_progress_hours,force:t,ifAvailable:r.ifAvailable===!0,takeoverStale:d});if(J.kind==="skip")return p=!0,_.push(`claim_skipped_held_by:${Vr(S)}`),{changedFields:[]};h=J.takeover,_.push(J.warning)}let F={assignee:a,claim_principal:c},L=["assignee","claim_principal"].filter(J=>w.metadata[J]!==F[J]);Object.assign(w.metadata,F);let H=w.metadata.status,{changedFields:B,warnings:Y,...re}=yC(w.metadata,r.start===!0,i,s);return Y.push(...await gC({pmRoot:o,settings:i,metadata:w.metadata,fromStatus:H,registry:s,force:t,start:r.start===!0})),f=re,_.push(...Y),{changedFields:[...L,...B],warnings:_}}}),y=tw(await nw("claim",g.item.id,n,p,()=>Ay({pmRoot:o,settings:i,principal:c,itemId:g.item.id})));return _.push(...y.warnings),{item:Uc(g.item),changed_fields:g.changedFields,claimed_by:p&&u!==null?fn(u):a,previous_assignee:u===null?null:fn(u),forced:t,...p?{skipped:!0}:{},..._.length>0?{warnings:_}:{},...el("suggestions",y.suggestions),...f,...h===void 0?{}:{takeover:h}}}async function dC(e){if(e.ifAvailable&&!e.takeoverStale)return{kind:"skip"};if(e.force)return{kind:"take",warning:`claim_takeover:${Vr(e.holder)}->${e.author}`};let t=await Cy(e.pmRoot,e.storageId,e.holder,{updated_at:e.metadata.updated_at,threshold_hours:e.thresholdHours}),n=e.takeoverStale?mC(t,e.author):void 0;if(n!==void 0)return{kind:"take",warning:`claim_stale_takeover:${n.previous_holder}->${e.author}:idle_hours=${n.idle_hours}`,takeover:n};if(e.takeoverStale&&e.ifAvailable)return{kind:"skip"};throw fC(e.metadata.id,t,e.takeoverStale)}function lC(e,t){if(!(!e||!t))throw new l("--takeover-stale cannot be combined with --force",m.USAGE,{code:"ambiguous_option_combination",required:"Pass --takeover-stale to take over only an idle claim, or --force for a coordinated unconditional takeover.",nextSteps:["Drop --force to let the stale-work policy decide, or drop --takeover-stale for a coordinated override."]})}function mC(e,t){let n=e.activity;if(n.stale_policy.stale)return{previous_holder:e.holder,new_holder:t,claimed_at:e.since,last_activity_at:n.last_activity_at,idle_hours:n.idle_hours,threshold_hours:n.stale_policy.threshold_hours,policy:n.stale_policy.setting}}var uC={claim_record_unavailable:"no original history record shows when the holder took it",discarded_history_tail:"a history salvage after the claim discarded a record whose time is unknown",rewritten_history:"a history repair, redaction or merge reconcile after the claim rewrote its records",workspace_restored:"a workspace snapshot restore at or after the claim may have replaced the holder's work"};function pC(e,t){return t.history_unreadable===!0?{reason:"its history stream could not be read, so idleness cannot be established",nextStep:`Repair the history stream of ${e} (pm history ${e} --verify), then retry --takeover-stale.`}:t.unproven_activity!==void 0?{reason:`${uC[t.unproven_activity]}, so idleness cannot be proven`,nextStep:`Ask the holder to release ${e} (pm release ${e}); a new claim starts a provable record.`}:t.stale_policy.eligible_at===null?{reason:t.idle_hours===null?"no valid activity time is recorded":`idle ${t.idle_hours}h of ${t.stale_policy.threshold_hours}h`,nextStep:`No eligibility time can be computed for ${e}; inspect pm history ${e}.`}:{reason:`idle ${t.idle_hours}h of ${t.stale_policy.threshold_hours}h`,nextStep:`Retry with --takeover-stale after ${t.stale_policy.eligible_at} if nothing else is recorded on ${e}.`}}function fC(e,t,n){let r=t.activity,o=r.stale_policy,i={item_id:e,claimed_by:t.holder,claimed_at:t.since,claim_source:t.source,claim_activity:r},s="Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",a="Re-run with --force only when taking over the item is coordinated.";if(n){let c=pC(e,r);return new l(`Item ${e} is ${t.phrase}, and its claim is not stale under ${o.setting} (${c.reason}).`,m.CONFLICT,{code:"stale_claim_takeover_refused",...i,required:`The claim must be idle for at least ${o.threshold_hours}h (${o.setting}) before --takeover-stale may take it.`,why:`${s} A stale takeover needs recorded evidence that the claim has been idle for the configured threshold, so an active claim is never taken over.`,nextSteps:[c.nextStep,"Run pm next to pick a different unclaimed item.",a]})}return new l(`Item ${e} is already ${t.phrase}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",...i,why:s,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.",...o.stale?[`Re-run with --takeover-stale: the claim has been idle ${r.idle_hours}h, past ${o.setting}=${o.threshold_hours}.`]:[],a]})}var _C="claim_semantic_attribution_unrecorded";function tw(e){return e?{warnings:[e.warning],suggestions:[e.suggestion]}:{warnings:[],suggestions:[]}}function el(e,t){return t.length>0?{[e]:t}:{}}var hC="release_semantic_attribution_unrecorded";async function nw(e,t,n,r,o){if(!r)try{await o();return}catch(i){let s=Zy(i)??"unexpected_error",a=ke(n);return{warning:e==="claim"?_C:hC,suggestion:`The ${e} of ${t} is saved, but the session attribution that names this agent's active work was not updated (${s}); nothing needs a retry. If ${P([...a,"health"])} reports a stale lock, remove it with ${P([...a,"gc","--scope","locks"])}.`}}}function rw(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new l(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 l("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 gC(e){return e.start?Bs(e):Yy(e)}function yC(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(Yn(e.status,r))throw new l(`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=Nt(r),i=n.governance.workflow_enforcement??"off",s=gr({enforcement:i,typeWorkflows:i==="off"?[]:Jn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:o}),a={from_status:e.status,to_status:o},c=e.status===o?[]:["status"];return e.status=o,{start:a,changedFields:c,warnings:s?[s]:[]}}async function ow(e,t,n={},r={}){if(n.takeoverStale===!0)throw new l("--takeover-stale cannot be combined with --next",m.USAGE,{code:"ambiguous_option_combination",required:"Pass an explicit item id with --takeover-stale; --next only selects work no other author holds.",nextSteps:["Retry as pm claim <id> --takeover-stale for the held item, or drop --takeover-stale to select with --next."]});let o=wC(n.maxAttempts),i=await A(E(process.cwd(),t.path)),s={...n,author:R(n.author,i.author_default)},a=await ko({...r,callerAuthor:s.author,limit:String(o)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return vC(c.slice(0,o),e,t,s)}function wC(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new l("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function vC(e,t,n,r={},o=Co){let i=0,s=[],a=()=>s.length>0?{start_refused:[...s]}:{};for(let c of e){i+=1;try{let d=await o(c.id,t,n,r),u={...d,recommendation:c,attempts:i,available:!0,...a()};if(!d.skipped)return u}catch(d){if(ew(d,Hs)){s.push(c.id);continue}if(!cC(d))throw d}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:R(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:i,...a(),warnings:[Qy]};throw bC(i,s,r.start===!0)}function bC(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 l(r?"No actionable items matched the selection filters":"No actionable item remained available to claim",r?m.NOT_FOUND:m.CONFLICT,{code:Qy,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]}}:{}})}function kC(e){if(e===void 0)return[];let t=e.trim();if(fn(t)===t)return t.startsWith("-")?[`--author=${t}`]:["--author",t]}var iw="release_claim_ended_by_close";function sw(e,t,n,r,o){let i=kC(o),s=i===void 0?void 0:P([...ke(r),"claim",e,"--force",...i]),a=s===void 0||Gf(s)!==s?"Take the item first with a coordinated pm claim --force as the same author only when that takeover is approved.":`Take the item first with a coordinated ${s} only when that takeover is approved.`;return new l(`A close of ${e} already ended your claim, and ${t} has claimed it since; ${n} cannot move or release another holder's claim.`,m.CONFLICT,{code:iw,item_id:e,claimed_by:t,required:`Only the current holder (${t}) can release or hand off ${e}.`,why:"A close ends its holder's claim, so that holder's later release must not change work another principal claimed after it.",nextSteps:[`Ask ${t} to release or hand off ${e}.`,a]})}function aw(e){let t=e.assignee?.trim();return t?e.claim_principal?.trim()||t:void 0}async function cw(e,t,n){let r=E(process.cwd(),t.path),o=await A(r),i=hn(R(n,o.author_default)),s=$(o,I()).type_to_folder,a=await j(r,e,o.id_prefix,o.item_format,s);if(!a)return h=>h();let c=Ze(r,a.id),d=Xy(c),{document:u}=await te(a,{schema:o.schema}),p=aw(u.metadata);if(p!==void 0&&p!==i&&await zd(r,a.id,i))throw sw(a.id,fn(u.metadata.assignee.trim()),"--pause",t,n);let f=Jy(u.metadata,d);return h=>Wi({pmRoot:r,id:a.id,validate:_=>{if(Jy(_.metadata,Xy(c))!==f)throw new l(`${a.id} changed while the pause was judged, so nothing was written.`,m.CONFLICT,{code:SC,item_id:a.id,nextSteps:[`Check the current holder with ${P([...ke(t),"get",a.id])}, reconfirm any override, then re-run the original pause command unchanged.`]})}},h)}var SC="pause_item_changed";function Jy(e,t){return JSON.stringify([aw(e)??null,e.status,e.updated_at,t])}function Xy(e){try{return sC("sha256").update(aC(e)).digest("hex")}catch{return"absent"}}async function wr(e,t,n,r={}){let o=E(process.cwd(),n.path);await O(o);let i=await A(o),s=R(r.author,i.author_default),a=hn(s),c=r.ownershipReleaseBypass===!0,d=null,u=D(i.schema),p=Ks(r,u);if(p!==void 0&&c)throw new l("Ownership-release bypass only clears ownership; it cannot change a handoff status.",m.USAGE);let f,h,_;try{_=await we({pmRoot:o,settings:i,id:e,op:"release",author:s,message:r.message,force:t,bypassAssigneeConflict:c,...c?{}:{callerClaimScope:({storageId:w,callerPrincipal:v})=>zd(o,w,v)},mutate(w,v){if(v.callerClaimScoped===!0){let S=fn(w.metadata.assignee.trim());if(p!==void 0)throw sw(w.metadata.id,S,"--handoff",n,r.author);return h=S,{changedFields:[],warnings:[`${iw}:${w.metadata.id}:${S}`]}}d=w.metadata.assignee??null;let k=p===void 0?void 0:Hy(w.metadata,p,i,u,r.message);return f=k?.receipt,!d&&!w.metadata.claim_principal?{changedFields:[]}:(delete w.metadata.assignee,delete w.metadata.claim_principal,{changedFields:["assignee","claim_principal",...k?.changedFields??[]],warnings:k?.warnings})}})}catch(w){Ao(w,{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."]})}let g=tw(await nw("release",_.item.id,n,!1,()=>Ey({pmRoot:o,principal:a,itemId:_.item.id}))),y=h===void 0?AC(_.item,u):{warnings:[],suggestions:[`A close of ${_.item.id} already ended your claim; ${h} claimed it afterwards and keeps it. The item was not changed.`]};return{item:Uc(_.item),released_by:s,changed_fields:_.changedFields,previous_assignee:d===null?null:fn(d),forced:t,...f===void 0?{}:{handoff:f},...el("warnings",[..._.warnings,...y.warnings,...g.warnings]),...el("suggestions",[...y.suggestions,...g.suggestions])}}function AC(e,t){return _n(e.status,t)===_n(t.in_progress_status,t)?{warnings:["released_unclaimed_in_progress"],suggestions:[`${e.id} remains ${e.status} and unclaimed. If work is paused, run pm release ${e.id} --pause to move it to ${t.open_status}.`]}:{warnings:[],suggestions:[]}}function EC(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 CC(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 TC(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 dw(e=Bi,t=Jr){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 wK(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 lw(e,t=Jr,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let i of t){let s=`${o.agent_harness}\0${i}`,a=r.get(s)??{harness:o.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=o.agent_provenance?.[i];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(s,a)}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 vK(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let u=`${c.agent_harness}\0${d}`,p=o.get(u)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[d];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),o.set(u,p)}let i=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[u])=>d.localeCompare(u)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),s=i.filter(c=>c.entries>=r),a=s.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:s.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:i,failures:a}}function bK(e){let t=[...e].sort((i,s)=>i.ts.localeCompare(s.ts)||i.author.localeCompare(s.author)||i.op.localeCompare(s.op)||i.before_hash.localeCompare(s.before_hash)||i.after_hash.localeCompare(s.after_hash)),n=new Map,r=new Map;for(let i of t){let s=i.agent_episode,a=EC(i),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(i);continue}let u={id:a.id,...s?.label===void 0?{}:{label:s.label},...s?.parent_id===void 0?{}:{parent_id:s.parent_id},source:a.source,entries:[i],children:[]};n.set(c,u),s!==void 0&&r.set(a.id,u)}let o=[];for(let i of n.values()){let s=i.parent_id?r.get(i.parent_id):void 0;s&&CC(i,s,r)?s.children.push(i):o.push(i)}return TC(o),o}var mw=100;function vr(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function RC(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=mw?n:`${n.slice(0,mw-3)}...`}function uw(e){return e.map((t,n)=>`${n+1}. ${RC(t)}`).join("; ")}function xC(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 IC(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function pw(e,t){let n=xC(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 l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,m.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let i=[],s=[];for(let a=0;a<e.length;a+=1)IC(e[a],o)&&(s.push(e[a]),i.push(a+1));if(s.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${uw(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:s,selected_indexes:i,selected_count:s.length,skipped_count:e.length-s.length}}if(r==="only-index"){let o=vr(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${uw(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}}var OC=["setup","test"];function Ie(e){return e.phase==="setup"}function br(e,t){if(e===void 0)return;let n=typeof e=="string"?e.trim().toLowerCase():e;if(n==="setup")return"setup";if(!(n==="test"||n===""))throw new l(`${t} field "phase" must be one of: ${OC.join(", ")}`,m.USAGE,{code:"invalid_argument_value",required:"Use phase=setup for a step that runs before the linked commands, or omit phase for a regular linked test.",examples:['pm test <id> --add "command=npm run build,phase=setup"']})}function Ws(e){return[...e.filter(Ie),...e.filter(t=>!Ie(t))]}function fw(e,t){if(!e.selected.some(i=>!Ie(i)))return e;let n=t.flatMap((i,s)=>Ie(i)?[s+1]:[]);if(n.length===0)return e;let r=e.selected_indexes.filter(i=>!Ie(t[i-1])),o=n.filter(i=>!e.selected_indexes.includes(i));return{...e,selected:[...n,...r].map(i=>t[i-1]),selected_indexes:[...n,...r],selected_count:n.length+r.length,skipped_count:t.length-n.length-r.length,...o.length>0?{setup_indexes:o}:{}}}function _w(e,t,n){if(!Ie(e))return;let r=[...n].filter(o=>o!==t).sort();if(r.length!==0)return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Setup entry runs in the ${t} workspace, but linked commands it prepares run in ${r.join(", ")}, so its output would not reach them. Set workspace_context_mode on the setup entry and the linked commands to one mode.`}}function To(){let e;return{blocked(t){if(e!==void 0)return{command:t.command,path:t.path,status:"skipped",...Ie(t)?{phase:"setup"}:{},error:`Skipped because setup entry "${e.label}" did not pass (${e.outcome}); no later linked command ran.`}},options(t,n){return!Ie(t)||n===void 0?n:{...n,failOnEmptyTestRun:!1,requireAssertionsForPm:!1}},record(t,n){if(!Ie(t))return n;if(n.status==="passed")return{...n,phase:"setup"};let o=n.status==="refused"||n.failure_category==="trust_refusal"||n.failure_category==="setup_failed"?{...n,phase:"setup"}:{...n,status:"failed",phase:"setup",failure_category:"setup_failed",...n.failure_category===void 0?{}:{setup_failure_cause:n.failure_category}};return e={label:t.command??t.path??"<no command>",outcome:o.failure_category??o.status},o}}}function $C(){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,setup_failed:0}}function kr(e){let t=$C();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}var In=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",yo,lg,"FORCE_COLOR"]),Js=/^[A-Za-z_][A-Za-z0-9_]*$/,xn=["schema","tracker","auto","none"],hw=["source","isolated","snapshot"];function Ro(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,m.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1);if(!Js.test(s))throw new l(`${t} env_set key "${s}" is invalid`,m.USAGE);if(In.has(s.toUpperCase()))throw new l(`${t} env_set key "${s}" is reserved for sandbox safety`,m.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function xo(e,t){if(!e)return;let n=cr(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let r of n){if(!Js.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,m.USAGE);if(In.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,m.USAGE)}return n}function Xs(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function Qs(e,t){if(!e)return;let n=e.trim().toLowerCase();if(xn.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${xn.join(", ")}`,m.USAGE)}function On(e,t){if(!e)return;let n=e.trim().toLowerCase();if(hw.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${hw.join(", ")}`,m.USAGE)}function $n(e){if(!e)return;let t=cr(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Sr(e,t,n){let r=$n(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(i){throw new l(`${t} ${n} includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`,m.USAGE)}return r}}function Zs(e,t){if(!e)return;let n=ge(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function ea(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0||a.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function ta(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0||a.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${s}" must be numeric`,m.USAGE);r[s]=c}return Object.keys(r).length>0?r:void 0}var PC=new Set($t);function na(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function LC(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!PC.has(s)){r.push(o);continue}if(Object.hasOwn(n,s))throw t(`provides key "${o}" more than once after case normalization`);n[s]=i}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${$t.join(", ")}.`);return n}function Rn(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 Vs(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(s=>typeof s!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=o.filter(s=>s.length>0);return i.length>0?i:void 0}function gw(e,t,n){let r=Vs(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 Ys(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 NC(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:Ys(n,"timeout_seconds",t),i=r===void 0?void 0:Ys(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 s=o??i;if(!Number.isInteger(s)||s<=0)throw t("timeout_seconds must be a positive integer");return s}function FC(e,t){let n=Rn(e,"scope",t);if(n===void 0)return"project";if(!St.includes(n))throw t(`field "scope" must be one of: ${St.join(", ")}`);return n}function MC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!na(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(!Js.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(In.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 DC(e,t){let n=Vs(e,"env_clear",t);if(n){for(let r of n){if(!Js.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(In.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function UC(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 jC(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=Ys(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 GC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!na(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 qC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!na(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]=Ys(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function KC(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,m.USAGE);if(!na(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${$t.join(", ")}.`);let o=LC(e,r),i=Rn(o,"command",r),s=Rn(o,"cmd",r);if(i!==void 0&&s!==void 0&&i!==s)throw r("command and cmd must match when both are provided");let a=i??s;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=Rn(o,"path",r),d=Rn(o,"pm_context_mode",r);if(d!==void 0&&!xn.includes(d))throw r(`field "pm_context_mode" must be one of: ${xn.join(", ")}`);let u=On(Rn(o,"workspace_context_mode",r),`${n} ${t}`),p=Rn(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:FC(o,r),timeout_seconds:NC(o,r),pm_context_mode:d,workspace_context_mode:u,env_set:MC(o,r),env_clear:DC(o,r),shared_host_safe:UC(o,"shared_host_safe",r),assert_stdout_contains:Vs(o,"assert_stdout_contains",r),assert_stdout_regex:gw(o,"assert_stdout_regex",r),assert_stderr_contains:Vs(o,"assert_stderr_contains",r),assert_stderr_regex:gw(o,"assert_stderr_regex",r),assert_stdout_min_lines:jC(o,r),assert_json_field_equals:GC(o,r),assert_json_field_gte:qC(o,r),note:p!==void 0&&p.trim().length>0?p.trim():void 0,phase:br(o.phase,`${n} ${t}`)}}function Io(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let r;try{r=JSON.parse(n)}catch(i){throw new l(`${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 l(`${t} array must include at least one linked-test entry object`,m.USAGE);return o.map((i,s)=>KC(i,o.length>1?`entry ${s+1}`:"entry",t))}var tl=["command","cmd"],Oo=Object.freeze($t.filter(e=>!["command","cmd","timeout"].includes(e)));function yw(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 l("Use exactly one --update or --update-index with --set-json",m.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new l("--set-json must contain a JSON object with explicit linked-test metadata fields",m.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:vr(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 ww(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 l("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",m.USAGE)}function zC(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("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 l("Select one linked test by index, command, or path",m.USAGE);if("index"in t){let r=vr(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 l("Linked-test selector must be a non-empty command or path",m.USAGE);let i=e.flatMap((s,a)=>s[r]===o?[a]:[]);if(i.length===1)return i[0];if(i.length>1)throw new l(`Linked-test selector is ambiguous; matching indexes: ${i.map(s=>s+1).join(", ")}`,m.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new l("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 vw(e,t){let n=Object.keys(e),r=n.filter(o=>!Oo.includes(o));if(n.length===0&&!t||r.length>0)throw new l("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: ${Oo.join(", ")}.`,recovery:{allowed_values:[...Oo]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new l("scope is required and cannot be cleared",m.USAGE)}function HC(e,t,n){let r={};for(let o of Oo){let i=t[o]!==void 0?t[o]:e[o];i!=null&&(r[o]=i)}return{command:n,...r}}function ra(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 BC(e,t,n){let r=tl.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 l("--set-json sets command and cmd to different values; send one command",m.USAGE,{code:"linked_test_command_immutable",...ra(t),nextSteps:["Send the replacement command once, as command."]});if(o.length===0||o===n.command)throw new l(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",...ra(t),nextSteps:[`Patch only editable fields: ${Oo.join(", ")}.`]});return vo(o),o}function WC(e){let{id:t,tests:n,index:r,identityKey:o,otherFields:i,requested:s,global:a}=e;vw(i,!0);let c=HC(n[r],i,s),d=Io(JSON.stringify(c),"--add-json")[0];_d(d);let u=n.findIndex((p,f)=>f!==r&&no(p,d));if(u>=0)throw new l(`--set-json cannot change ${o}: linked test ${u+1} already has the requested identity, so a replacement would merge into it`,m.USAGE,{code:"linked_test_command_immutable",...ra(o),nextSteps:[`Edit linked test ${u+1} instead: ${P([...ke(a),"test",t,"--update-index",String(u+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${P([...ke(a),"test",t,"--remove-index",String(r+1)])}`]});return c}function VC(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function YC(e){let{id:t,tests:n,index:r,patch:o,global:i,controls:s}=e;if(typeof o!="object"||o===null||Array.isArray(o))return;let a=o,c=tl.find(g=>Object.hasOwn(a,g));if(c===void 0)return;let d=n[r],u=BC(a,c,d),p=Object.fromEntries(Object.entries(a).filter(([g])=>!tl.includes(g))),f=WC({id:t,tests:n,index:r,identityKey:c,otherFields:p,requested:u,global:i}),h=d.command!==void 0&&n.filter(g=>g.command===d.command).length===1?["--remove",`command=${d.command}`]:["--remove-index",String(r+1)],_=[...ke(i),"test",t,...h,"--add-json",JSON.stringify(f),...VC(s)];throw new l(`--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",...ra(c),recovery:{suggested_retry:P(_),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 JC(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("Linked-test metadata patch must be a JSON object",m.USAGE);let n=Object.keys(t);vw(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([a])=>$t.includes(a))),o=Jf(Io(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([a,c])=>[a,c===null?void 0:c]))}),"--set-json")[0]);_d(o);let i=n.filter(a=>!ie(e[a],o[a])),s={...e};for(let a of i){let c=o[a];Object.assign(s,{[a]:c}),c===void 0&&delete s[a]}if(!s.command?.trim()&&!s.path?.trim())throw new l("Linked-test entry must retain a command or path",m.USAGE);return{test:s,fields:i}}async function bw(e,t,n={}){let r=E(process.cwd(),n.path);await O(r);let o=await A(r),i=R(t.author,o.author_default),s=$(o,I()),a=0,c=[],d=await Zt({pmRoot:r,settings:o,id:e,author:i,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:s.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:a,fields:c}}),mutate(p){let f=p.metadata.tests??[],h=zC(f,t.selector);YC({id:p.metadata.id,tests:f,index:h,patch:t.patch,global:n,controls:t});let _=JC(f[h],t.patch);return a=h+1,c=_.fields,_.fields.length===0?{changedFields:[]}:(p.metadata.tests=f.map((g,y)=>y===h?{..._.test,updated_by:i,updated_at:C()}:g),{changedFields:["tests"]})}}),u=d.item.tests;return{ok:!0,id:d.item.id,tests:u,count:u.length,changed:d.changedFields.length>0,updated_index:a,updated_fields:c}}function XC(){return{metadata:{},body:""}}import{AsyncLocalStorage as BG}from"node:async_hooks";import{realpathSync as WG}from"node:fs";import uu from"node:path";var QC=ld("list").properties.outputSession,ZC={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:{...QC},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},kw={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."}},Sw={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},pe={type:"string",description:"pm item id, for example pm-abc1."},eT=`Operation name (one of): ${Ic.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,tT={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."}},nT={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 q(e,t=[]){return{...Sw,properties:{...Sw.properties,...e},required:t}}var rT=[{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:q({action:{type:"string",enum:[...Ic],description:eT},id:pe,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."},...ZC},["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:q({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:q({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:q({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:q({query:{type:"string"},options:{type:"object"},...nT},["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:q({options:{type:"object"},...tT})},{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:q({id:pe,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:q({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:q({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:q({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:pe,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:q({id:pe,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:q({id:pe,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:q({id:pe,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:q({id:pe,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:q({id:pe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:q({id:pe,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:q({id:pe,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:q({id:pe,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:q({id:pe,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:q({id:pe,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:q({id:pe,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:q({id:pe,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:q({id:pe,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:q({subcommand:{type:"string",enum:[...Ju]},id:pe,target:pe,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:q({id:pe,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:q({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:q({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:q({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:q({...kw,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",...Wn],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:[...gc]},description:`Lifecycle roles for add-status: ${gc.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:kw}},["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:q({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:q({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:q({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."}})}],oT={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"},iT=rT.map(e=>{let t=oT[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:ld(t,{properties:n,required:r})}});function Aw(){return iT.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))}var Ew=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"]]]),sT=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Nw=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ia=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"]),Pn=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"]),Fw=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"]]),Mw=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"]]),Dw=new Map([...Mw.entries()].flatMap(([e,t])=>Ft(t).map(n=>[n,e]))),Uw=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],ol=new Map(Uw.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),aT=10,cT=20,Cw=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."]]),jw=[["init",Lp],["install",Fp],["uninstall",Mp],["explore",Dp],["inventory",Kr],["manage",zp],["describe",Up],["reload",Hp],["doctor",Bp],["catalog",Wp],["adopt",Vp],["adopt-all",jp],["activate",Gp],["deactivate",qp],["migrate",Kp]],dT=[...jw.map(([e,t])=>e==="init"?[e,Np]:[e,t]),["upgrade",zr]],lT=[...jw.map(([e,t])=>[`extension ${e}`,t]),...dT.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["package list",Kr],["packages list",Kr],["extension list",Kr],["init",_i],["config",Pp],["extension",hi],["package",qr],["packages",qr],["install",Yp],["create",ki],["item mutate",_f],["item complete",hf],["item reopen",gf],["copy",Si],["focus",Ai],["update",Ei],["update-many",Ci],["upgrade",zr],["calendar",Hr],["cal",Hr],["context",Br],["ctx",Br],["get",Ri],["search",Pi],["eval",wf],["events",Ti],["workspace",Kt],["workspace position",[]],["workspace snapshot",Kt],["workspace snapshot create",Kt],["workspace snapshot list",Kt],["workspace snapshot inspect",Kt],["workspace snapshot restore",Kt],["workspace snapshot delete",Kt],["next",$i],["aggregate",mi],["deps",Ii],["graph",Oi],["guide",xi],["reindex",Jp],["history",ui],["history-compact",xp],["history-attest",Ip],["history-redact",Tp],["history-repair",Rp],["history-author-acknowledge",pi],["merge",Cp],["schema",Op],["profile",$p],["plan",fi],["restore",Zp],["delete",ef],["close",Xp],["close-many",gi],["append",yi],["claim",Qp],["release",tf],["start-task",nf],["pause-task",rf],["close-task",of],["comments",bp],["notes",kp],["learnings",Sp],["files",Ap],["docs",Ep],["test",cf],["test-runs-worker",[]],["test-all",df],["telemetry",lf],["test-runs",mf],["gc",uf],["stats",wi],["ops",[]],["duplicates",vi],["validate",pf],["health",bi],["assurance",ff],...vf,["contracts",Li],["completion",Ni],["activity",yf],...[...Nw].map(e=>[e,li])],$o=new Map(lT);for(let{alias:e,canonical:t}of Te){let n=$o.get(e);n!==void 0&&$o.set(t,n)}function mT(e){let t=Dw.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Tw(e){let t=Te.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Rc.includes(e)?Ae(e):e.startsWith("extension-")?Ae(`extension ${e.slice(10)}`):e.startsWith("package-")?Ae(`package ${e.slice(8)}`):e.startsWith("item-")?Ae(`item ${e.slice(5)}`):e.startsWith("test-runs-")?Ae(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?Ae(`templates ${e.slice(10)}`):ia.has(e)?Mw.get(e)??Ae(e):null}function uT(e,t){let n=V(t);return n!==t||Te.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:Ft(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function Ft(e){return e.split("|").map(t=>Ae(t)).filter(t=>t.length>0)}function pT(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let i of Ft(o.command_path)){let s=i.split(" ").filter(a=>a.length>0);if(s.length!==0)for(let a=s.length;a>0;a-=1){let c=s.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function oa(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Po(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function fT(e,t){if(!t)return{...e};let r=Po(e).filter(o=>{let i=o.properties;if(typeof i!="object"||i===null)return!1;let s=i.action;return typeof s!="object"||s===null?!1:s.const===t});return{...e,oneOf:r}}function nl(e,t){let r=Po(e).filter(o=>{let i=o.properties;if(typeof i!="object"||i===null)return!1;let s=i.action;if(typeof s!="object"||s===null)return!1;let a=s.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function Ae(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Gw(e){return e.replace(/\s+/g,"-")}function tn(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Rw(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=tn(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function rl(e,t,n){n&&(e[t]=!0)}function xw(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?Fu(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function _T(e){let t=xw(e.long,"long"),n=xw(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),rl(o,"required",e.required===!0),rl(o,"repeatable",e.repeatable===!0),rl(o,"list",e.list===!0),e.default!==void 0&&(o.default=e.default);let i=tn(e.description);i&&(o.description=i);let s=ap(e);o.value_arity=s.value_arity;let a=tn(e.value_name)??s.value_name;a&&(o.value_name=a);let c=s.value_type??(s.value_name?"string":null);return c&&(o.value_type=c),o}function qw(e){let t=new Map;for(let r of e){let o=Ae(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},s=`${r.layer}:${r.name}`;i.sourceDedupe.has(s)||(i.sourceDedupe.add(s),i.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=_T(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;i.dedupe.has(d)||(i.dedupe.add(d),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,s)=>{let a=i.layer.localeCompare(s.layer);return a!==0?a:(i.name??"").localeCompare(s.name??"")})});return n}function hT(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...Fc.filter(({flag:n})=>n.startsWith("--output-"))]}}function gT(e){let t=qw(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let s=Ae(i.command);if(s.length===0)continue;let a=tn(i.action)??Gw(s),c=Array.isArray(i.arguments)?i.arguments.map(d=>{let u=tn(d.name);return u?{name:u,required:d.required===!0,variadic:d.variadic===!0,description:tn(d.description)}:null}).filter(d=>d!==null):[];n.set(s,{...i.tier===void 0?{}:{tier:i.tier},...hT(i,t.get(s)?.flags??[]),command:s,action:a,source:{layer:i.layer,name:i.name},description:tn(i.description),intent:tn(i.intent),arguments:c,examples:Rw(i.examples),failure_hints:Rw(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(Ae(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((s,a)=>s.localeCompare(a))){let s=n.get(i);o.push(yT(i,s,t.get(i)?.flags??[]))}return o}function yT(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Gw(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function wT(e){let t=e.flag.startsWith("--")?e.flag:void 0,n=Ad({long:t,short:t===void 0?e.flag:void 0});return n!==null&&/[a-z0-9]/iu.test(n)?n:null}function vT(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 bT(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 kT(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]=vT(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=wT(o);!i||n[i]!==void 0||(n[i]=Fc.some(s=>s.flag===o.flag&&s.flag.startsWith("--output-"))?N_[i]:bT(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 ST(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 AT(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,s)=>i.localeCompare(s)).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 s=`${i.flag}|${i.short??""}`;if(!o.has(s))o.add(s),r.flags.push(i);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===s);a&&ST(a,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 ET(e,t=A){let n={mode:mn.extensions.policy.mode,trust_mode:mn.extensions.policy.trust_mode,default_sandbox_profile:mn.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await W(ce(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await jr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),s=await Gr({...i,loaded:i.loaded});return{handlers:new Set(s.commands.handlers.map(c=>Ae(c.command))),disabledReason:null,commandDefinitions:s.registrations.commands,flagRegistrations:s.registrations.flags,registrations:s.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 CT(e,t={}){let n=new Map;for(let r of xc){let o=ia.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=Tw(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of ia)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Tw(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??Ae(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function TT(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&&(!Pn.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?Ft(e.command_path):[],r=n.some(s=>t.handlers.has(s)||t.handlers.has(V(s))),o=n.map(s=>Fw.get(V(s))).find(s=>typeof s=="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 Kw(e){let t=$o.get(e)??Vn,n=Ge(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function il(e){return Pn.has(V(e))?!1:$o.has(e)}function RT(e){return Nw.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Iw(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function xT(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function IT(e){let t=new Map;for(let r of e.definitions){let o=Iw(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(a=>xT(a)).find(a=>a!==null),s=r.cli_aliases.map(a=>Iw(a)).filter(a=>a!==null&&a!==o);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},d=i?{flag:o,short:i}:{flag:o},u=`${d.flag}|${d.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(d));for(let p of s){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,Nc(o.flags));return n}function Ow(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 Nc(n)}function OT(e){let t=Ad(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function $T(e,t,n,r){let o=(n??[]).map(OT),i=t==="extension"&&(n!==void 0||PT(e,r));return{flags:o,inherited:i?{inherited_flags:vp({readOutput:LT(e,r)})}:{}}}function zw(e,t){let n=V(e);return t.find(r=>V(r.command)===n)}function PT(e,t){return zw(e,t)!==void 0}function LT(e,t){return zw(e,t)?.read_output!==void 0}function NT(e,t,n,r,o){let i=new Map(t);for(let{alias:s,canonical:a}of Te){let c=t.get(a)??t.get(s);c&&(i.set(s,c),i.set(a,c))}return e.map(s=>{let a=il(s),c=a?Kw(s):[],d=n.get(RT(s))??[],u=i.get(s),p=Ow(c,d),f=c.length>0&&(u?.flags.length??0)>0?"mixed":a?"core":"extension",h=$T(s,f,u?.flags,o),_=Ow(p,h.flags);return{command:s,flags:_,...h.inherited,...r?{canonical_command:Bw(s),visibility:Hw(s,o),positionals:yp(s)?.slots??[],flag_invocations:ao(s,_)}:{},provider:f,extension_sources:u?.sources}}).sort((s,a)=>s.command.localeCompare(a.command))}function FT(e,t=un){let n=new Set(e),r=new Map;for(let o of Uw){let i=o.aliases.filter(s=>n.has(s));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 MT(){return{create_string_options:F_,create_repeatable_options:Xi,update_string_options:M_,update_repeatable_options:D_,list_string_options:lp,search_string_options:mp,calendar_string_options:up,context_string_options:pp,activity_string_options:fp}}function $w(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let a of e.required_create_fields)n.add(a);for(let a of e.required_create_repeatables)n.add(a)}let r=Bn(e,"create",n),o=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),i=[...new Set(o.map(a=>Oe("create",a)))].sort((a,c)=>a.localeCompare(c)),s=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:o,required_flags:i,required_type_options:s,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.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]=$w(o,"strict"),n[r]=$w(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function UT(e,t){let n=Po(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let s=i.properties;if(typeof s!="object"||s===null)return i;let a=s.action;return typeof a!="object"||a===null||a.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function jT(e){let t=oa(e.action)!==void 0||oa(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,s=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=oa(e.action),u=oa(e.command),p=!r&&!c&&!o&&!i&&!s&&!d&&!u;return{selectedAction:d,selectedCommand:u,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:s,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function GT(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function qT(e,t=A){try{return await t(e)}catch{return structuredClone(mn)}}async function KT(e,t,n){let r=await qT(t),o=await ET(e),i=$(r,o.registrations??I()),s=et(r.schema),a=gT(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:D(r.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:IT(s),createRequiredOptionContracts:DT(i),extensionContracts:a,mergedExtensionContracts:AT(a.filter(c=>sa(n,c.command,a))),extensionFlagMap:qw(o.flagRegistrations)}}function Pw(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ia.has(e.selectedAction)||e.selectedCommand!==void 0&&Pn.has(V(e.selectedCommand)))}function zT(e,t){let n=CT(t,{includePackageOwnedActions:Pw(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Zu);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(i=>i.action===o.action)?.tier??ws(o.action))!=="internal"))}return Pw(e)&&e.selectedCommand!==void 0&&Pn.has(V(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:mT(V(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function HT(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new l(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function BT(e,t){return[...new Set([...Rc.filter(n=>!Pn.has(V(n))),...[...$o.keys()].filter(n=>!Pn.has(V(n))),...e.flatMap(n=>n.command_path?Ft(n.command_path).filter(r=>n.provider==="extension"||!Pn.has(V(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=>Ae(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function WT(e,t){let n=t.slice(0,aT),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,cT),s=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new l(`Command "${e}" is a command namespace. Choose a concrete child command: ${o}.`,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:s,nextSteps:[`Retry with a child command, for example: ${s[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --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 l(`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 YT(e){return new l(`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 JT(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(i=>i.startsWith(`${e.selectedCommand} `));if(r.length>0)throw WT(e.selectedCommand,r);let o=Fw.get(V(e.selectedCommand));throw o?VT(e.selectedCommand,o):YT(e.selectedCommand)}function XT(e,t){let n=zT(e,t.mergedExtensionContracts);HT(e,n);let r=BT(n,t.mergedExtensionContracts);JT(e,r);let o=e.selectedCommand?Dw.get(V(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(d=>o?d.action===o:uT(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.some(d=>d.action===e.selectedAction))throw new l(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let s=e.selectedAction?i.filter(d=>d.action===e.selectedAction):i,a=[...new Map(s.map(d=>TT(d,t.runtimeProbe)).map(d=>[o?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:i,scopedActionDescriptors:s,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function QT(e){return new Set(Po(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 ZT(e){let t=U_,n=Po(t),r=QT(t),o=e.filter(i=>!r.has(i.action)).map(i=>kT(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function Lw(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?fT(n,e.selectedAction):e.selectedCommand?nl(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):nl(n,r);return e.runtimeOnly&&!e.selectedAction?nl(o,new Set(t.actions)):o}function eR(e,t,n){let r=ZT(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?UT(Lw(e,n,r),t.createRequiredOptionContracts):Lw(e,n,r);return{mergedSchema:r,filteredSchema:i}}function tR(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?pT(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Hw(e,t){return t.find(n=>V(n.command)===V(e))?.tier??ws(e)}function sa(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||Hw(t,n)!=="internal"}function nR(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(un.filter(o=>o.hidden&&(o.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(o=>o.alias));if(e.summary&&!e.fullOutput)for(let o of ol.keys())r.add(o);return t.filter(o=>!r.has(o)&&sa(e,o,n))}function Bw(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":ol.get(n)??n}var rR=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"]]),oR=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function iR(e,t){let n=Cw.get(V(e))??(e.includes(" ")?void 0:Cw.get(Bw(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>Ft(d.command).some(u=>V(u)===V(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),s=o.slice(0,-1).join(" "),a=rR.get(i),c=oR.get(e)??s;return{intent:a===void 0||s.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function sR(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(Ae))].filter(i=>i.length>0).sort((i,s)=>i.localeCompare(s)).map(i=>{let s=ad(i,{generateFallback:!0}),a=i.split(" ")[0],c=ol.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...Kw(i).map(f=>f.flag),...t.filter(f=>Ft(f.command).some(h=>V(h)===V(i))).flatMap(f=>f.flags.map(h=>h.flag))]),u=(Ew.get(V(i))??Ew.get(c)??sT).filter(f=>d.has(f)),p=iR(i,t);return{command:i,intent:p.intent,...o||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:s.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...s.default_max_estimated_tokens_by_format}}:{}}})}function aR(e){return e.map(t=>({budget:ad(t,{generateFallback:!0}),envelope:Ph(t)}))}function cR(e){let t=new Map;for(let n of e){let r=xh(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(","),s=t.get(i)??{commands:[],exit_codes:o};s.commands.push(n),t.set(i,s)}return[...t.values()]}function dR(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>Ft(r.command).some(o=>V(o)===V(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>Ft(o.command).some(i=>r.has(i)))}return t.extensionContracts.filter(r=>sa(e,r.command,t.extensionContracts))}function lR(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 mR(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=Mf);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(s=>`--${s.cli_flag}`))].sort((s,a)=>s.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...zu],services:[...Hu],policy_modes:[...Bu],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Yu],trust_modes:[...Wu],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Vu],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Ru],create_modes:[...xu],close_validation_modes:[...Iu],workflow_enforcement_modes:[...Ou]},e.relationship_kind_contracts=[...Mu,...(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 uR(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 pR(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=NT(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(gp).filter(([s])=>i.has(s)).map(([s,a])=>({command:s,default:a,brief_fields:[...hp,"priority"],compact_fields:[..._p]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:s})=>({canonical:i,aliases:s})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function fR(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=MT();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function _R(e,t,n,r){e.command_summaries=sR(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...k_],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(Ae))].filter(o=>E_(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...T_(o).keys()]}))}:{}},e.grammar_contracts={nouns:pn.nouns,shared_verbs:pn.shared_verbs,scope_before_verb:pn.scope_before_verb,visible_top_level_ceiling:pn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:pn.ceiling_raise_requires_pm_item,positional_shape_budget:pn.positional_shape_budget,positional_shape_count:new Set(Lc.map(({slots:o})=>wp(o))).size,positional_action_count:Pc.length,positional_action_parents:[...new Set(Pc.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:Lc}:{}}}async function sl(e,t){let n=jT(e);GT(n);let r=E(process.cwd(),t.path),o=await KT(t,r,n),i=XT(n,o),s=eR(n,o,i),a=tR(n,i),c=nR(n,a,o.extensionContracts),d=lR(n,s,i,c),u=dR(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&_R(d,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return d;let f=FT(i.commandCatalog.filter(h=>sa(n,h,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||mR(d,o,n),uR(d,n,s,u),pR(d,n,o,c,f),fR(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...ng],gate_triggers:[...tg]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=di.map(h=>({...h,reason:h.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=Aw(),d.context_intents=I_(),d.read_output_dimensions=A_,d.error_codes=Ih,d.command_output_contracts=aR(c),d.diagnostic_output_contracts=S_,d.command_exit_contracts={vocabulary:Rh,command_sets:cR(c)}),d}async function Ww(e,t,n=x_){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 hR}from"node:crypto";function al(e){let t=Du();for(let n of e)t.register(n);return t}function gR(e,t,n=[]){if(n.length===0)return e;let r=JSON.parse(e),o=JSON.parse(wd(t));for(let i of n){let s=i.split("."),a=o;for(let u of s){let p=Cc(a);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(u)||["constructor","prototype","__proto__"].includes(u)||p===null||!Object.hasOwn(p,u))throw new l(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,m.USAGE);a=p[u]}if(Cc(a)===null)throw new l(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,m.USAGE);let c=r,d=o;for(let u of s.slice(0,-1)){let p=c[u];d=d[u],p===void 0&&Object.defineProperty(c,u,{value:structuredClone(d),enumerable:!0,writable:!0,configurable:!0}),c=c[u]}Object.defineProperty(c,s.at(-1),{value:a,enumerable:!0,writable:!0,configurable:!0})}return ie(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
2
+ `}async function yR(e,t,n){let r=t.schema?.fields??[];if(r.length===0)return;let{normalizeCliToken:o,resolveRuntimeFieldRegistry:i}=await import("./runtime-schema-YXPYDD2C.js"),s=f=>i({fields:[f]}).definitions[0],a=f=>JSON.parse(JSON.stringify(f)),c=[...e.schema.fields,...Array.isArray(n)?n:[]].map(f=>({resolved:s(f),persisted:a(f)})),d=f=>[f.cli_flag,...Array.isArray(f.cli_aliases)?f.cli_aliases:[]].some(h=>typeof h=="string"&&o(h).length===0),u=r.filter(f=>{let h=s(f),_=c.some(g=>ie(g.persisted,a(f)));return h===void 0||d(f)?!_:!c.some(g=>ie(g.resolved,h))});if(u.length===0)return;let{assertFieldDefinitionOptionsAvailable:p}=await import("./field-option-collisions-BP7ILGQK.js");for(let f of u)p(f)}function Vw(e,t,n,r){return{fitOutputEnvelope:ig,client:t,isItemNotFoundError:o=>so(o)&&o.exitCode===m.NOT_FOUND,getItemAt:(o,i)=>og(o,i,{pmRoot:e}),readSettingsSection:(o,i)=>Sh(e,o,i),writeSettingsSection:(o,i,s)=>Ah(e,o,i,{author:n,...s}),openRelationshipEventStore:o=>ag.open({pmRoot:e,nodes:o.nodes,registry:al(o.definitions),...o.relativePath===void 0?{}:{relativePath:o.relativePath}}),createRelationshipGraph:o=>new Gu(o.nodes,o.edges,al(o.definitions)),analyzeRelationshipImpact:(o,i,s)=>cg(o,i,s),validateRelationshipEvents:o=>{let i=new sg(o.nodes,{registry:al(o.definitions)});return o.events.map(s=>i.append({...s,expectedVersion:i.version}))},commitWorkspaceTransaction:o=>dg({...o,pmRoot:e}),mutateWorkspaceSettings:async o=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(o.operationId))throw new l("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",m.USAGE);let i=o.dryRun===!0?await ir(e,()=>A(e)):await A(e);try{let s=await ds({pmRoot:e,filePath:ce(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${hR("sha256").update(r).digest("hex").slice(0,16)}:${o.operationId}`,author:R(n,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!1,dryRun:o.dryRun===!0,mutate:async a=>{let c=a===null?null:JSON.parse(a),d=_s(c);if(!d.success)throw new l("Workspace settings mutation requires a valid initialized settings.json.",m.USAGE);let u=yd(d.data),p=await o.mutate(structuredClone(u));if(!_s(p).success)throw new l("Workspace settings mutation returned invalid settings.json.",m.USAGE);await yR(u,p,c.schema?.fields);let f=ie(u,p)?a:wd(p,{source:{raw:c,validated:d.data}});f=gR(f,p,o.replaceSubtrees);let h=_s(JSON.parse(f));if(!h.success)throw new l("Workspace settings mutation serialized invalid settings.json.",m.USAGE);return{raw:f,result:o.includePreview===!0?yd(h.data):void 0}}});return s.changed&&o.dryRun!==!0&&await Z({path:ce(e),scope:"project",op:"extension:pm:settings"}),{changed:s.changed,dry_run:o.dryRun===!0,replayed:s.replayed===!0,...s.result===void 0?{}:{preview:s.result}}}finally{oh(e)}}}}function Yw(e){return{undeclaredKeys:il(e)?"pass":"refuse"}}import wR from"node:fs/promises";import ee from"node:path";import vR from"node:readline/promises";import{stdin as bR,stdout as ze}from"node:process";var dl=Symbol.for("pm.sdk.init-invocation-cwd");var kR=()=>vR.createInterface({input:bR,output:ze});function SR(){return structuredClone(mn)}var AR=["minimal","default","strict"];function Xw(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--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 l(`Invalid --preset value "${e}". Allowed: ${AR.join(", ")}`,m.USAGE)}function ER(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",m.USAGE);try{return Ef(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${Af.join(", ")}`,m.USAGE)}}}function CR(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new l("--author must not be empty",m.USAGE);return t}function cl(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:ee.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function TR(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new l("--workspace must not be empty",m.USAGE);if(o!==void 0){if(t.path!==void 0||cl(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",m.USAGE);let d=ee.resolve(e,o),u=ee.join(d,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:d}}}if(t.path===void 0&&cl(n)){let d=ee.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let i=E(e,t.path),s=ee.join(ee.resolve(e),".agents","pm"),a=ee.dirname(ee.dirname(i)),c=ee.resolve(i)===s?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:a,discovery:c,requested_cwd:ee.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:s}:{}}:{mode:"tracker-path",tracker_root:i}}}function RR(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new l("--id-prefix must not be empty",m.USAGE);if(cl(t))throw new l(`--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&&Yt(e)!==Yt(t))throw new l(`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 ${Yt(e)}`,`pm init --id-prefix ${Yt(t)}`]});return t}function xR(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--agent-guidance must not be empty",m.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new l(`Invalid --agent-guidance value "${e}". Allowed: ${$g.join(", ")}`,m.USAGE)}function IR(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Qw(e,t){let n=Lu[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function OR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $R(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(OR).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function PR(e,t,n){let r=Di(t.schema),o=Rt(e,r.files.types,Tt.types),s=kf(await oe(o)),a=[],c=[];for(let d of Cf(n)){let u=Sf(s,d);s=u.file,(u.replaced?c:a).push(u.definition.name)}return await ot({pmRoot:e,filePath:o,raw:Fi(s),op:"init:type-preset",author:R(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:o}}async function LR(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",ee.join(".agents","pm")];for(let n of t)if(await W(ee.join(e,n)))return!0;return!1}async function NR(e,t,n){if(!t||n||await W(ee.join(e,"settings.json"))||!await LR(e))return;let r=ee.join(e,".agents","pm");throw new l(`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 Zw(e,t){let n=[],r=[];for(let o of t){let i=o?ee.join(e,o):e,s=await W(i);await wR.mkdir(i,{recursive:!0}),s?r.push(`already_exists:${i}`):n.push(i),r.push(...await Z({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function FR(e,t){let n=kR(),r=t===void 0?2:3;try{ze.write(`pm init setup wizard (agent-optimized)
3
3
  `),ze.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
4
4
 
5
5
  `),ze.write(`1/${r} Item ID prefix
@@ -26,7 +26,7 @@ import{A as Ad,B as Ch,C as Th,n as Tf,o as Mi,p as Pf,q as Lf,r as Ui,s as Wr,t
26
26
  ${r(t.oursRaw)}||||||| pm base
27
27
  ${r(t.baseRaw)}=======
28
28
  ${r(t.theirsRaw)}>>>>>>> pm theirs
29
- `,"utf8"),new l(`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 Mk(e,t){let n=BF(e.artifact),r=WF(e.prefer),o=HF.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([Cm(e.basePath,"base"),Cm(e.oursPath,"ours"),Cm(e.theirsPath,"theirs")]),c,d,u=[],p={},f={baseRaw:i,oursRaw:s,theirsRaw:a,outputPath:o,itemPath:e.itemPath??o};if(n==="history"){let _=await Nk(()=>qg(i,s,a),f);c=_.merged,p.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=Kg(i,s,a);c=_.merged,p.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await VF(t),g=YF(e.itemPath??o,_),y=Ue(I()),w=await Nk(()=>zg(i,s,a,{format:g,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"}),f);if(c=w.merged,u.push(...w.conflict_fields),p.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 v=Xf(c,{format:g,schema:_?.schema,extensionFieldNames:y}),k=v.metadata,S=[...new Set([...w.fields_from_theirs,...w.union_fields,...w.conflict_decisions.map(T=>T.field)])];d={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:w.fields_from_theirs,unionFields:w.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,Gg(T==="body"?v.body:k[T])])),decisions:w.conflict_decisions,operation:await Bg(process.cwd(),e.itemPath,s)}}}else{let _=Hg(i,s,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await Fk(o,c,"utf8"),d!==void 0){let _=await Vg(d);_!==null&&(p.receipt=An(_))}let h=[];if(u.length>0){let _=p.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${p.receipt.receipt_id} with item ${p.receipt.item_id}; clone-local discarded values are never copied into this result.`;h.push(`Both branches changed ${u.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&p.history?.reanchored&&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:u.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:u,...p,guidance:h,generated_at:C()}}async function Dk(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await Wg(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await en(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await en(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:[{...An(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await Os(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as JF}from"node:fs/promises";import XF from"node:path";var QF=4;function Uk(e){let t=e.checks.find(a=>a.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,s=Array.isArray(o)?o.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:i,coordinates:s}}async function ZF(e,t){let n=[];for(let r of t){let o;try{o=await JF(XF.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 s;try{s=JSON.parse(i)}catch{continue}let a=ey(s,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!Zg(a)||a.eventTimestamp===void 0||Gi(a.eventTimestamp,Qg)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function eM(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 en(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 tM(e){try{return{status:"fulfilled",value:await en(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 nM(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 rM(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=>Os(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}function oM(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 iM(e,t){if(e.force===!0)throw new l("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-RG3PKST7.js"),i=await o(t),s=await $a({...n,dryRun:!0},i);return r({preview:s,dryRun:e.dryRun===!0,global:i,apply:()=>$a({...n,dryRun:!1},i)})}async function $a(e,t){return e.stage===!0?iM(e,t):sM(e,t)}async function sM(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await wo(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=Uk(o),s=await ZF(r,i.coordinates),a=await xs(r),c=a??r,d=await Yg(c,{includeLossless:!0,pmRoot:r});if(d.invalid_evidence_count>0)throw new l(`Merge reconciliation refused ${d.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"}});Jg(d.receipts.map(G=>G.id),d,n);let u=await eM({candidates:s,options:e,global:t}),p=d.receipts,f=await Dk({cwd:a,receipts:p,dryRun:n,author:e.author,message:e.message,global:t}),h=new Set(f),_=new Map;for(let G of p.filter(he=>!h.has(he.id))){let he=_.get(G.item_id)??[];he.push(G),_.set(G.item_id,he)}let g=Object.fromEntries([..._].map(([G,he])=>[G,{merge:{receipts:he.map(An)}}])),y=Object.fromEntries([..._].map(([G,he])=>[G,{gitWorkspaceRoot:a,receipts:he}])),w=await Ps({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,...p.length>0?{mergeReceiptProofById:y}:{}},t),v=new Set(w.streams.map(G=>G.id)),k=[..._.keys()].filter(G=>!v.has(G)),S=await yh(k,QF,G=>tM({id:G,dryRun:n,options:e,global:t,auditContext:g[G],mergeReceiptProof:y[G]}));nM({receiptOnlyIds:k,results:S,repair:w});let T=await rM({dryRun:n,pendingReceipts:p,repair:w,receiptWorkspaceRoot:c}),x=await Fs({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),F=u===0?o:await wo(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),L=Uk(F),H=x.checks.every(G=>G.status==="ok"),B=n?p.length===0:T+f.length===p.length,Y=[w.totals.failed===0,H,B,L.count===0,!L.truncated].every(Boolean),re=i.truncated||L.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,J=oM(p.length,Y),Gt=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",re,J,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:Y?["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.",re,J,...s.length>0&&u===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:Y,dry_run:n,repair:w,receipts:{pending_before:p.length,reconciled:T,abandoned:f.length,summaries:p.map(An),unstaged_durable_receipt_ids:d.unstaged_durable_receipt_ids,missing_history_references_before:i.count,legacy_disposition_eligible:s.length,legacy_disposition_recorded:u,missing_history_references_after:L.count},validation:x,guidance:Gt,generated_at:x.generated_at}}import{createHash as aM}from"node:crypto";var Kk=1,zk=/^[A-Za-z0-9_-]+$/,cM=100,jk=1e3;var HX=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function lt(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 dM(e){return aM("sha256").update(Ct({type:lt(e.type),author:lt(e.author),item:lt(e.item),harness:lt(e.harness),agent_instance:lt(e.agentInstance),provenance:lt(e.provenanceFilter)})).digest("hex").slice(0,24)}function Gk(e,t){let n={version:Kk,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 lM(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Kk,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 mM(e,t){let n=e.trim();if(n.length===0||n.length>4096||!zk.test(n))throw new l("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 l("Invalid mutation event cursor.",m.USAGE,{code:"invalid_event_cursor"})}if(!lM(r,t))throw new l("Mutation event cursor does not match this query.",m.USAGE,{code:"event_cursor_query_mismatch"});return r}function uM(e){let t=e??cM;if(!Number.isSafeInteger(t)||t<0||t>jk)throw new l(`Mutation event limit must be an integer from 0 to ${jk}.`,m.USAGE,{code:"invalid_event_limit"});return t}function pM(e,t){let n=e?.trim();if(!n)return{};if(zk.test(n))return{cursor:mM(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new l("Mutation event --since must be an event cursor or ISO timestamp.",m.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function fM(e,t){if(t.verify)return qk(e,t);let n=await Xc(e,t),r=n.result;if(r===null&&n.repair_needed)try{await a_(e,{lockWaitMs:0})&&(r=(await Xc(e,t)).result)}catch{}return r===null?qk(e,t):{...r,source:"derived_index"}}async function qk(e,t){try{return{...await c_(e,t),source:"authoritative_history"}}catch(n){throw n instanceof l?n:new l("Mutation events are unavailable because authoritative history could not be read.",m.GENERIC_FAILURE,{code:"event_index_unavailable",why:mt(n)})}}function _M(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new l("Mutation event cursor mode must be batch or row.",m.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Pa(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=uM(e.limit),r=_M(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new l("Mutation event projections are mutually exclusive. Use --provenance or --full.",m.USAGE);let o=await A(t),i=o.agent_identity.identity_vocabulary,s=Ty(o.agent_identity.harness_signals),a=Ry({provenance:e.provenanceFilter},s),c=lt(e.harness),d=dM(e),{cursor:u,sinceTimestamp:p}=pM(e.since,d),f={verify:e.verify===!0,...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:lt(e.type),authors:lt(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,g])=>c.includes(g)).map(([g])=>g):void 0,agent_instances:lt(e.agentInstance),provenance:[...a].map(([g,y])=>({dimension:g,values:[...y]})),stream_ids:lt(e.item),limit:n},h=await fM(t,f),_=h.events.map(g=>({...r==="row"?{cursor:Gk(g,d)}:{},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:xy(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:Gk(h.events[h.events.length-1],d)},source:h.source,...e.provenanceSummary===!0?{provenance_summary:Iy(h.events.map(g=>g.entry),i,s)}:{}}}var hM="1h",gM="now",yM="+1d";function sn(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Hk(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 ue(n,r)}async function Bk(e,t,n,r){let o=Hk(e,t,n),i=[];return sn(i,"start",n.start??gM),n.end!==void 0?sn(i,"end",n.end):sn(i,"duration",n.duration??hM),sn(i,"location",n.location),sn(i,"timezone",n.timezone),n.allDay===!0&&sn(i,"all_day","true"),o.event=[i.join(",")],rn(o,r)}function Wk(e,t,n){return Bk("Meeting",e,t,n)}function Vk(e,t,n){return Bk("Event",e,t,n)}function Yk(e,t,n){let r=Hk("Reminder",e,t),o=[];return sn(o,"at",t.at??yM),sn(o,"text",t.text??e),r.reminder=[o.join(",")],rn(r,n)}import Uo from"node:crypto";import{cp as Jk,lstat as wM,mkdir as Gn,readFile as xr,readdir as Rm,rename as Zk,rm as Im,writeFile as La}from"node:fs/promises";import U from"node:path";var eS="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var tS=U.join("runtime","workspace-snapshots"),vM=new Set(["checkpoints","locks","runtime","search","transactions"]),bM=/^[a-z0-9][a-z0-9._-]*$/,Rr="sdk-workspace-transaction",Tm={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},nS={renameEntry:Zk,removeEntry:async e=>{await Im(e,{recursive:!0,force:!0})}},xm=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 Qf(this.lockPath,Rr);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await xr(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!==Rr||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await ae(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
29
+ `,"utf8"),new l(`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 Mk(e,t){let n=BF(e.artifact),r=WF(e.prefer),o=HF.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([Cm(e.basePath,"base"),Cm(e.oursPath,"ours"),Cm(e.theirsPath,"theirs")]),c,d,u=[],p={},f={baseRaw:i,oursRaw:s,theirsRaw:a,outputPath:o,itemPath:e.itemPath??o};if(n==="history"){let _=await Nk(()=>qg(i,s,a),f);c=_.merged,p.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=Kg(i,s,a);c=_.merged,p.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await VF(t),g=YF(e.itemPath??o,_),y=Ue(I()),w=await Nk(()=>zg(i,s,a,{format:g,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"}),f);if(c=w.merged,u.push(...w.conflict_fields),p.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 v=Xf(c,{format:g,schema:_?.schema,extensionFieldNames:y}),k=v.metadata,S=[...new Set([...w.fields_from_theirs,...w.union_fields,...w.conflict_decisions.map(T=>T.field)])];d={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:w.fields_from_theirs,unionFields:w.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,Gg(T==="body"?v.body:k[T])])),decisions:w.conflict_decisions,operation:await Bg(process.cwd(),e.itemPath,s)}}}else{let _=Hg(i,s,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await Fk(o,c,"utf8"),d!==void 0){let _=await Vg(d);_!==null&&(p.receipt=An(_))}let h=[];if(u.length>0){let _=p.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${p.receipt.receipt_id} with item ${p.receipt.item_id}; clone-local discarded values are never copied into this result.`;h.push(`Both branches changed ${u.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&p.history?.reanchored&&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:u.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:u,...p,guidance:h,generated_at:C()}}async function Dk(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await Wg(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await en(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await en(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:[{...An(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await Os(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as JF}from"node:fs/promises";import XF from"node:path";var QF=4;function Uk(e){let t=e.checks.find(a=>a.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,s=Array.isArray(o)?o.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:i,coordinates:s}}async function ZF(e,t){let n=[];for(let r of t){let o;try{o=await JF(XF.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 s;try{s=JSON.parse(i)}catch{continue}let a=ey(s,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!Zg(a)||a.eventTimestamp===void 0||Gi(a.eventTimestamp,Qg)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function eM(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 en(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 tM(e){try{return{status:"fulfilled",value:await en(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 nM(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 rM(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=>Os(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}function oM(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 iM(e,t){if(e.force===!0)throw new l("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-NSX6ASBZ.js"),i=await o(t),s=await $a({...n,dryRun:!0},i);return r({preview:s,dryRun:e.dryRun===!0,global:i,apply:()=>$a({...n,dryRun:!1},i)})}async function $a(e,t){return e.stage===!0?iM(e,t):sM(e,t)}async function sM(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await wo(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=Uk(o),s=await ZF(r,i.coordinates),a=await xs(r),c=a??r,d=await Yg(c,{includeLossless:!0,pmRoot:r});if(d.invalid_evidence_count>0)throw new l(`Merge reconciliation refused ${d.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"}});Jg(d.receipts.map(G=>G.id),d,n);let u=await eM({candidates:s,options:e,global:t}),p=d.receipts,f=await Dk({cwd:a,receipts:p,dryRun:n,author:e.author,message:e.message,global:t}),h=new Set(f),_=new Map;for(let G of p.filter(he=>!h.has(he.id))){let he=_.get(G.item_id)??[];he.push(G),_.set(G.item_id,he)}let g=Object.fromEntries([..._].map(([G,he])=>[G,{merge:{receipts:he.map(An)}}])),y=Object.fromEntries([..._].map(([G,he])=>[G,{gitWorkspaceRoot:a,receipts:he}])),w=await Ps({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,...p.length>0?{mergeReceiptProofById:y}:{}},t),v=new Set(w.streams.map(G=>G.id)),k=[..._.keys()].filter(G=>!v.has(G)),S=await yh(k,QF,G=>tM({id:G,dryRun:n,options:e,global:t,auditContext:g[G],mergeReceiptProof:y[G]}));nM({receiptOnlyIds:k,results:S,repair:w});let T=await rM({dryRun:n,pendingReceipts:p,repair:w,receiptWorkspaceRoot:c}),x=await Fs({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),F=u===0?o:await wo(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),L=Uk(F),H=x.checks.every(G=>G.status==="ok"),B=n?p.length===0:T+f.length===p.length,Y=[w.totals.failed===0,H,B,L.count===0,!L.truncated].every(Boolean),re=i.truncated||L.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,J=oM(p.length,Y),Gt=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",re,J,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:Y?["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.",re,J,...s.length>0&&u===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:Y,dry_run:n,repair:w,receipts:{pending_before:p.length,reconciled:T,abandoned:f.length,summaries:p.map(An),unstaged_durable_receipt_ids:d.unstaged_durable_receipt_ids,missing_history_references_before:i.count,legacy_disposition_eligible:s.length,legacy_disposition_recorded:u,missing_history_references_after:L.count},validation:x,guidance:Gt,generated_at:x.generated_at}}import{createHash as aM}from"node:crypto";var Kk=1,zk=/^[A-Za-z0-9_-]+$/,cM=100,jk=1e3;var HX=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function lt(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 dM(e){return aM("sha256").update(Ct({type:lt(e.type),author:lt(e.author),item:lt(e.item),harness:lt(e.harness),agent_instance:lt(e.agentInstance),provenance:lt(e.provenanceFilter)})).digest("hex").slice(0,24)}function Gk(e,t){let n={version:Kk,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 lM(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Kk,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 mM(e,t){let n=e.trim();if(n.length===0||n.length>4096||!zk.test(n))throw new l("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 l("Invalid mutation event cursor.",m.USAGE,{code:"invalid_event_cursor"})}if(!lM(r,t))throw new l("Mutation event cursor does not match this query.",m.USAGE,{code:"event_cursor_query_mismatch"});return r}function uM(e){let t=e??cM;if(!Number.isSafeInteger(t)||t<0||t>jk)throw new l(`Mutation event limit must be an integer from 0 to ${jk}.`,m.USAGE,{code:"invalid_event_limit"});return t}function pM(e,t){let n=e?.trim();if(!n)return{};if(zk.test(n))return{cursor:mM(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new l("Mutation event --since must be an event cursor or ISO timestamp.",m.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function fM(e,t){if(t.verify)return qk(e,t);let n=await Xc(e,t),r=n.result;if(r===null&&n.repair_needed)try{await a_(e,{lockWaitMs:0})&&(r=(await Xc(e,t)).result)}catch{}return r===null?qk(e,t):{...r,source:"derived_index"}}async function qk(e,t){try{return{...await c_(e,t),source:"authoritative_history"}}catch(n){throw n instanceof l?n:new l("Mutation events are unavailable because authoritative history could not be read.",m.GENERIC_FAILURE,{code:"event_index_unavailable",why:mt(n)})}}function _M(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new l("Mutation event cursor mode must be batch or row.",m.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Pa(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=uM(e.limit),r=_M(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new l("Mutation event projections are mutually exclusive. Use --provenance or --full.",m.USAGE);let o=await A(t),i=o.agent_identity.identity_vocabulary,s=Ty(o.agent_identity.harness_signals),a=Ry({provenance:e.provenanceFilter},s),c=lt(e.harness),d=dM(e),{cursor:u,sinceTimestamp:p}=pM(e.since,d),f={verify:e.verify===!0,...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:lt(e.type),authors:lt(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,g])=>c.includes(g)).map(([g])=>g):void 0,agent_instances:lt(e.agentInstance),provenance:[...a].map(([g,y])=>({dimension:g,values:[...y]})),stream_ids:lt(e.item),limit:n},h=await fM(t,f),_=h.events.map(g=>({...r==="row"?{cursor:Gk(g,d)}:{},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:xy(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:Gk(h.events[h.events.length-1],d)},source:h.source,...e.provenanceSummary===!0?{provenance_summary:Iy(h.events.map(g=>g.entry),i,s)}:{}}}var hM="1h",gM="now",yM="+1d";function sn(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Hk(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 ue(n,r)}async function Bk(e,t,n,r){let o=Hk(e,t,n),i=[];return sn(i,"start",n.start??gM),n.end!==void 0?sn(i,"end",n.end):sn(i,"duration",n.duration??hM),sn(i,"location",n.location),sn(i,"timezone",n.timezone),n.allDay===!0&&sn(i,"all_day","true"),o.event=[i.join(",")],rn(o,r)}function Wk(e,t,n){return Bk("Meeting",e,t,n)}function Vk(e,t,n){return Bk("Event",e,t,n)}function Yk(e,t,n){let r=Hk("Reminder",e,t),o=[];return sn(o,"at",t.at??yM),sn(o,"text",t.text??e),r.reminder=[o.join(",")],rn(r,n)}import Uo from"node:crypto";import{cp as Jk,lstat as wM,mkdir as Gn,readFile as xr,readdir as Rm,rename as Zk,rm as Im,writeFile as La}from"node:fs/promises";import U from"node:path";var eS="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var tS=U.join("runtime","workspace-snapshots"),vM=new Set(["checkpoints","locks","runtime","search","transactions"]),bM=/^[a-z0-9][a-z0-9._-]*$/,Rr="sdk-workspace-transaction",Tm={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},nS={renameEntry:Zk,removeEntry:async e=>{await Im(e,{recursive:!0,force:!0})}},xm=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 Qf(this.lockPath,Rr);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await xr(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!==Rr||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await ae(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
30
30
  `)}finally{await t()}}};async function rS(e,t=""){let n=await Rm(U.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((i,s)=>i.name.localeCompare(s.name))){if(t.length===0&&vM.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 rS(e,i));else if(o.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function oS(e){let t=await rS(e),n=Uo.createHash("sha256"),r=[],o=0;for(let s of t){let a=await xr(U.join(e,s));r.push(a),o+=a.byteLength,n.update(s),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let i=n.digest("hex");return{manifest:{schema:eS,fingerprint:i,files:t,bytes:o},contents:r}}function Xk(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
31
31
  `).filter(t=>t.trim().length>0).length}async function kM(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 s=>[s,await xr(U.join(e,s))]));for(let[s,a]of i)n.set(s,a)}return n}function Om(e){if(!bM.test(e))throw new l("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 iS(e,t){return Ur(`workspace_snapshot_${e}`,t,{codes:{capacity:Tm.capacity.code,permission:Tm.permission.code,resource:Tm.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 qn(e){return U.join(e,tS)}function sS(e){return new l(`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 aS(e,t){try{return JSON.parse(await xr(e,"utf8"))}catch(n){throw je(n)?sS(t):n}}async function Qk(e,t,n){try{await Im(e,{recursive:n})}catch(r){throw je(r)?sS(t):r}}async function SM(e,t,n=nS){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 AM(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 EM(e,t){return Om(t),/^[a-f0-9]{64}$/.test(t)?t:(await aS(U.join(qn(e),"refs",`${t}.json`),t)).fingerprint}async function $m(e,t={}){if(t.name!==void 0&&(Om(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new l("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 oS(e),o=qn(e),i=U.join(o,"objects",n.fingerprint),s=!1;try{s=(await wM(i)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&je(a)))throw a}if(!s){let a=U.join(o,"objects",`.create-${process.pid}-${Uo.randomUUID()}`);await iS("create_object",async()=>{await Gn(U.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let u=U.join(a,"files",d);await Gn(U.dirname(u),{recursive:!0}),await La(u,r[c])}await La(U.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
32
32
  `,"utf8"),await Gn(U.dirname(i),{recursive:!0})}),s=await SM(a,i)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=U.join(o,"refs");await Gn(c,{recursive:!0});let d=U.join(c,`.ref-${process.pid}-${Uo.randomUUID()}`);await La(d,`${JSON.stringify(a,null,2)}
@@ -40,5 +40,5 @@ ${t}`;for(let r of G0)if(r.regex.test(n))return{code:r.code};return null}functio
40
40
  [pm linked-test output truncated at ${Ba} bytes per stream; the child process continued to completion]
41
41
  `:"";!_&&await ZS(e,{exitCode:v,stderr:T.text},n,i)&&(_="Linked test executable was not found. Install the tool or update the linked command before retrying.");let L={stdout:`${S.text}${F}`,stderr:T.text,exitCode:v,signal:k,timedOut:w,maxBufferExceeded:!1,outputTruncated:x,spawnError:_};return BD(r,L,s,o),L}finally{await Wo(a,{recursive:!0,force:!0})}}function QD(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Ba} 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 ZD(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
42
42
  `);return vD.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>bD.test(n)&&kD.test(n))}function eU(e){return ZD(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function sA(e,t){for(let[n,r]of Object.entries(t.env_set))In.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)In.has(n.toUpperCase())||delete e[n]}function tU(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 nU(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 EA(e,t,n){return{env_set:$D(e,"--env-set"),env_clear:PD(t,"--env-clear"),shared_host_safe:n===!0}}async function Bo(e,t,n=!1,r=Ym){if(await W(e))try{await Ur("seed_linked_test",async()=>{if(await r(me.dirname(t),{recursive:!0}),n){await nA(e,t,{recursive:!0,force:!0});return}await nA(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&&je(o))return;throw o}}async function aA(e,t,n,r=!1){for(let[o,i]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let s=await oe(ce(o));if(s!==null){let a=await A(i);await ot({pmRoot:i,filePath:ce(i),raw:s,op:"settings:write",author:R(void 0,a.author_default),lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Bo(ce(o),ce(i));await Bo(me.join(n.projectPmRoot,"extensions"),me.join(e,"extensions"),!0),await Bo(me.join(n.globalPmRoot,"extensions"),me.join(t,"extensions"),!0)}async function cA(e,t){if(!await W(e))return;let n=await Wm(e,{withFileTypes:!0});for(let r of n){if(yD.has(r.name))continue;let o=me.join(e,r.name),i=me.join(t,r.name);if(r.isDirectory()){await Bo(o,i,!0);continue}r.isFile()&&await Bo(o,i)}}async function dA(e,t){let n=await oe(ce(e));if(n===null||await W(hd(e)))return;let r=await A(t);await Wo(hd(t),{force:!0}),await Wo(ce(t),{force:!0}),await ot({pmRoot:t,filePath:ce(t),raw:n,op:"settings:write",author:R(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 Or(e){if(!await W(e))return 0;let t=0,n=await Wm(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||wD.has(r.name))continue;let o=me.join(e,r.name),i;try{i=await Wm(o,{withFileTypes:!0})}catch{continue}for(let s of i)s.isFile()&&Ku.some(a=>s.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function rU(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function oU(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 iU(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?ie(e,t):Object.is(e,t)}function sU(e,t,n){let r=[];r.push(...lA("stdout",t,e.assert_stdout_contains)),r.push(...mA("stdout",t,e.assert_stdout_regex)),r.push(...lA("stderr",n,e.assert_stderr_contains)),r.push(...mA("stderr",n,e.assert_stderr_regex)),r.push(...aU(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(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,d]of Object.entries(o)){let u=Gm(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=oU(d);iU(u.value,p)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(u.value)})`)}for(let[c,d]of Object.entries(i)){let u=Gm(a,c);if(!u.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof u.value!="number"||!Number.isFinite(u.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}u.value<d&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${d}, actual ${u.value})`)}return r}function lA(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function mA(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 aU(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 cU(e){let t=Ns(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Ls(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&kA(n))}function dU(e){return{root:e,schemaProjectPmPath:me.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:me.join(e,"schema","global"),trackerProjectPmPath:me.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:me.join(e,"tracker","global"),workspaceSnapshotRoot:me.join(e,"workspace","project"),workspaceIsolatedRoot:me.join(e,"workspace","isolated")}}function lU(e,t,n){return e.some(r=>yA(r,t,n)==="snapshot")}async function mU(e,t){let n=me.join(e,".agents"),r=me.join(n,"pm");await Ym(n,{recursive:!0}),await Wo(r,{recursive:!0,force:!0}),await fD(t,r,process.platform==="win32"?"junction":"dir")}async function uU(e,t=Lo,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 pU(e,t,n){t&&(await aA(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await aA(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await cA(t.projectPmRoot,e.trackerProjectPmPath),await cA(t.globalPmRoot,e.trackerGlobalPmPath),await dA(t.projectPmRoot,e.trackerProjectPmPath),await dA(t.globalPmRoot,e.trackerGlobalPmPath)))}function fU(e,t,n){return e.some(r=>{let o=r.command??"",i=o.length>0&&bA(o),s=n?.autoPmContext===!0&&i?"auto":wA(r,t,n?.overrideLinkedPmContext===!0);return vA(s,i)==="tracker"})}async function _U(e,t){return{sourceProjectItemCount:t?await Or(t.projectPmRoot):0,sourceGlobalItemCount:t?await Or(t.globalPmRoot):0,schemaProjectItemCount:await Or(e.schemaProjectPmPath),schemaGlobalItemCount:await Or(e.schemaGlobalPmPath),trackerProjectItemCount:await Or(e.trackerProjectPmPath),trackerGlobalItemCount:await Or(e.trackerGlobalPmPath)}}function hU(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,s=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":s;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:s,source_workspace_root:a,trust:e.trust}}async function gU(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Va(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?LD(n):!1,o=r&&n?bA(n):!1,i=e.options?.autoPmContext===!0&&o,s=i?"auto":wA(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=vA(s,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await mU(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await qd(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await qd(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:hU({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:s,effectivePmContextMode:a,autoPmContextApplied:i,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function uA(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function yU(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 wU(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 vU(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 wU(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 bU(e){if(!e.linkedTest.command)return uA(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=MD(e.linkedTest.command);return t?uA(e.linkedTest,e.executionContext,t):null}function kU(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Wa(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?Wa(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 Wa(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 SU(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=OD({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 Wa(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 AU(e){let t=bU(e);if(t)return t;let n=vU(e);if(n)return n;let r=kU(e);if(r)return r;let o=SU(e);return o||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!ID(e.linkedTest)?Wa(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function EU(e){let t=nU(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return sA(n,e.runtimeDirectives),sA(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&tU(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[yo]):(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[yo]="read_only"),n}function CU(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 pA(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 TU(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:rU(e.execution),failure_category:eU(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:QD(e.execution,e.timeoutMs)}}function RU(e){let t=zS(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&cU(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){let o=ja(e.execution.stdout,e.execution.stderr);if(o)return pA({...e,emptyRunSignal:o});if(n&&!t)return pA({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let r=sU(e.linkedTest,e.execution.stdout,e.execution.stderr);return r.length>0?yU(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${r.join("; ")}`,e.execution):CU(e.linkedTest,e.executionContext,e.execution,t)}async function xU(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await XD(t,n,EU(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?RU({...e,execution:r}):TU({...e,execution:r,timeoutMs:n})}async function Qm(e,t,n){let r=Ws(e);for(let y of r)to(y.command);let o=[],i=await _A(me.join(hA(),"pm-linked-test-")),s=dU(i),a=Va(n?.pmContext),c=gA(n?.workspaceContext),d=n?.progress===!0?"always":"auto",u=EA(n?.envSet,n?.envClear,n?.sharedHostSafe),p=n?.sourceRoots,f=yy(),h=fU(r,a,n),_=lU(r,c,n?.overrideLinkedWorkspaceContext===!0),g=await gy(f);try{await uU(s,Lo,h),await Ym(s.workspaceIsolatedRoot,{recursive:!0}),await pU(s,p,h),_&&await JS(f,s.workspaceSnapshotRoot,p?.projectPmRoot,h);let y=await _U(s,p),w=To(),v=T=>yA(T,c,n?.overrideLinkedWorkspaceContext===!0),k=new Set(r.filter(T=>!Ie(T)).map(v)),S=async(T,x)=>{let F=w.options(T,n),L=v(T),H=_w(T,L,k);if(H)return H;let B=await gU({linkedTest:T,layout:s,counts:y,sourceRoots:p,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:c,workspaceContextMode:L,currentSourceRef:g,sourceWorkspaceRoot:f});return AU({linkedTest:T,executionContext:B.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:B.linkedOverridePmContextMode,options:F})??await xU({linkedTest:T,index:x,total:r.length,defaultTimeoutSeconds:t,runtimeDirectives:u,progressMode:d,executionContext:B.executionContext,options:F})};for(let T=0;T<r.length;T+=1){let x=r[T];o.push(w.blocked(x)??w.record(x,await S(x,T)))}}finally{await Wo(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return o}function IU(e,t){let n=[...t];return e.filter(r=>{let o=n.findIndex(i=>no(i,r));return o>=0&&n.splice(o,1),o<0}).length}async function OU(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,i=await j(n,t,r.id_prefix,r.item_format,o);if(!i)throw new l(`Item ${t} not found`,m.NOT_FOUND);let s=await te(i,{schema:r.schema});return{itemId:i.id,tests:s.document.metadata.tests??[],testRuns:s.document.metadata.test_runs??[],changed:!1,removed:0}}function $U(e,t){let n=[...e];for(let r of t)n.some(o=>no(o,r))||n.push(r);return n}function PU(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((i,s)=>r.has(s+1)?!1:!t.some(a=>a.kind==="command"?i.command===a.value:a.kind==="path"?i.path===a.value:i.command===a.value||i.path===a.value));return{tests:o,removed:e.length-o.length}}function LU(e,t,n,r){return PU($U(e,t),n,r)}function NU(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.fullOutput===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function CA(e){if(NU(e)&&e.run!==!0)throw new l("--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, --full-output, and --auto-pm-context require --run",m.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--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 l("--match, --only-index, and --only-last require --run",m.USAGE)}async function FU(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:i,adds:s,removes:a,removeIndexes:c}=e;if(s.length===0&&a.length===0&&c.length===0)return OU({id:t,pmRoot:r,settings:o,typeToFolder:i});let d=0,u=[],p=await we({pmRoot:r,settings:o,id:t,op:s.length>0?"tests_add":"tests_remove",author:R(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(h){let _=h.metadata.tests??[],g=LU(_,s,a,c);if(fd(()=>TA(n,g.tests)),d=g.removed,(a.length>0||c.length>0)&&d===0)throw new l("No linked tests matched the requested removal selector",m.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(y=>`${y.kind}=${y.value}`),...c.map(y=>`index=${y}`)],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 h.metadata.tests=g.tests,u=_,{changedFields:ie(_,g.tests)?[]:["tests"]}}}),f=p.item.tests??[];return{itemId:p.item.id,tests:f,testRuns:p.item.test_runs??[],changed:p.changedFields.length>0,removed:d,written:p.changedFields.length>0?Fg(u,f):[],storedRemoved:IU(u,f)}}function TA(e,t){let n=Va(e.pmContext);gA(e.workspaceContext),EA(e.envSet,e.envClear,e.sharedHostSafe);let r={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:vr(e.onlyIndex),onlyLast:e.onlyLast},o=e.timeout===void 0?void 0:ge(e.timeout,"--timeout");if(o!==void 0&&o<=0)throw new l(`--timeout must be a positive number (got "${e.timeout}")`,m.USAGE);CA(e);let i=e.run===!0?fw(pw(t,r),t):void 0;if(i)for(let s of i.selected)to(s.command);return{defaultTimeoutSeconds:o,pmContextMode:n,runSelection:i,testsToRun:i?.selected??t}}async function MU(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Qm(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:$e(process.cwd())}})}function DU(e,t){let n=[];if(e.run===!0&&e.checkContext===!0){let r=Xm(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 UU(e){let t=RD(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=C(),i=Ko(e.options.measure,o);return{run_id:TD("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(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}}async function jU(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:i,runResults:s,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!i)return;let d=UU({options:t,runStartedAt:i,runResults:s,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return{entry:d,receipt:{recorded:!1,reason:"tracking_disabled",run_id:d.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Ua({pmRoot:n,settings:r,itemId:o,author:R(t.author,r.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),{entry:d,receipt:{recorded:!0,reason:"recorded",run_id:d.run_id}}}catch(u){if(En(u))throw u;return c.push(`test_result_tracking_failed:${o}:${u instanceof Error?u.message:String(u)}`),{entry:d,receipt:{recorded:!1,reason:"write_failed",run_id:d.run_id}}}}function fA(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),i=e.metricBelow.slice(0,o).trim(),s=e.metricBelow.slice(o+1).trim(),a=Number(s);if(o<=0||i.length===0||s.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",m.USAGE);r=xS(t,i,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:IS(t,e.metricDiff)}}async function GU(e,t,n){if(e.acknowledgeLinkedTests===!0)return wy(t,n,C())}function qU(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:i,warnings:s,recording:a,measurementProjection:c,restoreScope:d}=e,u=zU(t,e.fullHistory),p=KU(t,o,u,d),{counts:f,receipts:h}=Fd(u);return{ok:n.every(_=>_.status!=="failed"&&_.status!=="refused")&&i!==!0,id:t.itemId,tests:p.tests,...p.omitted,run_results:n,...e.ran?{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,...o.setup_indexes?{setup_indexes:o.setup_indexes}:{}}:void 0,fail_on_skipped_triggered:i?!0:void 0,warnings:s.length>0?s:void 0,changed:t.changed||a?.receipt.recorded===!0,...a?{evidence_recording:a.receipt}:{},count:p.count,...t.removed>0?{removed:t.removed}:{},...f,...c,...h}}function KU(e,t,n,r){return n!==void 0?{tests:n.entries,count:n.returned_count,omitted:{}}:t!==void 0&&t.selector!==null&&t.skipped_count>0?{tests:t.selected,count:e.tests.length,omitted:{tests_omitted:{count:e.tests.length-t.selected.length,restore_with:BS(e.itemId,r)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function zU(e,t){if(e.written!==void 0)return Nd({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function HU(e,t){let n=e.tests[e.updated_index-1],r=Nd({collectionKey:"tests",stored:e.tests,written:e.changed&&n!==void 0?[n]:[],removedCount:0,fullHistory:t}),{counts:o,receipts:i}=Fd(r);return{...e,tests:r.entries,run_results:[],count:r.returned_count,...o,...i}}async function Ya(e,t,n){let r=yw(t);if(r){ww(t),CA(t),Hm(e,t,n,E(process.cwd(),n.path));let B=await bw(e,{...r,author:t.author,message:t.message,force:t.force},n);return HU(B,t.fullHistory===!0)}let o=Vt(),i=E(process.cwd(),n.path);await O(i);let s=await A(i);Hm(e,t,n,i),Ko(t.measure,"validation"),fA(t,[],void 0);let a=$(s,I()),c=await o.resolveList(t.add,"--add"),d=await o.resolveList(t.addJson,"--add-json"),u=await o.resolveList(t.remove,"--remove"),p=[...DD(c),...GD(d)],f=await fr(p,R(t.author,s.author_default),C())??[],h=qD(u),_=KD(t.removeIndex),g=await FU({id:e,options:t,pmRoot:i,settings:s,typeToFolder:a.type_to_folder,adds:f,removes:h,removeIndexes:_}),y=fd(()=>TA(t,g.tests)),w=await GU(t,i,g.tests),v=t.run===!0?C():void 0,k=await MU({options:t,runOptions:y,pmRoot:i,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests});eA(e,t,n,i,k);let S=kr(k),T=t.run===!0&&t.failOnSkipped===!0&&k.some(B=>B.status==="skipped"),x=DU(t,k);w&&x.push(`linked_test_trust_acknowledged:${w.acknowledged}`);let F=await jU({options:t,pmRoot:i,settings:s,itemId:g.itemId,runStartedAt:v,runResults:k,failOnSkippedTriggered:T,warnings:x}),L=F?.receipt.recorded?jm([...g.testRuns,F.entry]):g.testRuns,H=fA(t,L,F?.entry);return qU({item:g,runResults:k,failureCategories:S,runSelection:y.runSelection,failOnSkippedTriggered:T,warnings:x,recording:F,measurementProjection:H,restoreScope:HS(n,i),ran:t.run===!0,fullHistory:t.fullHistory===!0})}var BU=(e,t)=>{if(e===void 0)return;let n=de(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE)}return n},WU=e=>{if(e===void 0)return;let t=ge(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",m.USAGE);return t},RA=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,m.USAGE);return n},VU=e=>e instanceof Error?e.message:String(e),YU=()=>{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)}`},JU=e=>e.trim().replaceAll(/\s+/g," "),XU=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),QU=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),ZU=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},ej=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Ja=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),xA=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),tj=e=>typeof e=="number"?e:void 0,nj=e=>{let t={assert_stdout_contains:Ja(e.assert_stdout_contains),assert_stdout_regex:Ja(e.assert_stdout_regex),assert_stderr_contains:Ja(e.assert_stderr_contains),assert_stderr_regex:Ja(e.assert_stderr_regex),assert_stdout_min_lines:tj(e.assert_stdout_min_lines),assert_json_field_equals:xA(e.assert_json_field_equals),assert_json_field_gte:xA(e.assert_json_field_gte)};return JSON.stringify(t)},rj=e=>{let t=eu(e.command);return t!==void 0?`command:${e.scope}:${JU(t)}`:`path:${e.scope}:${eu(e.path)??""}`},Zm=e=>{let t=XU(e.env_set),n=QU(e.env_clear),r=ZU(e.pm_context_mode),o=ej(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",s=nj(e);return`${rj(e)}:${t}:${n}:${r}:${o}:${i}:${s}`},oj=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,ij=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}},sj=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Xa=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
43
- `)}catch{}},aj=async(e,t,n)=>{let r=[],o=0;for(let i of e){let s=await Ya(i.id,{run:!1},{...t,path:n});o+=s.tests.length,r.push({item:i,tests:s.tests})}return{itemTests:r,linkedTests:o}},cj=async e=>{let t=D(e.settings.schema),n=$(e.settings,I()),r=BU(e.options.status,t),o=RA(e.options.limit,"--limit"),i=RA(e.options.offset,"--offset")??0,a=(await ye(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>r?d.status===r:!0).sort((d,u)=>d.id.localeCompare(u.id));return{filteredItems:o===void 0?a.slice(i):a.slice(i,i+o),statusFilter:r,limitFilter:o,offsetFilter:i}},IA=e=>{let t=e.filter(Ie).map(({provenance:n,provenance_invalid:r,updated_by:o,updated_at:i,note:s,timeout_seconds:a,...c})=>c);return t.length===0?"":Ct(t)},OA=(e,t)=>t.length===0?Zm(e):`${Zm(e)}:setup[${t}]`,dj=e=>{let t=new Map;for(let{tests:n}of e){let r=IA(n);for(let o of n){if(Ie(o))continue;let i=OA(o,r);if(!t.has(i)){t.set(i,o.timeout_seconds);continue}t.set(i,oj(t.get(i),o.timeout_seconds))}}return t};function lj(e,t){try{to(e.command);return}catch(n){if(!(n instanceof l)||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 mj=(e,t)=>{let n=[],r=[],o=Ws(e.tests),i=IA(o),s=To();return{plans:o.map(c=>{let d=Ie(c),u=d?Zm(c):OA(c,i),p=s.blocked(c);if(p)return{test:c,key:u,duplicate:!1,refusal:p};let f=lj(c,e.item.id);if(f)return{test:c,key:u,duplicate:!1,refusal:s.record(c,f)};if(d)return n.push(c),{test:c,key:u,duplicate:!1,refusal:void 0};if(t.seenTestKeys.has(u))return{test:c,key:u,duplicate:!0,refusal:void 0};t.seenTestKeys.add(u),r.push(u);let h=t.effectiveTimeoutByKey.get(u);return n.push(h===void 0?c:{...c,timeout_seconds:h}),{test:c,key:u,duplicate:!1,refusal:void 0}}),testsToRun:n,reservedKeys:r}},uj=(e,t,n)=>{if(e.some(r=>r.phase==="setup"&&r.status!=="passed"))for(let r of t)n.seenTestKeys.delete(r)},pj=async(e,t)=>{let{plans:n,testsToRun:r,reservedKeys:o}=mj(e,t),i=r.length>0?await Qm(r,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}):[];uj(i,o,t);let s=0,a=To(),c=n.map(({test:f,key:h,duplicate:_,refusal:g})=>{if(g)return a.blocked(f)??g;if(!_){let y=i[s];return s+=1,a.blocked(f)??a.record(f,y)}return a.blocked(f)??{command:f.command,path:f.path,status:"skipped",error:`Duplicate linked test skipped (key=${h}).`}}),d=ij(c),u=kr(c),p=await hj(e,d,c,t);return{passed:d.passed,failed:d.failed,skipped:d.skipped,trackingWarnings:p,failureCategories:u,result:{ok:d.failed===0&&!(t.options.failOnSkipped===!0&&d.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:d.passed,failed:d.failed,skipped:d.skipped,run_results:c,failure_categories:u}}},fj=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),_j=e=>e?!0:void 0,hj=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=fj(t,r.options);await Ua({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:C(),recorded_at:C(),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:_j(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 En(o)?(r.revisionConflicts.push(o),[]):[`test_result_tracking_failed:${e.item.id}:${VU(o)}`]}return[]},gj=()=>{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},eu=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},yj=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:$e(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:dj(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:R(e.options.author,e.settings.author_default),trackingRunId:YU(),trackingAttempt:gj(),trackingResumedFrom:eu(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),wj=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:kr([]),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}},vj=async(e,t,n)=>{for(let[o,i]of e.entries()){Xa(t.options,`item ${o+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let s=await pj(i,t);sj(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),Xa(t.options,`item ${o+1}/${e.length} end id=${i.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}let[r]=t.revisionConflicts;if(r!==void 0)throw r},bj=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=Xm(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}`)},kj=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}),Sj=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(" "),Aj=async(e,t)=>{let n=E(process.cwd(),t.path);await O(n);let r=await A(n),o=await cj({pmRoot:n,settings:r,options:e}),i=WU(e.timeout),s=C(),a=await aj(o.filteredItems,t,n);return Xa(e,Sj({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:i,runStartedAt:s}},Ej=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}},$A=async(e,t)=>{let n=await Aj(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=wj(e,n.linkedTests,n.filteredItems),i=yj({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await vj(n.itemTests,i,r),bj(e,r);let s=Ej({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Xa(e,`end status=${s.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),kj({ok:s.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:s.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};function PA(e,t,n){let r;if(typeof e.lines=="string")r=Dd(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=Dd(`${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 De(e,t){let n=b(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}function Kn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Cj(e){let t=b(e.args,"subcommand")??De(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:b(e.args,"name")??b(e.options,"name"),author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:Se(n)}}function Tj(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=Kn({list:()=>Sg(t.global),show:()=>Ag(r,t.global),"show-status":()=>Eg(r,t.global),"list-fields":()=>Rg(t.global),"show-field":()=>xg(r,t.global),"remove-type":()=>wg(r,{author:o,force:i},t.global),"remove-field":()=>Tg(r,{author:o,force:i},t.global),"remove-status":()=>kg(r,{author:o,force:i},t.global),"apply-preset":()=>Ig(b(t.args,"typePreset")??b(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function Rj(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return Cg(n,{type:b(t.args,"fieldType")??b(t.options,"fieldType"),commands:s===void 0?void 0:Se(s),description:b(t.args,"description")??b(t.options,"description"),cliFlag:b(t.args,"cliFlag")??b(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:a===void 0?void 0:Se(a),author:r,force:o},t.global)}function xj(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.role??t.options.role;return bg(n,{role:s===void 0?void 0:Se(s),alias:i,description:b(t.args,"description")??b(t.options,"description"),order:Ke(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function Ij(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return yg(n,{description:b(t.args,"description")??b(t.options,"description"),defaultStatus:b(t.args,"defaultStatus")??b(t.args,"default_status")??b(t.options,"defaultStatus")??b(t.options,"default_status"),folder:b(t.args,"folder")??b(t.options,"folder"),alias:i,author:r,force:o},t.global)}function Oj(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,s=b(t.args,"to")??De(t.options,"to"),a=b(t.args,"migrationId")??b(t.args,"migration_id")??b(t.options,"migrationId")??b(t.options,"migration_id"),c=b(t.args,"fieldTypeScope")??b(t.options,"fieldTypeScope")??b(t.args,"type")??b(t.options,"type"),d=n==="rename-type"?{kind:"rename-type",from:r??"",to:s}:n==="rename-field"?{kind:"rename-field",from:r??"",to:s,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:s};return hg(d,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function LA(e){let t=Cj(e);K_(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Wn.find(o=>o===t.subcommand);if(n)return _g(n,t.name,{definition:e.args.definition??e.options.definition,policy:b(e.args,"policy")??b(e.options,"policy"),message:b(e.args,"message")??b(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=Tj(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return Oj(t);if(t.subcommand==="add-field")return Rj(t);if(t.subcommand==="add-status")return xj(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Og({minCount:Ke(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):Ij(t);throw Pe({command_path:"schema",token:t.subcommand,allowed:gg,exit_code:64})}function Qa(e){return b(e.args,"target")??b(e.options,"target")}function Ee(e,t=e.options){return e.id??De(t,"id")}async function $j(e){let t=er("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),ll(await Lt(b(e.args,"status")??b(t,"status"),t,e.global),t)}async function Pj(e){let t=b(e.args,"query")??b(e.args,"keywords")??De(e.args,"query"),n=er("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),ll(await So(t,n,e.global),n)}async function Lj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return Re(await rn(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Nj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(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 Re(await Tl(Ee(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Fj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return Re(await ct(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Mj(e){let t=Tn(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),iv(Ee(e),t,e.global)}function NA(e,t){return Ug(PA(e.options,t,Ke),e.global)}function Dj(e){let t=Se(e.options.lookupPath);if(t&&t.length>0)return NA(e,t);let n=Ee(e);return e.options.discover===!0?Ud(n,As(e.options),e.global):Dg(n,po(Tn(e.options)),e.global)}function Uj(e){return GS({subcommand:b(e.args,"subcommand")??b(e.options,"subcommand"),limit:zh(e.args,e.options)},e.global)}function jj(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),wo(e.global,t)}function Gj(e){let t=b(e.args,"configAction")??b(e.options,"configAction")??b(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);let n=b(e.args,"value")??b(e.options,"value"),r=b(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options,o=b(e.args,"key")??b(e.options,"key");return Cv(b(e.args,"scope")??b(e.options,"scope")??X_(o),t,o,r,e.global,b(e.options,"policy")===void 0?n:void 0)}function qj(e){let t=e.options;return $y(Oy(t),e.global)}function Kj(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}async function zj(e){let t=b(e.args,"subcommand")??De(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=ve(e.args,e.options),i=await ak({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:Hj(e),reorderTo:Kj(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&Td(e.args)&&(i.mutation_receipt=Ra(i,void 0)),t==="show"?i:Re(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function Hj(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function Bj(e){let t=b(e.args,"subcommand")??De(e.options,"subcommand"),n=t.trim().toLowerCase(),r=b(e.args,"name")??b(e.options,"name"),i=Kn({list:()=>Ek(),show:()=>Ck(r),lint:()=>Tk(r),apply:()=>Rk(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!i)throw Pe({command_path:"profile",token:t,allowed:Ak,exit_code:64});return i()}async function Wj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return Re(await Uv(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Vj(e){let{changedFields:t,runnerOptions:n}=ve(e.args,e.options);return Re(await fk(Cs(n,!Td(e.args)),e.global),{changedFields:t})}async function Yj(e){let{changedFields:t,runnerOptions:n}=ve(e.args,e.options),r=b(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Re(await Vv(Es(o),e.global),{changedFields:t})}async function Jj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options),o=b(r,"target")??De(e.args,"target");return Re(await gm(Ee(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Xj(e){let t={...e.args,...e.options};return jg(De(t,"subcommand"),b(t,"id")??e.id,b(t,"target"),Yh(t),e.global)}function Qj(e){return Lg(E(process.cwd(),e.global.path),{...e.args,...e.options})}var FA={init:e=>Lo(b(e.args,"prefix"),e.global,e.options),context:e=>Hd(er("context",e.options),e.global),next:e=>ko(er("next",e.options),e.global),eval:lS,events:mS,merge:uS,workspace:pS,meet:Na,event:Na,remind:Na,list:$j,get:e=>{let t=Ee(e);return Wd(t,e.global,er("get",e.options,[t]))},search:Pj,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:Se(e.options.status);return Md(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:b(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Ke(e.options.limit,"limit")})},create:Lj,copy:Nj,focus:e=>Ul(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:Fj,"item-reopen":Yb,restore:Jj,claim:Bb,release:Vb,"start-task":e=>Dn(e,"start_task"),"pause-task":e=>Dn(e,"pause_task"),"close-task":e=>Dn(e,"close_task"),close:Wb,comments:Mj,notes:e=>hk(Ee(e),Tn(e.options),e.global),learnings:e=>Dv(Ee(e),Tn(e.options),e.global),files:Dj,docs:e=>Mg(Ee(e),po(Tn(e.options)),e.global),test:e=>Ya(Ee(e),Tn(e.options),e.global),"test-all":e=>$A(e.options,e.global),telemetry:Uj,validate:e=>Fs(e.options,e.global,{runUpdate:(t,n,r)=>ct(t,n,r)}),health:jj,assurance:e=>vy(e.args,e.options,e.global),contracts:e=>sl(e.options,e.global),config:Gj,activity:qj,aggregate:e=>Bd(e.options,e.global),extension:e=>mr(Qa(e),e.options,e.global),package:e=>mr(Qa(e),e.options,e.global),install:e=>mr(Qa(e),{...e.options,install:!0},e.global),upgrade:e=>ky(Qa(e),e.options,e.global),delete:e=>Dl(Ee(e),e.options,e.global),deps:e=>Ng(Ee(e),e.options,e.global),graph:Xj,"files-discover":e=>Ud(Ee(e),e.options,e.global),"files-lookup":e=>NA(e,Se(e.options.paths)),history:e=>Py(Ee(e),{...e.options,compact:e.options.full===!0||e.options.provenance===!0?!1:e.options.compact!==!1},e.global),"history-redact":e=>Mv(Ee(e),e.options,e.global),"history-repair":$v,"history-compact":Pv,"history-attest":e=>Sy(e.options,e.global),"history-author-acknowledge":Qj,plan:zj,schema:LA,profile:Bj,stats:e=>Fm(e.global,fS(e.options)),append:Wj,"update-many":Vj,"close-many":Yj,gc:e=>by(e.global,e.options)};var Zj=new Map;function tu(){Zj.clear()}var DA=[{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:$h().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 (repository checkout only; excluded from the npm package).",optional:!0},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes (repository checkout only; excluded from the npm package).",optional:!0},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering (repository checkout only; not in the npm package).",optional:!0}],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"]}],MA=new Map;for(let e of DA){MA.set(e.id,e);for(let t of e.aliases)MA.set(t,e)}function nu(){return DA.map(e=>e.id)}var S8=[..._c],A8=[...hc],ru=new Set(un.filter(e=>e.hidden).map(e=>e.alias)),UA=Oh("full").filter(e=>!e.includes(" ")&&!ru.has(e)),eG=M(li),tG=M(mi),nG=M(yi),rG=M(Si),jA=ao("restore",Ge("restore")),GA=ao("history-attest",Ge("history-attest")),oG=M(Ai),iG=M(sf),sG=M(af),aG=M(ki),cG=M(Ri),dG=M(Ei),lG=M(Ci),mG=M(gi),ou=[...new Set(Te.map(e=>e.canonical_argv[0]))],qA=[...new Set(Te.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],E8=new Set(di.filter(e=>e.disposition==="package_owned").map(e=>V(e.command))),KA=Te.filter(e=>e.canonical_argv[0]==="history"),uG=KA.map(e=>e.canonical_argv[1]).join(" ");var pG=KA.map(e=>({...e,flags:M(Ge(e.alias))})),fG=M(ui),_G=M(pi,!1),hG=M(Ti),gG=M(Hr),yG=M(Br),wG=M($i),vG=M(Ii),bG=M(vi),kG=M(Oi),SG=M(xi),AG=M(Pi),EG=M(wi),CG=M(bi),TG=M(_i),RG=M(Li),xG=M(fi),iu=`${Wn.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 IG=M(Ni),OG=`${IG} bash zsh fish`,su=ec(nu()),Za="init scaffold install uninstall list inventory explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",au=`${Za} upgrade`,$G=M(hi),PG=M(qr),LG=M(zr);var NG=M(Ge("close")),FG=M(Ge("close-task")),MG=M(Ge("release")),DG=M(Ge("claim"));var zA=Vn.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),cu=[...Yi].join("|"),du=[...Yi].map(e=>`${e}=*`).join("|"),lu=[...zA.split(" ").filter(e=>!Yi.has(e)),"-h","-V"].join("|");function ec(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}var Vo=Symbol("pm.active-extension-host-context");function Ve(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[Vo]=!0,n}run(t,n={}){return ZG({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}async withItemTransactionContext(t,n=!1){let r=E(this.defaults.cwd??process.cwd(),this.defaults.path),o=async()=>{let c=await ir(r,()=>A(r));return t({pmRoot:r,author:R(this.defaults.author,c.author_default)})};if(this.defaults[Vo]===!0){let c=process.cwd(),d=()=>JA(r,uo({path:r}),void 0,c,o);return n?ir(r,d):d()}let i=Pr()!==void 0;i&&pu(this.defaults.cwd);let s=i?void 0:this.defaults.cwd,a=()=>XA({...this.defaults,cwd:s,path:r},o);return n?ir(r,a):a()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-A6MVNPT7.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-A6MVNPT7.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,r)=>this.withItemTransactionContext(async o=>(await import("./item-transaction-A6MVNPT7.js")).abandonItemTransaction({...r,...o,transactionId:n}));return{status:n=>this.withItemTransactionContext(async r=>(await import("./item-transaction-A6MVNPT7.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-RPTXN7WW.js")).readItemRevision(t,{pmRoot:n}))}async withExpectedItemRevisions(t,n){let r=await import("./item-revision-RPTXN7WW.js"),o="",i=await this.withItemTransactionContext(({pmRoot:a})=>(o=a,r.bindExpectedItemRevisions(t,{pmRoot:a}))),s=this.defaults.noExtensions===!0&&this.defaults[Vo]!==!0;return r.runWithBoundItemRevisionScope(i,n,{scopeArgs:["--pm-path",o,...s?["--no-extensions"]:[]]})}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return tv(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Ld(await this.list(Pd(t)),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 Dh(r,"append"),await this.runTyped("append",{id:t,...Ve(wt(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:wt(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",Ve(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ve(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,...Ve(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ve(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ve(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ve(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ve(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ve(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},...Ve(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ve(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ve(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ve(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 $7(e={},t={}){return new z(t).context(e)}function P7(e={},t={}){return new z(t).list(e)}function L7(e={},t={}){return new z(t).listAllComplete(e)}function N7(e,t={},n={}){return new z(n).search(e,t)}function F7(e,t={},n={}){return new z(n).get(e,t)}function M7(e={},t={}){return new z(t).next(e)}function D7(e={},t={}){return new z(t).aggregate(e)}function U7(e,t={},n={}){return new z(n).comments(e,t)}function j7(e,t={},n={}){return new z(n).notes(e,t)}function G7(e,t={},n={}){return new z(n).learnings(e,t)}function q7(e,t={},n={}){return new z(n).files(e,t)}function K7(e,t={},n={}){return new z(n).filesDiscover(e,t)}function z7(e,t={},n={}){return new z(n).docs(e,t)}function H7(e,t={},n={}){return new z(n).deps(e,t)}function B7(e,t={},n={},r={}){return new z(r).graph(e,t,n)}function W7(e,t,n={},r={}){return new z(r).append(e,t,n)}function V7(e={},t={}){return new z(t).create(e)}function Y7(e,t={},n={}){return new z(n).update(e,t)}function J7(e,t,n={},r={}){return new z(r).reopen(e,t,n)}function X7(e,t,n={},r={}){return new z(r).close(e,t,n)}function Q7(e,t={},n={}){return new z(n).claim(e,t)}function Z7(e={},t={}){return new z(t).claimNext(e)}function eee(e,t={},n={}){return new z(n).release(e,t)}function tee(e,t={},n={}){return new z(n).copy(e,t)}function nee(e,t={},n={}){return new z(n).delete(e,t)}function ree(e,t,n={},r={}){return new z(r).restore(e,t,n)}function oee(e,t={},n={}){return new z(n).focus(e,t)}var VA=v_(),nc=new BG;function Yo(e){try{return WG(e)}catch{return uu.resolve(e)}}function Pr(){let e=nc.getStore();for(;e!==void 0&&!e.live;)e=e.parent;return e}async function $r(e,t,n,r=!0){let o={root:Yo(e),active:t,live:!0,parent:Pr(),ready:r};try{return await nc.run(o,n)}finally{o.live=!1}}function pu(e){if(e===void 0||Yo(e)===Yo(process.cwd()))return;let t="Omit cwd inside an open extension scope and address the tracker with path, or make the call outside the scope.";throw new l(`A nested SDK call cannot change the working directory to "${e}" while its caller's extension scope is open. ${t}`,m.USAGE,{code:"invalid_argument_value",reason:"nested_cwd_unavailable",changed:!1,field:"cwd",required:t,nextSteps:[t]})}function fu(e,t,n,r){let o=Pr();if(o===void 0)return;let i=o===nc.getStore(),s=o.root===Yo(e);if(s&&!o.ready){let a="Do the work from a command or hook handler, after the tracker's extensions have activated.";throw new l(`An extension lifecycle callback cannot run SDK work for tracker ${o.root} while its extensions activate or deactivate. ${a}`,m.USAGE,{code:"invalid_argument_value",reason:"extension_scope_not_ready",changed:!1,required:a,nextSteps:[a]})}return i&&s&&t.noExtensions!==!0?r(o.active):Zc(()=>$r(e,null,()=>mu(t,n,a=>$r(e,a,()=>r(a))),!1))}function JA(e,t,n,r,o){let i=nc.getStore();if(i===void 0)return o(null);let s=Pr(),a={...t,noExtensions:!1};return s===void 0?$r(e,null,()=>_u(a,n===void 0?void 0:r,r,c=>$r(e,c,()=>o(c))),!1):s===i&&s.ready&&s.root===Yo(e)?o(null):fu(e,a,r,o)}function tc(){ed(ep()),td(tp()),nd(np()),rd(rp()),od(op()),id(ip()),sd(sp())}async function _u(e,t,n,r){return Zc(()=>t===void 0?VA.read(()=>mu(e,n,r)):VA.write(()=>JG(t,()=>mu(e,n,r))))}async function XA(e,t){let n=e.cwd,r=n===void 0?process.cwd():uu.resolve(n),o=E(r,e.path),i=uo({path:o,noExtensions:e.noExtensions});Pr()!==void 0&&pu(n);let s=fu(o,i,r,()=>t());return s!==void 0?s:_u(i,n===void 0?void 0:r,r,a=>$r(o,a,t))}function iee(e,t){return XA({path:e},t)}function VG(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:gh(e);return typeof n=="string"?n:"Unknown failure"}catch{return"Unknown failure"}}async function mu(e,t,n){let r=E(t,e.path);if(e.noExtensions)return tc(),Yd({pmRoot:r},()=>n(null));if(!await W(ce(r)))return tc(),n(null);let o=null,i;try{let s=await A(r),a=await jr({pmRoot:r,settings:s,cwd:t,noExtensions:!1}),c=await Gr({...a,loaded:a.loaded});i={loadResult:a,activationResult:c},ed(c.hooks),td(c.commands),nd(c.parsers),rd(c.preflight),od(c.services),id(c.renderers),sd(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(s){tc(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",VG(s))}try{return await Yd({pmRoot:r,packages:o?.packages},()=>n(o))}finally{tc(),i&&await Oc(i.loadResult,i.activationResult).catch(()=>{})}}function QA(e,t){let n=dr(e);return t?.registrations.commands.find(r=>dr(r.action)===n)?.command??t?.commands.handlers.find(r=>dr(r.command)===n)?.command}async function YG(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,m.USAGE);let i=QA(e,o);if(!i)throw new l(`Unsupported native pm action: ${e}`,m.USAGE);let s=typeof n.author=="string"?n.author:r.author,a=xd(i),c=Th(Id(t,n),Ch(o.registrations,a),a,Yw(a)),d=await Vi({command:a,args:Se(n.args??t.args),options:c,global:{...r,author:s},pm_root:o.pmRoot,sdk:Vw(o.pmRoot,z.forActiveExtensionHost({pmRoot:o.pmRoot,author:s}),s,a)});if(!d.handled){if(Object.hasOwn(d,"cause"))throw ys(i,d);let u=d.warnings.length>0?` (${d.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${u}`,m.USAGE)}return d.result}async function JG(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function XG(e){let t=De(e,"action"),n=dr(t),r=Kn(rv,n),o=r?.action??n,i={...e,action:o};return r?.options!==void 0&&(i.options={...r.options,...Fr(e.options)}),o==="package"&&(i.options={...Fr(i.options),vocabulary:"package"}),{action:o,args:i}}function QG(e,t,n,r){let o=e[Vo]===!0,i=t.noExtensions===!0&&!o?["--no-extensions"]:[];if(n!==void 0)return["--pm-path",E(r,t.path),...i];let s=ke(t,r);return[...t.noExtensions===!0?s.slice(0,-1):s,...i]}async function ZG(e){let t=XG(e),n=uo(t.args);b_(n);let r=Wh(t.action),o=b(t.args,"cwd"),i=o===void 0?process.cwd():uu.resolve(o);t.action==="init"&&(n[dl]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(i,n.path));let{expectHash:s,dispatchArgs:a}=Xh(t.args),c=async d=>{if(s===void 0)return YA(t.action,a,n,d);let{dispatchWithExpectedItemRevisions:u}=await import("./item-revision-RPTXN7WW.js");return u({action:t.action,expectHash:s,defaultId:b(a,"id")??b(Fr(a.options),"id"),options:Fr(a.options),background:a.background,pmRoot:E(i,n.path),invocation:{scopeArgs:QG(e,n,o,i),...n.outputFormat===void 0?{}:{outputArgs:["--output-format",n.outputFormat]}},run:()=>YA(t.action,a,n,d)})};try{if(t.action==="history-attest")return await c(null);let d=E(i,n.path);if(Pr()!==void 0&&pu(o),e[Vo]===!0)return await JA(d,n,o,i,c);let u=fu(d,n,i,c);return u!==void 0?await u:await _u(n,o===void 0?void 0:i,i,p=>$r(d,p,()=>c(p)))}finally{r&&tu()}}async function YA(e,t,n,r){let o=Kn(FA,e),i=Rd(t,e,{nativeAction:o!==void 0});if(e==="create"||e==="update"){let{assertNativeMutationOptions:u}=await import("./mutation-admission-2DA4CINP.js");await u(e,t,i,n.path,Hh[e])}if(e==="update-many"){let{assertNativeUpdateManyOptions:u}=await import("./mutation-admission-2DA4CINP.js");await u(t,i,n.path)}let s=o?void 0:QA(e,r),a=s===void 0?e:`extension:${s}`;C_(a,i),R_(a,i);let c={action:e,args:t,options:i,id:b(t,"id"),force:t.force===!0||i.force===!0,global:n,activeExtensions:r},d=o?await o(c):await YG(e,t,i,n,r);if(e==="history-attest")return d;{let u=$_(a,i,d);return await Ww(E(process.cwd(),n.path),u),u}}var eq={closeManyOptionsFromFlat:Es,extensionOptionsFromArgs:Id,globalOptions:uo,mutationListOptions:Vh,normalizeActionName:dr,normalizeCommandPath:xd,normalizeMcpUpdateOptions:Jh,normalizeMcpOptionsArrays:Bh,optionsWithAuthor:Rd,readRequiredString:De,readScalarString:qh,readScalarStringAllowBlank:Kh,readStringArray:Se,updateManyOptionsFromFlat:Cs,withAddNoteOption:po,withFilesDiscoveryOptions:As,withMutationCompaction:ve};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=eq);export{Vd as a,cC as b,EC as c,dw as d,wK as e,lw as f,vK as g,bK as h,bw as i,XC as j,z as k,$7 as l,P7 as m,L7 as n,N7 as o,F7 as p,M7 as q,D7 as r,U7 as s,j7 as t,G7 as u,q7 as v,K7 as w,z7 as x,H7 as y,B7 as z,W7 as A,V7 as B,Y7 as C,J7 as D,X7 as E,Q7 as F,Z7 as G,eee as H,tee as I,nee as J,ree as K,oee as L,XA as M,iee as N,ZG as O};
44
- //# sourceMappingURL=chunk-AVLB4L7M.js.map
43
+ `)}catch{}},aj=async(e,t,n)=>{let r=[],o=0;for(let i of e){let s=await Ya(i.id,{run:!1},{...t,path:n});o+=s.tests.length,r.push({item:i,tests:s.tests})}return{itemTests:r,linkedTests:o}},cj=async e=>{let t=D(e.settings.schema),n=$(e.settings,I()),r=BU(e.options.status,t),o=RA(e.options.limit,"--limit"),i=RA(e.options.offset,"--offset")??0,a=(await ye(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>r?d.status===r:!0).sort((d,u)=>d.id.localeCompare(u.id));return{filteredItems:o===void 0?a.slice(i):a.slice(i,i+o),statusFilter:r,limitFilter:o,offsetFilter:i}},IA=e=>{let t=e.filter(Ie).map(({provenance:n,provenance_invalid:r,updated_by:o,updated_at:i,note:s,timeout_seconds:a,...c})=>c);return t.length===0?"":Ct(t)},OA=(e,t)=>t.length===0?Zm(e):`${Zm(e)}:setup[${t}]`,dj=e=>{let t=new Map;for(let{tests:n}of e){let r=IA(n);for(let o of n){if(Ie(o))continue;let i=OA(o,r);if(!t.has(i)){t.set(i,o.timeout_seconds);continue}t.set(i,oj(t.get(i),o.timeout_seconds))}}return t};function lj(e,t){try{to(e.command);return}catch(n){if(!(n instanceof l)||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 mj=(e,t)=>{let n=[],r=[],o=Ws(e.tests),i=IA(o),s=To();return{plans:o.map(c=>{let d=Ie(c),u=d?Zm(c):OA(c,i),p=s.blocked(c);if(p)return{test:c,key:u,duplicate:!1,refusal:p};let f=lj(c,e.item.id);if(f)return{test:c,key:u,duplicate:!1,refusal:s.record(c,f)};if(d)return n.push(c),{test:c,key:u,duplicate:!1,refusal:void 0};if(t.seenTestKeys.has(u))return{test:c,key:u,duplicate:!0,refusal:void 0};t.seenTestKeys.add(u),r.push(u);let h=t.effectiveTimeoutByKey.get(u);return n.push(h===void 0?c:{...c,timeout_seconds:h}),{test:c,key:u,duplicate:!1,refusal:void 0}}),testsToRun:n,reservedKeys:r}},uj=(e,t,n)=>{if(e.some(r=>r.phase==="setup"&&r.status!=="passed"))for(let r of t)n.seenTestKeys.delete(r)},pj=async(e,t)=>{let{plans:n,testsToRun:r,reservedKeys:o}=mj(e,t),i=r.length>0?await Qm(r,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}):[];uj(i,o,t);let s=0,a=To(),c=n.map(({test:f,key:h,duplicate:_,refusal:g})=>{if(g)return a.blocked(f)??g;if(!_){let y=i[s];return s+=1,a.blocked(f)??a.record(f,y)}return a.blocked(f)??{command:f.command,path:f.path,status:"skipped",error:`Duplicate linked test skipped (key=${h}).`}}),d=ij(c),u=kr(c),p=await hj(e,d,c,t);return{passed:d.passed,failed:d.failed,skipped:d.skipped,trackingWarnings:p,failureCategories:u,result:{ok:d.failed===0&&!(t.options.failOnSkipped===!0&&d.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:d.passed,failed:d.failed,skipped:d.skipped,run_results:c,failure_categories:u}}},fj=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),_j=e=>e?!0:void 0,hj=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=fj(t,r.options);await Ua({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:C(),recorded_at:C(),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:_j(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 En(o)?(r.revisionConflicts.push(o),[]):[`test_result_tracking_failed:${e.item.id}:${VU(o)}`]}return[]},gj=()=>{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},eu=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},yj=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:$e(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:dj(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:R(e.options.author,e.settings.author_default),trackingRunId:YU(),trackingAttempt:gj(),trackingResumedFrom:eu(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),wj=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:kr([]),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}},vj=async(e,t,n)=>{for(let[o,i]of e.entries()){Xa(t.options,`item ${o+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let s=await pj(i,t);sj(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),Xa(t.options,`item ${o+1}/${e.length} end id=${i.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}let[r]=t.revisionConflicts;if(r!==void 0)throw r},bj=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=Xm(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}`)},kj=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}),Sj=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(" "),Aj=async(e,t)=>{let n=E(process.cwd(),t.path);await O(n);let r=await A(n),o=await cj({pmRoot:n,settings:r,options:e}),i=WU(e.timeout),s=C(),a=await aj(o.filteredItems,t,n);return Xa(e,Sj({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:i,runStartedAt:s}},Ej=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}},$A=async(e,t)=>{let n=await Aj(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=wj(e,n.linkedTests,n.filteredItems),i=yj({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await vj(n.itemTests,i,r),bj(e,r);let s=Ej({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Xa(e,`end status=${s.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),kj({ok:s.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:s.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};function PA(e,t,n){let r;if(typeof e.lines=="string")r=Dd(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=Dd(`${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 De(e,t){let n=b(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}function Kn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Cj(e){let t=b(e.args,"subcommand")??De(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:b(e.args,"name")??b(e.options,"name"),author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:Se(n)}}function Tj(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=Kn({list:()=>Sg(t.global),show:()=>Ag(r,t.global),"show-status":()=>Eg(r,t.global),"list-fields":()=>Rg(t.global),"show-field":()=>xg(r,t.global),"remove-type":()=>wg(r,{author:o,force:i},t.global),"remove-field":()=>Tg(r,{author:o,force:i},t.global),"remove-status":()=>kg(r,{author:o,force:i},t.global),"apply-preset":()=>Ig(b(t.args,"typePreset")??b(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function Rj(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return Cg(n,{type:b(t.args,"fieldType")??b(t.options,"fieldType"),commands:s===void 0?void 0:Se(s),description:b(t.args,"description")??b(t.options,"description"),cliFlag:b(t.args,"cliFlag")??b(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:a===void 0?void 0:Se(a),author:r,force:o},t.global)}function xj(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.role??t.options.role;return bg(n,{role:s===void 0?void 0:Se(s),alias:i,description:b(t.args,"description")??b(t.options,"description"),order:Ke(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function Ij(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return yg(n,{description:b(t.args,"description")??b(t.options,"description"),defaultStatus:b(t.args,"defaultStatus")??b(t.args,"default_status")??b(t.options,"defaultStatus")??b(t.options,"default_status"),folder:b(t.args,"folder")??b(t.options,"folder"),alias:i,author:r,force:o},t.global)}function Oj(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,s=b(t.args,"to")??De(t.options,"to"),a=b(t.args,"migrationId")??b(t.args,"migration_id")??b(t.options,"migrationId")??b(t.options,"migration_id"),c=b(t.args,"fieldTypeScope")??b(t.options,"fieldTypeScope")??b(t.args,"type")??b(t.options,"type"),d=n==="rename-type"?{kind:"rename-type",from:r??"",to:s}:n==="rename-field"?{kind:"rename-field",from:r??"",to:s,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:s};return hg(d,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function LA(e){let t=Cj(e);K_(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Wn.find(o=>o===t.subcommand);if(n)return _g(n,t.name,{definition:e.args.definition??e.options.definition,policy:b(e.args,"policy")??b(e.options,"policy"),message:b(e.args,"message")??b(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=Tj(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return Oj(t);if(t.subcommand==="add-field")return Rj(t);if(t.subcommand==="add-status")return xj(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Og({minCount:Ke(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):Ij(t);throw Pe({command_path:"schema",token:t.subcommand,allowed:gg,exit_code:64})}function Qa(e){return b(e.args,"target")??b(e.options,"target")}function Ee(e,t=e.options){return e.id??De(t,"id")}async function $j(e){let t=er("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),ll(await Lt(b(e.args,"status")??b(t,"status"),t,e.global),t)}async function Pj(e){let t=b(e.args,"query")??b(e.args,"keywords")??De(e.args,"query"),n=er("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),ll(await So(t,n,e.global),n)}async function Lj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return Re(await rn(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Nj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(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 Re(await Tl(Ee(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Fj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return Re(await ct(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Mj(e){let t=Tn(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),iv(Ee(e),t,e.global)}function NA(e,t){return Ug(PA(e.options,t,Ke),e.global)}function Dj(e){let t=Se(e.options.lookupPath);if(t&&t.length>0)return NA(e,t);let n=Ee(e);return e.options.discover===!0?Ud(n,As(e.options),e.global):Dg(n,po(Tn(e.options)),e.global)}function Uj(e){return GS({subcommand:b(e.args,"subcommand")??b(e.options,"subcommand"),limit:zh(e.args,e.options)},e.global)}function jj(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),wo(e.global,t)}function Gj(e){let t=b(e.args,"configAction")??b(e.options,"configAction")??b(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);let n=b(e.args,"value")??b(e.options,"value"),r=b(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options,o=b(e.args,"key")??b(e.options,"key");return Cv(b(e.args,"scope")??b(e.options,"scope")??X_(o),t,o,r,e.global,b(e.options,"policy")===void 0?n:void 0)}function qj(e){let t=e.options;return $y(Oy(t),e.global)}function Kj(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}async function zj(e){let t=b(e.args,"subcommand")??De(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=ve(e.args,e.options),i=await ak({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:Hj(e),reorderTo:Kj(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&Td(e.args)&&(i.mutation_receipt=Ra(i,void 0)),t==="show"?i:Re(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function Hj(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function Bj(e){let t=b(e.args,"subcommand")??De(e.options,"subcommand"),n=t.trim().toLowerCase(),r=b(e.args,"name")??b(e.options,"name"),i=Kn({list:()=>Ek(),show:()=>Ck(r),lint:()=>Tk(r),apply:()=>Rk(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!i)throw Pe({command_path:"profile",token:t,allowed:Ak,exit_code:64});return i()}async function Wj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return Re(await Uv(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Vj(e){let{changedFields:t,runnerOptions:n}=ve(e.args,e.options);return Re(await fk(Cs(n,!Td(e.args)),e.global),{changedFields:t})}async function Yj(e){let{changedFields:t,runnerOptions:n}=ve(e.args,e.options),r=b(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Re(await Vv(Es(o),e.global),{changedFields:t})}async function Jj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options),o=b(r,"target")??De(e.args,"target");return Re(await gm(Ee(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Xj(e){let t={...e.args,...e.options};return jg(De(t,"subcommand"),b(t,"id")??e.id,b(t,"target"),Yh(t),e.global)}function Qj(e){return Lg(E(process.cwd(),e.global.path),{...e.args,...e.options})}var FA={init:e=>Lo(b(e.args,"prefix"),e.global,e.options),context:e=>Hd(er("context",e.options),e.global),next:e=>ko(er("next",e.options),e.global),eval:lS,events:mS,merge:uS,workspace:pS,meet:Na,event:Na,remind:Na,list:$j,get:e=>{let t=Ee(e);return Wd(t,e.global,er("get",e.options,[t]))},search:Pj,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:Se(e.options.status);return Md(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:b(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Ke(e.options.limit,"limit")})},create:Lj,copy:Nj,focus:e=>Ul(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:Fj,"item-reopen":Yb,restore:Jj,claim:Bb,release:Vb,"start-task":e=>Dn(e,"start_task"),"pause-task":e=>Dn(e,"pause_task"),"close-task":e=>Dn(e,"close_task"),close:Wb,comments:Mj,notes:e=>hk(Ee(e),Tn(e.options),e.global),learnings:e=>Dv(Ee(e),Tn(e.options),e.global),files:Dj,docs:e=>Mg(Ee(e),po(Tn(e.options)),e.global),test:e=>Ya(Ee(e),Tn(e.options),e.global),"test-all":e=>$A(e.options,e.global),telemetry:Uj,validate:e=>Fs(e.options,e.global,{runUpdate:(t,n,r)=>ct(t,n,r)}),health:jj,assurance:e=>vy(e.args,e.options,e.global),contracts:e=>sl(e.options,e.global),config:Gj,activity:qj,aggregate:e=>Bd(e.options,e.global),extension:e=>mr(Qa(e),e.options,e.global),package:e=>mr(Qa(e),e.options,e.global),install:e=>mr(Qa(e),{...e.options,install:!0},e.global),upgrade:e=>ky(Qa(e),e.options,e.global),delete:e=>Dl(Ee(e),e.options,e.global),deps:e=>Ng(Ee(e),e.options,e.global),graph:Xj,"files-discover":e=>Ud(Ee(e),e.options,e.global),"files-lookup":e=>NA(e,Se(e.options.paths)),history:e=>Py(Ee(e),{...e.options,compact:e.options.full===!0||e.options.provenance===!0?!1:e.options.compact!==!1},e.global),"history-redact":e=>Mv(Ee(e),e.options,e.global),"history-repair":$v,"history-compact":Pv,"history-attest":e=>Sy(e.options,e.global),"history-author-acknowledge":Qj,plan:zj,schema:LA,profile:Bj,stats:e=>Fm(e.global,fS(e.options)),append:Wj,"update-many":Vj,"close-many":Yj,gc:e=>by(e.global,e.options)};var Zj=new Map;function tu(){Zj.clear()}var DA=[{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:$h().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 (repository checkout only; excluded from the npm package).",optional:!0},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes (repository checkout only; excluded from the npm package).",optional:!0},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering (repository checkout only; not in the npm package).",optional:!0}],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"]}],MA=new Map;for(let e of DA){MA.set(e.id,e);for(let t of e.aliases)MA.set(t,e)}function nu(){return DA.map(e=>e.id)}var S8=[..._c],A8=[...hc],ru=new Set(un.filter(e=>e.hidden).map(e=>e.alias)),UA=Oh("full").filter(e=>!e.includes(" ")&&!ru.has(e)),eG=M(li),tG=M(mi),nG=M(yi),rG=M(Si),jA=ao("restore",Ge("restore")),GA=ao("history-attest",Ge("history-attest")),oG=M(Ai),iG=M(sf),sG=M(af),aG=M(ki),cG=M(Ri),dG=M(Ei),lG=M(Ci),mG=M(gi),ou=[...new Set(Te.map(e=>e.canonical_argv[0]))],qA=[...new Set(Te.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],E8=new Set(di.filter(e=>e.disposition==="package_owned").map(e=>V(e.command))),KA=Te.filter(e=>e.canonical_argv[0]==="history"),uG=KA.map(e=>e.canonical_argv[1]).join(" ");var pG=KA.map(e=>({...e,flags:M(Ge(e.alias))})),fG=M(ui),_G=M(pi,!1),hG=M(Ti),gG=M(Hr),yG=M(Br),wG=M($i),vG=M(Ii),bG=M(vi),kG=M(Oi),SG=M(xi),AG=M(Pi),EG=M(wi),CG=M(bi),TG=M(_i),RG=M(Li),xG=M(fi),iu=`${Wn.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 IG=M(Ni),OG=`${IG} bash zsh fish`,su=ec(nu()),Za="init scaffold install uninstall list inventory explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",au=`${Za} upgrade`,$G=M(hi),PG=M(qr),LG=M(zr);var NG=M(Ge("close")),FG=M(Ge("close-task")),MG=M(Ge("release")),DG=M(Ge("claim"));var zA=Vn.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),cu=[...Yi].join("|"),du=[...Yi].map(e=>`${e}=*`).join("|"),lu=[...zA.split(" ").filter(e=>!Yi.has(e)),"-h","-V"].join("|");function ec(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}var Vo=Symbol("pm.active-extension-host-context");function Ve(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[Vo]=!0,n}run(t,n={}){return ZG({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}async withItemTransactionContext(t,n=!1){let r=E(this.defaults.cwd??process.cwd(),this.defaults.path),o=async()=>{let c=await ir(r,()=>A(r));return t({pmRoot:r,author:R(this.defaults.author,c.author_default)})};if(this.defaults[Vo]===!0){let c=process.cwd(),d=()=>JA(r,uo({path:r}),void 0,c,o);return n?ir(r,d):d()}let i=Pr()!==void 0;i&&pu(this.defaults.cwd);let s=i?void 0:this.defaults.cwd,a=()=>XA({...this.defaults,cwd:s,path:r},o);return n?ir(r,a):a()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-O26COBOJ.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-O26COBOJ.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,r)=>this.withItemTransactionContext(async o=>(await import("./item-transaction-O26COBOJ.js")).abandonItemTransaction({...r,...o,transactionId:n}));return{status:n=>this.withItemTransactionContext(async r=>(await import("./item-transaction-O26COBOJ.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-NOHVIOQQ.js")).readItemRevision(t,{pmRoot:n}))}async withExpectedItemRevisions(t,n){let r=await import("./item-revision-NOHVIOQQ.js"),o="",i=await this.withItemTransactionContext(({pmRoot:a})=>(o=a,r.bindExpectedItemRevisions(t,{pmRoot:a}))),s=this.defaults.noExtensions===!0&&this.defaults[Vo]!==!0;return r.runWithBoundItemRevisionScope(i,n,{scopeArgs:["--pm-path",o,...s?["--no-extensions"]:[]]})}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return tv(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Ld(await this.list(Pd(t)),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 Dh(r,"append"),await this.runTyped("append",{id:t,...Ve(wt(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:wt(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",Ve(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ve(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,...Ve(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ve(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ve(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ve(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ve(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ve(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},...Ve(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ve(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ve(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ve(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 $7(e={},t={}){return new z(t).context(e)}function P7(e={},t={}){return new z(t).list(e)}function L7(e={},t={}){return new z(t).listAllComplete(e)}function N7(e,t={},n={}){return new z(n).search(e,t)}function F7(e,t={},n={}){return new z(n).get(e,t)}function M7(e={},t={}){return new z(t).next(e)}function D7(e={},t={}){return new z(t).aggregate(e)}function U7(e,t={},n={}){return new z(n).comments(e,t)}function j7(e,t={},n={}){return new z(n).notes(e,t)}function G7(e,t={},n={}){return new z(n).learnings(e,t)}function q7(e,t={},n={}){return new z(n).files(e,t)}function K7(e,t={},n={}){return new z(n).filesDiscover(e,t)}function z7(e,t={},n={}){return new z(n).docs(e,t)}function H7(e,t={},n={}){return new z(n).deps(e,t)}function B7(e,t={},n={},r={}){return new z(r).graph(e,t,n)}function W7(e,t,n={},r={}){return new z(r).append(e,t,n)}function V7(e={},t={}){return new z(t).create(e)}function Y7(e,t={},n={}){return new z(n).update(e,t)}function J7(e,t,n={},r={}){return new z(r).reopen(e,t,n)}function X7(e,t,n={},r={}){return new z(r).close(e,t,n)}function Q7(e,t={},n={}){return new z(n).claim(e,t)}function Z7(e={},t={}){return new z(t).claimNext(e)}function eee(e,t={},n={}){return new z(n).release(e,t)}function tee(e,t={},n={}){return new z(n).copy(e,t)}function nee(e,t={},n={}){return new z(n).delete(e,t)}function ree(e,t,n={},r={}){return new z(r).restore(e,t,n)}function oee(e,t={},n={}){return new z(n).focus(e,t)}var VA=v_(),nc=new BG;function Yo(e){try{return WG(e)}catch{return uu.resolve(e)}}function Pr(){let e=nc.getStore();for(;e!==void 0&&!e.live;)e=e.parent;return e}async function $r(e,t,n,r=!0){let o={root:Yo(e),active:t,live:!0,parent:Pr(),ready:r};try{return await nc.run(o,n)}finally{o.live=!1}}function pu(e){if(e===void 0||Yo(e)===Yo(process.cwd()))return;let t="Omit cwd inside an open extension scope and address the tracker with path, or make the call outside the scope.";throw new l(`A nested SDK call cannot change the working directory to "${e}" while its caller's extension scope is open. ${t}`,m.USAGE,{code:"invalid_argument_value",reason:"nested_cwd_unavailable",changed:!1,field:"cwd",required:t,nextSteps:[t]})}function fu(e,t,n,r){let o=Pr();if(o===void 0)return;let i=o===nc.getStore(),s=o.root===Yo(e);if(s&&!o.ready){let a="Do the work from a command or hook handler, after the tracker's extensions have activated.";throw new l(`An extension lifecycle callback cannot run SDK work for tracker ${o.root} while its extensions activate or deactivate. ${a}`,m.USAGE,{code:"invalid_argument_value",reason:"extension_scope_not_ready",changed:!1,required:a,nextSteps:[a]})}return i&&s&&t.noExtensions!==!0?r(o.active):Zc(()=>$r(e,null,()=>mu(t,n,a=>$r(e,a,()=>r(a))),!1))}function JA(e,t,n,r,o){let i=nc.getStore();if(i===void 0)return o(null);let s=Pr(),a={...t,noExtensions:!1};return s===void 0?$r(e,null,()=>_u(a,n===void 0?void 0:r,r,c=>$r(e,c,()=>o(c))),!1):s===i&&s.ready&&s.root===Yo(e)?o(null):fu(e,a,r,o)}function tc(){ed(ep()),td(tp()),nd(np()),rd(rp()),od(op()),id(ip()),sd(sp())}async function _u(e,t,n,r){return Zc(()=>t===void 0?VA.read(()=>mu(e,n,r)):VA.write(()=>JG(t,()=>mu(e,n,r))))}async function XA(e,t){let n=e.cwd,r=n===void 0?process.cwd():uu.resolve(n),o=E(r,e.path),i=uo({path:o,noExtensions:e.noExtensions});Pr()!==void 0&&pu(n);let s=fu(o,i,r,()=>t());return s!==void 0?s:_u(i,n===void 0?void 0:r,r,a=>$r(o,a,t))}function iee(e,t){return XA({path:e},t)}function VG(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:gh(e);return typeof n=="string"?n:"Unknown failure"}catch{return"Unknown failure"}}async function mu(e,t,n){let r=E(t,e.path);if(e.noExtensions)return tc(),Yd({pmRoot:r},()=>n(null));if(!await W(ce(r)))return tc(),n(null);let o=null,i;try{let s=await A(r),a=await jr({pmRoot:r,settings:s,cwd:t,noExtensions:!1}),c=await Gr({...a,loaded:a.loaded});i={loadResult:a,activationResult:c},ed(c.hooks),td(c.commands),nd(c.parsers),rd(c.preflight),od(c.services),id(c.renderers),sd(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(s){tc(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",VG(s))}try{return await Yd({pmRoot:r,packages:o?.packages},()=>n(o))}finally{tc(),i&&await Oc(i.loadResult,i.activationResult).catch(()=>{})}}function QA(e,t){let n=dr(e);return t?.registrations.commands.find(r=>dr(r.action)===n)?.command??t?.commands.handlers.find(r=>dr(r.command)===n)?.command}async function YG(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,m.USAGE);let i=QA(e,o);if(!i)throw new l(`Unsupported native pm action: ${e}`,m.USAGE);let s=typeof n.author=="string"?n.author:r.author,a=xd(i),c=Th(Id(t,n),Ch(o.registrations,a),a,Yw(a)),d=await Vi({command:a,args:Se(n.args??t.args),options:c,global:{...r,author:s},pm_root:o.pmRoot,sdk:Vw(o.pmRoot,z.forActiveExtensionHost({pmRoot:o.pmRoot,author:s}),s,a)});if(!d.handled){if(Object.hasOwn(d,"cause"))throw ys(i,d);let u=d.warnings.length>0?` (${d.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${u}`,m.USAGE)}return d.result}async function JG(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function XG(e){let t=De(e,"action"),n=dr(t),r=Kn(rv,n),o=r?.action??n,i={...e,action:o};return r?.options!==void 0&&(i.options={...r.options,...Fr(e.options)}),o==="package"&&(i.options={...Fr(i.options),vocabulary:"package"}),{action:o,args:i}}function QG(e,t,n,r){let o=e[Vo]===!0,i=t.noExtensions===!0&&!o?["--no-extensions"]:[];if(n!==void 0)return["--pm-path",E(r,t.path),...i];let s=ke(t,r);return[...t.noExtensions===!0?s.slice(0,-1):s,...i]}async function ZG(e){let t=XG(e),n=uo(t.args);b_(n);let r=Wh(t.action),o=b(t.args,"cwd"),i=o===void 0?process.cwd():uu.resolve(o);t.action==="init"&&(n[dl]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(i,n.path));let{expectHash:s,dispatchArgs:a}=Xh(t.args),c=async d=>{if(s===void 0)return YA(t.action,a,n,d);let{dispatchWithExpectedItemRevisions:u}=await import("./item-revision-NOHVIOQQ.js");return u({action:t.action,expectHash:s,defaultId:b(a,"id")??b(Fr(a.options),"id"),options:Fr(a.options),background:a.background,pmRoot:E(i,n.path),invocation:{scopeArgs:QG(e,n,o,i),...n.outputFormat===void 0?{}:{outputArgs:["--output-format",n.outputFormat]}},run:()=>YA(t.action,a,n,d)})};try{if(t.action==="history-attest")return await c(null);let d=E(i,n.path);if(Pr()!==void 0&&pu(o),e[Vo]===!0)return await JA(d,n,o,i,c);let u=fu(d,n,i,c);return u!==void 0?await u:await _u(n,o===void 0?void 0:i,i,p=>$r(d,p,()=>c(p)))}finally{r&&tu()}}async function YA(e,t,n,r){let o=Kn(FA,e),i=Rd(t,e,{nativeAction:o!==void 0});if(e==="create"||e==="update"){let{assertNativeMutationOptions:u}=await import("./mutation-admission-JRICEVYN.js");await u(e,t,i,n.path,Hh[e])}if(e==="update-many"){let{assertNativeUpdateManyOptions:u}=await import("./mutation-admission-JRICEVYN.js");await u(t,i,n.path)}let s=o?void 0:QA(e,r),a=s===void 0?e:`extension:${s}`;C_(a,i),R_(a,i);let c={action:e,args:t,options:i,id:b(t,"id"),force:t.force===!0||i.force===!0,global:n,activeExtensions:r},d=o?await o(c):await YG(e,t,i,n,r);if(e==="history-attest")return d;{let u=$_(a,i,d);return await Ww(E(process.cwd(),n.path),u),u}}var eq={closeManyOptionsFromFlat:Es,extensionOptionsFromArgs:Id,globalOptions:uo,mutationListOptions:Vh,normalizeActionName:dr,normalizeCommandPath:xd,normalizeMcpUpdateOptions:Jh,normalizeMcpOptionsArrays:Bh,optionsWithAuthor:Rd,readRequiredString:De,readScalarString:qh,readScalarStringAllowBlank:Kh,readStringArray:Se,updateManyOptionsFromFlat:Cs,withAddNoteOption:po,withFilesDiscoveryOptions:As,withMutationCompaction:ve};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=eq);export{Vd as a,cC as b,EC as c,dw as d,wK as e,lw as f,vK as g,bK as h,bw as i,XC as j,z as k,$7 as l,P7 as m,L7 as n,N7 as o,F7 as p,M7 as q,D7 as r,U7 as s,j7 as t,G7 as u,q7 as v,K7 as w,z7 as x,H7 as y,B7 as z,W7 as A,V7 as B,Y7 as C,J7 as D,X7 as E,Q7 as F,Z7 as G,eee as H,tee as I,nee as J,ree as K,oee as L,XA as M,iee as N,ZG as O};
44
+ //# sourceMappingURL=chunk-2XGHBYDA.js.map