@unbrained/pm-cli 2026.11.29 → 2026.12.1
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.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/commander-usage.js +10 -10
- package/dist/cli/error-guidance.js +5 -5
- package/dist/cli/extension-command-help.js +6 -6
- package/dist/cli/help-json-payload.js +7 -7
- package/dist/cli/main.js +5 -5
- package/dist/cli/register-list-query.js +10 -10
- package/dist/cli/register-mutation.js +3 -3
- package/dist/cli/runtime/invocation-command-path.js +2 -0
- package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-JQHLOSSS.js → chunk-3HKPVOAN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZSBPE36C.js → chunk-3KEMIPKG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JFPCL45G.js → chunk-4YQMQOUO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-EYEQC3L2.js → chunk-4YYFY33T.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-A5ZEMOVR.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-WLZ5KVM2.js → chunk-AHV3CSQG.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-AJLU6KLW.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-R6M5OGJH.js → chunk-C6WM6ZN4.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-CBUC4X7Q.js +127 -0
- package/dist/cli-bundle/chunks/{chunk-K3MVVDLN.js → chunk-CWPR234D.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-I4SPJQQI.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-VI3A7UZ2.js → chunk-L2ZSSMYY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DBASKWBO.js → chunk-MZZ4ZJ5Z.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CV2B4JUB.js → chunk-NA6D75V5.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-NRQCBUYD.js +113 -0
- package/dist/cli-bundle/chunks/{chunk-ZK4CY24V.js → chunk-OBPO6V7H.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3US5T6B2.js → chunk-OKEJ4U2I.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-3E53F7QY.js → chunk-OXC5KBIQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NLHNB2L3.js → chunk-PCDTWL6V.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-LQEB6GSY.js → chunk-Q6GLSAJY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3TK2YOVB.js → chunk-Q6K7HWZ7.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-QDV7S2QS.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-Q6GIFUCW.js → chunk-SY5C3U32.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-L7HON3BE.js → chunk-U7RBJGLF.js} +23 -23
- package/dist/cli-bundle/chunks/chunk-WSEIEDEK.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-FRYNDVLN.js → chunk-XME6GIFQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-WNB62BGK.js → chunk-YSVOXCYH.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KCR4NF2A.js → chunk-ZL6J6JYT.js} +6 -6
- package/dist/cli-bundle/chunks/{field-option-collisions-OZE43TOH.js → field-option-collisions-BBGTV7AD.js} +2 -2
- package/dist/cli-bundle/chunks/item-revision-3LENTXYF.js +2 -0
- package/dist/cli-bundle/chunks/item-transaction-66RDV7PH.js +2 -0
- package/dist/cli-bundle/chunks/{linked-resource-value-list-2655COY2.js → linked-resource-value-list-E2DX52LY.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-actor-QOKPDYM4.js → mutation-actor-NHN33ITJ.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-JNJHB3E6.js → mutation-admission-PGKJTCG6.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-YGVUE4YZ.js → register-list-query-7S5QWDTI.js} +11 -11
- package/dist/cli-bundle/chunks/{register-mutation-3JVZQDHH.js → register-mutation-2F6JUBST.js} +5 -5
- package/dist/cli-bundle/chunks/{register-operations-LCHUHKRA.js → register-operations-ET3UKPYK.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-IJ7M3VUK.js → register-setup-I63QTFCU.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-7BD7U2BX.js → stage-4ZCF74G4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NO5MUY4I.js → chunk-2DGKVXFT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2UWKU2BQ.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-42SU4LK3.js → chunk-4SCFAWAW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LSVRZ4KQ.js → chunk-6BKT6XQN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-6IY5CVGJ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-7A6SEZEY.js +4 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LKTRICZR.js → chunk-BHNBPCHP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PPCBCPIZ.js → chunk-EQCQTYKO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NNLENKU7.js → chunk-HTDYNY4L.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-S5VG7RFY.js → chunk-JPZGC3W4.js} +5 -5
- package/dist/cli-bundle/focused-chunks/{chunk-ACTBMSCH.js → chunk-KNBGHCIP.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-N64AC5G6.js +100 -0
- package/dist/cli-bundle/focused-chunks/{chunk-EUDAUT6T.js → chunk-OG57ESZK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2CQFGJQ6.js → chunk-P2H3GTJK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QTV6UE2Q.js → chunk-PT7RT3T6.js} +26 -26
- package/dist/cli-bundle/focused-chunks/chunk-QZRYGYTI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BPOU2S44.js → chunk-SQ72CVUH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SQMOF65W.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-T3ILWAEV.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KWKPX36T.js → chunk-TR22GU7M.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TSZVCALS.js → chunk-TXTPAFHJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VK3IE3TS.js +29 -0
- package/dist/cli-bundle/focused-chunks/{chunk-GTUPHXKR.js → chunk-VQIC3UZB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-S4AC7OMI.js → chunk-W4JMV7GF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{field-option-collisions-HABQYZMQ.js → field-option-collisions-2C6DLUC4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-revision-723XCQPS.js +2 -0
- package/dist/cli-bundle/focused-chunks/{item-transaction-YZ2PUPGM.js → item-transaction-2K4SFLJ7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-actor-DJ2VRLKG.js → mutation-actor-DJMZUIZI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-SDWQVVHN.js +2 -0
- package/dist/cli-bundle/focused-chunks/{stage-FEJT2UCG.js → stage-QBZIK3T5.js} +2 -2
- package/dist/cli-bundle/main.js +27 -27
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +63 -63
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +2 -2
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/shared/secret-rules.d.ts +86 -12
- package/dist/core/shared/secret-rules.js +7 -5
- package/dist/core/shared/url-credentials.d.ts +4 -2
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +50 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +3 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/extension/command-options.js +1 -1
- package/dist/sdk/lifecycle/expect-hash-admission.d.ts +15 -0
- package/dist/sdk/lifecycle/expect-hash-admission.js +2 -0
- package/dist/sdk/lifecycle/item-revision.d.ts +4 -1
- package/dist/sdk/lifecycle/item-revision.js +1 -1
- package/dist/sdk/mutation-guard.js +1 -1
- package/dist/sdk/output-contracts.js +1 -1
- package/dist/sdk/output-projection.d.ts +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/aggregate.js +1 -1
- package/dist/sdk/query/context.js +1 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/next.js +1 -1
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/read-output/surfaces.js +1 -1
- package/dist/sdk/read-output-budget.d.ts +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.js +1 -1
- package/docs/COMMANDS.md +37 -0
- package/docs/CONFIGURATION.md +22 -3
- package/docs/MUTATION_INTEGRITY.md +226 -10
- package/docs/READ_OUTPUT_CONTRACTS.md +5 -0
- package/docs/SDK.md +35 -9
- package/docs/agent-task-token-baseline.json +1 -1
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4EBHZBM2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-CNZOC6JD.js +0 -2
- package/dist/cli-bundle/chunks/chunk-JV7LREUF.js +0 -3
- package/dist/cli-bundle/chunks/chunk-NRCGGNOE.js +0 -2
- package/dist/cli-bundle/chunks/chunk-PY6A7ULK.js +0 -125
- package/dist/cli-bundle/chunks/chunk-RWHS77ME.js +0 -113
- package/dist/cli-bundle/chunks/chunk-SV27NNXQ.js +0 -2
- package/dist/cli-bundle/chunks/item-revision-3WXNNFLP.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-DJ5GAITL.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5NSWNLFE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-BPBKHY6H.js +0 -100
- package/dist/cli-bundle/focused-chunks/chunk-BZ3PUUPG.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-KLOHZNJ4.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-MYWUMVCZ.js +0 -4
- package/dist/cli-bundle/focused-chunks/chunk-NZA2LP4Y.js +0 -27
- package/dist/cli-bundle/focused-chunks/chunk-TX24L7RQ.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-WJAUHPXD.js +0 -2
- package/dist/cli-bundle/focused-chunks/item-revision-YH5R7YPW.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-3SECKVKY.js +0 -2
|
@@ -1,44 +1,44 @@
|
|
|
1
|
-
import{A as Ad,B as Th,C as Rh,n as Tf,o as Mi,p as Pf,q as Lf,r as Ui,s as Wr,t as Uc,u as jc,v as ji,y as G_,z as q_}from"./chunk-ACTBMSCH.js";import{a as xh,f as Ih,h as kn,m as Oh,o as ao,r as bs,s as $h,t as Ph,x as Lh}from"./chunk-WJAUHPXD.js";import{$ as Pg,A as lg,Ab as yy,Bb as wy,Cb as fr,Db as qd,Eb as vy,Ga as qg,Ha as Kg,Hb as Ds,I as hg,Ia as zg,J as gg,Ja as Hg,K as yg,Ka as Bg,L as wg,La as Wg,M as vg,Ma as Vg,N as bg,Na as An,O as kg,Oa as Yg,Ob as by,P as Sg,Pa as Jg,Pb as ky,Q as Ag,Qa as Xg,Qb as Sy,R as Eg,Ra as Ps,S as Cg,Sa as Qg,T as Tg,Ta as Zg,U as Rg,Ua as ey,Ub as Ay,V as xg,Va as ty,Vb as My,W as Ig,Wa as oy,X as Og,Xa as Ls,Y as $g,Ya as en,Z as $d,Za as iy,_ as mr,_a as Ns,aa as Lg,bb as wo,g as ng,h as rg,ia as Ng,ib as sy,jb as ay,ka as Mg,kb as cy,la as Nd,lb as dy,ma as Fd,mb as ly,na as Dg,nb as my,oa as Dd,ob as Fs,pb as jd,qa as Ug,qb as uy,ra as jg,rb as Gd,sa as Ud,sb as pr,tb as py,ub as fy,vb as _y,wb as hy,xb as gy,yb as vo,zb as Ms}from"./chunk-BPOU2S44.js";import{A as Hh,B as uo,C as Bh,D as Wh,E as Rd,F as po,G as Cs,H as dr,I as Vh,J as xd,K as Se,L as Id,M as ve,N as Yh,O as Jh,P as Ts,R as Xh,S as Rs,T as Qh,a as ks,b as co,c as Ss,d as Ne,e as As,f as Nh,g as Fh,h as Es,i as lo,j as Mh,k as Dh,l as Ed,m as Cd,n as yt,o as Uh,p as jh,q as Gh,r as mo,s as qh,t as Td,u as wt,v as b,w as Kh,x as zh,z as Ke}from"./chunk-LSVRZ4KQ.js";import{a as pg}from"./chunk-IIP6LZ5E.js";import{h as vt,i as En,m as ry}from"./chunk-5NSWNLFE.js";import{a as yo,b as mg,c as Os,h as fg,i as _g}from"./chunk-EUDAUT6T.js";import{c as Od}from"./chunk-XR6MLUVW.js";import{c as ug}from"./chunk-AIDL2ZNT.js";import{e as Af,g as Ef,h as Cf,l as $f}from"./chunk-PPCBCPIZ.js";import{h as j_}from"./chunk-BZ3PUUPG.js";import{S as N_,T as ld,U as F_,V as Xi,W as md,X as M_,Y as D_,a as lp,b as mp,c as up,d as pp,da as ud,f as fp,ha as U_}from"./chunk-S4AC7OMI.js";import{a as ag,b as cg,c as Us,d as js,e as Gs}from"./chunk-LKTRICZR.js";import{K as Gg,b as dg}from"./chunk-GTUPHXKR.js";import{$a as Fy,A as Oy,Aa as ko,B as $y,C as Py,Ca as Bd,Ha as Wd,Ja as Ly,Ya as So,_a as Ny,b as sg,e as Pd,g as Ld,i as Md,j as bo,l as Ey,m as Cy,n as Kd,q as Ty,r as zd,va as Hd,x as Ry,y as xy,z as Iy}from"./chunk-S5VG7RFY.js";import{T as $s,Y as ur,h as xs,k as eg,l as fo,o as tg,w as Lt,y as og,z as ig}from"./chunk-MYWUMVCZ.js";import{a as go,b as Sn,d as ny}from"./chunk-NO5MUY4I.js";import{$ as J_,$a as gh,A as _e,B as es,Bb as vh,C as fd,D as rt,E as H_,F as _d,Fb as bh,G as B_,H as ue,J as Ot,Jb as cr,K as W_,Kb as kh,L as ts,Lb as kd,M as Vt,Mb as Sh,N as ge,Nb as Ah,O as or,Ob as Eh,P as hd,Q as to,R as ns,Rb as Sd,S as no,Sb as Ch,T as $t,U as V_,V as rs,W as os,X as is,Y as ss,Ya as io,Z as as,_ as Y_,_a as hh,aa as X_,ab as ws,bb as vs,c as bf,cb as yh,ea as cs,f as kf,fa as ds,g as Sf,i as Fi,ia as ms,j as zt,ja as us,k as Jn,ka as th,l as Nf,la as ps,m as Ff,ma as fs,n as K_,na as Jt,p as ht,pa as yd,q as gt,qa as _s,r as tr,rb as wh,s as pd,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-NZA2LP4Y.js";import{$ as qr,$a as Ri,Aa as rf,B as Mc,Ba as of,C as Dc,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 Lc,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 Nc,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 Fc,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-KLOHZNJ4.js";import{A as Fg,a as _o,b as ho,c as lr,d as st,i as Is}from"./chunk-42SU4LK3.js";import{d as Zh}from"./chunk-NNLENKU7.js";import{B as Qt,D as j,E as te,F as uh,H as ye,I as ph,J as bn,K as it,L as fh,M as Zt,N as we,O as _h,P as bd,U as so,a as Pe,b as Q_,c as Z_,d as Yt,f as Le,g as ro,h as wn,i as ch,j as sr,k as ar,l as dh,r as vn,t as ys,z as Xt}from"./chunk-TSZVCALS.js";import{b as gd,e as eh,f as ls,g as ot,i as oh,j as ir,l as ih,m as Pt,n as sh,o as gs,p as wd,q as ah,r as A,s as xe,u as lh,v as vd,w as mh,x as O}from"./chunk-2CQFGJQ6.js";import{b as hs}from"./chunk-CWQLW4ZO.js";import{a as Ji,b as L_}from"./chunk-X6CXWWNB.js";import{$ as Vu,$c as l_,Aa as ip,Ab as Xf,Ac as Qr,Ba as sp,Bb as ut,Bc as Qc,Bd as w_,Cb as pt,Cc as _t,Da as Ur,Dc as Zr,Dd as v_,Ec as eo,Ef as I_,Fa as ap,Ff as O_,H as mt,Hc as o_,I as qu,Ia as cp,If as er,Ja as dp,Jb as Qf,Jd as td,K as Rc,L as Fr,Lc as i_,Ld as nd,M as Wn,Mb as Yr,Md as rd,Mf as $_,Nb as ft,Nd as od,Od as id,Pc as s_,Pd as sd,Qa as jr,Qd as ad,Qe as A_,Ra as Pc,Rd as cd,Re as E_,Sa as Gr,Sc as a_,Sd as I,Tc as c_,Tf as P_,Ub as Hi,Uc as Zc,Ud as Qn,Vb as Zf,Vd as gn,Wb as e_,Wd as Q,We as C_,X as zu,Xa as Mf,Xb as Jr,Xc as ed,Xe as T_,Y as Hu,Yb as Bi,Z as Bu,Zc as d_,Zd as yn,Ze as R_,_ as Wu,_d as Zn,a as Tu,aa as Yu,ad as m_,ba as Ic,ca as Ju,cb as It,cd as u_,ce as Vi,dd as p_,ea as Xu,ee as Re,fa as Qu,gb as zi,gc as Jc,h as Ue,hd as qe,i as oi,ia as Oc,ib as zc,id as Bt,ie as Yi,j as ii,ja as Zu,jd as Wi,k as Fu,ka as $c,lb as de,le as b_,mb as _n,mc as hn,me as ke,nb as le,nc as R,ne as k_,ob as Hc,oc as t_,od as f_,pb as Bc,qb as Wc,qd as __,r as Mu,re as S_,sb as Wf,sc as n_,t as Du,td as h_,ub as Vc,v as Uu,va as ep,wa as tp,wb as Vf,we as dd,wf as x_,x as ju,xa as np,xb as Yf,xc as r_,y as Gu,ya as rp,yb as Jf,yc as Xc,yd as g_,za as op,zb as Yc,zc as Xr,zd as y_}from"./chunk-BPBKHY6H.js";import{A as se,B as Df,C as P,F as fn,G as Gc,H as Uf,I as Xn,J as jf,K as Vr,L as Gf,O as qf,P as qc,Q as Kf,R as Kc,S as zf,T as qi,V as Hf,W as Bf,X as Ki,c as Ct,d as ee,k as Te,m as V,o as un,u as C,y as Gi}from"./chunk-TX24L7RQ.js";import{b as xc,c as Mr,d as Oe,g as $,h as Ce,i as si,j as Bn,k as Dr,l as Ku,n as E,o as ai,p as $e,q as ce,r as Et,t as Ze,u as ci}from"./chunk-26P6C6OO.js";import{$ as Of,G as Rf,I as xf,K as If,P as Tt,V as Di,Z as Rt,_ as Ht,a as gc,ba as D,c as yc,ca as xt,d as wc,da as et,fa as Yn,h as ni,i as St,j as Lr,k as Nr,l as vc,n as Ru,o as xu,p as Iu,q as Ou,s as $u,t as Pu,u as bc,v as kc,w as Sc,x as Ac,y as Ec,z as Cc}from"./chunk-JFICNN4T.js";import{A as l,C as W,D as At,E as je,F as oe,J as ae,L as Hn,m as ri,s as Tc,u as Lu,x as mn,y as Nu,z as m}from"./chunk-IRYNVGKH.js";import{readFile as FE}from"node:fs/promises";import ME from"node:path";var Vd="context-intents.json";function qs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DE(e,t,n){if(!qs(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 Dy(e,t){let n=Array.isArray(e)?e:qs(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)=>DE(r,t,o))}async function UE(e){let t=ME.join(e,Vd),n;try{n=await FE(t,"utf8")}catch(o){if(At(o))return[];throw await mh(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 Dy(r,Vd)}function jE(e){if(!qs(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return qs(n)?n.contextIntents??n.context_intents:void 0}function GE(e){return e.flatMap(t=>{let n=jE(t.module);return n===void 0?[]:Dy(n,`package ${t.name}`)})}async function qE(e){let t=await UE(e.pmRoot),n=GE(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Yd(e,t){let n=await qE(e);return await O_(n,t)}import{createHash as cC}from"node:crypto";import{readFileSync as dC}from"node:fs";import{readFile as KE}from"node:fs/promises";function Tn(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,ue(e,t)}function Ky(e){return Object.prototype.toString.call(e)==="[object Object]"}function zE(e,t,n,r){let o=C();if(!Ky(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 Uy(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 HE(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 KE(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 zs(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 HE(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 zy(e){return e==="comments"?"--stdin":"--add -"}function BE(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function WE(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function VE(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=WE(t),o=zy(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 YE(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!BE(e)))throw VE({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function JE(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 XE(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(QE(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> ${zy(e.collectionKey)}`]})}function QE(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 jy(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 ZE(e,t,n,r,o,i){let s=Cn(e.metadata,t),a=o?s.findIndex(c=>Ky(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 Gy(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){XE(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 Ks(_.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=qy(r.input.index,v.length,r.collectionKey);return jy(e,v,k,r,t.expectAt),Uy(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 Ks(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??"";YE(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(JE(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=qy(r.input.index,S.length,r.collectionKey);jy(e,S,T,r,t.expectAt);let x=S[T];return Uy(x,"edited"),S[T]=zE(x,u,c,r.createEntry),y=Gy(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 Ks(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=ZE(_,r.collectionKey,c,u,t.ifAbsent===!0,r.createEntry);return f=Gy(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(_){Ao(_,r.conflictGuidance)}let h=Cn(p.item,r.collectionKey);return Ks(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 qy(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 eC(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 Hy(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function tC(e,t){let n=e.length-t.length;return t.map((r,o)=>Hy(r,n+o+1))}function Ks(e,t,n,r,o,i,s=!1){let a=i===void 0||s?tC(n,Jd(n,i!==void 0&&s?void 0:r)):i.entry===void 0?[]:[Hy(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}:{}}:{},...eC(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 Hs(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 By(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 nC}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 rC="strict",Ws="start_blocked_by_open_dependency";function Wy(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 Bs(e,t,n){let r=o=>Le(o.trim(),n).toLowerCase();return r(e)===r(t)}var oC=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()&&oC.has(e.source_kind?.trim().toLowerCase()??"")}function iC(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"&&Bs(s.id,t,n)))return P(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&Bs(e.blocked_by,t,n))){let s=o.filter(a=>Bs(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=>Bs(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 sC=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function aC(e,t){try{return(await ny(e)).filter(n=>!n.resolved)}catch(n){let r=so(n)?n.context.code:void 0;if(!t||typeof r!="string"||!sC.has(r))throw n;return r}}async function Vy(e){let t=e.settings.governance.start_blocker_enforcement??rC;if(t==="off")return[];let n=$(e.settings,I()).type_to_folder,r=e.metadata.id,o=await aC({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])),iC(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 Vs(e){if(e.requested===!1||!Wy(e.fromStatus,e.metadata.status,e.registry))return[];let t=await Vy(e),n=Zd.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var Zd=new nC;function Yy(e){return Zd.run({warnings:new Set},e)}async function Jy(e){let t=Zd.getStore();if(t===void 0)return[];let n=Wy(e.metadata.status,Nt(e.registry),e.registry)?await Vy(e):[];for(let r of n)t.warnings.add(r);return n}var Zy="no_available_next_item";function ew(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 tw(e,t){return ew(e)===t}function lC(e){return tw(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;uC(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 mC({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}=vC(w.metadata,r.start===!0,i,s);return Y.push(...await wC({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=nw(await rw("claim",g.item.id,n,p,()=>Ey({pmRoot:o,settings:i,principal:c,itemId:g.item.id})));return _.push(...y.warnings),{item:Gc(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 mC(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 Ty(e.pmRoot,e.storageId,e.holder,{updated_at:e.metadata.updated_at,threshold_hours:e.thresholdHours}),n=e.takeoverStale?pC(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 hC(e.metadata.id,t,e.takeoverStale)}function uC(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 pC(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 fC={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 _C(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:`${fC[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 hC(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=_C(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 gC="claim_semantic_attribution_unrecorded";function nw(e){return e?{warnings:[e.warning],suggestions:[e.suggestion]}:{warnings:[],suggestions:[]}}function el(e,t){return t.length>0?{[e]:t}:{}}var yC="release_semantic_attribution_unrecorded";async function rw(e,t,n,r,o){if(!r)try{await o();return}catch(i){let s=ew(i)??"unexpected_error",a=ke(n);return{warning:e==="claim"?gC:yC,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 ow(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 wC(e){return e.start?Vs(e):Jy(e)}function vC(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 iw(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=bC(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 kC(c.slice(0,o),e,t,s)}function bC(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 kC(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(tw(d,Ws)){s.push(c.id);continue}if(!lC(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:[Zy]};throw SC(i,s,r.start===!0)}function SC(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:Zy,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 AC(e){if(e===void 0)return[];let t=e.trim();if(fn(t)===t)return t.startsWith("-")?[`--author=${t}`]:["--author",t]}var sw="release_claim_ended_by_close";function aw(e,t,n,r,o){let i=AC(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:sw,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 cw(e){let t=e.assignee?.trim();return t?e.claim_principal?.trim()||t:void 0}async function dw(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=Qy(c),{document:u}=await te(a,{schema:o.schema}),p=cw(u.metadata);if(p!==void 0&&p!==i&&await zd(r,a.id,i))throw aw(a.id,fn(u.metadata.assignee.trim()),"--pause",t,n);let f=Xy(u.metadata,d);return h=>Wi({pmRoot:r,id:a.id,validate:_=>{if(Xy(_.metadata,Qy(c))!==f)throw new l(`${a.id} changed while the pause was judged, so nothing was written.`,m.CONFLICT,{code:EC,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 EC="pause_item_changed";function Xy(e,t){return JSON.stringify([cw(e)??null,e.status,e.updated_at,t])}function Qy(e){try{return cC("sha256").update(dC(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=Hs(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 aw(w.metadata.id,S,"--handoff",n,r.author);return h=S,{changedFields:[],warnings:[`${sw}:${w.metadata.id}:${S}`]}}d=w.metadata.assignee??null;let k=p===void 0?void 0:By(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=nw(await rw("release",_.item.id,n,!1,()=>Cy({pmRoot:o,principal:a,itemId:_.item.id}))),y=h===void 0?CC(_.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:Gc(_.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 CC(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 TC(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 RC(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 xC(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 lw(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 AK(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 mw(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 EK(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 CK(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=TC(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&&RC(i,s,r)?s.children.push(i):o.push(i)}return xC(o),o}var uw=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 IC(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=uw?n:`${n.slice(0,uw-3)}...`}function pw(e){return e.map((t,n)=>`${n+1}. ${IC(t)}`).join("; ")}function OC(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 $C(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function fw(e,t){let n=OC(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)$C(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: ${pw(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: ${pw(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 PC=["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: ${PC.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 Ys(e){return[...e.filter(Ie),...e.filter(t=>!Ie(t))]}function _w(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 hw(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 LC(){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=LC();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,mg,"FORCE_COLOR"]),Qs=/^[A-Za-z_][A-Za-z0-9_]*$/,xn=["schema","tracker","auto","none"],gw=["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(!Qs.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(!Qs.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 Zs(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 ea(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(gw.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${gw.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 ta(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 na(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 ra(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 NC=new Set($t);function oa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function FC(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!NC.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 Js(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 yw(e,t,n){let r=Js(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 Xs(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 MC(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:Xs(n,"timeout_seconds",t),i=r===void 0?void 0:Xs(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 DC(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 UC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!oa(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(!Qs.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 jC(e,t){let n=Js(e,"env_clear",t);if(n){for(let r of n){if(!Qs.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 GC(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 qC(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=Xs(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 KC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!oa(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 zC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!oa(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]=Xs(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function HC(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,m.USAGE);if(!oa(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${$t.join(", ")}.`);let o=FC(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:DC(o,r),timeout_seconds:MC(o,r),pm_context_mode:d,workspace_context_mode:u,env_set:UC(o,r),env_clear:jC(o,r),shared_host_safe:GC(o,"shared_host_safe",r),assert_stdout_contains:Js(o,"assert_stdout_contains",r),assert_stdout_regex:yw(o,"assert_stdout_regex",r),assert_stderr_contains:Js(o,"assert_stderr_contains",r),assert_stderr_regex:yw(o,"assert_stderr_regex",r),assert_stdout_min_lines:qC(o,r),assert_json_field_equals:KC(o,r),assert_json_field_gte:zC(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)=>HC(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 ww(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 vw(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 BC(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 bw(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 WC(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 ia(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 VC(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",...ia(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",...ia(t),nextSteps:[`Patch only editable fields: ${Oo.join(", ")}.`]});return vo(o),o}function YC(e){let{id:t,tests:n,index:r,identityKey:o,otherFields:i,requested:s,global:a}=e;bw(i,!0);let c=WC(n[r],i,s),d=Io(JSON.stringify(c),"--add-json")[0];ns(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",...ia(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 JC(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function XC(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=VC(a,c,d),p=Object.fromEntries(Object.entries(a).filter(([g])=>!tl.includes(g))),f=YC({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),...JC(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",...ia(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 QC(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);bw(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]);ns(o);let i=n.filter(a=>!ee(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 kw(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=BC(f,t.selector);XC({id:p.metadata.id,tests:f,index:h,patch:t.patch,global:n,controls:t});let _=QC(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 ZC(){return{metadata:{},body:""}}import{AsyncLocalStorage as XG}from"node:async_hooks";import{realpathSync as QG}from"node:fs";import uu from"node:path";var eT=ud("list").properties.outputSession,tT={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:{...eT},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Sw={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."}},Aw={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."},nT=`Operation name (one of): ${$c.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,rT={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."}},oT={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{...Aw,properties:{...Aw.properties,...e},required:t}}var iT=[{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:[...$c],description:nT},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."},...tT},["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"},...oT},["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"},...rT})},{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({...Sw,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:[...wc]},description:`Lifecycle roles for add-status: ${wc.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:Sw}},["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."}})}],sT={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"},aT=iT.map(e=>{let t=sT[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:ud(t,{properties:n,required:r})}});function Ew(){return aT.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 Cw=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"]]]),cT=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Fw=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),aa=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"]),Mw=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"]]),Dw=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"]]),Uw=new Map([...Dw.entries()].flatMap(([e,t])=>Ft(t).map(n=>[n,e]))),jw=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],ol=new Map(jw.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),dT=10,lT=20,Tw=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."]]),Gw=[["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]],mT=[...Gw.map(([e,t])=>e==="init"?[e,Np]:[e,t]),["upgrade",zr]],uT=[...Gw.map(([e,t])=>[`extension ${e}`,t]),...mT.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],...[...Fw].map(e=>[e,li])],$o=new Map(uT);for(let{alias:e,canonical:t}of Te){let n=$o.get(e);n!==void 0&&$o.set(t,n)}function pT(e){let t=Uw.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Rw(e){let t=Te.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Ic.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)}`):aa.has(e)?Dw.get(e)??Ae(e):null}function fT(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 _T(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 sa(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 hT(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 qw(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 xw(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 Iw(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 gT(e){let t=Iw(e.long,"long"),n=Iw(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 Kw(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=gT(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 yT(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...Dc.filter(({flag:n})=>n.startsWith("--output-"))]}}function wT(e){let t=Kw(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)??qw(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},...yT(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:xw(i.examples),failure_hints:xw(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(vT(i,s,t.get(i)?.flags??[]))}return o}function vT(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:qw(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function bT(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 kT(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 ST(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 AT(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]=kT(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=bT(o);!i||n[i]!==void 0||(n[i]=Dc.some(s=>s.flag===o.flag&&s.flag.startsWith("--output-"))?N_[i]:ST(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 ET(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 CT(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&&ET(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 TT(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 RT(e,t={}){let n=new Map;for(let r of Oc){let o=aa.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=Rw(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of aa)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Rw(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 xT(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=>Mw.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 zw(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 IT(e){return Fw.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Ow(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function OT(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function $T(e){let t=new Map;for(let r of e.definitions){let o=Ow(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(a=>OT(a)).find(a=>a!==null),s=r.cli_aliases.map(a=>Ow(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,Mc(o.flags));return n}function $w(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 Mc(n)}function PT(e){let t=Ad(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function LT(e,t,n,r){let o=(n??[]).map(PT),i=t==="extension"&&(n!==void 0||NT(e,r));return{flags:o,inherited:i?{inherited_flags:vp({readOutput:FT(e,r)})}:{}}}function Hw(e,t){let n=V(e);return t.find(r=>V(r.command)===n)}function NT(e,t){return Hw(e,t)!==void 0}function FT(e,t){return Hw(e,t)?.read_output!==void 0}function MT(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?zw(s):[],d=n.get(IT(s))??[],u=i.get(s),p=$w(c,d),f=c.length>0&&(u?.flags.length??0)>0?"mixed":a?"core":"extension",h=LT(s,f,u?.flags,o),_=$w(p,h.flags);return{command:s,flags:_,...h.inherited,...r?{canonical_command:Ww(s),visibility:Bw(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 DT(e,t=un){let n=new Set(e),r=new Map;for(let o of jw){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 UT(){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 Pw(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 jT(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){let o=e.by_type[r];t[r]=Pw(o,"strict"),n[r]=Pw(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function GT(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 qT(e){let t=sa(e.action)!==void 0||sa(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=sa(e.action),u=sa(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 KT(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 zT(e,t=A){try{return await t(e)}catch{return structuredClone(mn)}}async function HT(e,t,n){let r=await zT(t),o=await TT(e),i=$(r,o.registrations??I()),s=et(r.schema),a=wT(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:D(r.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:$T(s),createRequiredOptionContracts:jT(i),extensionContracts:a,mergedExtensionContracts:CT(a.filter(c=>ca(n,c.command,a))),extensionFlagMap:Kw(o.flagRegistrations)}}function Lw(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&aa.has(e.selectedAction)||e.selectedCommand!==void 0&&Pn.has(V(e.selectedCommand)))}function BT(e,t){let n=RT(t,{includePackageOwnedActions:Lw(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??bs(o.action))!=="internal"))}return Lw(e)&&e.selectedCommand!==void 0&&Pn.has(V(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:pT(V(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function WT(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 VT(e,t){return[...new Set([...Ic.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 YT(e,t){let n=t.slice(0,dT),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,lT),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 JT(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 XT(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 QT(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 YT(e.selectedCommand,r);let o=Mw.get(V(e.selectedCommand));throw o?JT(e.selectedCommand,o):XT(e.selectedCommand)}function ZT(e,t){let n=BT(e,t.mergedExtensionContracts);WT(e,n);let r=VT(n,t.mergedExtensionContracts);QT(e,r);let o=e.selectedCommand?Uw.get(V(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(d=>o?d.action===o:fT(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=>xT(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 eR(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 tR(e){let t=U_,n=Po(t),r=eR(t),o=e.filter(i=>!r.has(i.action)).map(i=>AT(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function Nw(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?hT(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 nR(e,t,n){let r=tR(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?GT(Nw(e,n,r),t.createRequiredOptionContracts):Nw(e,n,r);return{mergedSchema:r,filteredSchema:i}}function rR(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?_T(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Bw(e,t){return t.find(n=>V(n.command)===V(e))?.tier??bs(e)}function ca(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||Bw(t,n)!=="internal"}function oR(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)&&ca(e,o,n))}function Ww(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 iR=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"]]),sR=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function aR(e,t){let n=Tw.get(V(e))??(e.includes(" ")?void 0:Tw.get(Ww(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=iR.get(i),c=sR.get(e)??s;return{intent:a===void 0||s.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function cR(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=dd(i,{generateFallback:!0}),a=i.split(" ")[0],c=ol.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...zw(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=(Cw.get(V(i))??Cw.get(c)??cT).filter(f=>d.has(f)),p=aR(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 dR(e){return e.map(t=>({budget:dd(t,{generateFallback:!0}),envelope:Lh(t)}))}function lR(e){let t=new Map;for(let n of e){let r=Ih(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 mR(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=>ca(e,r.command,t.extensionContracts))}function uR(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 pR(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 fR(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 _R(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=MT(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 hR(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=UT();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function gR(e,t,n,r){e.command_summaries=cR(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(Fc.map(({slots:o})=>wp(o))).size,positional_action_count:Nc.length,positional_action_parents:[...new Set(Nc.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:Fc}:{}}}async function sl(e,t){let n=qT(e);KT(n);let r=E(process.cwd(),t.path),o=await HT(t,r,n),i=ZT(n,o),s=nR(n,o,i),a=rR(n,i),c=oR(n,a,o.extensionContracts),d=uR(n,s,i,c),u=mR(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&gR(d,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return d;let f=DT(i.commandCatalog.filter(h=>ca(n,h,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||pR(d,o,n),fR(d,n,s,u),_R(d,n,o,c,f),hR(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...rg],gate_triggers:[...ng]}),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=Ew(),d.context_intents=I_(),d.read_output_dimensions=A_,d.error_codes=Oh,d.command_output_contracts=dR(c),d.diagnostic_output_contracts=S_,d.command_exit_contracts={vocabulary:xh,command_sets:lR(c)}),d}async function Vw(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 yR}from"node:crypto";function al(e){let t=Du();for(let n of e)t.register(n);return t}function wR(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=Rc(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(Rc(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 ee(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
|
|
2
|
-
`}function
|
|
1
|
+
import{A as Ad,B as $h,C as Lh,n as $f,o as Mi,p as Df,q as Uf,r as Ui,s as Wr,t as Uc,u as jc,v as ji,y as B_,z as W_}from"./chunk-KNBGHCIP.js";import{a as Ph,f as Nh,h as Sn,m as Fh,o as ao,r as bs,s as Mh,t as Dh,x as Uh}from"./chunk-6IY5CVGJ.js";import{$ as Ug,A as hg,Ab as Ay,Bb as Ey,Cb as fr,Db as qd,Eb as Cy,Ga as Vg,Ha as Yg,Hb as Ds,I as kg,Ia as Jg,J as Sg,Ja as Xg,K as Ag,Ka as Qg,L as Eg,La as Zg,M as Cg,Ma as ey,N as Tg,Na as En,O as Rg,Oa as ty,Ob as Ty,P as xg,Pa as ny,Pb as Ry,Q as Ig,Qa as ry,Qb as xy,R as Og,Ra as Ls,S as $g,Sa as oy,T as Lg,Ta as iy,U as Pg,Ua as sy,Ub as Iy,V as Ng,Va as ay,Vb as Ky,W as Fg,Wa as ly,X as Mg,Xa as Ps,Y as Dg,Ya as tn,Z as $d,Za as my,_ as mr,_a as Ns,aa as jg,bb as wo,g as cg,h as dg,ia as Gg,ib as uy,jb as py,ka as Kg,kb as fy,la as Nd,lb as _y,ma as Fd,mb as hy,na as zg,nb as gy,oa as Dd,ob as Fs,pb as jd,qa as Hg,qb as yy,ra as Bg,rb as Gd,sa as Ud,sb as pr,tb as wy,ub as vy,vb as by,wb as ky,xb as Sy,yb as vo,zb as Ms}from"./chunk-SQ72CVUH.js";import{A as Jh,B as uo,C as Xh,D as Qh,E as Rd,F as po,G as Cs,H as dr,I as Zh,J as xd,K as Se,L as Id,M as ve,N as eg,O as tg,P as Ts,R as ng,S as Rs,T as rg,a as ks,b as co,c as Ss,d as Ne,e as As,f as jh,g as Gh,h as Es,i as lo,j as qh,k as Kh,l as Ed,m as Cd,n as yt,o as zh,p as Hh,q as Bh,r as mo,s as Wh,t as Td,u as wt,v as b,w as Vh,x as Yh,z as Ke}from"./chunk-6BKT6XQN.js";import{a as wg}from"./chunk-IIP6LZ5E.js";import{a as og,i as vt,j as Cn,n as dy}from"./chunk-T3ILWAEV.js";import{a as yo,b as gg,c as Os,h as vg,i as bg}from"./chunk-OG57ESZK.js";import{c as Od}from"./chunk-XR6MLUVW.js";import{c as yg}from"./chunk-AIDL2ZNT.js";import{e as xf,g as If,h as Of,l as Mf}from"./chunk-EQCQTYKO.js";import{h as H_}from"./chunk-SQMOF65W.js";import{S as j_,T as ld,U as G_,V as Xi,W as md,X as q_,Y as K_,a as lp,b as mp,c as up,d as pp,da as ud,f as fp,ha as z_}from"./chunk-W4JMV7GF.js";import{a as pg,b as fg,c as Us,d as js,e as Gs}from"./chunk-BHNBPCHP.js";import{K as Wg,b as _g}from"./chunk-VQIC3UZB.js";import{$a as qy,A as My,Aa as ko,B as Dy,C as Uy,Ca as Bd,Ha as Wd,Ja as jy,Ya as So,_a as Gy,b as ug,e as Ld,g as Pd,i as Md,j as bo,l as Oy,m as $y,n as Kd,q as Ly,r as zd,va as Hd,x as Py,y as Ny,z as Fy}from"./chunk-JPZGC3W4.js";import{T as $s,Y as ur,h as xs,k as sg,l as fo,o as ag,w as Pt,y as lg,z as mg}from"./chunk-7A6SEZEY.js";import{a as go,b as An,d as cy}from"./chunk-2DGKVXFT.js";import{$ as th,$a as kh,A as _e,B as es,Bb as Eh,C as fd,D as rt,E as J_,F as _d,Fb as Ch,G as X_,H as ue,J as Ot,Jb as cr,K as Q_,Kb as Th,L as ts,Lb as kd,M as Yt,Mb as Rh,N as ge,Nb as xh,O as or,Ob as Ih,P as hd,Q as to,R as ns,Rb as Sd,S as no,Sb as Oh,T as $t,U as Z_,V as rs,W as os,X as is,Y as ss,Ya as io,Z as as,_ as eh,_a as bh,aa as nh,ab as ws,bb as vs,c as Cf,cb as Sh,ea as cs,f as Tf,fa as ds,g as Rf,i as Fi,ia as ms,j as Ht,ja as us,k as Jn,ka as sh,l as jf,la as ps,m as Gf,ma as fs,n as V_,na as Xt,p as ht,pa as yd,q as gt,qa as _s,r as tr,rb as Ah,s as pd,sa as ah,t as Y_,ta as ch,u as Vt,ua as oo,v as nr,w as Qi,x as rr,y as Zi}from"./chunk-VK3IE3TS.js";import{$ as Mp,$a as Ai,Aa as gi,B as Mc,Ba as yi,C as Dc,Ca as rf,Da as of,E as Kt,Ea as sf,F as vp,Fa as af,G as bp,Ga as cf,H as kp,Ha as df,I as Sp,Ia as lf,J as Vn,Ja as mf,K as li,L as mi,La as uf,M as Ap,Ma as pf,N as Ep,Na as ff,O as Cp,Oa as _f,P as Tp,Pa as hf,Q as Rp,Qa as gf,R as xp,Ra as wi,S as Ip,Sa as vi,T as ui,Ta as bi,U as Op,Ua as yf,V as $p,Va as wf,W as Lp,Wa as ki,X as pi,Xa as vf,Y as Pp,Ya as bf,Z as Np,Za as kf,_ as Fp,_a as Si,aa as fi,ab as Ei,b as _p,ba as _i,bb as Ci,c as hp,ca as Dp,cb as Hr,d as gp,da as hi,db as Sf,eb as Ti,fa as Up,fb as Br,ga as qr,gb as Ri,ha as jp,hb as xi,i as Pc,ia as Gp,ib as Ii,ja as qp,jb as Oi,ka as Kp,kb as Af,la as Kr,lb as zt,ma as zp,mb as $i,na as Hp,nb as Li,o as Nc,oa as Bp,ob as Pi,p as yp,pa as Wp,pb as Ni,qa as Vp,ra as Yp,s as di,sa as Jp,sb as Ef,t as Fc,ta as Xp,u as fn,ua as Qp,ub as Ge,va as Zp,vb as M,w as wp,wa as ef,xa as zr,ya as tf,za as nf}from"./chunk-QZRYGYTI.js";import{A as qg,a as _o,b as ho,c as lr,d as st,i as Is}from"./chunk-4SCFAWAW.js";import{d as ig}from"./chunk-HTDYNY4L.js";import{B as Zt,D as j,E as te,F as gh,H as ye,I as yh,J as kn,K as it,L as wh,M as en,N as we,O as vh,P as bd,U as so,a as Le,b as rh,c as oh,d as Jt,f as Pe,g as ro,h as vn,i as ph,j as sr,k as ar,l as fh,r as bn,t as ys,z as Qt}from"./chunk-TXTPAFHJ.js";import{b as gd,e as ih,f as ls,g as ot,i as dh,j as ir,l as lh,m as Lt,n as mh,o as gs,p as wd,q as uh,r as A,s as xe,u as _h,v as vd,w as hh,x as O}from"./chunk-P2H3GTJK.js";import{b as hs}from"./chunk-CWQLW4ZO.js";import{a as Ji,b as U_}from"./chunk-X6CXWWNB.js";import{$ as Vu,$c as h_,Aa as sp,Ab as ut,Ac as Qc,Ad as A_,Bb as pt,Bc as _t,Ca as Ur,Cc as Zr,Cd as E_,Dc as eo,Df as N_,Ea as ap,Ef as F_,Gc as d_,H as mt,Ha as cp,Hf as er,I as qu,Ia as dp,Ib as r_,Id as td,K as Rc,Kc as l_,Kd as nd,L as Fr,Lb as Yr,Ld as rd,Lf as M_,M as Wn,Mb as ft,Md as od,Nd as id,Oc as m_,Od as sd,Pa as jr,Pd as ad,Pe as x_,Qa as Lc,Qd as cd,Qe as I_,Ra as Gr,Rc as u_,Rd as I,Sc as p_,Sf as D_,Tb as Hi,Tc as Zc,Td as Qn,Ub as o_,Ud as yn,Vb as i_,Vd as Q,Ve as O_,Wa as qf,Wb as Jr,Wc as ed,We as $_,X as zu,Xb as Bi,Y as Hu,Yc as f_,Yd as wn,Ye as L_,Z as Bu,Zd as Zn,_ as Wu,_c as __,a as Tu,aa as Yu,ba as Ic,bb as It,bd as g_,be as Vi,ca as Ju,cd as y_,de as Re,ea as Xu,fa as Qu,fb as zi,fc as Jc,gd as qe,h as Ue,hb as zc,hd as Wt,he as Yi,i as oi,ia as Oc,id as Wi,j as ii,ja as Zu,k as Fu,ka as $c,kb as de,ke as C_,lb as hn,lc as gn,le as ke,mb as le,mc as R,me as T_,nb as Hc,nc as s_,nd as w_,ob as Bc,pb as Wc,pd as v_,qe as R_,r as Mu,rb as Qf,rc as a_,sd as b_,t as Du,tb as Vc,ua as ep,v as Uu,va as tp,vb as Zf,ve as dd,vf as P_,wa as np,wb as e_,wc as c_,x as ju,xa as rp,xb as t_,xc as Xc,xd as k_,y as Gu,ya as op,yb as Yc,yc as Xr,yd as S_,za as ip,zb as n_,zc as Qr}from"./chunk-N64AC5G6.js";import{$ as Kc,E as C,I as Gi,K as se,L as Kf,M as L,P as _n,Q as Gc,R as zf,S as Xn,T as Hf,U as Vr,V as Bf,Y as Wf,Z as qc,_ as Vf,aa as Yf,ba as qi,c as Ct,d as ee,da as Jf,ea as Xf,fa as Ki,k as Te,m as V,o as pn}from"./chunk-2UWKU2BQ.js";import{b as xc,c as Mr,d as Oe,g as $,h as Ce,i as si,j as Bn,k as Dr,l as Ku,n as E,o as ai,p as $e,q as ce,r as Et,t as Ze,u as ci}from"./chunk-26P6C6OO.js";import{$ as Ff,G as Lf,I as Pf,K as Nf,P as Tt,V as Di,Z as Rt,_ as Bt,a as gc,ba as D,c as yc,ca as xt,d as wc,da as et,fa as Yn,h as ni,i as St,j as Pr,k as Nr,l as vc,n as Ru,o as xu,p as Iu,q as Ou,s as $u,t as Lu,u as bc,v as kc,w as Sc,x as Ac,y as Ec,z as Cc}from"./chunk-JFICNN4T.js";import{A as l,C as W,D as At,E as je,F as oe,J as ae,L as Hn,m as ri,s as Tc,u as Pu,x as un,y as Nu,z as m}from"./chunk-IRYNVGKH.js";import{readFile as qE}from"node:fs/promises";import KE from"node:path";var Vd="context-intents.json";function qs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zE(e,t,n){if(!qs(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 zy(e,t){let n=Array.isArray(e)?e:qs(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)=>zE(r,t,o))}async function HE(e){let t=KE.join(e,Vd),n;try{n=await qE(t,"utf8")}catch(o){if(At(o))return[];throw await hh(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 zy(r,Vd)}function BE(e){if(!qs(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return qs(n)?n.contextIntents??n.context_intents:void 0}function WE(e){return e.flatMap(t=>{let n=BE(t.module);return n===void 0?[]:zy(n,`package ${t.name}`)})}async function VE(e){let t=await HE(e.pmRoot),n=WE(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Yd(e,t){let n=await VE(e);return await F_(n,t)}import{createHash as fC}from"node:crypto";import{readFileSync as _C}from"node:fs";import{readFile as YE}from"node:fs/promises";function Rn(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,ue(e,t)}function Yy(e){return Object.prototype.toString.call(e)==="[object Object]"}function JE(e,t,n,r){let o=C();if(!Yy(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 Hy(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 Tn(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 XE(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=Yt(),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 YE(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 zs(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 XE(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 Jy(e){return e==="comments"?"--stdin":"--add -"}function QE(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function ZE(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function eC(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=ZE(t),o=Jy(e.collectionKey),i=e.retryArgs===void 0?{}:{field:e.textFlag,recovery:{suggested_flags:[t],suggested_retry:L(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 tC(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!QE(e)))throw eC({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function nC(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:[L([...c,n.collectionKey,e,"--output-budget","unbounded","--json"]),`${L([...c,n.collectionKey,e,"--edit",String(a),"--file"])} <full-text-file>`]})}function rC(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(oC(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> ${Jy(e.collectionKey)}`]})}function oC(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 By(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 iC(e,t,n,r,o,i){let s=Tn(e.metadata,t),a=o?s.findIndex(c=>Yy(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 Wy(e,t,n){return Zf.has(e)?t.map((o,i)=>i).sort((o,i)=>e_(t[o],t[i])||o-i).indexOf(n)+1:n+1}async function hr(e,t,n,r){rC(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=Tn(g.document.metadata,r.collectionKey);return Ks(_.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=Tn(w.metadata,r.collectionKey),k=Vy(r.input.index,v.length,r.collectionKey);return By(e,v,k,r,t.expectAt),Hy(v[k],"deleted"),v.splice(k,1),w.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(w){Ao(w,r.conflictGuidance)}let y=Tn(g.item,r.collectionKey);return Ks(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??"";tC(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(nC(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=Tn(k.metadata,r.collectionKey),T=Vy(r.input.index,S.length,r.collectionKey);By(e,S,T,r,t.expectAt);let x=S[T];return Hy(x,"edited"),S[T]=JE(x,u,c,r.createEntry),y=Wy(r.collectionKey,S,T),k.metadata[r.collectionKey]=S,{changedFields:[r.collectionKey]}}})}catch(k){Ao(k,r.conflictGuidance)}let w=Tn(g.item,r.collectionKey),v=y;return Ks(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=iC(_,r.collectionKey,c,u,t.ifAbsent===!0,r.createEntry);return f=Wy(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(_){Ao(_,r.conflictGuidance)}let h=Tn(p.item,r.collectionKey);return Ks(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 Vy(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 sC(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 Xy(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function aC(e,t){let n=e.length-t.length;return t.map((r,o)=>Xy(r,n+o+1))}function Ks(e,t,n,r,o,i,s=!1){let a=i===void 0||s?aC(n,Jd(n,i!==void 0&&s?void 0:r)):i.entry===void 0?[]:[Xy(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}:{}}:{},...sC(t,i,c)}}function gr(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=jf({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: ${Gf(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,m.USAGE);return`workflow_transition_not_allowed: ${o}`}function Hs(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 Qy(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 cC}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 dC="strict",Ws="start_blocked_by_open_dependency";function Zy(e,t,n){if(t===void 0)return!1;let r=hn(Nt(n),n);return hn(t,n)===r&&hn(e??"",n)!==r}function Bs(e,t,n){let r=o=>Pe(o.trim(),n).toLowerCase();return r(e)===r(t)}var lC=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===Pe(t.trim(),n).toLowerCase()&&lC.has(e.source_kind?.trim().toLowerCase()??"")}function mC(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"&&Bs(s.id,t,n)))return L(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&Bs(e.blocked_by,t,n))){let s=o.filter(a=>Bs(a.id,t,n));return s.length===1&&s.every(a=>a.id===lr(a.id,n,void 0))?L(["update",e.id,"--dep-remove",`id=${s[0].id},kind=blocked_by`]):L(["get",e.id,"--fields","blocked_by,dependencies"])}return o.filter(s=>Bs(s.id,t,n)).every(s=>Qd(s,e.blocked_by,n))?L(["update",e.id,"--unset","blocked_by"]):L(["get",e.id,"--fields","blocked_by,dependencies"])}var uC=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function pC(e,t){try{return(await cy(e)).filter(n=>!n.resolved)}catch(n){let r=so(n)?n.context.code:void 0;if(!t||typeof r!="string"||!uC.has(r))throw n;return r}}async function ew(e){let t=e.settings.governance.start_blocker_enforcement??dC;if(t==="off")return[];let n=$(e.settings,I()).type_to_folder,r=e.metadata.id,o=await pC({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=>L(["get",s.id])),mC(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 Vs(e){if(e.requested===!1||!Zy(e.fromStatus,e.metadata.status,e.registry))return[];let t=await ew(e),n=Zd.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var Zd=new cC;function tw(e){return Zd.run({warnings:new Set},e)}async function nw(e){let t=Zd.getStore();if(t===void 0)return[];let n=Zy(e.metadata.status,Nt(e.registry),e.registry)?await ew(e):[];for(let r of n)t.warnings.add(r);return n}var iw="no_available_next_item";function sw(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 aw(e,t){return sw(e)===t}function hC(e){return aw(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=gn(a),d=r.takeoverStale===!0;yC(d,t);let u=null,p=!1,f={},h,_=[],g=await en({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 gC({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},P=["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}=CC(w.metadata,r.start===!0,i,s);return Y.push(...await EC({pmRoot:o,settings:i,metadata:w.metadata,fromStatus:H,registry:s,force:t,start:r.start===!0})),f=re,_.push(...Y),{changedFields:[...P,...B],warnings:_}}}),y=cw(await dw("claim",g.item.id,n,p,()=>Oy({pmRoot:o,settings:i,principal:c,itemId:g.item.id})));return _.push(...y.warnings),{item:Gc(g.item),changed_fields:g.changedFields,claimed_by:p&&u!==null?_n(u):a,previous_assignee:u===null?null:_n(u),forced:t,...p?{skipped:!0}:{},..._.length>0?{warnings:_}:{},...el("suggestions",y.suggestions),...f,...h===void 0?{}:{takeover:h}}}async function gC(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 Ly(e.pmRoot,e.storageId,e.holder,{updated_at:e.metadata.updated_at,threshold_hours:e.thresholdHours}),n=e.takeoverStale?wC(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 kC(e.metadata.id,t,e.takeoverStale)}function yC(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 wC(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 vC={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 bC(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:`${vC[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 kC(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=bC(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 SC="claim_semantic_attribution_unrecorded";function cw(e){return e?{warnings:[e.warning],suggestions:[e.suggestion]}:{warnings:[],suggestions:[]}}function el(e,t){return t.length>0?{[e]:t}:{}}var AC="release_semantic_attribution_unrecorded";async function dw(e,t,n,r,o){if(!r)try{await o();return}catch(i){let s=sw(i)??"unexpected_error",a=ke(n);return{warning:e==="claim"?SC:AC,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 ${L([...a,"health"])} reports a stale lock, remove it with ${L([...a,"gc","--scope","locks"])}.`}}}function lw(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 EC(e){return e.start?Vs(e):nw(e)}function CC(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 mw(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=TC(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 RC(c.slice(0,o),e,t,s)}function TC(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 RC(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(aw(d,Ws)){s.push(c.id);continue}if(!hC(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:[iw]};throw xC(i,s,r.start===!0)}function xC(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:iw,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 IC(e){if(e===void 0)return[];let t=e.trim();if(_n(t)===t)return t.startsWith("-")?[`--author=${t}`]:["--author",t]}var uw="release_claim_ended_by_close";function pw(e,t,n,r,o){let i=IC(o),s=i===void 0?void 0:L([...ke(r),"claim",e,"--force",...i]),a=s===void 0||Bf(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:uw,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 fw(e){let t=e.assignee?.trim();return t?e.claim_principal?.trim()||t:void 0}async function _w(e,t,n){let r=E(process.cwd(),t.path),o=await A(r),i=gn(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=ow(c),{document:u}=await te(a,{schema:o.schema}),p=fw(u.metadata);if(p!==void 0&&p!==i&&await zd(r,a.id,i))throw pw(a.id,_n(u.metadata.assignee.trim()),"--pause",t,n);let f=rw(u.metadata,d);return h=>Wi({pmRoot:r,id:a.id,validate:_=>{if(rw(_.metadata,ow(c))!==f)throw new l(`${a.id} changed while the pause was judged, so nothing was written.`,m.CONFLICT,{code:OC,item_id:a.id,nextSteps:[`Check the current holder with ${L([...ke(t),"get",a.id])}, reconfirm any override, then re-run the original pause command unchanged.`]})}},h)}var OC="pause_item_changed";function rw(e,t){return JSON.stringify([fw(e)??null,e.status,e.updated_at,t])}function ow(e){try{return fC("sha256").update(_C(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=gn(s),c=r.ownershipReleaseBypass===!0,d=null,u=D(i.schema),p=Hs(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=_n(w.metadata.assignee.trim());if(p!==void 0)throw pw(w.metadata.id,S,"--handoff",n,r.author);return h=S,{changedFields:[],warnings:[`${uw}:${w.metadata.id}:${S}`]}}d=w.metadata.assignee??null;let k=p===void 0?void 0:Qy(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=cw(await dw("release",_.item.id,n,!1,()=>$y({pmRoot:o,principal:a,itemId:_.item.id}))),y=h===void 0?$C(_.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:Gc(_.item),released_by:s,changed_fields:_.changedFields,previous_assignee:d===null?null:_n(d),forced:t,...f===void 0?{}:{handoff:f},...el("warnings",[..._.warnings,...y.warnings,...g.warnings]),...el("suggestions",[...y.suggestions,...g.suggestions])}}function $C(e,t){return hn(e.status,t)===hn(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 LC(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 PC(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 NC(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 hw(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 $K(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 gw(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 LK(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 PK(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=LC(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&&PC(i,s,r)?s.children.push(i):o.push(i)}return NC(o),o}var yw=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 FC(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=yw?n:`${n.slice(0,yw-3)}...`}function ww(e){return e.map((t,n)=>`${n+1}. ${FC(t)}`).join("; ")}function MC(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 DC(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function vw(e,t){let n=MC(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)DC(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: ${ww(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: ${ww(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 UC=["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: ${UC.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 Ys(e){return[...e.filter(Ie),...e.filter(t=>!Ie(t))]}function bw(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 kw(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 jC(){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=jC();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}var On=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,gg,"FORCE_COLOR"]),Qs=/^[A-Za-z_][A-Za-z0-9_]*$/,In=["schema","tracker","auto","none"],Sw=["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(!Qs.test(s))throw new l(`${t} env_set key "${s}" is invalid`,m.USAGE);if(On.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(!Qs.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,m.USAGE);if(On.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,m.USAGE)}return n}function Zs(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 ea(e,t){if(!e)return;let n=e.trim().toLowerCase();if(In.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${In.join(", ")}`,m.USAGE)}function $n(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Sw.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${Sw.join(", ")}`,m.USAGE)}function Ln(e){if(!e)return;let t=cr(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Sr(e,t,n){let r=Ln(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 ta(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 na(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 ra(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 GC=new Set($t);function oa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qC(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!GC.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 xn(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 Js(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 Aw(e,t,n){let r=Js(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 Xs(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 KC(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:Xs(n,"timeout_seconds",t),i=r===void 0?void 0:Xs(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 zC(e,t){let n=xn(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 HC(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!oa(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(!Qs.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(On.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 BC(e,t){let n=Js(e,"env_clear",t);if(n){for(let r of n){if(!Qs.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(On.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function WC(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 VC(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=Xs(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 YC(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!oa(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 JC(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!oa(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]=Xs(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function XC(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,m.USAGE);if(!oa(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${$t.join(", ")}.`);let o=qC(e,r),i=xn(o,"command",r),s=xn(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=xn(o,"path",r),d=xn(o,"pm_context_mode",r);if(d!==void 0&&!In.includes(d))throw r(`field "pm_context_mode" must be one of: ${In.join(", ")}`);let u=$n(xn(o,"workspace_context_mode",r),`${n} ${t}`),p=xn(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:zC(o,r),timeout_seconds:KC(o,r),pm_context_mode:d,workspace_context_mode:u,env_set:HC(o,r),env_clear:BC(o,r),shared_host_safe:WC(o,"shared_host_safe",r),assert_stdout_contains:Js(o,"assert_stdout_contains",r),assert_stdout_regex:Aw(o,"assert_stdout_regex",r),assert_stderr_contains:Js(o,"assert_stderr_contains",r),assert_stderr_regex:Aw(o,"assert_stderr_regex",r),assert_stdout_min_lines:VC(o,r),assert_json_field_equals:YC(o,r),assert_json_field_gte:JC(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)=>XC(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 Ew(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 Cw(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 QC(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 Tw(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 ZC(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 ia(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 eT(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",...ia(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",...ia(t),nextSteps:[`Patch only editable fields: ${Oo.join(", ")}.`]});return vo(o),o}function tT(e){let{id:t,tests:n,index:r,identityKey:o,otherFields:i,requested:s,global:a}=e;Tw(i,!0);let c=ZC(n[r],i,s),d=Io(JSON.stringify(c),"--add-json")[0];ns(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",...ia(o),nextSteps:[`Edit linked test ${u+1} instead: ${L([...ke(a),"test",t,"--update-index",String(u+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${L([...ke(a),"test",t,"--remove-index",String(r+1)])}`]});return c}function nT(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function rT(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=eT(a,c,d),p=Object.fromEntries(Object.entries(a).filter(([g])=>!tl.includes(g))),f=tT({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),...nT(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",...ia(c),recovery:{suggested_retry:L(_),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 oT(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);Tw(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([a])=>$t.includes(a))),o=t_(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]);ns(o);let i=n.filter(a=>!ee(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 Rw(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 en({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=QC(f,t.selector);rT({id:p.metadata.id,tests:f,index:h,patch:t.patch,global:n,controls:t});let _=oT(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 iT(){return{metadata:{},body:""}}import{AsyncLocalStorage as iq}from"node:async_hooks";import{realpathSync as sq}from"node:fs";import uu from"node:path";var sT=ud("list").properties.outputSession,aT={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:{...sT},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},xw={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."}},Iw={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."},cT=`Operation name (one of): ${$c.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,dT={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."}},lT={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{...Iw,properties:{...Iw.properties,...e},required:t}}var mT=[{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:[...$c],description:cT},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."},...aT},["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"},...lT},["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"},...dT})},{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({...xw,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:[...wc]},description:`Lifecycle roles for add-status: ${wc.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:xw}},["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."}})}],uT={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"},pT=mT.map(e=>{let t=uT[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:ud(t,{properties:n,required:r})}});function Ow(){return pT.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 $w=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"]]]),fT=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],qw=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),aa=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"]),Kw=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"]]),zw=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"]]),Hw=new Map([...zw.entries()].flatMap(([e,t])=>Ft(t).map(n=>[n,e]))),Bw=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],ol=new Map(Bw.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),_T=10,hT=20,Lw=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."]]),Ww=[["init",Up],["install",Gp],["uninstall",qp],["explore",Kp],["inventory",Kr],["manage",Yp],["describe",zp],["reload",Jp],["doctor",Xp],["catalog",Qp],["adopt",Zp],["adopt-all",Hp],["activate",Bp],["deactivate",Wp],["migrate",Vp]],gT=[...Ww.map(([e,t])=>e==="init"?[e,jp]:[e,t]),["upgrade",zr]],yT=[...Ww.map(([e,t])=>[`extension ${e}`,t]),...gT.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["package list",Kr],["packages list",Kr],["extension list",Kr],["init",_i],["config",Dp],["extension",hi],["package",qr],["packages",qr],["install",ef],["create",ki],["item mutate",vf],["item complete",bf],["item reopen",kf],["copy",Si],["focus",Ai],["update",Ei],["update-many",Ci],["upgrade",zr],["calendar",Hr],["cal",Hr],["context",Br],["ctx",Br],["get",Ri],["search",Li],["eval",Af],["events",Ti],["workspace",zt],["workspace position",[]],["workspace snapshot",zt],["workspace snapshot create",zt],["workspace snapshot list",zt],["workspace snapshot inspect",zt],["workspace snapshot restore",zt],["workspace snapshot delete",zt],["next",$i],["aggregate",mi],["deps",Ii],["graph",Oi],["guide",xi],["reindex",tf],["history",ui],["history-compact",Pp],["history-attest",Np],["history-redact",$p],["history-repair",Lp],["history-author-acknowledge",pi],["merge",Op],["schema",Fp],["profile",Mp],["plan",fi],["restore",of],["delete",sf],["close",nf],["close-many",gi],["append",yi],["claim",rf],["release",af],["start-task",cf],["pause-task",df],["close-task",lf],["comments",Ap],["notes",Ep],["learnings",Cp],["files",Tp],["files discover",Rp],["files lookup",xp],["docs",Ip],["test",pf],["test-runs-worker",[]],["test-all",ff],["telemetry",_f],["test-runs",hf],["gc",gf],["stats",wi],["ops",[]],["duplicates",vi],["validate",yf],["health",bi],["assurance",wf],...Ef,["contracts",Pi],["completion",Ni],["activity",Sf],...[...qw].map(e=>[e,li])],$o=new Map(yT);for(let{alias:e,canonical:t}of Te){let n=$o.get(e);n!==void 0&&$o.set(t,n)}function wT(e){let t=Hw.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Pw(e){let t=Te.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Ic.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)}`):aa.has(e)?zw.get(e)??Ae(e):null}function vT(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 bT(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 sa(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Lo(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function kT(e,t){if(!t)return{...e};let r=Lo(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=Lo(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 Vw(e){return e.replace(/\s+/g,"-")}function nn(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Nw(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=nn(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function rl(e,t,n){n&&(e[t]=!0)}function Fw(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 ST(e){let t=Fw(e.long,"long"),n=Fw(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=nn(e.description);i&&(o.description=i);let s=ap(e);o.value_arity=s.value_arity;let a=nn(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 Yw(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=ST(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 AT(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...Dc.filter(({flag:n})=>n.startsWith("--output-"))]}}function ET(e){let t=Yw(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let s=Ae(i.command);if(s.length===0)continue;let a=nn(i.action)??Vw(s),c=Array.isArray(i.arguments)?i.arguments.map(d=>{let u=nn(d.name);return u?{name:u,required:d.required===!0,variadic:d.variadic===!0,description:nn(d.description)}:null}).filter(d=>d!==null):[];n.set(s,{...i.tier===void 0?{}:{tier:i.tier},...AT(i,t.get(s)?.flags??[]),command:s,action:a,source:{layer:i.layer,name:i.name},description:nn(i.description),intent:nn(i.intent),arguments:c,examples:Nw(i.examples),failure_hints:Nw(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(CT(i,s,t.get(i)?.flags??[]))}return o}function CT(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Vw(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function TT(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 RT(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 xT(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 IT(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]=RT(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=TT(o);!i||n[i]!==void 0||(n[i]=Dc.some(s=>s.flag===o.flag&&s.flag.startsWith("--output-"))?j_[i]:xT(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 OT(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 $T(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&&OT(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 LT(e,t=A){let n={mode:un.extensions.policy.mode,trust_mode:un.extensions.policy.trust_mode,default_sandbox_profile:un.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 PT(e,t={}){let n=new Map;for(let r of Oc){let o=aa.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=Pw(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of aa)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Pw(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 NT(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&&(!Kt.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=>Kw.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 Jw(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 Kt.has(V(e))?!1:$o.has(e)}function FT(e){return qw.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Mw(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function MT(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function DT(e){let t=new Map;for(let r of e.definitions){let o=Mw(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(a=>MT(a)).find(a=>a!==null),s=r.cli_aliases.map(a=>Mw(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,Mc(o.flags));return n}function Dw(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 Mc(n)}function UT(e){let t=Ad(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function jT(e,t,n,r){let o=(n??[]).map(UT),i=t==="extension"&&(n!==void 0||GT(e,r));return{flags:o,inherited:i?{inherited_flags:bp({readOutput:qT(e,r)})}:{}}}function Xw(e,t){let n=V(e);return t.find(r=>V(r.command)===n)}function GT(e,t){return Xw(e,t)!==void 0}function qT(e,t){return Xw(e,t)?.read_output!==void 0}function KT(e,t,n,r){return r&&t!=="extension"&&vp(e)?{inherited_flags:kp(e,Sp(n),{expectHashAdmissible:og(V(e))})}:{}}function zT(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?Jw(s):[],d=n.get(FT(s))??[],u=i.get(s),p=Dw(c,d),f=c.length>0&&(u?.flags.length??0)>0?"mixed":a?"core":"extension",h=jT(s,f,u?.flags,o),_=Dw(p,h.flags);return{command:s,flags:_,...h.inherited,...KT(s,f,_,r),...r?{canonical_command:Zw(s),visibility:Qw(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 HT(e,t=pn){let n=new Set(e),r=new Map;for(let o of Bw){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 BT(){return{create_string_options:G_,create_repeatable_options:Xi,update_string_options:q_,update_repeatable_options:K_,list_string_options:lp,search_string_options:mp,calendar_string_options:up,context_string_options:pp,activity_string_options:fp}}function Uw(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 WT(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){let o=e.by_type[r];t[r]=Uw(o,"strict"),n[r]=Uw(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function VT(e,t){let n=Lo(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 YT(e){let t=sa(e.action)!==void 0||sa(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=sa(e.action),u=sa(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 JT(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 XT(e,t=A){try{return await t(e)}catch{return structuredClone(un)}}async function QT(e,t,n){let r=await XT(t),o=await LT(e),i=$(r,o.registrations??I()),s=et(r.schema),a=ET(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:D(r.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:DT(s),createRequiredOptionContracts:WT(i),extensionContracts:a,mergedExtensionContracts:$T(a.filter(c=>ca(n,c.command,a))),extensionFlagMap:Yw(o.flagRegistrations)}}function jw(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&aa.has(e.selectedAction)||e.selectedCommand!==void 0&&Kt.has(V(e.selectedCommand)))}function ZT(e,t){let n=PT(t,{includePackageOwnedActions:jw(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??bs(o.action))!=="internal"))}return jw(e)&&e.selectedCommand!==void 0&&Kt.has(V(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:wT(V(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function eR(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 tR(e,t){return[...new Set([...Ic.filter(n=>!Kt.has(V(n))),...[...$o.keys()].filter(n=>!Kt.has(V(n))),...e.flatMap(n=>n.command_path?Ft(n.command_path).filter(r=>n.provider==="extension"||!Kt.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 nR(e,t){let n=t.slice(0,_T),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,hT),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 rR(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 oR(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 iR(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 nR(e.selectedCommand,r);let o=Kw.get(V(e.selectedCommand));throw o?rR(e.selectedCommand,o):oR(e.selectedCommand)}function sR(e,t){let n=ZT(e,t.mergedExtensionContracts);eR(e,n);let r=tR(n,t.mergedExtensionContracts);iR(e,r);let o=e.selectedCommand?Hw.get(V(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(d=>o?d.action===o:vT(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=>NT(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 aR(e){return new Set(Lo(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 cR(e){let t=z_,n=Lo(t),r=aR(t),o=e.filter(i=>!r.has(i.action)).map(i=>IT(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function Gw(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?kT(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 dR(e,t,n){let r=cR(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?VT(Gw(e,n,r),t.createRequiredOptionContracts):Gw(e,n,r);return{mergedSchema:r,filteredSchema:i}}function lR(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?bT(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Qw(e,t){return t.find(n=>V(n.command)===V(e))?.tier??bs(e)}function ca(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||Qw(t,n)!=="internal"}function mR(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(pn.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)&&ca(e,o,n))}function Zw(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 uR=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"]]),pR=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function fR(e,t){let n=Lw.get(V(e))??(e.includes(" ")?void 0:Lw.get(Zw(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=uR.get(i),c=pR.get(e)??s;return{intent:a===void 0||s.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function _R(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=dd(i,{generateFallback:!0}),a=i.split(" ")[0],c=ol.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...Jw(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=($w.get(V(i))??$w.get(c)??fT).filter(f=>d.has(f)),p=fR(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 hR(e){return e.map(t=>({budget:dd(t,{generateFallback:!0}),envelope:Uh(t)}))}function gR(e){let t=new Map;for(let n of e){let r=Nh(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 yR(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=>ca(e,r.command,t.extensionContracts))}function wR(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 vR(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=qf);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 bR(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}}var kR="command_scoped; core rows list inherited host flags for pm contracts --command <command> --flags-only --json";function SR(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=zT(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]})),t.selectedCommand===void 0&&(e.core_inherited_flags_omitted_reason=kR)}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 AR(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=BT();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function ER(e,t,n,r){e.command_summaries=_R(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...T_],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=>I_(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...$_(o).keys()]}))}:{}},e.grammar_contracts={nouns:fn.nouns,shared_verbs:fn.shared_verbs,scope_before_verb:fn.scope_before_verb,visible_top_level_ceiling:fn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:fn.ceiling_raise_requires_pm_item,positional_shape_budget:fn.positional_shape_budget,positional_shape_count:new Set(Fc.map(({slots:o})=>wp(o))).size,positional_action_count:Nc.length,positional_action_parents:[...new Set(Nc.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:Fc}:{}}}async function sl(e,t){let n=YT(e);JT(n);let r=E(process.cwd(),t.path),o=await QT(t,r,n),i=sR(n,o),s=dR(n,o,i),a=lR(n,i),c=mR(n,a,o.extensionContracts),d=wR(n,s,i,c),u=yR(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&ER(d,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return d;let f=HT(i.commandCatalog.filter(h=>ca(n,h,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||vR(d,o,n),bR(d,n,s,u),SR(d,n,o,c,f),AR(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...dg],gate_triggers:[...cg]}),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=Ow(),d.context_intents=N_(),d.read_output_dimensions=x_,d.error_codes=Fh,d.command_output_contracts=hR(c),d.diagnostic_output_contracts=R_,d.command_exit_contracts={vocabulary:Ph,command_sets:gR(c)}),d}async function ev(e,t,n=P_){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 CR}from"node:crypto";function al(e){let t=Du();for(let n of e)t.register(n);return t}function TR(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=Rc(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(Rc(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 ee(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
|
|
2
|
+
`}function tv(e,t,n){let r=new Map;for(let o of[...t,...n]){let i=e(o);i!==void 0&&r.set(i.key,i)}return r}function RR(e,t){return[...t].filter(([n,r])=>!ee(e.get(n),r)).map(([,n])=>n)}async function xR(e,t,n,r){let o=t.schema?.fields??[],{normalizeCliToken:i,resolveRuntimeFieldRegistry:s}=await import("./runtime-schema-IDRXWCC4.js"),a=h=>s({fields:[h]}).definitions[0],c=h=>JSON.parse(JSON.stringify(h)),d=[...e.schema.fields,...Array.isArray(n)?n:[]].map(h=>({resolved:a(h),persisted:c(h)})),u=h=>[h.cli_flag,...Array.isArray(h.cli_aliases)?h.cli_aliases:[]].some(_=>typeof _=="string"&&i(_).length===0),p=o.filter(h=>{let _=a(h),g=d.some(y=>ee(y.persisted,c(h)));return _===void 0||u(h)?!g:!d.some(y=>ee(y.resolved,_))});if(p.push(...RR(r.before===void 0?new Map:tv(a,e.schema.fields,r.before),r.after===void 0?new Map:tv(a,r.inlineAfter,r.after))),p.length===0)return;let{assertFieldDefinitionOptionsAvailable:f}=await import("./field-option-collisions-2C6DLUC4.js");for(let h of p)f(h)}async function IR(e,t,n,r){let{readAdmittedFieldsFileDefinitions:o}=await import("./field-definition-losses-GGA6FUHD.js"),i=c=>mh(e,c).then(()=>!0,()=>!1),[s,a]=await Promise.all([i(t),i(n)]);return{before:s?await o(e,t.schema):void 0,after:a?await o(e,r):void 0,inlineAfter:r?.fields??[]}}function nv(e,t,n,r){return{fitOutputEnvelope:ug,client:t,isItemNotFoundError:o=>so(o)&&o.exitCode===m.NOT_FOUND,getItemAt:(o,i)=>mg(o,i,{pmRoot:e}),readSettingsSection:(o,i)=>xh(e,o,i),writeSettingsSection:(o,i,s)=>Ih(e,o,i,{author:n,...s}),openRelationshipEventStore:o=>fg.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)=>_g(o,i,s),validateRelationshipEvents:o=>{let i=new pg(o.nodes,{registry:al(o.definitions)});return o.events.map(s=>i.append({...s,expectedVersion:i.version}))},commitWorkspaceTransaction:o=>hg({...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 ls({pmRoot:e,filePath:ce(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${CR("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=hs(c);if(!d.success)throw new l("Workspace settings mutation requires a valid initialized settings.json.",m.USAGE);let u=gs(d.data),p=await o.mutate(structuredClone(u));if(!hs(p).success)throw new l("Workspace settings mutation returned invalid settings.json.",m.USAGE);let f=ee(u,p)?a:wd(p,{source:{raw:c,validated:d.data}});f=TR(f,p,o.replaceSubtrees);let h=hs(JSON.parse(f));if(!h.success)throw new l("Workspace settings mutation serialized invalid settings.json.",m.USAGE);return await xR(u,p,c.schema?.fields,await IR(e,u,gs(h.data),h.data.schema)),{raw:f,result:o.includePreview===!0?gs(h.data):void 0}}});return s.changed&&o.dryRun!==!0&&await Q({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{dh(e)}}}}function rv(e){return{undeclaredKeys:il(e)?"pass":"refuse"}}import OR from"node:fs/promises";import Z from"node:path";import $R from"node:readline/promises";import{stdin as LR,stdout as ze}from"node:process";var dl=Symbol.for("pm.sdk.init-invocation-cwd");var PR=()=>$R.createInterface({input:LR,output:ze});function NR(){return structuredClone(un)}var FR=["minimal","default","strict"];function iv(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: ${FR.join(", ")}`,m.USAGE)}function MR(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",m.USAGE);try{return If(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${xf.join(", ")}`,m.USAGE)}}}function DR(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:Z.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function UR(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=Z.resolve(e,o),u=Z.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=Z.resolve(e,n.trim());return{pmRoot:d,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:d}}}let i=E(e,t.path),s=Z.join(Z.resolve(e),".agents","pm"),a=Z.dirname(Z.dirname(i)),c=Z.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:Z.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:s}:{}}:{mode:"tracker-path",tracker_root:i}}}function jR(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&&Jt(e)!==Jt(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 ${Jt(e)}`,`pm init --id-prefix ${Jt(t)}`]});return t}function GR(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: ${Ug.join(", ")}`,m.USAGE)}function qR(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function sv(e,t){let n=Pu[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function KR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zR(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(KR).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function HR(e,t,n){let r=Di(t.schema),o=Rt(e,r.files.types,Tt.types),s=Tf(await oe(o)),a=[],c=[];for(let d of Of(n)){let u=Rf(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 BR(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",Z.join(".agents","pm")];for(let n of t)if(await W(Z.join(e,n)))return!0;return!1}async function WR(e,t,n){if(!t||n||await W(Z.join(e,"settings.json"))||!await BR(e))return;let r=Z.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 av(e,t){let n=[],r=[];for(let o of t){let i=o?Z.join(e,o):e,s=await W(i);await OR.mkdir(i,{recursive:!0}),s?r.push(`already_exists:${i}`):n.push(i),r.push(...await Q({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function VR(e,t){let n=PR(),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
|
|
6
6
|
`),ze.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
|
|
7
|
-
`);let o=await n.question(`Item ID prefix [${e}]: `),i=o.trim().length>0?
|
|
7
|
+
`);let o=await n.question(`Item ID prefix [${e}]: `),i=o.trim().length>0?Jt(o):e;ze.write(`
|
|
8
8
|
2/${r} Governance preset
|
|
9
9
|
`),ze.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
10
10
|
`),ze.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
11
11
|
`),ze.write(`strict: ownership blocking, strict create defaults, close validation strict.
|
|
12
|
-
`);let s=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),a=s.trim().length>0?s.trim():"minimal",c="minimal";try{c=
|
|
12
|
+
`);let s=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),a=s.trim().length>0?s.trim():"minimal",c="minimal";try{c=iv(a)}catch{ze.write(`Unrecognized governance preset "${a}"; using minimal.
|
|
13
13
|
`)}let d;if(t!==void 0){ze.write(`
|
|
14
14
|
3/3 Telemetry
|
|
15
15
|
`),ze.write(`Telemetry helps improve reliability. The choice applies to this CLI install; change it with pm config global set telemetry-tracking.
|
|
16
|
-
`);let u=await n.question(`Enable telemetry for this CLI install? [${t?"Y/n":"y/N"}] `);d=
|
|
17
|
-
`),{prefix:i,preset:c,telemetry_enabled:d}}finally{n.close()}}function GR(e){return{presetFromOption:Zw(e.preset),useDefaults:e.defaults===!0,authorFromOption:IR(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:PR(e.agentGuidance),typePreset:xR(e.typePreset)}}function qR(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function KR(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,m.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function zR(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(ev(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function HR(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=qR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return KR(e.settingsPath,n,e.options.force===!0,e.target),zR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await xe(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function BR(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let d=await jR(t,await WR());t=d.prefix,n=d.preset,r=d.telemetry_enabled,o=!0}let i=n??"minimal",s=TR();s.id_prefix=t,ev(s,i);let a=Jc()?.trim()||void 0;s.author_default=e.normalizedOptions.authorFromOption??a??"";let c=nv(e.pmRoot);return r!==void 0&&(s.telemetry.enabled=r,s.telemetry.first_run_prompt_completed=!0),await xe(e.pmRoot,s,void 0,c),r!==void 0&&c.omitSections&&await VR(r,e.warnings),{settings:s,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}function nv(e){return Z.resolve(e)===Z.resolve($e(process.cwd()))?{}:{omitSections:["telemetry"]}}async function WR(){let e=await A($e(process.cwd()));if(!(ws().telemetry_disabled||e.telemetry.first_run_prompt_completed||Pt(e)))return e.telemetry.enabled}async function VR(e,t){let n=$e(process.cwd()),r=await A(n);if(Pt(r)){t.push("telemetry_consent_not_recorded:global_settings_unreadable");return}let o=!1;r.telemetry.enabled=e,r.telemetry.first_run_prompt_completed=!0,await xe(n,r,"telemetry:first_run_prompt",{skipIfStored:i=>o=i.telemetry?.first_run_prompt_completed===!0}),o&&t.push("telemetry_consent_kept:recorded_while_prompting")}async function YR(e){let{telemetry:t}=await A($e(process.cwd()));return{...e,telemetry:{...e.telemetry,enabled:t.enabled,first_run_prompt_completed:t.first_run_prompt_completed,capture_level:t.capture_level}}}async function Qw(e){return e.settingsExists?await HR(e):await BR({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions,warnings:e.warnings})}async function JR(e){let t=await Lg({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await xe(e.pmRoot,e.settings,void 0,nv(e.pmRoot)),{...t.summary,next_steps:t.next_steps}}async function XR(e,t){let n=[],r=[],o=await Of(e,t.schema);for(let i of o.created_paths)n.push(i),r.push(...await Q({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function QR(e){if(e.typePreset===void 0)return;let t=await MR(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await Q({path:t.file,scope:"project",op:"init:type_preset"})),t}async function ZR(e){let n=$(e.settings,I()).folders.filter(o=>!Tc.includes(o)),r=await tv(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function ex(e){let t=Z.resolve(e.tracker_root),n=Z.dirname(t);return Z.basename(t)==="pm"&&Z.basename(n)===".agents"?Z.dirname(n):e.workspace_root}async function tx(e,t,n,r){if(!e)return;let o=await mr("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let i=FR(o),s=i.packages.filter(a=>!a.ok).map(a=>a.alias);if(!i.installed_all||s.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${s.length>0?`: ${s.join(", ")}`:"."}`,m.GENERIC_FAILURE);return i}function nx(e){let t=r=>P([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function rx(e,t,n,r=_g){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function ox(e,t,n,r){if(e==null||n==="status")return;let o=await Od(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Lo(e,t,n={}){let r=t[dl],o=typeof r=="string"?r:process.cwd(),i=OR(o,t,e,n.workspace),s=i.pmRoot;e=$R(i.prefixArg,n.idPrefix);let a=GR(n);await UR(s,i.target.mode==="tracker-path",n.force===!0);let c=[],d=[],u=Z.join(s,"settings.json"),p=await W(u),f;p&&(f=await Qw({pmRoot:s,settingsPath:u,settingsExists:p,normalizedPrefix:Yt(e),prefixArg:e,options:n,normalizedOptions:a,warnings:d,target:i.target}));let h=await tv(s,Tc);c.push(...h.createdDirs),d.push(...h.warnings),f??=await Qw({pmRoot:s,settingsPath:u,settingsExists:p,normalizedPrefix:Yt(e),prefixArg:e,options:n,normalizedOptions:a,warnings:d,target:i.target});let{settings:_}=f,g=ex(i.target),y=await Os(g??Z.dirname(s)),w=g??y,v=await JR({pmRoot:s,cwd:w??o,agentGuidanceMode:a.agentGuidanceMode,settings:_,warnings:d}),k=await XR(s,_);c.push(...k.createdDirs),d.push(...k.warnings);let S=await QR({pmRoot:s,settings:_,typePreset:a.typePreset,warnings:d});S&&(_=await A(s)),await ZR({pmRoot:s,settings:_,createdDirs:c,warnings:d}),await ox(w,s,a.agentGuidanceMode,d),!p&&n.mergeFence!==!1&&a.agentGuidanceMode!=="status"&&await rx(s,y,d);let T=await tx(a.installBundledPackages,t,s,d),x=nx({installBundledPackages:a.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:v.next_steps,target:i.target});return{ok:!0,path:s,target:i.target,settings:await YR(_),created_dirs:c,warnings:d,governance_preset:_.governance.preset,wizard_used:f.wizardUsed,...S?{registered_type_preset:S}:{},...T?{installed_packages:T}:{},next_steps:x,agent_guidance:v}}async function rv(e,t){let n=E(t??process.cwd(),e),r=await A(n);return ye(n,r.item_format,$(r,null).type_to_folder,void 0,r.schema)}var ix={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function ov(e){return Object.fromEntries(Xu.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var iv={ctx:{action:"context"},...ix,...ov("extension"),...ov("package"),...Object.fromEntries(Qu.map(e=>[`package-${e}`,{action:e}]))};function sv(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function sx(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function ll(e,t){let n=sx(t),r=n==="brief"?n:sv(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:sv(e.filters)?e.filters:{},projection:r}}}import{readFile as ax}from"node:fs/promises";async function ml(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",i=Number(n)+Number(r)+Number(o);if(i===0)return;if(i>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",m.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",Ot(e))??"",emptyFlag:"--add"};if(r)return Eo(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let s=e.file.trim();if(!s)throw new l("--file path cannot be empty",m.USAGE);if(s==="-")return Eo(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await ax(s,"utf8"),emptyFlag:"--file"}}catch(a){if(Xd(a)&&At(a))throw new l(`--file path not found: ${s}. Use --file - to read stdin.`,m.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${s}": ${c}. Use --file - to read stdin.`,m.USAGE)}}async function cx(e,t){let n=e.edit,r=e.delete,o=n!==void 0,i=r!==void 0;if(o&&i)throw new l("Specify only one of --edit or --delete",m.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",m.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",m.USAGE);if(i){if(await ml(e,t)!==void 0)throw new l("--delete does not take comment text",m.USAGE);return{mode:"delete",index:r}}if(o){let c=await ml(e,t);if(c===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let s=await ml(e,t);return s===void 0?{mode:"list"}:{mode:s.emptyFlag==="--add"?"add":s.emptyFlag==="--stdin"?"stdin":"file",value:s.value,emptyFlag:s.emptyFlag}}async function av(e,t,n){let r=Vt(),o=await cx(t,r),i=o.mode==="add"||o.mode==="edit",s=o.value??"";return hr(e,t,n,{input:{...o,rawValue:t.add??s,value:i?_r(s,{stripPlainTextPrefix:!0}):s},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm comments --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}var dx=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function cv(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>128)throw new Error("A legacy author must contain 1-128 characters.");return t}function lx(e){let t=e?.trim().toLowerCase();if(!t||!dx.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function mx(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function ux(e,t){let n=new Set;for(let r of(e??[]).slice(0,1e4)){let o=r.trim().slice(0,128);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function px(e,t){let n=cv(t.legacy_author),r=lx(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function fx(e,t){if(t.operation==="add")return px(e,t);if(t.operation==="remove"){let r=cv(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function ul(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function dv(e,t){let n=e?.version??1,r={...e?.aliases},o=fx(r,t),i={version:o?n+1:n,aliases:mx(r)};return{vocabulary:i,preview:{operation:t.operation,changed:o,version_before:n,version_after:i.version,alias_count:Object.keys(i.aliases).length,residual_author_count:ux(t.observed_authors,i.aliases)}}}var lv=["project","global"],nn={definition_of_done:["definition-of-done","definition_of_done","workflow.definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy","history.missing_stream"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy","validation.sprint_release_format"],parent_reference_policy:["parent-reference-policy","parent_reference_policy","validation.parent_reference"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile","validation.metadata_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields","validation.metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns","validation.lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns","validation.lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns","validation.lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns","validation.lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset","governance.preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement","governance.ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default","governance.create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default","governance.close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason","governance.require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type","governance.create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement","governance.workflow_enforcement"],governance_start_blocker_enforcement:["governance-start-blocker-enforcement","governance_start_blocker_enforcement","governance.start_blocker_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy","governance.parent_reference"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile","governance.metadata_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock","governance.force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking","testing.record_results_to_items"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution","testing.allow_untrusted_linked_tests"],telemetry_tracking:["telemetry-tracking","telemetry_tracking","telemetry.enabled"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary","agent_identity.identity_vocabulary"],context:["context"]},mv=Object.fromEntries(Object.keys(nn).flatMap(e=>nn[e].map(t=>[t,e]))),_x={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_start_blocker_enforcement:"Governance admission for starting an item whose declared blocker is still open (off|warn|strict; strict by default).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},hx=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],gx=new Set(["metadata_required_fields",...hx]),yx=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),wx=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),vx=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),bx=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement","governance_start_blocker_enforcement"]),kx=new Set(["governance_preset","governance_create_default_type"]),gv=e=>gx.has(e),Sx=e=>vx.has(e),Ax=e=>bx.has(e),Ex=e=>kx.has(e);function pl(e){return e==="definition_of_done"||gv(e)}function Cx(e){if(lv.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${lv.join(", ")}`,m.USAGE)}function Tx(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Pe({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function Rx(e,t="global",n){let r=Object.hasOwn(mv,e)?mv[e]:void 0;if(r)return r;let o=[...Object.values(nn),...Ui.map(u=>[u.key.replaceAll("_","-"),u.path])],i=e.toLowerCase().replaceAll(/[_.]/gu,"-"),s=o.map(u=>({key:u[0],distance:Math.min(...u.map(p=>Tu(i,p.replaceAll(/[_.]/gu,"-"),3)??1/0))})).filter(({distance:u})=>Number.isFinite(u)).sort((u,p)=>u.distance-p.distance||u.key.localeCompare(p.key)).slice(0,3).map(({key:u})=>u),a=n?ke(n):[],c=P([...a,"config",t,"list","--json"]),d=s.length>0?` Did you mean ${s.map(u=>u==="telemetry-tracking"&&t==="project"?`${u} (global only)`:u).join(", ")}?`:"";throw new l(`Invalid config key "${e}".${d} Inspect keys and aliases with ${c}.`,m.USAGE,{code:"config_key_unknown",changed:!1,required:`Use a key or settings path from ${c}.`,examples:[c],recovery:{allowed_values:[...new Set([...wl(t).flatMap(u=>nn[u]),...Ui.flatMap(u=>[u.key,u.key.replaceAll("_","-"),u.path])])],candidate_commands:s.map(u=>P([...a,"config",u==="telemetry-tracking"?"global":t,"get",u,"--json"])),next_best_command:c}})}function xx(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",m.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",m.USAGE);return n}function Ix(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",m.USAGE):new l("Config set item-format requires --format toon",m.USAGE)}function yv(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",m.USAGE)}function Ox(e){return hl(e,"test-result-tracking")}function hl(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,m.USAGE)}function wv(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",m.USAGE)}function gl(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",m.USAGE)}function vv(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",m.USAGE)}function bv(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",m.USAGE)}function kv(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",m.USAGE)}function Sv(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",m.USAGE)}function fl(e,t="governance-workflow-enforcement"){let n=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(n==="off"||n==="warn"||n==="strict")return n;if(n==="none"||n==="disabled")return"off";throw new l(`Config set ${t} requires one of: off, warn, strict`,m.USAGE)}function Av(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",m.USAGE)}function Ev(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",m.USAGE)}var $x={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"},Px={governance_workflow_enforcement:"governance-workflow-enforcement",governance_start_blocker_enforcement:"governance-start-blocker-enforcement"};function uv(e,t){let n=$x[e];if(n)return hl(t,n);let r=Px[e];if(r)return fl(t,r);switch(e){case"history_missing_stream_policy":return yv(t);case"sprint_release_format_policy":return yd(t);case"parent_reference_policy":case"governance_parent_reference_policy":return ms(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return gl(t);case"governance_preset":return vv(t);case"governance_ownership_enforcement":return bv(t);case"governance_create_mode_default":return kv(t);case"governance_close_validation_default":return Sv(t);case"governance_require_close_reason":return Ev(t);case"governance_force_required_for_stale_lock":return Av(t);case"telemetry_tracking":return wv(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var pv={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},Lx=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function Nx(e,t){let n=[...new Set((e??[]).map(i=>i.trim()).filter(i=>i.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",m.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",m.USAGE);let r=n.map(i=>i.toLowerCase().replaceAll("-","_")),o=r.filter(i=>pv[i]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${Lx.join(", ")}`,m.USAGE);return[...new Set(r.map(i=>pv[i]))].sort((i,s)=>i.localeCompare(s))}function Fx(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));if(n){if(r.length>0)throw new l(`Config set ${nn[e][0]} cannot combine --clear-criteria with --criterion values`,m.USAGE);return[]}if(r.length===0)throw new l(`Config set ${nn[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,m.USAGE);return r}function Mx(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function Dx(e,t,n,r){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,m.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,m.USAGE);return Rx(t,n,r)}function Cv(e){if(!e)throw new l("Config action requires <key>",m.USAGE)}var Ux={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_start_blocker_enforcement:e=>e.governance.start_blocker_enforcement??"strict",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>ul(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,next_ranking_policy:e.context.next_ranking_policy,sections:{...e.context.sections}})};function yl(e,t){return Ux[t](e)}function Fe(e,t){return t.length===0?e:{...e,warnings:t}}async function jx(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):$e(n),o=ce(r);return e==="project"&&await O(r),{pmRoot:r,settingsPath:o}}function Gx(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,m.USAGE)}function fv(e,t){let n=Wr(t==="--activity-limit"?"context_activity_limit":"context_stale_threshold_days"),r=Uc(n,e);if(r.ok)return r.parsed.value;throw new l(`Context ${t}: ${r.error.message}`,m.USAGE)}async function qx(e,t,n,r,o){let i=!1,s=e.context,a=[];if(t.defaultDepth!==void 0){let d=t.defaultDepth.trim().toLowerCase();if(!Cc.includes(d))throw new l(`Context --default-depth must be one of ${Cc.join("|")}`,m.USAGE);a.push("context.default_depth"),s.default_depth!==d&&(s.default_depth=d,i=!0)}if(t.activityLimit!==void 0){let d=fv(t.activityLimit,"--activity-limit");a.push("context.activity_limit"),s.activity_limit!==d&&(s.activity_limit=d,i=!0)}if(t.staleThresholdDays!==void 0){let d=fv(t.staleThresholdDays,"--stale-threshold-days");a.push("context.stale_threshold_days"),s.stale_threshold_days!==d&&(s.stale_threshold_days=d,i=!0)}let c=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[d,u]of c){let p=Gx(u);if(p!==void 0){let f=d;a.push(`context.sections.${d}`),s.sections[f]!==p&&(s.sections[f]=p,i=!0)}}return(i||Pt(e))&&(await xe(n.pmRoot,e,"config:set:context",{assignedPaths:a}),i=!0),Fe({scope:r,key:"context",context_settings:{default_depth:s.default_depth,activity_limit:s.activity_limit,stale_threshold_days:s.stale_threshold_days,next_ranking_policy:s.next_ranking_policy,sections:{...s.sections}},settings_path:n.settingsPath,changed:i},o)}function Kx(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,m.USAGE);return{...n,value:t}}function zx(e,t,n,r,o,i){if(o===void 0)return i;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,m.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',m.USAGE);if(r)return Kx(t,o,i);Cv(n);let s=J_(n,o);if(!s.routable)throw new l(s.reason,m.USAGE);if(s.flag==="criterion"){if(i.criterion!==void 0&&i.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,m.USAGE);return{...i,criterion:s.values}}if(s.flag==="format")return{...i,format:s.value};if(i.policy!==void 0&&uv(n,i.policy)!==uv(n,s.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${i.policy}". Pass only one.`,m.USAGE);return{...i,policy:s.value}}function Tv(e,t){let n=`pm config global ${e} telemetry-tracking${t}`;throw new l(`Config ${e} telemetry-tracking applies to this CLI install, not one project. Run: ${n}`,m.USAGE,{code:"invalid_argument_value",reason:"telemetry_consent_is_global",field:"scope",changed:!1,required:`Run: ${n}`,examples:[n]})}function wl(e){return Object.keys(nn).filter(t=>e==="global"||t!=="telemetry_tracking")}function Hx(e){let t=wl(e.scope).map(r=>({key:r,aliases:nn[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":pl(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:pl(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:_x[r],value:yl(e.settings,r)})),n=Ui.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:jc(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Fe({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function Bx(e){let t=Object.fromEntries(wl(e.scope).map(n=>[n,yl(e.settings,n)]));return Fe({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function Wx(e,t){let n=yl(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Fe({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Fe({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Fe({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Fe({...r,criteria:n},e.warnings):Fe({...r,policy:n},e.warnings)}async function Vx(e,t,n,r){if(t==="get"){let a=jc(e.settings,n);return Fe({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,m.USAGE);let i=Uc(n,o);if(!i.ok)throw new l(i.error.message,m.USAGE);let s=ji(e.settings,n,i.parsed.value)||Pt(e.settings);return s&&await xe(e.target.pmRoot,e.settings,`config:set:${n.path}`,{assignedPaths:[n.path]}),Fe({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:i.parsed.value},settings_path:e.target.settingsPath,changed:s},e.warnings)}async function ne(e,t,n,r=[]){(t||Pt(e.settings))&&(await xe(e.target.pmRoot,e.settings,n,{assignedPaths:r}),Pt(e.settings)&&(e.fallbackRepairWritten=!0))}function _v(e,t,n){return e!==n||t!==n}function fe(e,t,n,r){return Fe({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function _l(e,t,n,r){return Fe({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function hv(e,t,n){let r=$(t,I()),o=await kh(e,n,"config:set:item_format:migrate",r.type_to_folder,t.schema);return{target_format:o.target_format,scanned:o.scanned,migrated:o.migrated,removed:o.removed,warnings:o.warnings}}async function Yx(e,t){let n=Ix(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){e.settings.item_format=n;let i={assignedPaths:["item_format"]};Pt(e.settings)?(await xe(e.target.pmRoot,e.settings,"config:set:item_format",i),e.fallbackRepairWritten=!0,o=await hv(e.target.pmRoot,await A(e.target.pmRoot),n)):(o=await hv(e.target.pmRoot,e.settings,n),await xe(e.target.pmRoot,e.settings,"config:set:item_format",i))}return Fe({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function Jx(e,t,n){if(t==="history_missing_stream_policy"){let i=yv(n.policy),s=e.settings.history.missing_stream!==i;return e.settings.history.missing_stream=i,await ne(e,s,"config:set:history_missing_stream_policy",["history.missing_stream"]),fe(e,t,e.settings.history.missing_stream,s)}if(t==="sprint_release_format_policy"){let i=yd(n.policy),s=e.settings.validation.sprint_release_format!==i;return e.settings.validation.sprint_release_format=i,await ne(e,s,"config:set:sprint_release_format_policy",["validation.sprint_release_format"]),fe(e,t,e.settings.validation.sprint_release_format,s)}if(t==="parent_reference_policy"){let i=ms(n.policy),s=e.settings.validation.parent_reference!==i||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==i;return e.settings.validation.parent_reference=i,e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,await ne(e,s,"config:set:parent_reference_policy",["validation.parent_reference","governance.preset","governance.parent_reference"]),fe(e,t,e.settings.validation.parent_reference,s)}let r=gl(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await ne(e,o,"config:set:metadata_validation_profile",["validation.metadata_profile","governance.preset","governance.metadata_profile"]),fe(e,t,e.settings.validation.metadata_profile,o)}async function Xx(e,t,n){if(t==="metadata_required_fields"){let a=Nx(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((d,u)=>d!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await ne(e,c,"config:set:metadata_required_fields",["validation.metadata_required_fields"]),_l(e,t,[...e.settings.validation.metadata_required_fields],c)}let o={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],i=Fx(t,n.criterion,n.clearCriteria),s=i.length!==o.length||i.some((a,c)=>a!==o[c]);return o.splice(0,o.length,...i),await ne(e,s,`config:set:${t}`,[`validation.${t}`]),_l(e,t,[...o],s)}async function Qx(e,t,n){if(t==="governance_preset"){let c=vv(n.policy),d=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await ne(e,d,"config:set:governance_preset",["governance.preset"]),fe(e,t,e.settings.governance.preset,d)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await ne(e,c,"config:set:governance_create_default_type",["governance.create_default_type"]),fe(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',m.USAGE);let i=$(e.settings,I()),s=Ce(o,i);if(!s)throw new l(zt(o,i.types,Ht(e.target.pmRoot,e.settings.schema)),m.USAGE);let a=e.settings.governance.create_default_type!==s;return e.settings.governance.create_default_type=s,await ne(e,a,"config:set:governance_create_default_type",["governance.create_default_type"]),fe(e,t,e.settings.governance.create_default_type,a)}async function Zx(e,t,n){if(t==="governance_ownership_enforcement"){let i=bv(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==i;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=i,await ne(e,s,"config:set:governance_ownership_enforcement",["governance.preset","governance.ownership_enforcement"]),fe(e,t,e.settings.governance.ownership_enforcement,s)}if(t==="governance_create_mode_default"){let i=kv(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==i;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=i,await ne(e,s,"config:set:governance_create_mode_default",["governance.preset","governance.create_mode_default"]),fe(e,t,e.settings.governance.create_mode_default,s)}let r=Sv(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await ne(e,o,"config:set:governance_close_validation_default",["governance.preset","governance.close_validation_default"]),fe(e,t,e.settings.governance.close_validation_default,o)}async function eI(e,t,n){if(t==="governance_parent_reference_policy"){let i=ms(n.policy),s=e.settings.governance.preset!=="custom"||_v(e.settings.governance.parent_reference,e.settings.validation.parent_reference,i);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,e.settings.validation.parent_reference=i,await ne(e,s,"config:set:governance_parent_reference_policy",["governance.preset","governance.parent_reference","validation.parent_reference"]),fe(e,t,e.settings.governance.parent_reference,s)}if(t==="governance_metadata_validation_profile"){let i=gl(n.policy),s=e.settings.governance.preset!=="custom"||_v(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,i);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=i,e.settings.validation.metadata_profile=i,await ne(e,s,"config:set:governance_metadata_validation_profile",["governance.preset","governance.metadata_profile","validation.metadata_profile"]),fe(e,t,e.settings.governance.metadata_profile,s)}if(t==="governance_start_blocker_enforcement"){let i=fl(n.policy,"governance-start-blocker-enforcement"),s=(e.settings.governance.start_blocker_enforcement??"strict")!==i;return e.settings.governance.start_blocker_enforcement=i,await ne(e,s,"config:set:governance_start_blocker_enforcement",["governance.start_blocker_enforcement"]),fe(e,t,i,s)}let r=fl(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await ne(e,o,"config:set:governance_workflow_enforcement",["governance.workflow_enforcement"]),fe(e,t,e.settings.governance.workflow_enforcement,o)}async function tI(e,t,n){if(t==="governance_require_close_reason"){let a=Ev(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await ne(e,c,"config:set:governance_require_close_reason",["governance.require_close_reason"]),fe(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let o=Av(n.policy)==="enabled",i=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==o;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=o,await ne(e,i,"config:set:governance_force_required_for_stale_lock",["governance.preset","governance.force_required_for_stale_lock"]),fe(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",i)}async function nI(e,t,n){if(t==="test_result_tracking"){let a=Ox(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await ne(e,c,"config:set:test_result_tracking",["testing.record_results_to_items"]),fe(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}if(t==="untrusted_linked_test_execution"){let a=hl(n.policy,"untrusted-linked-test-execution")==="enabled",c=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await ne(e,c,"config:set:untrusted_linked_test_execution",["testing.allow_untrusted_linked_tests"]),fe(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",c)}let r=wv(n.policy);e.scope==="project"&&Tv("set",` --policy ${r}`);let o=r==="enabled",i=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await ne(e,i,"config:set:telemetry_tracking",["telemetry.enabled","telemetry.first_run_prompt_completed"]),fe(e,t,e.settings.telemetry.enabled?"enabled":"disabled",i)}async function rI(e,t,n){let r=xx(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((i,s)=>i!==e.settings.workflow.definition_of_done[s]);return e.settings.workflow.definition_of_done=r,await ne(e,o,"config:set:definition_of_done",["workflow.definition_of_done"]),_l(e,t,[...e.settings.workflow.definition_of_done],o)}function oI(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",m.USAGE)}function iI(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',m.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",m.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",m.USAGE);return{}}async function sI(e,t){let{operation:n,dryRun:r}=oI(t.policy),o=iI(n,t.value),i;try{i=dv(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(s){throw new l(s.message,m.USAGE)}return i.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:i.vocabulary},await ne(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${i.preview.version_after}`,["agent_identity"])),Fe({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:ul(r?e.settings.agent_identity?.identity_vocabulary:i.vocabulary),vocabulary_mutation:i.preview,settings_path:e.target.settingsPath,changed:i.preview.changed&&!r},e.warnings)}async function aI(e,t,n){let r=await cI(e,t,n);return e.fallbackRepairWritten===!0?{...r,changed:!0}:r}async function cI(e,t,n){if(n.clearCriteria===!0&&!pl(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",m.USAGE);return t==="item_format"?Yx(e,n):t==="context"?qx(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?sI(e,n):t==="definition_of_done"?rI(e,t,n):gv(t)?Xx(e,t,n):yx.has(t)?nI(e,t,n):wx.has(t)?tI(e,t,n):Sx(t)?Zx(e,t,n):Ax(t)?eI(e,t,n):Ex(t)?Qx(e,t,n):Jx(e,t,n)}async function Rv(e,t,n,r,o,i){let s=Cx(e),a=Tx(t),c=a==="get"||a==="set"?Wr(n):void 0,d=c?void 0:Dx(a,n,s,o),u=zx(a,n,d,c,i,r),p=await jx(s,o),{settings:f,metadata:h,warnings:_}=await ah(p.pmRoot),g={scope:s,target:p,settings:f,metadata:h,warnings:Mx(_)};return c?Vx(g,a,c,u):a==="list"?Hx(g):a==="export"?Bx(g):(Cv(d),a==="get"&&d==="telemetry_tracking"&&s==="project"&&Tv("get",""),a==="get"?Wx(g,d):aI(g,d,u))}import Iv from"node:fs/promises";import Ov from"node:path";function dI(e,t,n){let r=new Set,o=[];for(let i of e){let s=i.trim();if(s.length===0||r.has(s))continue;r.add(s);let a=t.get(s);if(a===void 0){o.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){o.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return o}function lI(e,t){let n=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function xv(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return dI(t.ids,n,t.minEntries)}return lI(e,t)}function mI(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",m.USAGE);if(/^\d+$/.test(n)){let i=Number.parseInt(n,10),s=wn(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new l(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,m.USAGE);let a=i-s-1;return{kind:"version",raw:n,compactCount:a,retainedCount:t.length-a}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,m.USAGE);let o=0;for(let[i,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new l(`History for this item contains invalid timestamp at entry ${i+1}.`,m.GENERIC_FAILURE);if(a>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function uI(e,t){let n=Xr(),r=Xr();for(let o=0;o<e.length;o+=1){let i=e[o];n=sr(n,i.patch,o+1,i.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function pI(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:d_.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&Qc(eo(e.document),r,It(n.hash_algorithm)).includes(n.after_hash))}}function fI(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function _I(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function hI(e,t){let n=e.slice(0,t).findIndex(o=>!vh(o));if(n===-1)return;let r=Number.isFinite(Date.parse(e[n].ts))?"a malformed record or compaction receipt":"invalid timestamp";throw new l(`History for this item contains ${r} at entry ${n+1}.`,m.GENERIC_FAILURE)}function gI(e,t){let n=e[t.start].ts,r=e.slice(0,t.end+1).map(i=>Date.parse(i.ts));if(!r.every(Number.isFinite))return["that boundary",`Choose a --before timestamp at or before "${n}".`,`Run pm history-compact <id> --before "${n}".`];let o=new Date(r.reduce((i,s)=>Math.max(i,s),Number.NEGATIVE_INFINITY)).toISOString();return["that boundary",`Choose a --before timestamp at or before "${n}", or after "${o}".`,`Run pm history-compact <id> --before "${n}", or with a timestamp after "${o}".`]}function yI(e,t){let n=t-1,r=(o_(e).bridged_segments??[]).find(({start:c,end:d})=>c<=n&&n<d);if(r===void 0)return;let o=wn(e,!0),[i,s,a]=o===null?gI(e,r):[`version ${o+t}`,`Choose --before ${o+r.start+1} or lower, or --before ${o+r.end+2} or higher.`,`Run pm history-compact <id> --before ${o+r.start+1} or --before ${o+r.end+2}.`];throw new l(`history-compact cannot checkpoint ${i}: it lies inside a bridged segment whose states cannot be reconstructed.`,m.USAGE,{code:"history_compact_boundary_bridged",required:s,nextSteps:[a]})}function wI(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};yI(e.historyEntries,e.boundary.compactCount);let{checkpoint:t,finalReplay:n}=uI(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=wn(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=qe({hashAlgorithm:It(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:_t(Xr()),after:_t(t),message:_I(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",last_activity_at:bh(e.historyEntries.slice(0,e.boundary.compactCount)),pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:l_(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[m_({...s,before_hash:Qc(Xr(),i.item_hash_version??1,It(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version,...i.replay_inexact===!0?{replay_inexact:!0}:{}}),...r];return e.dryRun||a.push(qe({nowIso:C(),author:e.author,op:"history_compact",before:_t(n),after:_t(n),message:fI(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function vl(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await go(n.path),s=await Sn(r,e,o,i.type_to_folder);return Ls({pmRoot:r,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>vI(s,t,a)})}function vI(e,t,n){let r=e.historyPath,o=n.entries,i=n.verification;if(!i.ok)throw new l(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,m.CONFLICT);let s=mI(t.before,o);hI(o,s.compactCount);let a=s.compactCount>0,c=!!t.dryRun,d=n.author,u=[];a||u.push("history_compact_noop_before_boundary");let p=pI(n.loadedItem,o);p.matchedChainBefore===!1&&u.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:h,auditEntryAdded:_}=wI({historyEntries:o,boundary:s,changed:a,dryRun:c,author:d,options:t}),g=wn(o,!0),y=s.retainedCount>0&&g!==null?g+s.compactCount+1:null;return{changed:a,rewrittenEntries:f,report:({verification:w,warnings:v})=>({id:e.id,dry_run:c,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:y},history:{path:r,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:h,audit_entry_added:_,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:p.matchedChainBefore},warnings:[...new Set([...u,...v])].sort((k,S)=>k.localeCompare(S)),generated_at:C()})}}var bI=3;function kI(e){for(let n of["allOver","minEntries"]){let r=e[n];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new l(`history-compact ${n} must be a non-negative safe integer.`,m.USAGE)}let t=ds(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",m.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:cs(t)}}function $v(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",m.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",m.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",m.USAGE)}function SI(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function AI(e){let t=D(e.settings.schema),n=xs(t),r=await ye(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(d=>[d.id,n.classify(d.status)])),i=Ov.join(e.pmRoot,"history"),s=[],a=[];if(!await W(i))return{candidates:s,preselectionErrors:a};let c=(await Iv.readdir(i)).filter(d=>d.endsWith(".jsonl")).sort((d,u)=>d.localeCompare(u));for(let d of c){let u=Ov.join(i,d),p=d.slice(0,-6);try{let f=await Iv.readFile(u,"utf8");await Zn({path:u,scope:"project"}),s.push({id:p,entries:SI(f),bucket:o.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:s,preselectionErrors:a}}async function EI(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await vl(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t),...await vt(t,e.pmRoot)}}}}async function Pv(e,t){let n=kI(e),{pmRoot:r,settings:o,typeRegistry:i}=await go(t.path),{candidates:s,preselectionErrors:a}=await AI({pmRoot:r,settings:o,typeToFolder:i.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",d=e.minEntries??bI,u=o.history.compact_policy,p=c==="scan"&&e.allOver===void 0&&u.enabled,f=e.allOver??(p?u.max_entries:void 0),h=xv(s,{ids:n.ids,scope:e.scope,minEntries:d,allOver:f}),_=!!e.dryRun,g=[...a],y={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of h){let v=await EI({pmRoot:r,row:w,options:n,dryRun:_,global:t});if(g.push(v.result),!v.selected){y.items_skipped+=1;continue}y.selected+=1,v.compacted&&(y.items_compacted+=1),v.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:_,mode:c,scope:e.scope??null,criteria:{min_entries:d,all_over:f??null,policy_threshold_applied:p},totals:y,results:g,generated_at:C()}}function Lv(e){let t=e.options.all===!0,n=e.id??b(e.options,"id");return iy(n,t),t?Ns(e.options,e.global):en(n,e.options,e.global)}function Nv(e){let t=e.options.ids,n=ds(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",m.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:cs(n),o=Ke(e.options.allOver??e.options.all_over,"history-compact allOver"),i=Ke(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),s=b(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(s==="closed"||s==="all-streams")&&a.push(s);let c=[...new Set(a)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",m.USAGE);let d=c[0];return $v(e.id,{ids:r,allOver:o,scope:d}),e.id!==void 0?vl(e.id,{before:b(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global):Pv({ids:r,scope:d,allOver:o,minEntries:i,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global)}import kl from"node:fs/promises";function Fv(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function CI(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function bl(e,t){return new l(`Invalid --regex value at --regex #${e}: ${t}`,m.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${e}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function TI(e,t=1){let n=e.trim();if(n.length===0)throw bl(t,"provide a non-empty pattern.");let r=n,o="g";if(n.startsWith("/")&&n.length>1){let i=n.lastIndexOf("/"),s=0;for(let a=i-1;a>=0&&n[a]==="\\";a--)s++;i>0&&s%2===0&&/^[dgimsuvy]*$/u.test(n.slice(i+1))&&(r=n.slice(1,i),o=CI(n.slice(i+1)))}if(r.length===0)throw bl(t,"an empty pattern is not allowed.");try{new RegExp(r,o)}catch{throw bl(t,"provide a valid JavaScript regular expression.")}return{kind:"regex",source:r,flags:o}}function RI(e,t){let n=[...new Set(Fv(e).map(s=>s.trim()))].filter(s=>s.length>0).map(s=>({kind:"literal",value:s})),r=new Set,o=Fv(t).flatMap((s,a)=>{let c=s.trim();return r.has(c)?[]:(r.add(c),[TI(c,a+1)])}),i=[...n,...o];if(i.length===0)throw new l("history-redact requires at least one matcher via --literal or --regex.",m.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return i}function xI(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){let i=e.indexOf(t,r);if(i===-1)break;o+=1,r=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function II(e,t,n){let r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function Dv(e,t,n){let r=e,o=0;for(let i of t){let s=i.kind==="literal"?xI(r,i.value,n):II(r,i,n);r=s.value,o+=s.replacements}return{value:r,replacements:o}}function da(e,t,n){if(typeof e=="string")return Dv(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(i=>{let s=da(i,t,n);return r+=s.replacements,s.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,o={};for(let[i,s]of Object.entries(e)){let a=da(s,t,n);r+=a.replacements,o[i]=a.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function Mv(e,t,n){let r=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=da(i.value,t,n);return r+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:r}}function OI(e){let t=structuredClone(Xc),n=0,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];Qr(t,void 0,It(i.hash_algorithm))!==i.before_hash&&(n+=1),t=sr(t,i.patch,o+1,i.op),Qr(t,void 0,It(i.hash_algorithm))!==i.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function $I(e,t,n){let r=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let d=Dv(e.message,t,n);s=d.value,r+=d.replacements,d.replacements>0&&(o=!0)}let a=Mv(e.patch,t,n);r+=a.replacements,o||=a.replacements>0;let c=e.reanchor_evidence?.map(d=>{let u=d.patch?Mv(d.patch,t,n):{patch:void 0,replacements:0},p=d.record?da(d.record,t,n):{value:void 0,replacements:0};r+=u.replacements,r+=p.replacements;let f=u.replacements>0||p.replacements>0;if(o||=f,!f)return d;i=!0;let{patch:h,record:_,record_hash:g,record_hash_version:y,...w}=d;return u.replacements>0?w:{...w,patch:d.patch}});return{entry:{...e,message:s,patch:a.patch,...c?{reanchor_evidence:c}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:i}}function PI(e,t,n){let r=structuredClone(Xc),o=0,i=0,s=[],a=r_(e),c=[...a.unlocated,...a.undigested];if(c.length>0)throw new l(`history-redact refuses a stream whose bridge at record ${Math.min(...c)+1} does not prove its segment; repair the history first.`,m.GENERIC_FAILURE,{code:"history_redact_bridge_unlocated",required:"Every bridge's segment digest must match the records it covers, so redaction can keep that segment's versions refused.",nextSteps:["Run pm history-repair <id> --dry-run to see how the stream would be repaired."]});let d=i_(a.segments);for(let u=0;u<e.length;u+=1){let p=e[u],f=u_(p);if(!f.ok)throw new l(`history-redact refuses invalid immutable record ${u+1} (${f.error}).`,m.GENERIC_FAILURE);let h=$I(p,t,n);i+=h.replacements,h.changed&&(o+=1);let _=Qr(r,void 0,It(p.hash_algorithm));r=sr(r,h.entry.patch,u+1,h.entry.op);let g=Qr(r,void 0,It(p.hash_algorithm)),{bridge:y,...w}=h.entry;s.push(p_(p,{...w,...d.has(u)?{replay_inexact:!0}:{},before_hash:_,after_hash:g},{retainPriorRecord:h.changed||y!==void 0,retainPriorRecordHash:!h.changed}))}return{entries:s,finalDocument:r,entriesChanged:o,replacements:i}}function LI(e){return Object.keys(e.metadata).length>0}function NI(e){if(!LI(e.finalDocument))return{raw:null,path:null,document:null};let t=pt(_t(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new l("history-redact would change the item id; narrow your patterns.",m.USAGE);return{document:t,path:Et(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:ut(t,{format:"toon",schema:e.settings.schema})}}function FI(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function MI(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??_t(e.rewritten.finalDocument);return t.push(qe({nowIso:C(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function DI(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await Xt(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await ae(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await kl.rm(e.currentItem.path,{force:!0}),await ae(e.subject.historyPath,s_(e.rewrittenEntries))}catch(c){try{await UI(e.subject.historyPath,n,o,i)}finally{await ed(e.subject.historyPath)}throw c}await ed(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Qt({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(a=>{s=()=>{throw a}})}s()},afterWrite:async()=>[...t,...await jI(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function UI(e,t,n,r){t===null?await kl.rm(e,{force:!0}):await ae(e,t);for(let o of n){let i=r.get(o);i===void 0?await kl.rm(o,{force:!0}):await ae(o,i)}}async function jI(e,t){let n=[],r=new Set(t.filter(o=>o!==null));for(let o of r)n.push(...await Q({path:o,scope:"project",op:"history_redact"}));return n.push(...await Q({path:e,scope:"project",op:"history_redact:history"})),n}async function Uv(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await go(n.path),s=t.replacement??"",a=s.length===0,c=a?"[redacted]":s,d=RI(t.literal,t.regex),u=await Sn(r,e,o,i.type_to_folder);return Ls({pmRoot:r,subject:u,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:p=>GI({pmRoot:r,subject:u,settings:o,typeRegistry:i,options:t,rules:d,replacement:c,replacementIsDefault:a},p)})}function GI(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:i,options:s,rules:a,replacement:c,replacementIsDefault:d}=e,u=t.entries,p=OI(u),f=PI(u,a,c),h=p.hashMismatchesBefore+p.hashMismatchesAfter,_=!!s.dryRun,g=f.replacements>0,y=[];h>0&&y.push(`history_redact_preexisting_hash_mismatches:${h}`),g||y.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},v=NI({pmRoot:n,subject:r,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),k=(w.path??null)!==(v.path??null)||(w.raw??null)!==(v.raw??null),S=t.author,T=FI(s,f),{rewrittenEntries:x,auditEntryAdded:F}=MI({rewritten:f,dryRun:_,changed:g,nextItemDocument:v.document,author:S,message:T});return{changed:g,rewrittenEntries:x,...DI({pmRoot:n,subject:r,settings:o,typeRegistry:i,currentItem:w,nextItem:v,author:S,rewrittenEntries:x}),report:({verification:L,warnings:H})=>({id:r.id,dry_run:_,changed:g,patterns:{literal_count:a.filter(B=>B.kind==="literal").length,regex_count:a.filter(B=>B.kind==="regex").length,total_count:a.length,replacement_is_default:d},history:{path:r.historyPath,entries_scanned:u.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:p.hashMismatchesBefore,hash_mismatches_after:p.hashMismatchesAfter,preexisting_hash_mismatches:h,audit_entry_added:F,verify_ok:L.ok,verify_errors:L.errors},item:{existed_before:w.path!==null,exists_after:v.path!==null,path_before:w.path,path_after:v.path,changed:k},warnings:[...new Set([...y,...H])].sort((B,Y)=>B.localeCompare(Y)),generated_at:C()})}}async function jv(e,t,n){return hr(e,t,n,{input:await zs(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>_r(r),createEntry:r=>r,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm learnings --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}async function Gv(e,t,n){if(jh(t),yt(e,"append","id"),t=H_(t),t.body===void 0)throw new l("Missing required --body text",m.USAGE);let r=Vt(),o=E(process.cwd(),n.path);await O(o);let i=await A(o),s=R(t.author,i.author_default),c=(await r.resolveValue(t.body,"--body",W_(t,"body"))).trim();if(c.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",m.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let d=await we({pmRoot:o,settings:i,id:e,op:"append",author:s,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
|
|
16
|
+
`);let u=await n.question(`Enable telemetry for this CLI install? [${t?"Y/n":"y/N"}] `);d=qR(u,t)}return ze.write(`
|
|
17
|
+
`),{prefix:i,preset:c,telemetry_enabled:d}}finally{n.close()}}function YR(e){return{presetFromOption:iv(e.preset),useDefaults:e.defaults===!0,authorFromOption:DR(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:GR(e.agentGuidance),typePreset:MR(e.typePreset)}}function JR(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function XR(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,m.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function QR(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(sv(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function ZR(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=JR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return XR(e.settingsPath,n,e.options.force===!0,e.target),QR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await xe(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function ex(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let d=await VR(t,await tx());t=d.prefix,n=d.preset,r=d.telemetry_enabled,o=!0}let i=n??"minimal",s=NR();s.id_prefix=t,sv(s,i);let a=Jc()?.trim()||void 0;s.author_default=e.normalizedOptions.authorFromOption??a??"";let c=cv(e.pmRoot);return r!==void 0&&(s.telemetry.enabled=r,s.telemetry.first_run_prompt_completed=!0),await xe(e.pmRoot,s,void 0,c),r!==void 0&&c.omitSections&&await nx(r,e.warnings),{settings:s,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}function cv(e){return Z.resolve(e)===Z.resolve($e(process.cwd()))?{}:{omitSections:["telemetry"]}}async function tx(){let e=await A($e(process.cwd()));if(!(ws().telemetry_disabled||e.telemetry.first_run_prompt_completed||Lt(e)))return e.telemetry.enabled}async function nx(e,t){let n=$e(process.cwd()),r=await A(n);if(Lt(r)){t.push("telemetry_consent_not_recorded:global_settings_unreadable");return}let o=!1;r.telemetry.enabled=e,r.telemetry.first_run_prompt_completed=!0,await xe(n,r,"telemetry:first_run_prompt",{skipIfStored:i=>o=i.telemetry?.first_run_prompt_completed===!0}),o&&t.push("telemetry_consent_kept:recorded_while_prompting")}async function rx(e){let{telemetry:t}=await A($e(process.cwd()));return{...e,telemetry:{...e.telemetry,enabled:t.enabled,first_run_prompt_completed:t.first_run_prompt_completed,capture_level:t.capture_level}}}async function ov(e){return e.settingsExists?await ZR(e):await ex({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions,warnings:e.warnings})}async function ox(e){let t=await jg({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await xe(e.pmRoot,e.settings,void 0,cv(e.pmRoot)),{...t.summary,next_steps:t.next_steps}}async function ix(e,t){let n=[],r=[],o=await Ff(e,t.schema);for(let i of o.created_paths)n.push(i),r.push(...await Q({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function sx(e){if(e.typePreset===void 0)return;let t=await HR(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await Q({path:t.file,scope:"project",op:"init:type_preset"})),t}async function ax(e){let n=$(e.settings,I()).folders.filter(o=>!Tc.includes(o)),r=await av(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function cx(e){let t=Z.resolve(e.tracker_root),n=Z.dirname(t);return Z.basename(t)==="pm"&&Z.basename(n)===".agents"?Z.dirname(n):e.workspace_root}async function dx(e,t,n,r){if(!e)return;let o=await mr("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let i=zR(o),s=i.packages.filter(a=>!a.ok).map(a=>a.alias);if(!i.installed_all||s.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${s.length>0?`: ${s.join(", ")}`:"."}`,m.GENERIC_FAILURE);return i}function lx(e){let t=r=>L([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function mx(e,t,n,r=bg){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function ux(e,t,n,r){if(e==null||n==="status")return;let o=await Od(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Po(e,t,n={}){let r=t[dl],o=typeof r=="string"?r:process.cwd(),i=UR(o,t,e,n.workspace),s=i.pmRoot;e=jR(i.prefixArg,n.idPrefix);let a=YR(n);await WR(s,i.target.mode==="tracker-path",n.force===!0);let c=[],d=[],u=Z.join(s,"settings.json"),p=await W(u),f;p&&(f=await ov({pmRoot:s,settingsPath:u,settingsExists:p,normalizedPrefix:Jt(e),prefixArg:e,options:n,normalizedOptions:a,warnings:d,target:i.target}));let h=await av(s,Tc);c.push(...h.createdDirs),d.push(...h.warnings),f??=await ov({pmRoot:s,settingsPath:u,settingsExists:p,normalizedPrefix:Jt(e),prefixArg:e,options:n,normalizedOptions:a,warnings:d,target:i.target});let{settings:_}=f,g=cx(i.target),y=await Os(g??Z.dirname(s)),w=g??y,v=await ox({pmRoot:s,cwd:w??o,agentGuidanceMode:a.agentGuidanceMode,settings:_,warnings:d}),k=await ix(s,_);c.push(...k.createdDirs),d.push(...k.warnings);let S=await sx({pmRoot:s,settings:_,typePreset:a.typePreset,warnings:d});S&&(_=await A(s)),await ax({pmRoot:s,settings:_,createdDirs:c,warnings:d}),await ux(w,s,a.agentGuidanceMode,d),!p&&n.mergeFence!==!1&&a.agentGuidanceMode!=="status"&&await mx(s,y,d);let T=await dx(a.installBundledPackages,t,s,d),x=lx({installBundledPackages:a.installBundledPackages,registeredTypePreset:S,agentGuidanceNextSteps:v.next_steps,target:i.target});return{ok:!0,path:s,target:i.target,settings:await rx(_),created_dirs:c,warnings:d,governance_preset:_.governance.preset,wizard_used:f.wizardUsed,...S?{registered_type_preset:S}:{},...T?{installed_packages:T}:{},next_steps:x,agent_guidance:v}}async function dv(e,t){let n=E(t??process.cwd(),e),r=await A(n);return ye(n,r.item_format,$(r,null).type_to_folder,void 0,r.schema)}var px={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function lv(e){return Object.fromEntries(Xu.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var mv={ctx:{action:"context"},...px,...lv("extension"),...lv("package"),...Object.fromEntries(Qu.map(e=>[`package-${e}`,{action:e}]))};function uv(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fx(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function ll(e,t){let n=fx(t),r=n==="brief"?n:uv(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:uv(e.filters)?e.filters:{},projection:r}}}import{readFile as _x}from"node:fs/promises";async function ml(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",i=Number(n)+Number(r)+Number(o);if(i===0)return;if(i>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",m.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",Ot(e))??"",emptyFlag:"--add"};if(r)return Eo(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let s=e.file.trim();if(!s)throw new l("--file path cannot be empty",m.USAGE);if(s==="-")return Eo(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await _x(s,"utf8"),emptyFlag:"--file"}}catch(a){if(Xd(a)&&At(a))throw new l(`--file path not found: ${s}. Use --file - to read stdin.`,m.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${s}": ${c}. Use --file - to read stdin.`,m.USAGE)}}async function hx(e,t){let n=e.edit,r=e.delete,o=n!==void 0,i=r!==void 0;if(o&&i)throw new l("Specify only one of --edit or --delete",m.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",m.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",m.USAGE);if(i){if(await ml(e,t)!==void 0)throw new l("--delete does not take comment text",m.USAGE);return{mode:"delete",index:r}}if(o){let c=await ml(e,t);if(c===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let s=await ml(e,t);return s===void 0?{mode:"list"}:{mode:s.emptyFlag==="--add"?"add":s.emptyFlag==="--stdin"?"stdin":"file",value:s.value,emptyFlag:s.emptyFlag}}async function pv(e,t,n){let r=Yt(),o=await hx(t,r),i=o.mode==="add"||o.mode==="edit",s=o.value??"";return hr(e,t,n,{input:{...o,rawValue:t.add??s,value:i?_r(s,{stripPlainTextPrefix:!0}):s},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm comments --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}var gx=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function fv(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>128)throw new Error("A legacy author must contain 1-128 characters.");return t}function yx(e){let t=e?.trim().toLowerCase();if(!t||!gx.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function wx(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function vx(e,t){let n=new Set;for(let r of(e??[]).slice(0,1e4)){let o=r.trim().slice(0,128);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function bx(e,t){let n=fv(t.legacy_author),r=yx(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function kx(e,t){if(t.operation==="add")return bx(e,t);if(t.operation==="remove"){let r=fv(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function ul(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function _v(e,t){let n=e?.version??1,r={...e?.aliases},o=kx(r,t),i={version:o?n+1:n,aliases:wx(r)};return{vocabulary:i,preview:{operation:t.operation,changed:o,version_before:n,version_after:i.version,alias_count:Object.keys(i.aliases).length,residual_author_count:vx(t.observed_authors,i.aliases)}}}var hv=["project","global"],rn={definition_of_done:["definition-of-done","definition_of_done","workflow.definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy","history.missing_stream"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy","validation.sprint_release_format"],parent_reference_policy:["parent-reference-policy","parent_reference_policy","validation.parent_reference"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile","validation.metadata_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields","validation.metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns","validation.lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns","validation.lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns","validation.lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns","validation.lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset","governance.preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement","governance.ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default","governance.create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default","governance.close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason","governance.require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type","governance.create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement","governance.workflow_enforcement"],governance_start_blocker_enforcement:["governance-start-blocker-enforcement","governance_start_blocker_enforcement","governance.start_blocker_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy","governance.parent_reference"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile","governance.metadata_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock","governance.force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking","testing.record_results_to_items"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution","testing.allow_untrusted_linked_tests"],telemetry_tracking:["telemetry-tracking","telemetry_tracking","telemetry.enabled"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary","agent_identity.identity_vocabulary"],context:["context"]},gv=Object.fromEntries(Object.keys(rn).flatMap(e=>rn[e].map(t=>[t,e]))),Sx={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_start_blocker_enforcement:"Governance admission for starting an item whose declared blocker is still open (off|warn|strict; strict by default).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},Ax=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],Ex=new Set(["metadata_required_fields",...Ax]),Cx=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),Tx=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),Rx=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),xx=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement","governance_start_blocker_enforcement"]),Ix=new Set(["governance_preset","governance_create_default_type"]),Sv=e=>Ex.has(e),Ox=e=>Rx.has(e),$x=e=>xx.has(e),Lx=e=>Ix.has(e);function pl(e){return e==="definition_of_done"||Sv(e)}function Px(e){if(hv.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${hv.join(", ")}`,m.USAGE)}function Nx(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Le({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function Fx(e,t="global",n){let r=Object.hasOwn(gv,e)?gv[e]:void 0;if(r)return r;let o=[...Object.values(rn),...Ui.map(u=>[u.key.replaceAll("_","-"),u.path])],i=e.toLowerCase().replaceAll(/[_.]/gu,"-"),s=o.map(u=>({key:u[0],distance:Math.min(...u.map(p=>Tu(i,p.replaceAll(/[_.]/gu,"-"),3)??1/0))})).filter(({distance:u})=>Number.isFinite(u)).sort((u,p)=>u.distance-p.distance||u.key.localeCompare(p.key)).slice(0,3).map(({key:u})=>u),a=n?ke(n):[],c=L([...a,"config",t,"list","--json"]),d=s.length>0?` Did you mean ${s.map(u=>u==="telemetry-tracking"&&t==="project"?`${u} (global only)`:u).join(", ")}?`:"";throw new l(`Invalid config key "${e}".${d} Inspect keys and aliases with ${c}.`,m.USAGE,{code:"config_key_unknown",changed:!1,required:`Use a key or settings path from ${c}.`,examples:[c],recovery:{allowed_values:[...new Set([...wl(t).flatMap(u=>rn[u]),...Ui.flatMap(u=>[u.key,u.key.replaceAll("_","-"),u.path])])],candidate_commands:s.map(u=>L([...a,"config",u==="telemetry-tracking"?"global":t,"get",u,"--json"])),next_best_command:c}})}function Mx(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",m.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",m.USAGE);return n}function Dx(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",m.USAGE):new l("Config set item-format requires --format toon",m.USAGE)}function Av(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",m.USAGE)}function Ux(e){return hl(e,"test-result-tracking")}function hl(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,m.USAGE)}function Ev(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",m.USAGE)}function gl(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",m.USAGE)}function Cv(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",m.USAGE)}function Tv(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",m.USAGE)}function Rv(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",m.USAGE)}function xv(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",m.USAGE)}function fl(e,t="governance-workflow-enforcement"){let n=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(n==="off"||n==="warn"||n==="strict")return n;if(n==="none"||n==="disabled")return"off";throw new l(`Config set ${t} requires one of: off, warn, strict`,m.USAGE)}function Iv(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",m.USAGE)}function Ov(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",m.USAGE)}var jx={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"},Gx={governance_workflow_enforcement:"governance-workflow-enforcement",governance_start_blocker_enforcement:"governance-start-blocker-enforcement"};function yv(e,t){let n=jx[e];if(n)return hl(t,n);let r=Gx[e];if(r)return fl(t,r);switch(e){case"history_missing_stream_policy":return Av(t);case"sprint_release_format_policy":return yd(t);case"parent_reference_policy":case"governance_parent_reference_policy":return ms(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return gl(t);case"governance_preset":return Cv(t);case"governance_ownership_enforcement":return Tv(t);case"governance_create_mode_default":return Rv(t);case"governance_close_validation_default":return xv(t);case"governance_require_close_reason":return Ov(t);case"governance_force_required_for_stale_lock":return Iv(t);case"telemetry_tracking":return Ev(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var wv={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},qx=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function Kx(e,t){let n=[...new Set((e??[]).map(i=>i.trim()).filter(i=>i.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",m.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",m.USAGE);let r=n.map(i=>i.toLowerCase().replaceAll("-","_")),o=r.filter(i=>wv[i]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${qx.join(", ")}`,m.USAGE);return[...new Set(r.map(i=>wv[i]))].sort((i,s)=>i.localeCompare(s))}function zx(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));if(n){if(r.length>0)throw new l(`Config set ${rn[e][0]} cannot combine --clear-criteria with --criterion values`,m.USAGE);return[]}if(r.length===0)throw new l(`Config set ${rn[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,m.USAGE);return r}function Hx(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function Bx(e,t,n,r){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,m.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,m.USAGE);return Fx(t,n,r)}function $v(e){if(!e)throw new l("Config action requires <key>",m.USAGE)}var Wx={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_start_blocker_enforcement:e=>e.governance.start_blocker_enforcement??"strict",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>ul(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,next_ranking_policy:e.context.next_ranking_policy,sections:{...e.context.sections}})};function yl(e,t){return Wx[t](e)}function Fe(e,t){return t.length===0?e:{...e,warnings:t}}async function Vx(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):$e(n),o=ce(r);return e==="project"&&await O(r),{pmRoot:r,settingsPath:o}}function Yx(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,m.USAGE)}function vv(e,t){let n=Wr(t==="--activity-limit"?"context_activity_limit":"context_stale_threshold_days"),r=Uc(n,e);if(r.ok)return r.parsed.value;throw new l(`Context ${t}: ${r.error.message}`,m.USAGE)}async function Jx(e,t,n,r,o){let i=!1,s=e.context,a=[];if(t.defaultDepth!==void 0){let d=t.defaultDepth.trim().toLowerCase();if(!Cc.includes(d))throw new l(`Context --default-depth must be one of ${Cc.join("|")}`,m.USAGE);a.push("context.default_depth"),s.default_depth!==d&&(s.default_depth=d,i=!0)}if(t.activityLimit!==void 0){let d=vv(t.activityLimit,"--activity-limit");a.push("context.activity_limit"),s.activity_limit!==d&&(s.activity_limit=d,i=!0)}if(t.staleThresholdDays!==void 0){let d=vv(t.staleThresholdDays,"--stale-threshold-days");a.push("context.stale_threshold_days"),s.stale_threshold_days!==d&&(s.stale_threshold_days=d,i=!0)}let c=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[d,u]of c){let p=Yx(u);if(p!==void 0){let f=d;a.push(`context.sections.${d}`),s.sections[f]!==p&&(s.sections[f]=p,i=!0)}}return(i||Lt(e))&&(await xe(n.pmRoot,e,"config:set:context",{assignedPaths:a}),i=!0),Fe({scope:r,key:"context",context_settings:{default_depth:s.default_depth,activity_limit:s.activity_limit,stale_threshold_days:s.stale_threshold_days,next_ranking_policy:s.next_ranking_policy,sections:{...s.sections}},settings_path:n.settingsPath,changed:i},o)}function Xx(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,m.USAGE);return{...n,value:t}}function Qx(e,t,n,r,o,i){if(o===void 0)return i;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,m.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',m.USAGE);if(r)return Xx(t,o,i);$v(n);let s=th(n,o);if(!s.routable)throw new l(s.reason,m.USAGE);if(s.flag==="criterion"){if(i.criterion!==void 0&&i.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,m.USAGE);return{...i,criterion:s.values}}if(s.flag==="format")return{...i,format:s.value};if(i.policy!==void 0&&yv(n,i.policy)!==yv(n,s.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${i.policy}". Pass only one.`,m.USAGE);return{...i,policy:s.value}}function Lv(e,t){let n=`pm config global ${e} telemetry-tracking${t}`;throw new l(`Config ${e} telemetry-tracking applies to this CLI install, not one project. Run: ${n}`,m.USAGE,{code:"invalid_argument_value",reason:"telemetry_consent_is_global",field:"scope",changed:!1,required:`Run: ${n}`,examples:[n]})}function wl(e){return Object.keys(rn).filter(t=>e==="global"||t!=="telemetry_tracking")}function Zx(e){let t=wl(e.scope).map(r=>({key:r,aliases:rn[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":pl(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:pl(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:Sx[r],value:yl(e.settings,r)})),n=Ui.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:jc(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Fe({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function eI(e){let t=Object.fromEntries(wl(e.scope).map(n=>[n,yl(e.settings,n)]));return Fe({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function tI(e,t){let n=yl(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Fe({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Fe({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Fe({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Fe({...r,criteria:n},e.warnings):Fe({...r,policy:n},e.warnings)}async function nI(e,t,n,r){if(t==="get"){let a=jc(e.settings,n);return Fe({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,m.USAGE);let i=Uc(n,o);if(!i.ok)throw new l(i.error.message,m.USAGE);let s=ji(e.settings,n,i.parsed.value)||Lt(e.settings);return s&&await xe(e.target.pmRoot,e.settings,`config:set:${n.path}`,{assignedPaths:[n.path]}),Fe({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:i.parsed.value},settings_path:e.target.settingsPath,changed:s},e.warnings)}async function ne(e,t,n,r=[]){(t||Lt(e.settings))&&(await xe(e.target.pmRoot,e.settings,n,{assignedPaths:r}),Lt(e.settings)&&(e.fallbackRepairWritten=!0))}function bv(e,t,n){return e!==n||t!==n}function fe(e,t,n,r){return Fe({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function _l(e,t,n,r){return Fe({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function kv(e,t,n){let r=$(t,I()),o=await Th(e,n,"config:set:item_format:migrate",r.type_to_folder,t.schema);return{target_format:o.target_format,scanned:o.scanned,migrated:o.migrated,removed:o.removed,warnings:o.warnings}}async function rI(e,t){let n=Dx(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){e.settings.item_format=n;let i={assignedPaths:["item_format"]};Lt(e.settings)?(await xe(e.target.pmRoot,e.settings,"config:set:item_format",i),e.fallbackRepairWritten=!0,o=await kv(e.target.pmRoot,await A(e.target.pmRoot),n)):(o=await kv(e.target.pmRoot,e.settings,n),await xe(e.target.pmRoot,e.settings,"config:set:item_format",i))}return Fe({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function oI(e,t,n){if(t==="history_missing_stream_policy"){let i=Av(n.policy),s=e.settings.history.missing_stream!==i;return e.settings.history.missing_stream=i,await ne(e,s,"config:set:history_missing_stream_policy",["history.missing_stream"]),fe(e,t,e.settings.history.missing_stream,s)}if(t==="sprint_release_format_policy"){let i=yd(n.policy),s=e.settings.validation.sprint_release_format!==i;return e.settings.validation.sprint_release_format=i,await ne(e,s,"config:set:sprint_release_format_policy",["validation.sprint_release_format"]),fe(e,t,e.settings.validation.sprint_release_format,s)}if(t==="parent_reference_policy"){let i=ms(n.policy),s=e.settings.validation.parent_reference!==i||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==i;return e.settings.validation.parent_reference=i,e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,await ne(e,s,"config:set:parent_reference_policy",["validation.parent_reference","governance.preset","governance.parent_reference"]),fe(e,t,e.settings.validation.parent_reference,s)}let r=gl(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await ne(e,o,"config:set:metadata_validation_profile",["validation.metadata_profile","governance.preset","governance.metadata_profile"]),fe(e,t,e.settings.validation.metadata_profile,o)}async function iI(e,t,n){if(t==="metadata_required_fields"){let a=Kx(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((d,u)=>d!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await ne(e,c,"config:set:metadata_required_fields",["validation.metadata_required_fields"]),_l(e,t,[...e.settings.validation.metadata_required_fields],c)}let o={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],i=zx(t,n.criterion,n.clearCriteria),s=i.length!==o.length||i.some((a,c)=>a!==o[c]);return o.splice(0,o.length,...i),await ne(e,s,`config:set:${t}`,[`validation.${t}`]),_l(e,t,[...o],s)}async function sI(e,t,n){if(t==="governance_preset"){let c=Cv(n.policy),d=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await ne(e,d,"config:set:governance_preset",["governance.preset"]),fe(e,t,e.settings.governance.preset,d)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await ne(e,c,"config:set:governance_create_default_type",["governance.create_default_type"]),fe(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',m.USAGE);let i=$(e.settings,I()),s=Ce(o,i);if(!s)throw new l(Ht(o,i.types,Bt(e.target.pmRoot,e.settings.schema)),m.USAGE);let a=e.settings.governance.create_default_type!==s;return e.settings.governance.create_default_type=s,await ne(e,a,"config:set:governance_create_default_type",["governance.create_default_type"]),fe(e,t,e.settings.governance.create_default_type,a)}async function aI(e,t,n){if(t==="governance_ownership_enforcement"){let i=Tv(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==i;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=i,await ne(e,s,"config:set:governance_ownership_enforcement",["governance.preset","governance.ownership_enforcement"]),fe(e,t,e.settings.governance.ownership_enforcement,s)}if(t==="governance_create_mode_default"){let i=Rv(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==i;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=i,await ne(e,s,"config:set:governance_create_mode_default",["governance.preset","governance.create_mode_default"]),fe(e,t,e.settings.governance.create_mode_default,s)}let r=xv(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await ne(e,o,"config:set:governance_close_validation_default",["governance.preset","governance.close_validation_default"]),fe(e,t,e.settings.governance.close_validation_default,o)}async function cI(e,t,n){if(t==="governance_parent_reference_policy"){let i=ms(n.policy),s=e.settings.governance.preset!=="custom"||bv(e.settings.governance.parent_reference,e.settings.validation.parent_reference,i);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,e.settings.validation.parent_reference=i,await ne(e,s,"config:set:governance_parent_reference_policy",["governance.preset","governance.parent_reference","validation.parent_reference"]),fe(e,t,e.settings.governance.parent_reference,s)}if(t==="governance_metadata_validation_profile"){let i=gl(n.policy),s=e.settings.governance.preset!=="custom"||bv(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,i);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=i,e.settings.validation.metadata_profile=i,await ne(e,s,"config:set:governance_metadata_validation_profile",["governance.preset","governance.metadata_profile","validation.metadata_profile"]),fe(e,t,e.settings.governance.metadata_profile,s)}if(t==="governance_start_blocker_enforcement"){let i=fl(n.policy,"governance-start-blocker-enforcement"),s=(e.settings.governance.start_blocker_enforcement??"strict")!==i;return e.settings.governance.start_blocker_enforcement=i,await ne(e,s,"config:set:governance_start_blocker_enforcement",["governance.start_blocker_enforcement"]),fe(e,t,i,s)}let r=fl(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await ne(e,o,"config:set:governance_workflow_enforcement",["governance.workflow_enforcement"]),fe(e,t,e.settings.governance.workflow_enforcement,o)}async function dI(e,t,n){if(t==="governance_require_close_reason"){let a=Ov(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await ne(e,c,"config:set:governance_require_close_reason",["governance.require_close_reason"]),fe(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let o=Iv(n.policy)==="enabled",i=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==o;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=o,await ne(e,i,"config:set:governance_force_required_for_stale_lock",["governance.preset","governance.force_required_for_stale_lock"]),fe(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",i)}async function lI(e,t,n){if(t==="test_result_tracking"){let a=Ux(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await ne(e,c,"config:set:test_result_tracking",["testing.record_results_to_items"]),fe(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}if(t==="untrusted_linked_test_execution"){let a=hl(n.policy,"untrusted-linked-test-execution")==="enabled",c=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await ne(e,c,"config:set:untrusted_linked_test_execution",["testing.allow_untrusted_linked_tests"]),fe(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",c)}let r=Ev(n.policy);e.scope==="project"&&Lv("set",` --policy ${r}`);let o=r==="enabled",i=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await ne(e,i,"config:set:telemetry_tracking",["telemetry.enabled","telemetry.first_run_prompt_completed"]),fe(e,t,e.settings.telemetry.enabled?"enabled":"disabled",i)}async function mI(e,t,n){let r=Mx(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((i,s)=>i!==e.settings.workflow.definition_of_done[s]);return e.settings.workflow.definition_of_done=r,await ne(e,o,"config:set:definition_of_done",["workflow.definition_of_done"]),_l(e,t,[...e.settings.workflow.definition_of_done],o)}function uI(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",m.USAGE)}function pI(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',m.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",m.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",m.USAGE);return{}}async function fI(e,t){let{operation:n,dryRun:r}=uI(t.policy),o=pI(n,t.value),i;try{i=_v(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(s){throw new l(s.message,m.USAGE)}return i.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:i.vocabulary},await ne(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${i.preview.version_after}`,["agent_identity"])),Fe({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:ul(r?e.settings.agent_identity?.identity_vocabulary:i.vocabulary),vocabulary_mutation:i.preview,settings_path:e.target.settingsPath,changed:i.preview.changed&&!r},e.warnings)}async function _I(e,t,n){let r=await hI(e,t,n);return e.fallbackRepairWritten===!0?{...r,changed:!0}:r}async function hI(e,t,n){if(n.clearCriteria===!0&&!pl(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",m.USAGE);return t==="item_format"?rI(e,n):t==="context"?Jx(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?fI(e,n):t==="definition_of_done"?mI(e,t,n):Sv(t)?iI(e,t,n):Cx.has(t)?lI(e,t,n):Tx.has(t)?dI(e,t,n):Ox(t)?aI(e,t,n):$x(t)?cI(e,t,n):Lx(t)?sI(e,t,n):oI(e,t,n)}async function Pv(e,t,n,r,o,i){let s=Px(e),a=Nx(t),c=a==="get"||a==="set"?Wr(n):void 0,d=c?void 0:Bx(a,n,s,o),u=Qx(a,n,d,c,i,r),p=await Vx(s,o),{settings:f,metadata:h,warnings:_}=await uh(p.pmRoot),g={scope:s,target:p,settings:f,metadata:h,warnings:Hx(_)};return c?nI(g,a,c,u):a==="list"?Zx(g):a==="export"?eI(g):($v(d),a==="get"&&d==="telemetry_tracking"&&s==="project"&&Lv("get",""),a==="get"?tI(g,d):_I(g,d,u))}import Fv from"node:fs/promises";import Mv from"node:path";function gI(e,t,n){let r=new Set,o=[];for(let i of e){let s=i.trim();if(s.length===0||r.has(s))continue;r.add(s);let a=t.get(s);if(a===void 0){o.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){o.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return o}function yI(e,t){let n=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function Nv(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return gI(t.ids,n,t.minEntries)}return yI(e,t)}function wI(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",m.USAGE);if(/^\d+$/.test(n)){let i=Number.parseInt(n,10),s=vn(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new l(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,m.USAGE);let a=i-s-1;return{kind:"version",raw:n,compactCount:a,retainedCount:t.length-a}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,m.USAGE);let o=0;for(let[i,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new l(`History for this item contains invalid timestamp at entry ${i+1}.`,m.GENERIC_FAILURE);if(a>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function vI(e,t){let n=Xr(),r=Xr();for(let o=0;o<e.length;o+=1){let i=e[o];n=sr(n,i.patch,o+1,i.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function bI(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:f_.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&Qc(eo(e.document),r,It(n.hash_algorithm)).includes(n.after_hash))}}function kI(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function SI(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function AI(e,t){let n=e.slice(0,t).findIndex(o=>!Eh(o));if(n===-1)return;let r=Number.isFinite(Date.parse(e[n].ts))?"a malformed record or compaction receipt":"invalid timestamp";throw new l(`History for this item contains ${r} at entry ${n+1}.`,m.GENERIC_FAILURE)}function EI(e,t){let n=e[t.start].ts,r=e.slice(0,t.end+1).map(i=>Date.parse(i.ts));if(!r.every(Number.isFinite))return["that boundary",`Choose a --before timestamp at or before "${n}".`,`Run pm history-compact <id> --before "${n}".`];let o=new Date(r.reduce((i,s)=>Math.max(i,s),Number.NEGATIVE_INFINITY)).toISOString();return["that boundary",`Choose a --before timestamp at or before "${n}", or after "${o}".`,`Run pm history-compact <id> --before "${n}", or with a timestamp after "${o}".`]}function CI(e,t){let n=t-1,r=(d_(e).bridged_segments??[]).find(({start:c,end:d})=>c<=n&&n<d);if(r===void 0)return;let o=vn(e,!0),[i,s,a]=o===null?EI(e,r):[`version ${o+t}`,`Choose --before ${o+r.start+1} or lower, or --before ${o+r.end+2} or higher.`,`Run pm history-compact <id> --before ${o+r.start+1} or --before ${o+r.end+2}.`];throw new l(`history-compact cannot checkpoint ${i}: it lies inside a bridged segment whose states cannot be reconstructed.`,m.USAGE,{code:"history_compact_boundary_bridged",required:s,nextSteps:[a]})}function TI(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};CI(e.historyEntries,e.boundary.compactCount);let{checkpoint:t,finalReplay:n}=vI(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=vn(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=qe({hashAlgorithm:It(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:_t(Xr()),after:_t(t),message:SI(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",last_activity_at:Ch(e.historyEntries.slice(0,e.boundary.compactCount)),pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:__(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[h_({...s,before_hash:Qc(Xr(),i.item_hash_version??1,It(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version,...i.replay_inexact===!0?{replay_inexact:!0}:{}}),...r];return e.dryRun||a.push(qe({nowIso:C(),author:e.author,op:"history_compact",before:_t(n),after:_t(n),message:kI(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function vl(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await go(n.path),s=await An(r,e,o,i.type_to_folder);return Ps({pmRoot:r,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>RI(s,t,a)})}function RI(e,t,n){let r=e.historyPath,o=n.entries,i=n.verification;if(!i.ok)throw new l(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,m.CONFLICT);let s=wI(t.before,o);AI(o,s.compactCount);let a=s.compactCount>0,c=!!t.dryRun,d=n.author,u=[];a||u.push("history_compact_noop_before_boundary");let p=bI(n.loadedItem,o);p.matchedChainBefore===!1&&u.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:h,auditEntryAdded:_}=TI({historyEntries:o,boundary:s,changed:a,dryRun:c,author:d,options:t}),g=vn(o,!0),y=s.retainedCount>0&&g!==null?g+s.compactCount+1:null;return{changed:a,rewrittenEntries:f,report:({verification:w,warnings:v})=>({id:e.id,dry_run:c,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:y},history:{path:r,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:h,audit_entry_added:_,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:p.matchedChainBefore},warnings:[...new Set([...u,...v])].sort((k,S)=>k.localeCompare(S)),generated_at:C()})}}var xI=3;function II(e){for(let n of["allOver","minEntries"]){let r=e[n];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new l(`history-compact ${n} must be a non-negative safe integer.`,m.USAGE)}let t=ds(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",m.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:cs(t)}}function Dv(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",m.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",m.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",m.USAGE)}function OI(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function $I(e){let t=D(e.settings.schema),n=xs(t),r=await ye(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(d=>[d.id,n.classify(d.status)])),i=Mv.join(e.pmRoot,"history"),s=[],a=[];if(!await W(i))return{candidates:s,preselectionErrors:a};let c=(await Fv.readdir(i)).filter(d=>d.endsWith(".jsonl")).sort((d,u)=>d.localeCompare(u));for(let d of c){let u=Mv.join(i,d),p=d.slice(0,-6);try{let f=await Fv.readFile(u,"utf8");await Zn({path:u,scope:"project"}),s.push({id:p,entries:OI(f),bucket:o.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:s,preselectionErrors:a}}async function LI(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await vl(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t),...await vt(t,e.pmRoot)}}}}async function Uv(e,t){let n=II(e),{pmRoot:r,settings:o,typeRegistry:i}=await go(t.path),{candidates:s,preselectionErrors:a}=await $I({pmRoot:r,settings:o,typeToFolder:i.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",d=e.minEntries??xI,u=o.history.compact_policy,p=c==="scan"&&e.allOver===void 0&&u.enabled,f=e.allOver??(p?u.max_entries:void 0),h=Nv(s,{ids:n.ids,scope:e.scope,minEntries:d,allOver:f}),_=!!e.dryRun,g=[...a],y={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of h){let v=await LI({pmRoot:r,row:w,options:n,dryRun:_,global:t});if(g.push(v.result),!v.selected){y.items_skipped+=1;continue}y.selected+=1,v.compacted&&(y.items_compacted+=1),v.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:_,mode:c,scope:e.scope??null,criteria:{min_entries:d,all_over:f??null,policy_threshold_applied:p},totals:y,results:g,generated_at:C()}}function jv(e){let t=e.options.all===!0,n=e.id??b(e.options,"id");return my(n,t),t?Ns(e.options,e.global):tn(n,e.options,e.global)}function Gv(e){let t=e.options.ids,n=ds(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",m.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:cs(n),o=Ke(e.options.allOver??e.options.all_over,"history-compact allOver"),i=Ke(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),s=b(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(s==="closed"||s==="all-streams")&&a.push(s);let c=[...new Set(a)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",m.USAGE);let d=c[0];return Dv(e.id,{ids:r,allOver:o,scope:d}),e.id!==void 0?vl(e.id,{before:b(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global):Uv({ids:r,scope:d,allOver:o,minEntries:i,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global)}import kl from"node:fs/promises";function qv(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function PI(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function bl(e,t){return new l(`Invalid --regex value at --regex #${e}: ${t}`,m.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${e}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function NI(e,t=1){let n=e.trim();if(n.length===0)throw bl(t,"provide a non-empty pattern.");let r=n,o="g";if(n.startsWith("/")&&n.length>1){let i=n.lastIndexOf("/"),s=0;for(let a=i-1;a>=0&&n[a]==="\\";a--)s++;i>0&&s%2===0&&/^[dgimsuvy]*$/u.test(n.slice(i+1))&&(r=n.slice(1,i),o=PI(n.slice(i+1)))}if(r.length===0)throw bl(t,"an empty pattern is not allowed.");try{new RegExp(r,o)}catch{throw bl(t,"provide a valid JavaScript regular expression.")}return{kind:"regex",source:r,flags:o}}function FI(e,t){let n=[...new Set(qv(e).map(s=>s.trim()))].filter(s=>s.length>0).map(s=>({kind:"literal",value:s})),r=new Set,o=qv(t).flatMap((s,a)=>{let c=s.trim();return r.has(c)?[]:(r.add(c),[NI(c,a+1)])}),i=[...n,...o];if(i.length===0)throw new l("history-redact requires at least one matcher via --literal or --regex.",m.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return i}function MI(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){let i=e.indexOf(t,r);if(i===-1)break;o+=1,r=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function DI(e,t,n){let r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function zv(e,t,n){let r=e,o=0;for(let i of t){let s=i.kind==="literal"?MI(r,i.value,n):DI(r,i,n);r=s.value,o+=s.replacements}return{value:r,replacements:o}}function da(e,t,n){if(typeof e=="string")return zv(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(i=>{let s=da(i,t,n);return r+=s.replacements,s.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,o={};for(let[i,s]of Object.entries(e)){let a=da(s,t,n);r+=a.replacements,o[i]=a.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function Kv(e,t,n){let r=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=da(i.value,t,n);return r+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:r}}function UI(e){let t=structuredClone(Xc),n=0,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];Qr(t,void 0,It(i.hash_algorithm))!==i.before_hash&&(n+=1),t=sr(t,i.patch,o+1,i.op),Qr(t,void 0,It(i.hash_algorithm))!==i.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function jI(e,t,n){let r=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let d=zv(e.message,t,n);s=d.value,r+=d.replacements,d.replacements>0&&(o=!0)}let a=Kv(e.patch,t,n);r+=a.replacements,o||=a.replacements>0;let c=e.reanchor_evidence?.map(d=>{let u=d.patch?Kv(d.patch,t,n):{patch:void 0,replacements:0},p=d.record?da(d.record,t,n):{value:void 0,replacements:0};r+=u.replacements,r+=p.replacements;let f=u.replacements>0||p.replacements>0;if(o||=f,!f)return d;i=!0;let{patch:h,record:_,record_hash:g,record_hash_version:y,...w}=d;return u.replacements>0?w:{...w,patch:d.patch}});return{entry:{...e,message:s,patch:a.patch,...c?{reanchor_evidence:c}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:i}}function GI(e,t,n){let r=structuredClone(Xc),o=0,i=0,s=[],a=c_(e),c=[...a.unlocated,...a.undigested];if(c.length>0)throw new l(`history-redact refuses a stream whose bridge at record ${Math.min(...c)+1} does not prove its segment; repair the history first.`,m.GENERIC_FAILURE,{code:"history_redact_bridge_unlocated",required:"Every bridge's segment digest must match the records it covers, so redaction can keep that segment's versions refused.",nextSteps:["Run pm history-repair <id> --dry-run to see how the stream would be repaired."]});let d=l_(a.segments);for(let u=0;u<e.length;u+=1){let p=e[u],f=g_(p);if(!f.ok)throw new l(`history-redact refuses invalid immutable record ${u+1} (${f.error}).`,m.GENERIC_FAILURE);let h=jI(p,t,n);i+=h.replacements,h.changed&&(o+=1);let _=Qr(r,void 0,It(p.hash_algorithm));r=sr(r,h.entry.patch,u+1,h.entry.op);let g=Qr(r,void 0,It(p.hash_algorithm)),{bridge:y,...w}=h.entry;s.push(y_(p,{...w,...d.has(u)?{replay_inexact:!0}:{},before_hash:_,after_hash:g},{retainPriorRecord:h.changed||y!==void 0,retainPriorRecordHash:!h.changed}))}return{entries:s,finalDocument:r,entriesChanged:o,replacements:i}}function qI(e){return Object.keys(e.metadata).length>0}function KI(e){if(!qI(e.finalDocument))return{raw:null,path:null,document:null};let t=pt(_t(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new l("history-redact would change the item id; narrow your patterns.",m.USAGE);return{document:t,path:Et(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:ut(t,{format:"toon",schema:e.settings.schema})}}function zI(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function HI(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??_t(e.rewritten.finalDocument);return t.push(qe({nowIso:C(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function BI(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await Qt(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await ae(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await kl.rm(e.currentItem.path,{force:!0}),await ae(e.subject.historyPath,m_(e.rewrittenEntries))}catch(c){try{await WI(e.subject.historyPath,n,o,i)}finally{await ed(e.subject.historyPath)}throw c}await ed(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Zt({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(a=>{s=()=>{throw a}})}s()},afterWrite:async()=>[...t,...await VI(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function WI(e,t,n,r){t===null?await kl.rm(e,{force:!0}):await ae(e,t);for(let o of n){let i=r.get(o);i===void 0?await kl.rm(o,{force:!0}):await ae(o,i)}}async function VI(e,t){let n=[],r=new Set(t.filter(o=>o!==null));for(let o of r)n.push(...await Q({path:o,scope:"project",op:"history_redact"}));return n.push(...await Q({path:e,scope:"project",op:"history_redact:history"})),n}async function Hv(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await go(n.path),s=t.replacement??"",a=s.length===0,c=a?"[redacted]":s,d=FI(t.literal,t.regex),u=await An(r,e,o,i.type_to_folder);return Ps({pmRoot:r,subject:u,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:p=>YI({pmRoot:r,subject:u,settings:o,typeRegistry:i,options:t,rules:d,replacement:c,replacementIsDefault:a},p)})}function YI(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:i,options:s,rules:a,replacement:c,replacementIsDefault:d}=e,u=t.entries,p=UI(u),f=GI(u,a,c),h=p.hashMismatchesBefore+p.hashMismatchesAfter,_=!!s.dryRun,g=f.replacements>0,y=[];h>0&&y.push(`history_redact_preexisting_hash_mismatches:${h}`),g||y.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},v=KI({pmRoot:n,subject:r,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),k=(w.path??null)!==(v.path??null)||(w.raw??null)!==(v.raw??null),S=t.author,T=zI(s,f),{rewrittenEntries:x,auditEntryAdded:F}=HI({rewritten:f,dryRun:_,changed:g,nextItemDocument:v.document,author:S,message:T});return{changed:g,rewrittenEntries:x,...BI({pmRoot:n,subject:r,settings:o,typeRegistry:i,currentItem:w,nextItem:v,author:S,rewrittenEntries:x}),report:({verification:P,warnings:H})=>({id:r.id,dry_run:_,changed:g,patterns:{literal_count:a.filter(B=>B.kind==="literal").length,regex_count:a.filter(B=>B.kind==="regex").length,total_count:a.length,replacement_is_default:d},history:{path:r.historyPath,entries_scanned:u.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:p.hashMismatchesBefore,hash_mismatches_after:p.hashMismatchesAfter,preexisting_hash_mismatches:h,audit_entry_added:F,verify_ok:P.ok,verify_errors:P.errors},item:{existed_before:w.path!==null,exists_after:v.path!==null,path_before:w.path,path_after:v.path,changed:k},warnings:[...new Set([...y,...H])].sort((B,Y)=>B.localeCompare(Y)),generated_at:C()})}}async function Bv(e,t,n){return hr(e,t,n,{input:await zs(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>_r(r),createEntry:r=>r,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm learnings --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}async function Wv(e,t,n){if(Hh(t),yt(e,"append","id"),t=J_(t),t.body===void 0)throw new l("Missing required --body text",m.USAGE);let r=Yt(),o=E(process.cwd(),n.path);await O(o);let i=await A(o),s=R(t.author,i.author_default),c=(await r.resolveValue(t.body,"--body",Q_(t,"body"))).trim();if(c.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",m.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let d=await we({pmRoot:o,settings:i,id:e,op:"append",author:s,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
|
|
18
18
|
|
|
19
19
|
`:"";return u.body=`${u.body.trimEnd()}${p}${c}
|
|
20
|
-
`,{changedFields:["body"]}}});return{item:d.item,appended:c,changed_fields:d.changedFields}}function qI(e,t,n){let r={...t.metadata,body:t.body},o={...n.metadata,body:n.body};for(let i of new Set([...Object.keys(r),...Object.keys(o)])){if(i==="updated_at"||i==="pm_format_version")continue;let s=r[i],a=o[i];if(ee(s,a))continue;let c=e.get(i);if(c&&!ee(c.after,s))throw new l(`Rollback conflict on ${i}: the batch effects contain an intervening edit. Inspect pm history before resolving it.`,m.CONFLICT);e.set(i,{field:i,before:c?c.before:s,after:a})}}function KI(e,t,n){let r=new Map;for(let[o,i]of e.entries()){if(i.context?.bulk_checkpoint!==t)continue;let s=Zr(ar(e,o-1),{schema:n}),a=Zr(ar(e,o),{schema:n});qI(r,s,a)}return[...r.values()].filter(o=>!ee(o.before,o.after))}function zI(e,t){let n={...e.metadata,body:e.body},r=t.filter(o=>!ee(n[o.field],o.after));if(r.length>0)throw new l(`Rollback conflict on ${r.map(o=>o.field).join(", ")}: a later edit changed a batch field. Inspect pm get/history and reconcile it explicitly before retrying.`,m.CONFLICT);for(let o of t)o.field==="body"?e.body=o.before:o.before===void 0?delete e.metadata[o.field]:e.metadata[o.field]=structuredClone(o.before);return t.map(o=>o.field)}async function la(e,t,n){if(t.record.rollback_strategy!=="guarded_inverse")throw new l("This legacy checkpoint has no attributable inverse effects. Inspect pm history and use an explicit pm restore only after reviewing later edits.",m.CONFLICT);let r=await A(e),o=new Map,i=await Y_(t.items,async a=>{try{return await HI(e,r,t,a,n)}catch(c){throw o.set(a,c),c}}),s=[];for(let a of i.rows)s.push(a.status==="failed"?{...a,...await vt(o.get(a.id),e)}:a);return{...i,rows:s}}async function HI(e,t,n,r,o){let i=await fh({pmRoot:e,settings:t,id:r,op:"restore",author:R(o.author,t.author_default),message:o.message,force:o.force,skipNoop:!0,historyContext:{bulk_rollback:n.id},async mutate(s){let a=await n_(Ze(e,r),r);if(!og(a,s).ok)throw new l(`Cannot safely roll back ${r}: item/history verification failed. Inspect pm history --verify before recovery.`,m.CONFLICT);return a.some(d=>d.context?.bulk_rollback===n.id)?{changedFields:[]}:{changedFields:zI(s,KI(a,n.id,t.schema))}}});return{changed_fields:i.changedFields,warnings:i.warnings,skipped:i.changedFields.length===0}}var BI=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function qv(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function No(e,t){return Sl(e,t,{operation:"close"})}function Sl(e,t,n){let r=qv(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",m.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function Al(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],i=o.filter(d=>d.kind==="blocked_by"),s=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),s&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&i.length>0){let d=new Set(i),u=o.filter(p=>!d.has(p));u.length>0?e.dependencies=u:delete e.dependencies,a.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:a,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...i.length>0?[`closed_removed_predecessors:${e.id}:${i.map(d=>d.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${i.length}`]:[]]};let c=[...new Set([...n?[n]:[],...i.map(d=>d.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}var WI=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function VI(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new l(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,m.USAGE)}function zv(e){let t=[];for(let n of WI){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function Hv(e,t,n={}){let r=zv(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},i=r.map(a=>`--${a.key.replaceAll("_","-")}`),s=[...t,"update",e.id,...r.flatMap((a,c)=>[i[c],o[a.key]?.trim()||"<value>"])];return{missing:i,suggested_retry:P(s),suggested_retry_args:s}}async function YI(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let i=o.trim();if(i===n)return!0;if(r.has(i))return!1;r.add(i),o=(await e(i))?.duplicate_of}return!1}function JI(e){return typeof e!="string"||e.trim().length===0}async function XI(e,t,n,r){let o=n?.trim();if(!o)return;if(o===r)throw new l("An item cannot be closed as a duplicate of itself.",m.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let i=$(t,I()),s=new Map,a=async d=>{if(s.has(d))return s.get(d)??null;let u=await j(e,d,t.id_prefix,t.item_format,i.type_to_folder);if(!u)return s.set(d,null),null;let{document:p}=await te(u,{schema:t.schema});return s.set(d,p.metadata),p.metadata},c=await a(o);if(!c)throw new l(`Duplicate target "${o}" was not found. Create or locate the canonical item first.`,m.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await YI(a,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${o}" points back to "${r}".`,m.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new l(`Duplicate target "${o}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,m.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function QI(e,t,n){return e.filter(r=>r.parent===t&&!le(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function ZI(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),o=Zh(e),i=t.trim().toLowerCase(),s=n.blocked_statuses;return e.filter(a=>s.has(a.status)).map(a=>({item:a,blockerIds:o.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(i)).filter(({blockerIds:a})=>a.every(c=>{if(c===i)return!0;let d=r.get(c);return d!==void 0&&le(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function eO(e,t,n,r,o,i,s){let a=ZI(n,r,i),c=[],d=[],u=[],p=[],f;for(let h of a)try{let _=await we({pmRoot:e,settings:t,id:h.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(g){let y=g.metadata.dependencies??[],w=y.filter(k=>{let S=k.id.trim().toLowerCase();return k.kind!=="blocked_by"||!h.blocker_ids.includes(S)});g.metadata.status=i.open_status,delete g.metadata.blocked_by,delete g.metadata.blocked_reason,g.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${h.blocker_ids.join(", ")}).`,w.length>0?g.metadata.dependencies=w:delete g.metadata.dependencies;let v=["status","blocked_by","blocked_reason","unblock_note"];return w.length!==y.length&&v.push("dependencies"),{changedFields:v}}});c.push(`auto_unblocked:${_.item.id}:resolved_blockers=${h.blocker_ids.join(",")}`),d.push(_.item.id)}catch(_){let g=_ instanceof Error?_.message.replace(/\s+/g," ").trim():"unknown";En(_)?(f??=_,u.push(h.id)):p.push({id:h.id,reason:g}),c.push(`auto_unblock_failed:${h.id}:${g}`)}if(f!==void 0){let h=await ry(f,e),_=[...i.blocked_statuses].sort().join(",");throw oO(h,{closedId:r,unblockedIds:d,conflictIds:u,failed:p,openStatus:i.open_status,blockedStatuses:_,commandScope:s})}return c}var Mt=10,El=20,tO=[{list:"auto_unblock_failed",omitted:"auto_unblock_failed_omitted",floor:0},{list:"changes_since",omitted:"changes_since_omitted",floor:0},{list:"pending_unblock",omitted:"pending_unblock_omitted",floor:1}];function nO(e){for(let t of tO){let n=e[t.list];if(Array.isArray(n))for(;n.length>t.floor&&!bd(e);)n.pop(),Reflect.set(e,t.omitted,Number(e[t.omitted])+1)}return e}function Kv(e){let t=e.length-Mt;return`${e.slice(0,Mt).join(", ")}${t>0?`, and ${t} more`:""}`}var rO="post_close_auto_unblock_refused";function oO(e,t){let{closedId:n,conflictIds:r,failed:o,commandScope:i}=t,s=String(e.context.item_id),a=_=>P([...i,"update",_,"--status",t.openStatus,"--unset","blocked_by","--unset","blocked_reason","--expect-hash",`${_}=<item_hash>`]),c=o.slice(0,Mt).map(_=>({id:_.id,reason:cp(_.reason,160)})),d=o.length===0?"":` Auto-unblocking also failed for ${Kv(o.map(_=>_.id))}; details.auto_unblock_failed gives the reasons it kept (auto_unblock_failed_omitted counts the rest; their get step shows the item). Fix that cause before unblocking it.`,u=P([...i,"list","--status",t.blockedStatuses,"--fields","id,title,blocked_by,dependencies","--limit","200"]),p=[...r.slice(0,Mt).flatMap(_=>[P([...i,"get",_,"--json"]),a(_)]),...c.map(_=>P([...i,"get",_.id,"--json"]))],f=r.length>Mt||o.length>Mt||p.length>El,h=p.slice(0,f?El-1:El);return new l(`${n} was closed, but auto-unblocking ${s} was refused. ${e.message}`,e.exitCode,{...e.context,reason:rO,examples:h_(s,!1,{scopeArgs:i}).examples,required:`The close of ${n} is complete; do not retry it. Only unblocking ${r.length===1?s:`the guarded dependents it refused (${Kv(r)})`} remains: re-read each one (pm get <id> --json reports item_hash), check that every blocker it declares is resolved, then unblock it with ${a(s)}${r.length===1?"":" for each id"}.${d}${f?` This refusal does not list a step for every dependent left blocked; list them with ${u}, and while it reports has_more, continue with --after <next_cursor>.`:""}`,nextSteps:f?[...h,u]:h,details:nO({...structuredClone(e.context.details),pending_unblock:r.slice(0,Mt),pending_unblock_omitted:Math.max(0,r.length-Mt),auto_unblock_failed:c,auto_unblock_failed_omitted:Math.max(0,o.length-Mt)}),side_effects:[{path:`history/${n}.jsonl`,op:"close"},...t.unblockedIds.map(_=>({path:`history/${_}.jsonl`,op:"update"}))]})}async function ma(e,t,n){if(!En(e)||!e.context.side_effects?.some(i=>`${i.op}:${i.path}`==`close:history/${t}.jsonl`))return;let r=String(e.context.item_id);return{warnings:[...e.context.side_effects.filter(i=>i.op==="update").map(i=>i.path.slice(8,-6)).map(i=>`auto_unblocked:${i}`),`auto_unblock_refused:${r}:item_revision_conflict`],dependent_revision_conflict:{item_id:r,error:mt(e),...await vt(e,n)}}}function iO(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:i}of r){if(typeof o!="string")continue;let s=o.trim();s.length!==0&&(e[i]=s,n.push(i))}return n}function sO(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:i}of r)JI(e[o])&&(e[o]=i,n.push(o));return n}function aO(e,t){let r=[["--resolution",e.resolution],["--expected-result",e.expectedResult],["--actual-result",e.actualResult],["--validate-close",e.validateClose],["--completed-at",e.completedAt],["--message",e.message],["--author",e.author]].flatMap(([o,i])=>t.has(o)||i===void 0||i.trim().length===0?[]:[`${o}=${i}`]);return e.force===!0?[...r,"--force"]:r}function cO(e,t,n){let r=t.map(y=>y.label),o=t.map(y=>`--${y.key.replaceAll("_","-")}`),i=o.flatMap(y=>[y,"<value>"]),s=[...n.commandScope,"update",e.id,...i],a=`Cannot close item ${e.id}: missing ${r.join(", ")}. Populate fields or use --validate-close warn.`,c="Use --validate-close warn only when governance permits an evidenced exception.",d=Object.entries(n.options.lifecyclePolicy??{}).filter(([,y])=>y!==void 0).map(([y])=>y),u=f_(n.pmRoot),p=typeof n.options.author=="string"&&n.options.author.trim().length===0,f=d.length>0?`its lifecyclePolicy override (${d.join(", ")}) has no CLI spelling`:p?"its explicitly blank author has no CLI spelling (pm close refuses an empty --author)":u===void 0?"its revision guards cannot be replayed as typed (nested revision guards expect different revisions of one item, or a write in the same operation advanced a guarded revision)":void 0;if(f!==void 0)return new l(a,m.USAGE,{code:"close_validation_missing_fields",required:`Pass ${t.map(y=>y.key).join(", ")} on the same SDK close; ${f}, so no CLI retry reproduces it.`,recovery:{missing:o,next_best_command:P(s)},nextSteps:["Retry the same SDK close with the missing evidence supplied, inside the same lifecycle policy and revision guards.",c]});let h=n.closeReason===void 0?[]:[`--reason=${n.closeReason}`],_=u.map(y=>`--expect-hash=${y}`),g=[...n.commandScope,"close",e.id,...h,...aO(n.options,new Set(o)),..._,...i];return new l(a,m.USAGE,{code:"close_validation_missing_fields",required:`Supply ${o.join(", ")}: pm close accepts them and records them in the same write as the closure.`,recovery:{missing:o,suggested_retry:P(g),suggested_retry_args:g,next_best_command:P(s)},nextSteps:["Run recovery.suggested_retry when it is present: the same close with the missing flags added, so one write records the evidence and the closure.","Without it, record the evidence with recovery.next_best_command, then repeat the original close.",c]})}function dO(e,t,n,r){let o=t.map(a=>Wc(a.field).flag),i=[...r.author?.trim()?[`--author=${r.author}`]:[],...r.force===!0?["--force"]:[]],s=[...n,"update",e.id,...i,...o.flatMap(a=>[a,"<value>"])];return new l(`Cannot close item ${e.id}: deferred fields still have no value (${t.map(a=>a.field).join(", ")}). Supply them or use --validate-close warn.`,m.USAGE,{code:"close_validation_deferred_fields",required:`Supply ${o.join(", ")}: each was deferred at create (${t.map(a=>`${a.field}: ${a.reason}`).join("; ")}).`,recovery:{missing:o,next_best_command:P(s)},nextSteps:["Record the now-known values with recovery.next_best_command; the update resolves each deferral, then repeat the close.","Use --validate-close warn only when governance permits closing with deferred values still unknown."]})}function lO(e,t,n){let r=Wf(e);if(r.length===0)return[];if(t==="strict")throw dO(e,r,n.commandScope,n.options);return[`close_validation_deferred_fields:${e.id}:${r.map(o=>o.field).join(",")}`]}function mO(e,t,n,r){let o=[];if(t!=="off"){o.push(...lO(e,t,r));let i=zv(e);if(i.length>0){let s=i.map(a=>a.label);if(t==="strict")throw cO(e,i,r);o.push(`close_validation_missing_fields:${e.id}:${s.join(",")}`)}if(n.length>0){if(t==="strict")throw new l(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,m.USAGE);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function uO(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function pO(e){let t=["assignee","claim_principal"].filter(n=>e[n]!==void 0);for(let n of t)delete e[n];return[...t]}function fO(e,t){if(le(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,m.CONFLICT,{recovery:Hv(e,t.commandScope,t.options)});let n=iO(e,t.options),r=sO(e,t.duplicateOf),o=mO(e,t.validateCloseMode,t.activeChildIds,t);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let i=t.options.completedAt!==void 0||e.completed_at===void 0;i&&(e.completed_at=t.completedAt);let s=["status","closed_at",...i?["completed_at"]:[],...uO(e,t.closeReason),...n];if(Sh(e)&&(e.plan_mode="completed",s.push("plan_mode")),t.duplicateOf!==void 0){s.push("duplicate_of");for(let c of r)s.includes(c)||s.push(c)}s.push(...pO(e));let a=Al(e,t.lifecyclePolicy);return s.push(...a.changedFields),o.push(...a.warnings),{changedFields:s,...o.length>0?{warnings:o}:{}}}async function Bv(e,t,n,r){let o=E(process.cwd(),r.path),i=ke(r);await O(o);let s=await A(o),a=D(s.schema),c=R(n.author,s.author_default),d=$(s,I()).type_to_folder,u=await j(o,e,s.id_prefix,s.item_format,d);if(!u)throw await it(o,e,s.id_prefix,d);let p=await XI(o,s,n.duplicateOf,u.id),f={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},h=No({explicit:t,duplicateOf:p,resolution:n.resolution,message:n.message},f.requireCloseReason).closeReason,_=VI(n.validateClose)??s.governance.close_validation_default,g=await ye(o,s.item_format,d,void 0,s.schema),y=QI(g,u.id,a),w=C(),v=n.completedAt===void 0?w:se(n.completedAt,new Date(w),"completed-at"),k={timestamp:v,source:n.completedAt===void 0?"close_time":"asserted",...n.completedAt===void 0?{hint:`completed_at defaults to the close time. If work finished earlier, correct it with ${P([...i,"update",u.id,"--completed-at","<ISO>"])}.`}:{}},S=await Zt({pmRoot:o,settings:s,id:u.id,op:"close",author:c,message:n.message,force:n.force,resolveHistoryContext:()=>({completion:{timestamp:k.timestamp,source:k.source}}),mutate(x){return n.completedAt===void 0&&x.metadata.completed_at!==void 0&&(k={timestamp:x.metadata.completed_at,source:"existing"}),fO(x.metadata,{pmRoot:o,commandScope:i,statusRegistry:a,force:n.force,options:n,duplicateOf:p,validateCloseMode:_,activeChildIds:y,closeReason:h,closedAt:w,completedAt:v,lifecyclePolicy:f})}}),T=_==="warn"?Hv(S.item,i):void 0;return{item:S.item,changed_fields:S.changedFields,...T?{follow_up:{kind:"complete_close_evidence",missing:T.missing,suggested_command:T.suggested_retry,suggested_command_args:T.suggested_retry_args}}:{},warnings:[...S.warnings,...await eO(o,s,g,u.id,c,a,i)],completion:k}}function Dt(e,t,n,r){return Bv(e,t,n,r)}var Vv=2,Cl="close-many",_O=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function hO(e,t){return bo(e,t,{includePagination:!1})}function gO(e,t){return bo(e,t)}function yO(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",m.USAGE)}function wO(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function vO(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new l("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",m.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function bO(e,t){let n=D(t.schema),r=$(t,I()),o=await ye(e,t.item_format,r.type_to_folder,void 0,t.schema),i=new Map,s=new Map;for(let a of o){if(typeof a.parent!="string"||a.parent.length===0||(s.set(a.id,a.parent),le(a.status,n)))continue;let c=i.get(a.parent);c?c.push(a.id):i.set(a.parent,[a.id])}for(let a of i.values())a.sort((c,d)=>c.localeCompare(d));return{childrenByParent:i,parentByChild:s}}function Wv(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,i=t.get(e),s=[],a=new Set,c=!1;for(;i!==void 0&&!a.has(i);){let d=n?.get(i);if(d!==void 0){o+=d+1;break}a.add(i),s.push(i),o+=1,i=t.get(i)}if(i!==void 0&&a.has(i)&&(c=!0),!c){n?.set(e,o);for(let[d,u]of s.entries())n?.set(u,o-d-1)}return o}async function kO(e){let t=await as(e.pmRoot,Cl,e.rollbackId,Vv),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await la(e.pmRoot,t,{author:e.options.author,message:n,force:e.options.force}),o=r.rows.filter(i=>i.status==="skipped").length;return{...kn({applied:r.restored_ids.length,skipped:o,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:r.restored_ids.length,skipped_count:o,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function SO(e,t,n,r,o){return e.map(i=>{let s=(t.get(i.id)??[]).filter(c=>!n.has(c)),a=!Yv(i,r,o);return{id:i.id,title:typeof i.title=="string"?i.title:"",status:i.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...s.length>0?{active_child_ids:s}:{}}})}async function AO(e){let t=await ss(e.pmRoot,Cl,e.checkpointId,{schema_version:Vv,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:R(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function EO(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await ys({pmRoot:e.pmRoot,itemId:r.id,checkpointId:e.checkpointId},()=>Dt(r.id,e.reason,e.closeOptions,e.global));t.push({id:r.id,status:"closed",completion:o.completion,changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){let i=await ma(o,r.id,e.pmRoot);if(i!==void 0){t.push({id:r.id,status:"closed",...i}),n.push(r.id);continue}t.push({id:r.id,status:"failed",error:mt(o),...await vt(o,e.pmRoot)})}}return{rows:t,closedIds:n}}function CO(e){return os(e.rollback)}function TO(e){if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",m.USAGE);if(gO(e.list,e.status))throw new l("Rollback mode does not accept filter options",m.USAGE)}function RO(e){if(!hO(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${_O}). Refusing to match every item.`,m.USAGE)}function xO(e,t){let n=new Map;return[...e].sort((r,o)=>{let i=Wv(o.id,t,n)-Wv(r.id,t,n);return i!==0?i:r.id.localeCompare(o.id)})}function Yv(e,t,n){return n||!le(e.status,t)}function IO(e,t,n){return new Set(e.filter(r=>Yv(r,t,n)).map(r=>r.id))}async function OO(e){RO(e.options);let t=D(e.settings.schema),n=vO(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await Lt(e.options.status,wO(e.options.list),e.global),{childrenByParent:i,parentByChild:s}=await bO(e.pmRoot,e.settings),a=xO(o.items,s),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],d=c.length===0?[]:(await Lt(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,u=new Set(d.map(f=>f.id)),p=IO(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!u.has(f)),planRows:SO(a,i,p,t,r)}}function $O(e){return{outcome:"effect",exit_code:m.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function PO(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return AO({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function Jv(e,t){let n=CO(e),r=E(process.cwd(),t.path);await O(r);let o=await A(r),i=e.dryRun===!0;if(yO(e.list),n!==void 0)return TO(e),kO({pmRoot:r,rollbackId:n,options:e,global:t});let s=await OO({pmRoot:r,settings:o,options:e,global:t});if(i)return $O(s);let a=new Set(s.planRows.filter(w=>w.action==="close").map(w=>w.id)),c=C(),d=is(Cl,c),u=await PO({context:s,options:e,closableIds:a,checkpointId:d,nowValue:c}),p={author:e.author,message:e.message??`close-many apply ${d}`,completedAt:e.completedAt,validateClose:s.validateCloseMode,force:s.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:h}=await EO({pmRoot:r,checkpointId:d,matched:s.matched,closableIds:a,reason:s.reason,closeOptions:p,global:t}),_=f.filter(w=>w.status==="closed").length,g=f.filter(w=>w.status==="skipped").length,y=f.filter(w=>w.status==="failed").length;return{...kn({applied:_,skipped:g,failed:y,unmatched:s.unmatchedIds?.length??0}),mode:"apply",matched_count:s.matched.length,dry_run:!1,...s.reason!==void 0?{reason:s.reason}:{},filters:s.listed.filters,...s.validateCloseMode?{validate_close:s.validateCloseMode}:{},...u?{checkpoint:u}:{},closed_count:_,skipped_count:g,failed_count:y,rows:f,ids:h,...s.unmatchedIds!==void 0?{unmatched_ids:s.unmatchedIds,unmatched_count:s.unmatchedIds.length}:{}}}function LO(e,t){return[...new Set([...ri.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,o)=>r.localeCompare(o))}function NO(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Tl(e,t,n){let r=E(process.cwd(),n.path);await O(r);let o=await A(r),i=$(o,I()),s=await j(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!s)throw await it(r,e,o.id_prefix,i.type_to_folder);let a=await te(s,{schema:o.schema}),c=a.document.metadata,d=C(),u=R(t.author,o.author_default),p=await ro(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:i.type_to_folder,probeExisting:!1}),f=D(o.schema),h=t.title?.trim();if(h!==void 0&&h.length===0)throw new l("Copy --title must not be empty",m.USAGE);let _={...c,id:p,title:h??c.title,status:f.open_status,created_at:d,updated_at:d};delete _.closed_at,delete _.completed_at,delete _.close_reason,delete _.test_runs;let g=Ue(I()),y=pt({metadata:_,body:a.document.body},{schema:o.schema,extensionFieldNames:g}),w=await ur({title:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[s.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=LO(y.metadata,y.body),k=Et(r,y.metadata.type,p,o.item_format,i.type_to_folder),S=Ze(r,p),T=await ft(r,p,o.locks.ttl_seconds,u,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),x={metadata:{},body:""},F,L,H;try{let B=await Xt(r,u,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await ur({title:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[s.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let Y=await j(r,p,o.id_prefix,o.item_format,i.type_to_folder);if(Y)throw new l(`Cannot copy to ${p}: an item with that id already exists at ${Y.itemPath}. Retry the copy to allocate a new id.`,m.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${Y.itemPath}.`,recovery:{suggested_retry:`pm copy ${s.id}`}});let re=await vn({pmRoot:r,settings:o,operation:"create",author:u,before:null,after:y});H=re.warnings,await yn({pm_root:r,operation:"create",before:null,after:y,changed_fields:v,author:u,sdk:bn({pmRoot:r,settings:o,typeToFolder:i.type_to_folder})}),await T.fence(async()=>{await ae(k,ut(y,{format:o.item_format,schema:o.schema,extensionFieldNames:g}));try{let J=qe({nowIso:d,author:u,op:"create",before:x,after:y,message:NO(s.id,t.message),context:re.decisions.length===0?void 0:{workflow_policies:re.decisions}});await Bt(S,J)}catch(J){throw await Hn(k),J}}),L=await Qt({pmRoot:r,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:k,document:y})}finally{await B()}F=[...await Q({path:k,scope:"project",op:"create",item_id:y.metadata.id,item_type:y.metadata.type,before:x,after:y,changed_fields:v}),...await Q({path:S,scope:"project",op:"create:history",item_id:y.metadata.id,item_type:y.metadata.type,before:x,after:y,changed_fields:v})],Qn({id:y.metadata.id,op:"create",item_type:y.metadata.type,status:y.metadata.status,current:gn(y.metadata,v),changed_fields:v})}finally{await T.release()}return{source_id:s.id,item:structuredClone(y.metadata),changed_fields:v,warnings:[...$s(w),...H,...L,...F],...w===void 0?{}:{similarity_advisory:w}}}function Rl(){return Hc.map(e=>e.field).join(", ")}var FO=Object.freeze({fields:[],reason:void 0,optionKeys:new Set});function MO(e){return(e??[]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function Xv(e,t){let n=tr(t,"defer"),r=tr(t,"defer-reason"),o=MO(e.defer),i=e.deferReason?.trim();if(o.length===0){if(i!==void 0&&i.length>0)throw new l(`${r} needs ${n}: name the fields whose values are not known yet.`,m.USAGE,{code:"create_deferral_fields_required",required:`Pass ${n} with ${r}, or drop ${r}.`,nextSteps:[`Deferrable fields: ${Rl()}.`]});return FO}let s=new Map;for(let c of o){let d=Bc(c);if(d===void 0)throw new l(`${n} cannot defer "${c}". Deferrable fields: ${Rl()}.`,m.USAGE,{code:"create_deferral_field_unsupported",required:`Defer only ${Rl()}; supply every other field, or clear a repeatable option with its --clear-* flag.`});s.set(d.field,d)}if(i===void 0||i.length===0)throw new l(`${n} requires ${r}: record why the deferred values are not known yet.`,m.USAGE,{code:"create_deferral_reason_required",required:`Pass ${r} "<why>", for example the system the record was imported from.`});let a=Hc.filter(c=>s.has(c.field));return{fields:a,reason:i,optionKeys:new Set(a.map(c=>c.option))}}function xl(e,t,n,r,o={}){let i=e.fields.filter(c=>{let d=t[c.option];return typeof d=="string"&&d.trim().length>0||o[c.field]!==void 0||n.has(c.field)});if(i.length===0)return;let s=tr(r,"defer"),a=i.map(c=>c.field).join(", ");throw new l(`Cannot both defer and set ${a}: ${s} records a value as not known yet.`,m.USAGE,{code:"create_deferral_conflict",required:`Drop ${s} for ${a}, or drop the value (or unset) you supplied for it.`})}function Qv(e){if(e.fields.length!==0)return Vc(e.fields.map(t=>({field:t.field,reason:e.reason})))}function Zv(e,t=[]){let r=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(s=>typeof s=="string").flatMap(s=>s.split(",")).map(s=>Bc(s)).filter(s=>s!==void 0),o=new Set(r.map(s=>s.field)),i=t.filter(s=>s.commands.includes("create")&&o.has(s.metadata_key)).flatMap(s=>zf(s));return[...r.map(s=>s.option),...i]}function eb(e,t,n,r,o={}){let i=new Set(t.fields.map(u=>u.field)),s=n.filter(u=>u.commands.includes("create")),a=u=>u.required!==!0&&i.has(u.metadata_key),c=new Set(s.filter(a).map(u=>`--${u.cli_flag}`)),d=new Set(s.filter(u=>!a(u)&&Hf(u,r)&&qi(o,u)===void 0).map(u=>`--${u.cli_flag}`));return e.filter(u=>!c.has(u)||d.has(u))}var DO="hierarchy-integrity";async function ua(e){let t=e.required?await Yr(e.pmRoot,DO,e.ttlSeconds,e.author,!1,!1,e.waitMs,{waitPolicy:"progress"}):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}function pa(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function fa(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function _a(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(vc.includes(t))return t;let n=ge(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new l("Confidence must be an integer 0..100 or one of low|med|medium|high",m.USAGE);return n}function ha(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new l("Regression must be one of true|false|1|0",m.USAGE)}var tb=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds","phase"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];var UO=["documentAnnotationSnapshot","runtimeFieldCommands","ownershipMetadataBypass","ownershipDependencyBypass"];function ga(e){let t=tb.find(([r])=>r===e)?.[1]??e.replaceAll(/_([a-z])/gu,(r,o)=>o.toUpperCase()),n=[["update",md],["create",ld]].flatMap(([r,o])=>o.flatMap(i=>{if(i.target!==t)return[];let s=i.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:r,flag:s}]}));return{recovery:{provided_fields:[e],...n.length>0?{suggested_flags:[...new Set(n.map(r=>r.flag))]}:{}},nextSteps:n.length>0?n.map(({command:r,flag:o})=>`Use the declared core mutation: pm ${r}${r==="update"?" <id>":""} ${o} <value>; inspect its help for other required options.`):[`No dedicated create/update CLI mutation flag is declared for "${e}". Use its owning lifecycle, evidence, or importer API; --field cannot mutate core metadata.`]}}var rb={create:{name:"create",usage:"pm create",sdkScope:"create options"},update:{name:"update",usage:"pm update <id>",sdkScope:"update options"},update_many:{name:"update-many",usage:"pm update-many <selection flags>",sdkScope:"update options of the update-many request"}};function nb(e){return e.flatMap(t=>[t.flag,...t.short===void 0?[]:[t.short],...t.aliases??[]])}function ob(e){if(e==="update_many"){let o=ob("update"),i=nb(Ge("update-many"));return{options:new Set([...o.options,...i.map(s=>Kc(s))]),flags:new Set([...o.flags,...i])}}let t=e==="update"?md:ld,n=nb([...Ge(e),...Vn]),r=[...t.flatMap(o=>[o.target,...o.keys]),...n.map(o=>Kc(o)),...e==="update"?UO:[]];return{options:new Set(r),flags:new Set(n)}}function jO(e,t){let n=rb[t];return e===void 0?`SDK: every option name for this field is shared with another declared field or an option of pm ${n.name}; no SDK option sets it alone.`:`SDK: pass ${e} in the ${n.sdkScope}.`}function GO(e,t,n,r){return e.definitions.some(o=>o.metadata_key===t.metadata_key&&o.commands.includes(n)&&qi(r,o)!==void 0)}function ya(e,t,n){let r=rb[t],o=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([i])=>i!=="field"));return i=>{let s=Rf(i),a=e.definitions.filter(h=>h.metadata_key===s||h.key===s),c=a.find(h=>h.commands.includes(t))??a[0];if(c===void 0)return;let d=`Inspect the value contract with: pm schema show-field ${c.key}`;if(!c.commands.includes(t))return{recovery:{provided_fields:[i]},nextSteps:[`The project schema declares "${c.key}" for ${c.commands.join(", ")} only; ${r.name} cannot set it.`,d]};if(o!==void 0&&GO(e,c,t,o))return{recovery:{provided_fields:[i]},nextSteps:[`This invocation already sets "${c.key}" through a declared flag or option; drop the --field ${i} assignment so the field receives one value.`,d]};let u=ob(t),p=Kf(c,e,u,t),f=p===void 0?`Every CLI spelling of "${c.key}" is shared with another declared field or an option of pm ${r.name}; give it a distinct cli_flag in the project schema.`:`Use the declared project-schema flag: ${r.usage} ${qc(p)} <value>`;return{recovery:{provided_fields:[i],...p===void 0?{}:{suggested_flags:[qc(p)]}},nextSteps:[f,jO(qf(c,e,u.options,t),t),d]}}}var qO=new Set(["event","meeting","reminder","milestone","decision","adr"]);function ib(e,t,n,r){if(qO.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=xt("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm claim ${e} --start`,to_status:o}}function ab(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,m.USAGE)}function Il(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function at(e,t,n,r=n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,m.USAGE,{field:r,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var cb=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function KO(e,t){return t==="defined"?e!==void 0:!!e}function sb(e,t,n){if(!KO(e,n))return;let r=ge(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,m.USAGE);return r}function zO(e,t,n){let r=e?se(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new l("--event recur_until must be at or after start",m.USAGE);return r}function HO(e){return Array.from(new Set(Il(e).map(t=>at(t.toLowerCase(),Pu,"event weekday")))).sort((t,n)=>bc(t)-bc(n))}function BO(e){return Array.from(new Set(Il(e).map(t=>{let n=ge(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new l("--event recur_by_month_day values must be integers 1..31",m.USAGE);return n}))).sort((t,n)=>t-n)}function WO(e,t){return Array.from(new Set(Il(e).map(n=>se(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function db(e,t,n,r){let o=e.recur_freq?.trim(),i=e.recur_interval?.trim(),s=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![o,i,s,a,c,d,u].some(k=>k!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",m.USAGE);let f=at(o.toLowerCase(),$u,"event recurrence frequency"),h=sb(i,"recur_interval",r),_=sb(s,"recur_count",r),g=zO(a,t,n),y=HO(c),w=BO(d),v=WO(u,n);return{freq:f,interval:h,count:_,until:g,by_weekday:y.length>0?y:void 0,by_month_day:w.length>0?w:void 0,exdates:v.length>0?v:void 0}}function Ar(e,t=st()){let n=t.resolve(e);if(n)return n.kind;let r=new Set(ni),o=[...ni,...t.list().filter(({kind:i})=>!r.has(i)).flatMap(({kind:i,aliases:s})=>[i,...s])];throw new l(`Invalid dependency kind value "${e}". Allowed: ${o.join(", ")}`,m.USAGE,{field:"kind",value:e,recovery:{allowed_values:o},required:`dependency kind must be one of: ${o.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function Fo(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,m.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function Mo(e,t,n=st()){for(let r of t??[])try{ju(e,r.id,r.kind,n)}catch(o){throw new l(mt(o),m.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function lb(e,t){return(await te(e,{schema:t})).document.metadata.created_at}async function VO(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await j(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:lb(n,t.schema)}function YO(e){let t=e.registry.require(e.dependency.kind);return new l(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,m.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function JO(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:i})=>i===null?[]:[[o,i]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await lb(n.get(o),e.context.schema)])));for(let o of e.holders){let i=await VO(o,e.context);if(i!==void 0)for(let s of t){let a=r.get(s.id),c=Date.parse(i),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw YO({holder:o,dependency:s,sourceCreatedAt:i,targetCreatedAt:a,registry:e.registry})}}}async function Ln(e){let t=e.registry??st(),n=(e.dependencies??[]).filter(s=>!L_(s.source_kind)),r=[...new Set(n.map(s=>s.id))],o=await Promise.all(r.map(async s=>({target:s,located:await j(e.pmRoot,s,e.idPrefix,e.itemFormat,e.typeToFolder)}))),i=o.filter(({located:s})=>s===null).map(({target:s})=>s).sort((s,a)=>s<a?-1:1);if(i.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${i.length===1?"":"s"} not found: ${i.join(", ")}`,m.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:i,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${i.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:i,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${i[0]}" --limit 10`}});return await JO({dependencies:n,missingTargets:i,resolutions:o,holders:e.holders??[],registry:t,context:e}),i.map(s=>`dependency_target_unresolved:${s}`)}var XO={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function QO(e){return XO[e]}function Ol(e){return QO(e)!==void 0}var mb="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",ZO="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",e$=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,t$=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,pb=1e3,$l=60*pb,n$=60*$l;function ub(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new l(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,m.USAGE);return n.toISOString()}function r$(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new l(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,m.USAGE);let o=r.replace(/^([+-]?\d+)mo$/i,"$1m"),i=e$.exec(r);if(i){let c=i[1]==="-"?-1:1,d=Number.parseInt(i[2],10)*c;return ub(n.getTime()+d*$l,r)}let s=t$.exec(r);if(s){let[,c,d,u,p]=s;if(d||u||p){let h=c==="-"?-1:1,_=Number.parseInt(d??"0",10),g=Number.parseInt(u??"0",10),y=Number.parseInt(p??"0",10),w=_*n$+g*$l+y*pb;return ub(n.getTime()+h*w,r)}}let a=o.startsWith("+")||o.startsWith("-")?o:`+${o}`;return se(a,n,"event.duration")}function fb(e,t,n,r){if(t&&n)throw new l(ZO,m.USAGE);if(n){let i=r$(e,n);if(i<e)throw new l(mb,m.USAGE);return i===e?void 0:i}if(!t)return;let o=se(t,r,"event.end");if(o<e)throw new l(mb,m.USAGE);if(o!==e)return o}var o$=["at","date","text","title"],i$=["start","date","end","duration","title","description","location","timezone","all_day",...cb],s$=["key","value"];function _b(e,t){return t==="trimmed"?e?.trim():e}function a$(e,t){return t==="defined"?e!==void 0:!!e}function wa(e,t,n){return e.map(r=>{let o=_e(r,"--reminder");rt(o,"--reminder",o$);let i=_b(o.at??o.date,n.valueMode),s=_b(o.text??o.title,n.valueMode);if(!i||!s)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",m.USAGE);let a=s.trim();if(!a)throw new l("--reminder text must not be empty",m.USAGE);return{at:se(i,t,"reminder.at"),text:a}})}function va(e,t,n){return e.map(r=>{let o=_e(r,"--event");rt(o,"--event",i$);let i=(o.start??o.date)?.trim();if(!i)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",m.USAGE);let s=se(i,t,"event.start"),a=o.end?.trim(),c=o.duration?.trim(),d=fb(s,a,c,t),u=o.title,p=o.description,f=o.location,h=o.timezone,_=u?.trim(),g=p?.trim(),y=f?.trim(),w=h?.trim(),v=[["title",u,_],["description",p,g],["location",f,y],["timezone",h,w]];for(let[x,F,L]of v)if(F!==void 0&&!L)throw new l(`--event ${x} must not be empty`,m.USAGE);let k=o.all_day?.trim(),S=db(o,s,t,n.recurrenceEmptyNumericGuard),T=a$(k,n.allDayEmptyGuard)?ab(k,"--event all_day"):void 0;return{start_at:s,end_at:d,title:_,description:g,location:y,all_day:T,timezone:w,recurrence:S}})}function ba(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new l("--type-option values must not be empty",m.USAGE);let o,i;if(r.includes(",")||r.includes(`
|
|
21
|
-
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=_e(r,"--type-option");rt(a,"--type-option",s$),o=a.key?.trim(),i=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),d=a;if(a<=0&&c>0&&(d=c),d<=0||d===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",m.USAGE);o=r.slice(0,d).trim(),i=r.slice(d+1).trim()}if(!o||!i)throw new l("--type-option requires key and value",m.USAGE);t[o]=i}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}var c$=["strict","progressive"],d$=["lightweight"],wb=new Set(["Reminder","Meeting","Event"]),l$=new Set(["author","created_at","text"]),ka=new Map(Fh.map(e=>[e.optionKey,e.canonical]));function m$(e,t){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,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function u$(e,t){let n=e.default_status;if(n!==void 0){let r=de(n,t);if(r)return r}return t.open_status}function Pl(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid created_at timestamp "${e}"`,m.USAGE);return new Date(n).toISOString()}var p$=ks();function vb(e){if(ht(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i};co(t.template)&&(t.template=void 0);let r=new Set([...ka.keys(),"rank"]);for(let o of r){if(ht(e,o))continue;let i=t[o];if(typeof i!="string"||!co(i))continue;let s=o==="rank"?"order":ka.get(o)??o;n(s),t[o]=void 0}return ue(e,As(t,p$))}function He(e){if(e!==void 0)return e}var hb=["id","kind","type","author","created_at","source_kind"],Sa=["path","scope","note"];function f$(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(i=>{let s=i.trim(),a=Aa(s,hb);Fo(s,a);let c=a?_e(i,"--dep"):{id:s,kind:"related"};a&&rt(c,"--dep",hb);let d=He(c.id),u=_$(He(c.kind??c.type));if(!d||!u)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",m.USAGE);if(d.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,m.USAGE);let p=_o(He(c.source_kind)),f=Xn(c.author,"--dep author");return{id:ho(d,n,p),kind:Ar(u),created_at:Pl(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function _$(e){return typeof e=="string"?st().resolve(e)?.kind??e.trim():e}function Aa(e,t){return z_(e,t)?!0:es(e)}function Fn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Ne(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(s=>{let a=s.trim(),c=()=>{if(a.length===0)throw new l(`${e} requires text=<value>`,m.USAGE);return{created_at:n,author:r,text:a}},d;try{d=_e(s,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(d).filter(f=>!l$.has(f)).length>0)return{created_at:Pl(d.created_at,n),author:Xn(d.author,`${e} author`)??r,text:a};let p=d.text??"";if(p==="")throw new l(`${e} requires text=<value>`,m.USAGE);return{created_at:Pl(d.created_at,n),author:Xn(d.author,`${e} author`)??r,text:p}}),explicitEmpty:!1})}function Ll(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),o=Aa(r,Sa);fd(r,"--file","file path",o);let i=o?_e(n,"--file"):{path:r};if(o&&rt(i,"--file",Sa),!i.path)throw new l("--file requires path=<value> or a bare file path",m.USAGE);return{path:i.path,scope:at(i.scope??"project",St,"file scope"),note:He(i.note)}}),explicitEmpty:!1})}function Nl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),o=Aa(r,$t);fd(r,"--test","test command",o);let i=o?rs(_e(n,"--test"),"--test"):{command:r},s=He(i.command),a=He(i.path);if(!s)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);let c=He(i.timeout_seconds),d=He(i.timeout);if(c&&d&&c!==d)throw new l("--test timeout and timeout_seconds must match when both are provided",m.USAGE);let u=c??d;return{command:s,path:a,scope:at(i.scope??"project",St,"test scope"),timeout_seconds:u?ge(u,"timeout_seconds"):void 0,pm_context_mode:ea(i.pm_context_mode,"--test"),workspace_context_mode:On(i.workspace_context_mode,"--test"),env_set:Ro(i.env_set,"--test"),env_clear:xo(i.env_clear,"--test"),shared_host_safe:Zs(i.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:$n(i.assert_stdout_contains),assert_stdout_regex:Sr(i.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:$n(i.assert_stderr_contains),assert_stderr_regex:Sr(i.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:ta(i.assert_stdout_min_lines,"--test"),assert_json_field_equals:na(i.assert_json_field_equals,"--test"),assert_json_field_gte:ra(i.assert_json_field_gte,"--test"),note:He(i.note),phase:br(i.phase,"--test")}}),explicitEmpty:!1})}function Fl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),o=Aa(r,Sa),i=o?_e(n,"--doc"):{path:r};if(o&&rt(i,"--doc",Sa),!i.path)throw new l("--doc requires path=<value> or a bare doc path",m.USAGE);return{path:i.path,scope:at(i.scope??"project",St,"doc scope"),note:He(i.note)}}),explicitEmpty:!1})}function h$(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--reminder","Use --clear-reminders to clear reminders."),{values:wa(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function g$(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--event","Use --clear-events to clear linked events."),{values:va(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function y$(e,t,n,r=[]){let o=[...ri.filter(i=>e[i]!==void 0),...r.filter(i=>e[i]!==void 0),...t.length>0?["body"]:[],...n.map(i=>`unset:${i}`)];return Array.from(new Set(o))}function w$(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function gb(e,t,n){let r=Mr("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,m.CONFLICT);return r}function v$(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function bb(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function b$(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(gb(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(gb(r,e.name,"required_create_repeatables"));return n}function k$(e,t,n,r){for(let o of e)if(!(!bb(t,o)&&!n.has(o)))throw new l(`Option ${Oe("create",o)} is disabled for type "${r}" by command_option_policies`,m.USAGE)}function S$(e,t,n){if(t!=="strict")return;let r=e.filter(i=>n.has(i)&&!Ol(i));if(r.length===0)return;let o=[...new Set(r.map(i=>Oe("create",i)))].sort((i,s)=>i.localeCompare(s));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset cannot satisfy a required scalar option (only repeatable options accept an explicit --clear-* empty set)`,m.USAGE)}function A$(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:ba(e),explicitEmpty:!1})}async function E$(e){return await ts(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function C$(e){return Ot(e)?await E$(e):e}function T$(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${c$.join(", ")}`,m.USAGE)}function R$(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new l("--schedule-preset must not be empty",m.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new l(`Invalid --schedule-preset value "${e}". Allowed: ${d$.join(", ")}`,m.USAGE)}function x$(e,t,n){let r=T$(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",m.USAGE);return"progressive"}function I$(e,t,n,r,o,i){let s=e.name,a=v$(t),c=b$(e,n),d=Bn(e,"create",c);if(d.errors.length>0)throw new l(d.errors.join("; "),m.CONFLICT);k$(d.disabled,a,r,s),S$(d.required,n,r);let u=f=>f==="author"&&o!=="unknown"||f==="status"&&e.default_status!==void 0||i.has(f)||r.has(f)&&Ol(f)?!0:bb(a,f),p=d.required.filter(f=>!u(f));return[...new Set(p.map(f=>Oe("create",f)))].sort((f,h)=>f.localeCompare(h))}var kb=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function O$(e,t){let n=[];for(let r of e){let o=r.match(kb);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function $$(e,t){return e.filter(n=>{let r=n.match(kb);return!r||r[2]!==t})}function P$(e,t,n,r){let o=$$(e,t);if(o.length===0)return;let i=Sb(n,[],[],r.open_status);throw new l(o.join("; "),m.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[i],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function L$(e,t){let r=e.options.find(o=>o.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function N$(e,t,n){let r=e.split("/")[0];switch(r){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[r,'"<value>"']}}function Sb(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],i=["--status","--priority","--message"],s=[...new Set([...i,...t])],a=new Set(["--title","--description","--type"]);for(let c of s){if(a.has(c))continue;let d=Eb[c];o.push(...d?[d]:N$(c,e.name,r)),a.add(c)}for(let c of n){let d=L$(e,c);o.push("--type-option",`${c}=${d}`)}return o.join(" ")}function Ml(e,t,n="cli"){let r=e?.trim();if(!r){let o=n==="sdk";throw t==="--title"?e!==void 0?new l(o?"Title cannot be empty or whitespace-only. Retry: pass a non-empty title.":"Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",m.USAGE):new l(o?'Missing required option title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass title (example: client.create({ type: "Issue", title: "Fix login bug" })).':'Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',m.USAGE):new l(`Missing required option ${o?tr("sdk",t.replace(/^--/u,"")):t}`,m.USAGE)}return r}function F$(e,t,n){let r={};for(let[o,i]of Object.entries(e))r[o]=Array.isArray(i)?[...i]:i;for(let[o,i]of Object.entries(t))i!==void 0&&(r[o]=Array.isArray(i)?[...i]:i);return M$(r,t,n),ue(t,r)}function M$(e,t,n){let r=[...Cd(t.unset,n).optionKeys,...Zv(t.defer,n?.definitions)].flatMap(o=>o==="order"?[o,"rank"]:o==="tags"?[o,"addTags"]:[o]);for(let o of r)Reflect.get(t,o)===void 0&&Reflect.deleteProperty(e,o)}function D$(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function U$(){let e=I();return e?e.commands.some(t=>t.action==="templates-show"||D$(t.command)==="templates show"):!1}function j$(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new l(`Templates package returned invalid payload for template "${t}". Expected an options object.`,m.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Templates package returned invalid options for template "${t}".`,m.GENERIC_FAILURE);let r={};for(let[o,i]of Object.entries(n)){if(typeof i=="string"||typeof i=="number"||typeof i=="boolean"){r[o]=i;continue}if(Array.isArray(i)&&i.every(s=>typeof s=="string")){r[o]=[...i];continue}throw new l(`Templates package returned unsupported option value for "${o}" in template "${t}".`,m.GENERIC_FAILURE)}return r}async function G$(e,t,n){if(!U$())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",m.USAGE);let r=await Vi({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled)throw Object.hasOwn(r,"cause")?vs("templates show",r):new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.`,m.USAGE);return j$(r.result,e)}function X(e,t,n){return e.has(t)||n===void 0?void 0:He(n)}function Nn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var q$=new Set(["milestone","meeting","reminder","event"]);function Ab(e,t,n,r){let o=t!==void 0,i=n!==void 0&&n.length>0,s=r!==void 0&&r.length>0;return q$.has(e.toLowerCase())&&!o&&!i&&!s}function K$(e,t,n,r,o){let i=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&i.push(`event_without_schedule:${t}:no_time_set`),Ab(e,n,r,o)&&i.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),i}async function z$(e,t,n,r){if(t.inheritFocus!==!0||e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await Hi(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function H$(e,t,n,r,o,i,s){let a=lr(us(o,s),t.id_prefix);if(Ji(a))return{parent:a,warnings:[]};if(fs(r,a,t.id_prefix,s),await j(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let d=Le(a,t.id_prefix);return{parent:a,warnings:ps(d,i,s).warnings}}async function B$(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await H$(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy,e.audience)}async function W$(e){if(e.explicitId===void 0)return ro(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});yt(e.explicitId,"create","id");let t=e.explicitId.trim();if(t.length===0||th(t))throw new l("--id must not be empty or use a placeholder token",m.USAGE);let n=Le(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",m.USAGE);return n}function yb(e,t,n,r,o,i){let s=X(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let a=_s(r,s,o,i);return{value:a.value,warnings:a.warnings}}async function V$(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:i,status:s,statusExplicit:a,nowValue:c,author:d}=e,u=e.dependencyValues;if(i===void 0)return{dependencyValues:u,status:s};let p=Le(i,n.id_prefix),f=await j(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:s};if((u??[]).some(g=>g.id===f.id&&g.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:s};let _=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((g,y)=>g.localeCompare(y))[0]??o.open_status;return{dependencyValues:u,status:_}}function Y$(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let o=t.governance.create_default_type?.trim();if(o&&o.length>0&&Ce(o,n)){e.type=o;return}Ce("Task",n)&&(e.type="Task")}function J$(e,t){return e.options.filter(n=>Mr("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,m.USAGE)})}async function X$(e,t,n,r,o){let i=e,s=[];if(i.template!==void 0){let _=i.template.trim();if(_.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",m.USAGE);let g=await G$(_,t,n);i=vb(mo("create",F$(g,i,et(r.schema))))}if(i.type===void 0&&Y$(i,r,o),i.type===void 0)throw new l("Missing required option --type <value>",m.USAGE);let a=Ce(i.type,o);if(!a){let _=rh(i.type),g=_?Ce(_,o):void 0;if(g)s.push(`type_coercion:${i.type.trim()}:${g}`),i.type=g,a=g;else throw new l(zt(i.type,o.types,Ht(n,r.schema)),m.USAGE)}let c=si(a,o);if(!c)throw new l(`Invalid type value "${i.type}"`,m.USAGE);let d=c.name,u=J$(c,i),p=u.map(_=>`${_.key}=${String(i[_.key])}`);if(p.length>0){i.typeOption=[...p,...i.typeOption??[]];for(let _ of u)delete i[_.key]}let f=R$(i.schedulePreset);if(f!==void 0&&!wb.has(d))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,m.USAGE);let h=x$(i.createMode,f,r.governance.create_mode_default);return{resolvedOptions:i,typeDefinition:c,type:d,schedulePreset:f,createMode:h,warnings:s}}function Q$(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let i of o)if(i.enabled){if(i.values&&i.values.length>0)throw new l(`Cannot combine ${i.clearFlag} with ${i.valueFlag}`,m.USAGE);n.add(i.metadataKey),r.add(i.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function Z$(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=ka.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Oe("create",r)}`,m.USAGE)}}function eP(e){if(ht(e))return;let t=(n,r)=>{if(ht(e,r))return;let o=ka.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;Ss(n,Oe("create",r),i)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function tP(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,m.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,m.USAGE)}var Eb={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function nP(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:i,type:s,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(_=>{let g=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${g}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),u=[Sb(n,r,o,i),...d.map(_=>_.example)].join(" "),p=[`Run "pm create --help --type ${s}" for type-aware required option guidance.`,...t.filter(_=>_==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+s+").")];a==="strict"&&(p.push('For staged onboarding, retry with "--create-mode progressive".'),wb.has(s)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&p.push(`Required custom field formats: ${d.map(_=>_.description).join("; ")}.`);let f=[...new Set(t.flatMap(_=>{let g=_.split(" ",1)[0],y=Eb[g];return y?[y]:[]}))];f.length>0&&p.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let h=t.length===1?`Missing required option ${t[0]} for type "${s}"`:`Missing required options ${t.join(", ")} for type "${s}"`;throw new l(h,m.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${s}" in one invocation.`,examples:[...f.map(_=>`pm create --type ${s} ${_} ...`),u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function rP(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",m.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Wt(t.tags):[];return rr(n,t.addTags)}function oP(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new l("--order and --rank must match when both are provided",m.USAGE);let n=t.order??t.rank,r=Nn(e,"order",n,o=>ge(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",m.USAGE);return r}function iP(e,t,n,r,o,i){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",m.USAGE);let s=e!==t.close_status?void 0:r.completedAt===void 0?i:se(r.completedAt,new Date(i),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:s,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:Sl(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:s,warnings:[]}}async function sP(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:i,author:s,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:h,allowDuplicate:_}=e,g=Et(t,n,r,o.item_format,i.type_to_folder),y=Ze(t,r),w=st(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(x=>js(x.kind,w)),k=await ua({pmRoot:t,author:s,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:v}),S=v,T=[];try{let x=await ft(t,r,o.locks.ttl_seconds,s,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let F=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await ye(t,o.item_format,i.type_to_folder,void 0,o.schema):void 0,L=await j(t,r,o.id_prefix,o.item_format,i.type_to_folder);if(L)throw new l(`Item "${r}" already exists`,m.CONFLICT,{code:"item_already_exists",id:L.id,path:L.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${L.id}.`]});if(F){Gs(F,[...F,c.metadata],w);let re=D(o.schema);Is(F,[...F,c.metadata],r,J=>le(J,re),w)}let H=await vn({pmRoot:t,settings:o,operation:"create",author:s,before:null,after:c});await yn({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,author:s,sdk:bn({pmRoot:t,settings:o,typeToFolder:i.type_to_folder})});let B=await Xt(t,s,{required:o.governance.duplicate_detection_mode==="strict"&&_!==!0}),Y=[];try{o.governance.duplicate_detection_mode==="strict"&&_!==!0&&await ur(h,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await x.fence(async()=>{await ae(g,ut(c,{format:o.item_format,schema:o.schema,extensionFieldNames:a}));try{let re=qe({nowIso:f,author:s,op:"create",before:d,after:c,message:u,context:H.decisions.length===0?void 0:{workflow_policies:H.decisions}});await Bt(y,re)}catch(re){throw await Hn(g),re}}),S&&(await k(),S=!1),Y=await Qt({pmRoot:t,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:g,document:c})}finally{await B()}T=[...H.warnings,...F?Us(F,[...F,c.metadata],r):[],...Y,...await Q({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:p}),...await Q({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:p})],Qn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:gn(c.metadata,p),changed_fields:p})}finally{await x.release()}}finally{S&&await k()}return T}async function rn(e,t){let n=mo("create",e),r=gt(n),o=vb(await C$(n)),i=E(process.cwd(),t.path);await O(i);let s=await A(i),a=D(s.schema),c=et(s.schema),d=$(s,I()),u=await X$(o,t,i,s,d);o=u.resolvedOptions;let{typeDefinition:p,type:f,createMode:h}=u,_=Cd(o.unset,c),{explicitUnsets:g,clearOptionKeys:y}=Q$(o,_);Z$(o,_),eP(o);let w=Xv(o,r);xl(w,o,_.metadataKeys,r);let v=R(He(o.author),s.author_default),k=I$(p,o,h,y,v,w.optionKeys),S=C(),T=f$(o.dep,S,s.id_prefix,v),x=Fn("--comment",o.comment,S,v),F=Fn("--note",o.note,S,v),L=Fn("--learning",o.learning,S,v),H=Ll(o.file),B=Nl(o.test);B.values=await fr(B.values,v,S);let Y=Fl(o.doc),re=h$(o.reminder,S),J=g$(o.event,S),Gt=A$(o.typeOption),G=Dr(f,Gt.values,d),he=I(),qt=Ue(he),cn=oi(o.field,he,ga,ya(c,"create",o)),Ye=Bf(o,c,f);xl(w,o,_.metadataKeys,r,Ye.values),Ye.missing_required_flags=eb(Ye.missing_required_flags,w,c.definitions,f,o);let Jo=new Set(Ye.missing_required_flags),dn=c.definitions.filter(ie=>Jo.has(`--${ie.cli_flag}`));tP(cn,Ye,_);let ic=O$(G.errors,f),Xo=ic.map(ie=>`--type-option ${ie}=<value>`),sc=[...new Set([...k,...Xo,...Ye.missing_required_flags])].sort((ie,hc)=>ie.localeCompare(hc));nP({combinedMissingFlags:sc,typeDefinition:p,missingRequiredCreateFlags:k,missingRequiredTypeOptionKeys:ic,openStatus:a.open_status,type:f,createMode:h,missingRequiredRuntimeFields:dn}),P$(G.errors,f,p,a);let Je=await W$({pmRoot:i,settings:s,typeRegistry:d,explicitId:o.id}),kt=o.status!==void 0?m$(o.status,a):u$(p,a),Xe=o.priority!==void 0?Jt(o.priority):2,N=_.metadataKeys,Qo=rP(N,o),nt=Nn(N,"deadline",o.deadline,ie=>se(ie,new Date(S),"deadline")),ac=Nn(N,"estimated_minutes",o.estimatedMinutes,ie=>or(ie,"estimated-minutes")),Qe=X(N,"acceptance_criteria",o.acceptanceCriteria),cc=X(N,"definition_of_ready",o.definitionOfReady),Zo=oP(N,o),dc=X(N,"goal",o.goal),ei=X(N,"objective",o.objective),tE=X(N,"value",o.value),nE=X(N,"impact",o.impact),rE=X(N,"outcome",o.outcome),oE=X(N,"why_now",o.whyNow),iE=X(N,"assignee",o.assignee),sE=N.has("author")?void 0:He(o.author)??v,aE=X(N,"parent",o.parent),hu=await z$(aE,o,N,i),lc=hu.parent,cE=hu.parentSource,dE=X(N,"reviewer",o.reviewer),lE=Nn(N,"risk",o.risk,ie=>at(pa(ie),Lr,"risk")),mE=Nn(N,"confidence",o.confidence,ie=>_a(ie)),uE=o.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,gu=s.validation.sprint_release_format,ln=[...u.warnings,...K$(f,Je,nt,re.values,J.values)],yu=await B$({itemId:Je,parent:lc,pmRoot:i,settings:s,typeRegistry:d,policy:uE,audience:r});lc=yu.parent,ln.push(...yu.warnings);let wu=yb(N,"sprint",o.sprint,"sprint",gu,r),pE=wu.value;ln.push(...wu.warnings);let vu=yb(N,"release",o.release,"release",gu,r),fE=vu.value;ln.push(...vu.warnings);let bu=X(N,"blocked_by",o.blockedBy),ku=await V$({pmRoot:i,settings:s,typeRegistry:d,statusRegistry:a,blockedBy:bu,dependencyValues:T.values,status:kt,statusExplicit:o.status!==void 0,nowValue:S,author:v}),mc=ku.dependencyValues;Mo(Je,mc),ln.push(...await Ln({pmRoot:i,dependencies:mc,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:d.type_to_folder,allowUnresolved:o.allowUnresolvedDeps,holders:[{id:Je,createdAt:S}],schema:s.schema})),kt=ku.status;let _E=X(N,"blocked_reason",o.blockedReason),hE=X(N,"unblock_note",o.unblockNote),gE=X(N,"reporter",o.reporter),yE=Nn(N,"severity",o.severity,ie=>at(fa(ie),Nr,"severity")),wE=X(N,"environment",o.environment),vE=X(N,"repro_steps",o.reproSteps),Su=X(N,"resolution",o.resolution),bE=X(N,"expected_result",o.expectedResult),kE=X(N,"actual_result",o.actualResult),SE=X(N,"affected_version",o.affectedVersion),AE=X(N,"fixed_version",o.fixedVersion),EE=X(N,"component",o.component),CE=Nn(N,"regression",o.regression,ie=>ha(ie)),TE=X(N,"customer_impact",o.customerImpact),uc=Ml(o.title,"--title",r),pc=o.description??"",ti=o.body??"",Au=await ur({title:uc,description:pc,body:ti},{pmRoot:i,mode:s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:o.allowDuplicate});ln.push(...$s(Au));let fc=iP(kt,a,s,o,Su,S),RE=fc.closeReason,xE=kt===a.close_status?S:void 0,IE=fc.completedAt;ln.push(...fc.warnings);let zn=Yc({id:Je,title:uc,description:pc,type:f,type_options:G.normalized,status:kt,closed_at:xE,completed_at:IE,close_reason:RE,priority:Xe,tags:Qo,created_at:S,updated_at:S,deadline:nt,assignee:iE,author:sE,estimated_minutes:ac,acceptance_criteria:Qe,deferred_fields:Qv(w),definition_of_ready:cc,order:Zo,goal:dc,objective:ei,value:tE,impact:nE,outcome:rE,why_now:oE,parent:lc,reviewer:dE,risk:lE,confidence:mE,sprint:pE,release:fE,blocked_by:bu,blocked_reason:_E,unblock_note:hE,reporter:gE,severity:yE,environment:wE,repro_steps:vE,resolution:Su,expected_result:bE,actual_result:kE,affected_version:SE,fixed_version:AE,component:EE,regression:CE,customer_impact:TE,dependencies:mc,comments:x.values,notes:F.values,learnings:L.values,files:H.values,tests:B.values,docs:Y.values,reminders:re.values,events:J.values,...cn,...Ye.values});jf(zn),ii(zn,he),vd(zn,i);let OE=pt({metadata:zn,body:ti},{schema:s.schema,extensionFieldNames:qt}),$E={metadata:{},body:""},Eu=[...g].sort((ie,hc)=>ie.localeCompare(hc)),PE=w$(o.message,Eu),Cu=y$(zn,ti,Eu,[...Object.keys(cn),...Object.keys(Ye.values??{})]),LE=await sP({pmRoot:i,type:f,id:Je,settings:s,typeRegistry:d,author:v,extensionFieldNames:qt,afterDocument:OE,beforeDocument:$E,historyMessage:PE,changedFields:Cu,nowValue:S,similarityCandidate:{title:uc,description:pc,body:ti},allowDuplicate:o.allowDuplicate}),_c=structuredClone(zn);h==="strict"&&g.has("dependencies")&&(_c.dependencies=[]);let NE=ib(Je,f,kt,a);return Ab(f,nt,re.values,J.values)&&P_(`[pm] warning: ${f} '${Je}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Je} --deadline <ISO>' or 'pm update ${Je} --event "start=<ISO>,end=<ISO>"'.`),{item:_c,changed_fields:Cu,warnings:[...lo("create",o,r==="sdk",_c),...ln,...LE],...Object.fromEntries([["parent_source",cE],["next_transition",NE],["similarity_advisory",Au]].filter(ie=>ie[1]!==void 0))}}import Ea from"node:path";async function Dl(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=await _h({pmRoot:r,settings:o,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),a=s.targetPath?Ea.relative(r,s.targetPath).split(Ea.sep).join("/"):void 0;return{item:s.item,changed_fields:s.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:s.item.status,...a?{target_path:a}:{},history_retained:Ea.relative(r,Ze(r,s.item.id)).split(Ea.sep).join("/"),tombstone_retention:"retain_append_only",warnings:s.warnings}}async function aP(e){await O(e)}async function Ul(e,t,n){let r=E(process.cwd(),n.path);if(await aP(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",m.USAGE);let p=await A(r),f=hn(R(void 0,p.author_default));return await e_(r),await Kd({pmRoot:r,settings:p,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await Hi(r);if(p===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let f=await cP(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let i=await A(r),s=$(i,I()),a=await j(r,e,i.id_prefix,i.item_format,s.type_to_folder);if(!a)throw await it(r,e,i.id_prefix,s.type_to_folder);let c=Le(a.id,i.id_prefix),d=await te(a,{schema:i.schema}),u=Cb(d.document.metadata.title);return await Zf(r,c),await Kd({pmRoot:r,settings:i,principal:hn(R(void 0,i.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function cP(e,t){let n=await A(e),r=$(n,I()),o=await j(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let i=await te(o,{schema:n.schema});return Cb(i.document.metadata.title)}function Cb(e){return e.trim().length>0?e:null}var Tb="terminal_state_unchanged";function Rb(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function dP(e,t){return de(e,t)===t.close_status}function lP(e){let t=n=>Nh.includes(n.trim().toLowerCase());return Mh(e.unset??[],t).some(t)}function xb(e){!e.settings.governance.require_close_reason||!lP(e.options)||No({explicit:e.options.closeReason},!0)}function jl(e,t,n,r=!1){if(!dP(e.status,n))return!1;let o=Rb(t.closeReason);return r&&t.closeReason!==void 0&&o===void 0||o!==void 0&&o!==Rb(e.close_reason)?!1:t.completedAt===void 0||se(t.completedAt,new Date,"completed-at")===e.completed_at}async function Ib(e){let t=await j(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await it(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await te(t,{schema:e.settings.schema});return n.metadata}async function Ob(e,t,n,r,o){if(n.length===0)return{item:t,changed_fields:[],warnings:[...e.workflowTransitionWarnings,Tb]};let i=ue(e.options,{...e.options,status:void 0,closeReason:void 0,completedAt:void 0}),s=await r(e.id,i,e.global);return jl(s.item,e.options,e.statusRegistry,e.settings.governance.require_close_reason)?{item:s.item,changed_fields:s.changed_fields,warnings:[...e.workflowTransitionWarnings,...s.warnings,Tb]}:o(s)}function Ca(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),i=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,i].join("\0")}function Gl(e,t){return!(t.id!==void 0&&e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function $b(e,t,n){let r=t.filter(o=>!e.some(i=>Gl(i,o)));if(r.length!==0)throw new l(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,m.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r.map(o=>({...o,id:o.id??"*"})),available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function Pb(e,t){if(!Array.isArray(e)||e.length===0)return;let n=i=>(Array.isArray(i)?i:[]).filter(s=>typeof s=="object"&&s!==null&&typeof s.id=="string"),r=new Map;for(let i of n(t)){let s=Ca(i);r.set(s,(r.get(s)??0)+1)}let o=[];for(let i of n(e)){let s=Ca(i),a=r.get(s)??0;a>0?r.set(s,a-1):o.push(`${i.id}/${i.kind}`)}return o.length>0?o.join(","):void 0}var mP=(()=>{let e=new Map;for(let t of Es)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Ta=new Map(Es.map(e=>[e.optionKey,e.canonical])),uP=Es.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),pP=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),fP=ks({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function qb(e){if(ht(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i},r=new Set([...Ta.keys(),"rank"]);for(let o of r){if(ht(e,o))continue;let i=t[o];if(typeof i!="string"||!co(i))continue;let s=o==="rank"?"order":Ta.get(o)??o;n(s),t[o]=void 0}return ue(e,As(t,fP))}function Hl(e,t,n,r=["update"]){return[...Bl([...e],t,n,r).metadataKeys]}function Bl(e,t,n=[],r=["update"]){return Dh({raw:e,supportedFields:uP,resolveDefinition:o=>{let i=n.find(a=>{let c=a.toLowerCase();return c===o||c.replaceAll("_","-")===o||c.replaceAll("-","_")===o});return mP.get(o)??r.map(a=>Ed(o,a,t)).find(a=>a!==void 0)??(i?{optionKey:"field",metadataKey:i}:void 0)}})}var Lb=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function Nb(e){let t=e.disallowedFlags.flatMap(r=>{let o=Lb.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=Lb.get(r);return o?[`Replace ${r} with: ${o(e.id)}`]:[]});return new l(e.message,m.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function _P(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new l("Choose only one package-provided ownership bypass mode.",m.USAGE);let i=(c,d,u)=>{c&&u.push(d)};if(o){let c=[];if(i(t.title!==void 0,"--title",c),i(t.description!==void 0,"--description",c),i(t.body!==void 0,"--body",c),i(t.status!==void 0,"--status",c),i(t.closeReason!==void 0,"--close-reason",c),i(t.priority!==void 0,"--priority",c),i(t.type!==void 0,"--type",c),i(t.tags!==void 0,"--tags",c),i(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),i(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),i(t.deadline!==void 0,"--deadline",c),i(t.estimatedMinutes!==void 0,"--estimate",c),i(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),i(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),i(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),i(t.definitionOfReady!==void 0,"--definition-of-ready",c),i(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),i(t.goal!==void 0,"--goal",c),i(t.objective!==void 0,"--objective",c),i(t.value!==void 0,"--value",c),i(t.impact!==void 0,"--impact",c),i(t.outcome!==void 0,"--outcome",c),i(t.whyNow!==void 0,"--why-now",c),i(t.assignee!==void 0,"--assignee",c),i(t.parent!==void 0,"--parent",c),i(t.reviewer!==void 0,"--reviewer",c),i(t.risk!==void 0,"--risk",c),i(t.confidence!==void 0,"--confidence",c),i(t.sprint!==void 0,"--sprint",c),i(t.release!==void 0,"--release",c),i(t.blockedBy!==void 0,"--blocked-by",c),i(t.blockedReason!==void 0,"--blocked-reason",c),i(t.unblockNote!==void 0,"--unblock-note",c),i(t.reporter!==void 0,"--reporter",c),i(t.severity!==void 0,"--severity",c),i(t.environment!==void 0,"--environment",c),i(t.reproSteps!==void 0,"--repro-steps",c),i(t.resolution!==void 0,"--resolution",c),i(t.expectedResult!==void 0,"--expected-result",c),i(t.actualResult!==void 0,"--actual-result",c),i(t.affectedVersion!==void 0,"--affected-version",c),i(t.fixedVersion!==void 0,"--fixed-version",c),i(t.component!==void 0,"--component",c),i(t.regression!==void 0,"--regression",c),i(t.customerImpact!==void 0,"--customer-impact",c),i(t.depRemove!==void 0,"--dep-remove",c),i(t.replaceDeps===!0,"--replace-deps",c),i(t.replaceTests===!0,"--replace-tests",c),i(t.replaceFiles===!0,"--replace-files",c),i(t.replaceDocs===!0,"--replace-docs",c),i(t.comment!==void 0,"--comment",c),i(t.note!==void 0,"--note",c),i(t.learning!==void 0,"--learning",c),i(t.file!==void 0,"--file",c),i(t.test!==void 0,"--test",c),i(t.doc!==void 0,"--doc",c),i(t.reminder!==void 0,"--reminder",c),i(t.event!==void 0,"--event",c),i(t.typeOption!==void 0,"--type-option",c),i(t.clearDeps===!0,"--clear-deps",c),i(t.clearComments===!0,"--clear-comments",c),i(t.clearNotes===!0,"--clear-notes",c),i(t.clearLearnings===!0,"--clear-learnings",c),i(t.clearFiles===!0,"--clear-files",c),i(t.clearTests===!0,"--clear-tests",c),i(t.clearDocs===!0,"--clear-docs",c),i(t.clearReminders===!0,"--clear-reminders",c),i(t.clearEvents===!0,"--clear-events",c),i(t.clearTypeOptions===!0,"--clear-type-options",c),i(t.force===!0,"--force",c),i(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",m.USAGE);if(c.length>0)throw Nb({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let s=[];i(t.status!==void 0,"--status",s),i(t.closeReason!==void 0,"--close-reason",s),i(t.assignee!==void 0,"--assignee",s),i(t.parent!==void 0,"--parent",s),i(t.blockedBy!==void 0,"--blocked-by",s),i(t.blockedReason!==void 0,"--blocked-reason",s),i(t.unblockNote!==void 0,"--unblock-note",s),i(t.dep!==void 0,"--dep",s),i(t.depRemove!==void 0,"--dep-remove",s),i(t.replaceDeps===!0,"--replace-deps",s),i(t.replaceTests===!0,"--replace-tests",s),i(t.replaceFiles===!0,"--replace-files",s),i(t.replaceDocs===!0,"--replace-docs",s),i(t.note!==void 0,"--note",s),i(t.learning!==void 0,"--learning",s),i(t.test!==void 0,"--test",s),i(t.reminder!==void 0,"--reminder",s),i(t.event!==void 0,"--event",s),i(t.clearDeps===!0,"--clear-deps",s),i(t.clearComments===!0,"--clear-comments",s),i(t.clearNotes===!0,"--clear-notes",s),i(t.clearLearnings===!0,"--clear-learnings",s),i(t.clearFiles===!0,"--clear-files",s),i(t.clearTests===!0,"--clear-tests",s),i(t.clearDocs===!0,"--clear-docs",s),i(t.clearReminders===!0,"--clear-reminders",s),i(t.clearEvents===!0,"--clear-events",s);let a=[...n].filter(c=>pP.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(s.push(...a),s.length>0)throw Nb({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${s.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:s})}function hP(e,t){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,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function gP(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:Kb(e)}function Kb(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new l(`Invalid dependency created_at timestamp "${e}"`,m.USAGE);return new Date(t).toISOString()}function Mn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var yP=["id","kind","type","author","created_at","source_kind"],wP=["id","kind","type","author","created_at","source_kind"];function zb(e){return e.startsWith("```")||e.includes(`
|
|
22
|
-
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:es(e)}function Wl(e){return typeof e=="string"?st().resolve(e)?.kind??e.trim():e}function xa(e,t,n,r){return e?(Ne(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(i=>{let s=i.trim(),a=zb(s);Fo(s,a);let c=a?_e(i,"--dep"):{id:s,kind:"related"};a&&rt(c,"--dep",yP);let d=c.id?.trim(),u=Wl((c.kind??c.type)?.trim());if(!d||!u)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",m.USAGE);if(d.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,m.USAGE);let p=_o(Mn(c.source_kind)),f=Mn(c.author);return{id:ho(d,t,p),kind:Ar(u),created_at:gP(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function vP(e,t){return e?(Ne(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new l("--dep-remove requires id or key/value selectors",m.USAGE);let o=zb(r);if(Fo(r,o,"--dep-remove"),o){let i=_e(r,"--dep-remove");rt(i,"--dep-remove",wP);let s=i.id?.trim();if(i.id===void 0)return bP(i);if(!s)throw new l("--dep-remove key/value form requires a non-empty id=<value>",m.USAGE);if(s.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${s}"`,m.USAGE);let a=Wl(Mn(i.kind??i.type)),c=_o(Mn(i.source_kind)),d=Mn(i.author),u=Mn(i.created_at);return{id:ho(s,t,c),kind:a?Ar(a):void 0,source_kind:c,author:d,created_at:u?Kb(u):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,m.USAGE);return{id:Le(r,t)}})):[]}function bP(e){let t=Wl(Mn(e.kind??e.type)),n=Object.keys(e).filter(r=>r!=="kind"&&r!=="type");if(!t||n.length>0||e.kind!==void 0&&e.type!==void 0)throw new l("--dep-remove key/value form requires id=<value>, or kind=<kind> alone to remove every row of that kind",m.USAGE);return{kind:Ar(t)}}function Ra(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function kP(e,t,n,r,o){let i=[...e??[]],s=!1;if(t===void 0){let a=i.filter(c=>o===void 0||!Qd(c,o.value,o.idPrefix));return a.length!==i.length&&(i=a,s=!0),s?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}return i.some(a=>a.kind==="blocked_by"&&a.id===t)||(i.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}async function SP(e,t,n,r,o,i){if(e===void 0||t)return{};let s=e.trim();if(s.length===0)return{};let a=await j(n,Le(s,r),r,o,i);return a?{id:a.id}:{unresolved:s}}function AP(e,t,n,r,o,i){let s=kP(e.dependencies,t,n,r,i);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,o.includes("dependencies")||o.push("dependencies"))}function EP(e){return`${e.path}::${e.scope}`}function CP(e){return`${e.path}::${e.scope}`}function TP(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function Fb(e,t){let n=Mr("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,m.CONFLICT);return n}function RP(e,t,n){let r=new Set,o=(i,s)=>{s&&r.add(i)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let i=Bl(e.unset,t,n,e.runtimeFieldCommands);for(let s of i.optionKeys)o(s,!0)}return r}function xP(e,t,n,r,o){let i=si(e,n);if(!i)throw new l(`Invalid type value "${e}"`,m.USAGE);let s=Bn(i,"update",[]);if(s.errors.length>0)throw new l(s.errors.join("; "),m.CONFLICT);let a=RP(t,r,o);for(let c of s.disabled)if(a.has(Fb(c,e)))throw new l(`Option ${Oe("update",c)} is disabled for type "${e}" by command_option_policies`,m.USAGE);for(let c of s.required)if(!a.has(Fb(c,e)))throw new l(`Missing required option ${Oe("update",c)} for type "${e}"`,m.USAGE)}var IP=new Set(["order","rank"]),OP=xc.filter(e=>!IP.has(e)),Hb=["tags","closeReason",...OP],$P=["title","description","body","status","closeReason","completedAt","priority","type",...xc,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],PP=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>se(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>or(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],LP=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>at(pa(e),Lr,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>_a(e)}],NP=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>at(fa(e),Nr,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>ha(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function zl(e,t,n){for(let r of e){let o=t[r.optionKey],i=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!i)){if(i){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new l(`${Oe("update",String(r.optionKey))} must be a string value`,m.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function FP(e){return qb(await ts(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function Vl(e){let t=mo("update",e);return Ot(t)?await FP(t):qb(t)}function MP(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function ql(e){if(e.enabled&&(!e.values||e.values.length===0))throw new l(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,m.USAGE);if(e.enabled&&e.clearEnabled)throw new l(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,m.USAGE)}function Yl(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new l("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",m.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new l("--replace-deps requires at least one --dep entry",m.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new l("--replace-deps cannot be combined with --dep-remove",m.USAGE);ql({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),ql({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),ql({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function DP(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new l(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,m.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function UP(e){let t={};for(let n of Hb)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function jP(e,t){let n=UP(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=Ta.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Oe("update",r)}`,m.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --add-ac",m.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --remove-ac",m.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",m.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new l("Cannot combine --unset tags with --remove-tags",m.USAGE)}}function GP(e){if(ht(e))return;let t=(n,r)=>{if(ht(e,r))return;let o=Ta.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;Ss(n,Oe("update",r),i)};for(let n of Hb)t(e[n],String(n));t(e.order??e.rank,"order"),Ne(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Ne(e.event,"--event","Use --clear-events to clear linked events.")}function qP(e,t){let n={};for(let r of $P)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function KP(e){let t=await j(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await it(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await te(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function zP(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return ye(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function HP(e){e.before&&(Gs(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Is(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>le(t,e.statusRegistry),st()))}function BP(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new l("--order and --rank must match when both are provided",m.USAGE)}async function WP(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=gt(e.options),n=lr(us(e.options.parent,t),e.settings.id_prefix);if(Ji(n))return{resolvedParentValue:n,warnings:[]};if(fs(e.id,n,e.settings.id_prefix,t),await j(e.pmRoot,n,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:n,warnings:[]};let o=Le(n,e.settings.id_prefix);return{resolvedParentValue:n,warnings:ps(o,e.parentReferencePolicy,t).warnings}}function VP(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function YP(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await j(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await it(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await te(t,{schema:e.settings.schema}),r=e.options.type!==void 0?Ce(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=gr({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function JP(e){if(!e.fieldFlags.status||de(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;xb(e);let n=Object.entries(e.fieldFlags).filter(([i,s])=>s&&i!=="status"&&i!=="closeReason"&&i!=="completedAt").map(([i])=>i),r=await Ib(e);if(jl(r,e.options,e.statusRegistry,e.settings.governance.require_close_reason))return Ob(e,r,n,ct,i=>Mb(e,i));let o;if(n.length>0){let i=ue(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0});o=await ct(e.id,i,e.global)}return Mb(e,o)}async function Mb(e,t){let n=await Dt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),o=[...lo("update",e.options,gt(e.options)==="sdk",n.item),...e.workflowTransitionWarnings,...(t?.warnings??[]).filter(i=>!i.startsWith("literal_sentinel_stored:")),...n.warnings,"auto_routed_from_update_to_close"];return{item:n.item,changed_fields:[...t?.changed_fields??[],...n.changed_fields],warnings:o}}function XP(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Ml(t.title,"--title",gt(t)),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),de(e.metadata.status,n)??e.metadata.status}var QP=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function ZP(e,t){for(let n of QP)e[n]!==void 0&&(delete e[n],t.push(n))}function eL(e,t,n,r,o){let i=hP(n,t.statusRegistry);if(e.metadata.status=i,o.push("status"),i===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!le(i,t.statusRegistry)&&le(r,t.statusRegistry)&&ZP(e.metadata,o)}function tL(e,t,n,r){if(t.options.status!==void 0&&eL(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!le(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",m.USAGE);e.metadata.completed_at=se(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function nL(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new l(pd(gt(t.options),"close-reason"),m.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&le(n,t.statusRegistry)&&!le(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function rL(e,t,n,r){tL(e,t,n,r),nL(e,t,n,r)}function oL(e,t,n){let r=Ce(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=Jt(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=Ce(t.options.type,t.typeRegistry);if(!o)throw new l(zt(t.options.type,t.typeRegistry.types,Ht(t.pmRoot,t.settings.schema)),m.USAGE);e.metadata.type=o,r=o,n.push("type")}return xP(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),iL(e,t,r,n),r}function iL(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let i=ba(t.options.typeOption??[]),s=Dr(n,i,t.typeRegistry);if(s.errors.length>0)throw new l(s.errors.join("; "),m.USAGE);e.metadata.type_options=s.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let o=Dr(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,m.USAGE);e.metadata.type_options=o.normalized}function sL(e,t){let n=new Set(t.map(o=>Ra(o))),r=new Set;return e.filter(o=>{if(!n.has(Ra(o)))return!0;let i=Ca(o);return r.has(i)?!1:(r.add(i),!0)})}function aL(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=sL(r,t.dependencyUpdates.additions);let o=new Set(r.map(i=>Ra(i)));for(let i of t.dependencyUpdates.additions){let s=Ra(i);o.has(s)||(r.push(i),o.add(s))}}t.dependencyRemovals.length>0&&($b(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(i=>Gl(o,i)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function cL(e,t,n){Kl(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Kl(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Kl(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Kl(e,t,n,r,o,i){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],i.push(t))}function dL(e,t,n){Db(e,"files",t.options.file,t.fileUpdates.values,EP,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),lL(e,t,n),Db(e,"docs",t.options.doc,t.docUpdates.values,CP,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Db(e,t,n,r,o,i,s,a){if(!(n===void 0&&!s.has(t))){if(i)e.metadata[t]=r;else if(s.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(u=>o(u)));for(let u of r){let p=o(u);d.has(p)||(c.push(u),d.add(p))}e.metadata[t]=c}a.push(t)}}function lL(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Ub(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Ub([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Ub(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=TP(r);n.has(o)||(t.push(r),n.add(o))}return t}function mL(e,t,n){let r=t.options.addTags,o=t.options.removeTags,i=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||i){let s=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Wt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Zi(rr(s,r),o),n.changedFields.push("tags")}zl(PP,t.options,n),pL(e,t,n.changedFields)}function uL(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let i=Qi(nr(e.metadata.acceptance_criteria),r,o);if(i.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${i.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:i.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let s=i.criteria.join("; ");e.metadata.acceptance_criteria!==s&&(s===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=s,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function pL(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=ge(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",m.USAGE);e.metadata.order=o}n.push("order")}}function fL(e,t,n,r){_L(e,t,n.changedFields),hL(e,t,n.changedFields),zl(LP,t.options,n),jb(e,t,"sprint",r,n.changedFields),jb(e,t,"release",r,n.changedFields),gL(e,t,n.changedFields),zl(NP,t.options,n)}function _L(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new l(pd(gt(t.options),"assignee",". Use --unset assignee to clear it."),m.USAGE);Uf(r,"--assignee"),e.metadata.assignee=r}n.push("assignee")}}function hL(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function jb(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let i=_s(n,t.options[n]??"",t.settings.validation.sprint_release_format,gt(t.options));e.metadata[n]=i.value,r.push(...i.warnings)}o.push(n)}}function gL(e,t,n){if(t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by"))return;let r=t.clearItemMetadataKeys.has("blocked_by")?e.metadata.blocked_by:void 0;t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&AP(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n,{value:r,idPrefix:t.settings.id_prefix})}function yL(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=wa(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=va(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function wL(e,t,n){Gb(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),Gb(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,i]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let s=o.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(d=>d.metadata_key===o)?.cli_flag??s;throw new l(`Cannot combine --unset ${s} with --${c}`,m.USAGE)}ee(e[o],i)||(e[o]=i,n.push(o))}let r=oi(t.options.field,t.extensionRegistrations,ga,ya(t.runtimeFieldRegistry,(t.options.runtimeFieldCommands??[]).includes("update_many")?"update_many":"update",t.options));for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new l(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,m.USAGE);for(let[o,i]of Object.entries(r))ee(e[o],i)||(e[o]=i,n.push(o))}function Gb(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function vL(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(o=>{let i=t[o];return i!==void 0&&(!Array.isArray(i)||!ee(i,n[o]??[]))});if(r!==void 0)throw new l(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,m.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${r}_requires_annotation_command`,required:`Use pm ${r} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${r} with pm ${r} ${e.metadata.id}.`,`Apply the correction with pm ${r} ${e.metadata.id} --edit <index> --add <text>.`]})}function bL(e,t){vL(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,o=[],i=[],s=XP(e,t.options,t.statusRegistry,o),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};rL(e,t,s,o),oL(e,t,o),aL(e,t,o),cL(e,t,o),dL(e,t,o),mL(e,t,c),uL(e,t,c),fL(e,t,c,i),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&Mo(e.metadata.id,e.metadata.dependencies),de(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),yL(e,t,o),wL(a,t,o),ii(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys});let d=e.metadata,u=[...new Set(o)].filter(f=>f==="body"?e.body!==r:!ee(n[f],d[f])),p=Pb(n.dependencies,d.dependencies);return p!==void 0&&i.push(`dependencies_removed:${e.metadata.id}:${p}`),t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&i.push(`acceptance_criteria_replaced:${nr(n.acceptance_criteria).length}:${nr(d.acceptance_criteria).length}`),{changedFields:u,warnings:i}}async function Bb(e,t,n,r={}){yt(e,"update","id");let o=await Vl(t),i=E(process.cwd(),n.path);await O(i);let s=await A(i),a=D(s.schema),c=et(s.schema),d=I(),u=Ue(d),p=$(s,d),f=s.governance.workflow_enforcement??"off",h=f==="off"?[]:Jn(s.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(o.allowMissingParent===!0)][s.validation.parent_reference],g=Bl(o.unset,c,u,o.runtimeFieldCommands),y=new Set(g.optionKeys),w=new Set(g.metadataKeys);Yl(o),DP({definitions:MP(o),options:o,clearOptionKeys:y,clearItemMetadataKeys:w}),_P(e,o,w),jP(o,g),GP(o);let v=R(o.author,s.author_default),k=new Date,S=k.toISOString(),T=xa(o.dep,s.id_prefix,S,v);Mo(e,T.additions);let x=await Ln({pmRoot:i,dependencies:T.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:p.type_to_folder,allowUnresolved:o.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),F=vP(o.depRemove,s.id_prefix),L=Fn("--comment",o.comment,S,v),H=o.ownershipMetadataBypass===!0&&L.values?{...L,values:L.values.map(Xe=>({...Xe,author:v}))}:L,B=Fn("--note",o.note,S,v),Y=Fn("--learning",o.learning,S,v),re=Ll(o.file),J=Nl(o.test);J.values=await fr(J.values,v,S);let Gt=Fl(o.doc),G=[],he=await WP({id:e,options:o,unsetTargets:g,pmRoot:i,settings:s,typeRegistry:p,parentReferencePolicy:_}),qt=await SP(o.blockedBy,w.has("blocked_by"),i,s.id_prefix,s.item_format,p.type_to_folder),cn=qt.id,Ye=[...he.warnings,...VP(qt)],Jo=Ki(o,c,o.runtimeFieldCommands),dn=qP(o,Jo);if(!Object.values(dn).some(Boolean))return KP({pmRoot:i,id:e,settings:s,typeRegistry:p});G.push(...await YP({options:o,fieldFlags:dn,workflowEnforcement:f,typeWorkflows:h,statusRegistry:a,typeRegistry:p,pmRoot:i,id:e,settings:s}));let Xo=await JP({options:o,fieldFlags:dn,statusRegistry:a,workflowTransitionWarnings:G,global:n,id:e,pmRoot:i,settings:s,typeRegistry:p});if(Xo)return Xo;BP(o);let sc=st(),Je=dn.parent&&!w.has("parent")||T.additions.some(Xe=>js(Xe.kind,sc)),kt=await ua({pmRoot:i,author:v,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Je});try{let Xe=await zP({fieldFlags:dn,clearedMetadataKeys:w,pmRoot:i,settings:s,typeToFolder:p.type_to_folder}),N,Qo,nt=await Zt({pmRoot:i,settings:s,typeToFolder:p.type_to_folder,id:e,op:kL(o,r),author:v,message:o.message,resolveHistoryContext:()=>Qo,force:o.force,bypassAssigneeConflict:o.ownershipMetadataBypass===!0||o.ownershipDependencyBypass===!0,extensionFieldNames:u,skipNoop:!0,async mutate(Qe){let cc=Qe.metadata.status;N=SL({document:Qe,recurrenceReason:r.recurrenceReason,requestedStatus:o.status,statusRegistry:a}),Qo=N?{recurrence:N}:void 0,Xe=Xe?.map(ei=>ei.id===Qe.metadata.id?structuredClone(Qe.metadata):ei);let Zo=bL(Qe,{options:o,settings:s,typeRegistry:p,statusRegistry:a,runtimeFieldRegistry:c,extensionRegistrations:d,extensionFieldNames:u,clearItemMetadataKeys:w,dependencyUpdates:T,dependencyRemovals:F,commentUpdates:H,noteUpdates:B,learningUpdates:Y,fileUpdates:re,testUpdates:J,docUpdates:Gt,resolvedParentValue:he.resolvedParentValue,resolvedBlockedByDependencyId:cn,runtimeFieldUpdates:Jo,nowValue:k,nowIso:S,author:v,pmRoot:i});HP({before:Xe,document:Qe,statusRegistry:a});let dc=await Vs({pmRoot:i,settings:s,metadata:Qe.metadata,fromStatus:cc,registry:a,force:o.force===!0});return{...Zo,warnings:[...Zo.warnings,...dc]}}});await kt();let ac=Xe?Us(Xe,Xe.map(Qe=>Qe.id===nt.item.id?nt.item:Qe),nt.item.id):[];return{item:nt.item,changed_fields:nt.changedFields,warnings:[...lo("update",o,gt(o)==="sdk",nt.item),...G,...Ye,...x,...ac,...nt.warnings],...N===void 0?{}:{lifecycle_transition:N}}}finally{await kt()}}function kL(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function SL(e){if(e.recurrenceReason===void 0)return;let t=de(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!le(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,m.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=de(n,e.statusRegistry)??n,o=e.document.metadata,i=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(s=>{let a=o[s];return typeof a=="string"?[[s,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:i}}async function ct(e,t,n){return Bb(e,t,n)}async function Wb(e,t,n,r){yt(r,"reopen","reason");let o=await Bb(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,m.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}async function Jl(e,t,n,r){yt(e,"reopen","id"),yt(t,"reopen","reason"),Gh(n);let o=t.trim();if(o.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",m.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let i=E(process.cwd(),r.path),s=n.expectedResult?.trim();if(s!==void 0&&s.length===0)throw new l("Reopen expected result must describe the current active outcome.",m.USAGE);let a=D((await A(i)).schema),c=a.open_status,d=Nt(a),u=n.status??c,p=de(u,a)??u;if(p!==c&&p!==d)throw new l(`Reopen target status must be ${c} or ${d}; received ${u}.`,m.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([c,d])],suggested_retry:`pm item reopen ${e} "${o}" --status ${c}`,suggested_retry_args:["item","reopen",e,o,"--status",c]}});let f=await Wb(e,{status:p,expectedResult:s,unset:["close-reason","resolution",...s===void 0?["expected-result"]:[],"actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:f.item,changed_fields:f.changed_fields,warnings:f.warnings,recurrence:f.lifecycle_transition,...s===void 0?{recovery:{missing:["expected_result"],suggested_retry_args:["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"],suggested_retry:P(["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"])}}:{}}}async function Xl(e,t,n){try{return await n()}catch(r){let o=r instanceof l?r.context:{},i=new l(r instanceof Error?r.message:String(r),r instanceof l?r.exitCode:m.GENERIC_FAILURE,{...o,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${o.why?` ${o.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...o.nextSteps??[]]});throw i.cause=r,i}}async function Ql(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new l("--start cannot be combined with --next or --if-available for an explicit item",m.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let r=await A(E(process.cwd(),n.path)),o=Nt(D(r.schema));return Yy(async()=>{let i=await Co(e,t.force===!0,n,wt(t,{},["start"])),s=i.item.id,a=await Xl(s,"claim",()=>ct(s,wt(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts","takeoverStale"]),n)).catch(async c=>{throw await AL(c,i,n,t.author)});return{id:s,action:"start_task",claim:i,update:a}})}async function AL(e,t,n,r){if(!(e instanceof l)||e.code!==Ws||t.previous_assignee!==null)return e;let o=String(t.item.id);try{await Wi({pmRoot:E(process.cwd(),n.path),id:o,validate:s=>{if(s.metadata.assignee!==t.claimed_by||s.metadata.claim_principal!==t.item.claim_principal)throw new l("The claim this start took is no longer its own.",m.CONFLICT)}},()=>wr(o,!1,n,{author:r,message:"Release the claim: a blocker opened before its start could be recorded"}))}catch{return e}let i=e.cause instanceof l?e.cause:e;return new l(i.message,i.exitCode,{...i.context,why:`${i.context.why??""} A blocker opened after this start's claim, so the claim was released and no ownership remains.`.trim()})}async function Zl(e,t,n){let r=await A(E(process.cwd(),n.path)),o=D(r.schema);Hs({...t,pause:!0},o);let i=await dw(e,n,t.author),s=o.open_status,a=await i(()=>ct(e,wt(t,{status:s},["assignee","pause"]),n)),c=a.item.id,d=await Xl(c,"update",()=>wr(c,t.force===!0,n,t));return{id:c,action:"pause_task",update:a,release:d}}async function em(e,t,n,r){let o=await Dt(e,t,n,r),i=o.item.id,s=await Xl(i,"close",()=>wr(i,n.force===!0,r,n));return{id:i,action:"close_task",close:o,release:s}}async function Vb(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options),o=e.force===!0||r.force===!0,i={...e.args,...r},s=r.next===!0,a=e.id??b(r,"id");if(i.start===!0){if(a)return Dn(e,"start_task");ow(a,s,!0)}let c=s?await iw(o,e.global,i,i):await Co(Do(e,r),o,e.global,i);return Re(c,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Do(e,t){let n=e.id??b(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function tm(e,t){return b(e.args,"reason")??b(e.args,"text")??b(t,"reason")??b(t,"text")}async function Yb(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return r.releaseAssignment===!0?Dn(e,"close_task"):Re(await Dt(Do(e,r),tm(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Dn(e,t){let{changedFields:n,idOnly:r,runnerOptions:o}=ve(e.args,e.options),i=Do(e,o),s=wt(o,{force:e.force===!0||o.force===!0}),a=t==="start_task"?await Ql(i,s,e.global):t==="pause_task"?await Zl(i,s,e.global):await em(i,tm(e,o),s,e.global);return Re(a,{changedFields:n,idOnly:r,compactEnvelope:n==="compact"&&!r})}async function Jb(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options),o=wt(r,{message:b(Object.hasOwn(r,"message")?r:e.args,"message")});if(o.pause===!0)return Dn({...e,options:o},"pause_task");let i=await wr(Do(e,o),e.force===!0||o.force===!0,e.global,o);return Re(i,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function Xb(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return Re(await Jl(Do(e,r),tm(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Ia(e,t){let n=P(["plan","show",e.plan.id,"--depth","deep",...t===void 0?[]:["--pm-path",t]]);return{kind:"plan_mutation",action:e.action,id:e.plan.id,status:e.plan.status,mode:e.plan.mode,steps_summary:e.plan.steps_summary,...e.step===void 0?{}:{step:{id:e.step.id,order:e.step.order,status:e.step.status}},materialized_count:e.materialized?.length??0,skipped_count:e.materialize_skipped?.length??0,warning_count:e.warnings.length,warnings:e.warnings.slice(0,3).map(r=>r.slice(0,160)),warnings_truncated:e.warnings.length>3||e.warnings.some(r=>r.length>160),next_action:e.next_actions?.[0]===void 0?n:t===void 0?e.next_actions[0]:`${e.next_actions[0]} --pm-path ${Df(t)}`,inspection_command:n,omission_receipt:{has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"plan_detail",restore_with:n}]}}}var EL=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"];var ek="plan-step-",am="draft",sm=["bug-investigation","feature-implementation","refactoring-sprint"],Qb={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function CL(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(Qb,t)?Qb[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${sm.join(", ")}`,m.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${sm[0]}`]});return n.map(r=>({...r}))}function TL(e,t){return t>0?Math.round(e/t*100):0}function tk(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function tt(e){return Array.isArray(e)?e.flatMap(t=>cr(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?cr(e,{unique:!1}):[]}function Me(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function nk(e,t=am){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=kc.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${kc.join(", ")}`,m.USAGE);return r}function cm(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Sc.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${Sc.join(", ")}`,m.USAGE);return r}function rk(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ec.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${Ec.join(", ")}`,m.USAGE);return r}function RL(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ac.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${Ac.join(", ")}`,m.USAGE);return n}function xL(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=Lc.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${Lc.join(", ")}`,m.USAGE);return n}function IL(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new l("Plan --fields requires a comma-separated list of plan field names",m.USAGE);return t}var nm=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function OL(e,t){let n=e,r={},o=[];for(let i of t){let s=i.startsWith("plan.")?i.slice(5):i;if(s.length!==0){if(!nm.has(s)){o.push(i);continue}Object.prototype.hasOwnProperty.call(n,s)&&(r[s]=n[s])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,m.USAGE,{nextSteps:[`Use --fields ${[...nm].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...nm].join(",")}`}});return r}function dm(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let i=o.indexOf("=");if(i<=0)throw new l(`Invalid ${t} entry "${o}"; expected key=value`,m.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[o.slice(0,i).trim().toLowerCase()]=o.slice(i+1).trim()}return n}function lm(e){let t=dm(e,"--file");if(!t.path)throw new l("--file requires path=<value>",m.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function mm(e){let t=dm(e,"--test");if(!t.command&&!t.path)throw new l("--test requires at least command=<value> or path=<value>",m.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function um(e){let t=dm(e,"--doc");if(!t.path)throw new l("--doc requires path=<value>",m.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function $L(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=TL(t.completed,t.total),t}function PL(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${ek}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new l("Could not allocate step id (limit reached)",m.GENERIC_FAILURE)}function Er(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",m.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),i=e.find(s=>s.order===o);if(i)return i}throw new l(`Step "${t}" not found in plan`,m.NOT_FOUND)}function Zb(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function LL(e,t){let n=t.filter(s=>s.trim().toLowerCase()==="all"),r=[],o=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",m.USAGE);for(let s of e.slice().sort((a,c)=>a.order-c.order)){let a=Zb(s);if(a){o.push({from_step:s.id,...a});continue}r.push(s)}return{targets:r,skipped:o}}let i=new Set;for(let s of t){let a=Er(e,s);if(i.has(a.id))continue;i.add(a.id);let c=Zb(a);if(c){o.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:o}}function NL(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function FL(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function ML(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function Be(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((s,a)=>s.order-a.order),r=$L(n),o=FL(n),i={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??am,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:ML(n),linked_items:(e.dependencies??[]).map(s=>({id:s.id,kind:s.kind}))};return(t==="standard"||t==="deep")&&(i.steps=n),t==="deep"&&(i.decisions=e.plan_decisions??[],i.discoveries=e.plan_discoveries??[],i.validation=e.plan_validation??[]),i}function We(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!kd(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function ok(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new l(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,m.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function DL(e){let t=E(process.cwd(),e.path);await O(t);let n=await A(t);return{pmRoot:t,settings:n}}async function ik(e,t){let n=$(e.settings,I()),r=await j(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,m.NOT_FOUND);let o=await te(r,{schema:e.settings.schema});return ok(o.document.metadata),{document:o.document,itemId:r.id}}function UL(e){let t=[];for(let n of tt(e.related))t.push(`id=${n},kind=related`);for(let n of tt(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of tt(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function jL(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function GL(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||tt(e.dependsOn).length>0||tt(e.link).length>0}function qL(e){let t=e.stepTitle?.trim()||void 0,n=tk(e.step),r=e.template?.trim()?CL(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function KL(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",m.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${sm[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",m.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function zL(e,t){let n=cm(e.stepStatus,"pending"),r=pm(e,"depends_on"),o=Me(e.file).map(lm),i=Me(e.test).map(mm),s=Me(e.doc).map(um),a=C();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:fm(e.stepOwner),evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function HL(e){let t=qL(e),n=GL(e);if(KL(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[zL(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=C();return{steps:t.stepTitles.map((o,i)=>({id:`${ek}${String(i+1).padStart(3,"0")}`,order:i+1,title:o,body:t.templateSteps[i]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function sk(e,t,n=[]){ue(e,t),n.length>0&&B_(t,n)}async function BL(e,t,n){let r=e.title?.trim();if(!r)throw new l("pm plan create requires --title",m.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let o=nk(e.mode,am),i=RL(e.harness),s=e.fromSearch?.trim(),a=jL(e),{steps:c,hasPerStepDetailOptions:d}=HL(e);if(c.length===0&&d)throw new l("pm plan create step options require --step-title (or a single --step)",m.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?R(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:Me(e.file),test:Me(e.test),doc:Me(e.doc),field:Me(e.field),assignee:R(e.author,n.settings.author_default),blockedBy:void 0,dep:UL(e),message:e.message??(s?`plan create (search: ${s})`:"plan create")};sk(e,f);let h=await rn(f,t),_=await we({pmRoot:n.pmRoot,settings:n.settings,id:h.item.id,op:"plan_create_metadata",author:R(e.author,n.settings.author_default),message:"seed plan metadata",mutate(y){let w=["plan_mode"];y.metadata.plan_mode=o,i&&(y.metadata.plan_harness=i,w.push("plan_harness"));let v=e.scope?.trim();v&&(y.metadata.plan_scope=v,w.push("plan_scope"));let k=e.resumeContext?.trim();return k&&(y.metadata.plan_resume_context=k,w.push("plan_resume_context")),y.metadata.plan_steps=c,w.push("plan_steps"),a&&(y.metadata.plan_validation=[...y.metadata.plan_validation??[],a],w.push("plan_validation")),p&&(y.metadata.assignee=p,w.push("assignee")),{changedFields:w}}}),g=Be(_.item,"brief");return{action:"create",plan:g,step:c[0],next_actions:We(h.item.id,g),warnings:[...h.warnings],generated_at:C()}}async function WL(e,t,n){let r=xL(t.depth),o=IL(t.fields),{document:i,itemId:s}=await ik(n,e),a=Be(i.metadata,o===null?r:"deep");return{action:"show",plan:o===null?a:OL(a,o),next_actions:We(s,a),warnings:[],generated_at:C()}}function VL(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function bt(e){let t=R(e.options.author,e.ctx.settings.author_default),n,r=await we({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){ok(o.metadata);let i=D(e.ctx.settings.schema);if(le(o.metadata.status,i)||kd(o.metadata.plan_mode))throw new l(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.metadata.plan_mode??"unset"}) and cannot be mutated.`,m.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let s=(o.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(o.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(s,o);n=c.resultStep;let d=s.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));o.metadata.plan_steps=d;let u=VL(a,o.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function YL(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",m.USAGE);let o=cm(t.stepStatus,"pending"),i=t.allowMultipleActive===!0,{document:s,resultStep:a,itemId:c}=await bt({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;ak(u,void 0,o,i);let f=JL(u,t,{order:p,title:r,status:o});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),d=Be(s.metadata,"standard");return{action:"add-step",plan:d,step:a,next_actions:We(c,d),warnings:[],generated_at:C()}}function ak(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(i=>i.id!==t&&i.status==="in_progress");if(o)throw new l(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,m.CONFLICT)}function JL(e,t,n){let r=pm(t,"depends_on"),o=Me(t.file).map(lm),i=Me(t.test).map(mm),s=Me(t.doc).map(um),a=C();return{id:PL(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:fm(t.stepOwner),evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function pm(e,t){let n=tt(e.dependsOn).map(u=>({id:u,kind:t})),r=tt(e.related).map(u=>({id:u,kind:"related"})),o=tt(e.blocks).map(u=>({id:u,kind:"blocks"})),i=tt(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),s=tt(e.link),a=rk(e.linkKind,t),c=e.linkNote?.trim(),d=s.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...o,...i,...d]}async function rm(e,t,n,r){let{document:o,resultStep:i,itemId:s}=await bt({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,d){let u=Er(c,r.stepRef),p=C(),f=r.finalStatus??cm(t.stepStatus,u.status),h=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return ak(c,u.status==="in_progress"?u.id:void 0,f,h),XL(u,t,f,p),d.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Be(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:i,next_actions:We(s,a),warnings:[],generated_at:C()}}function fm(e){return Xn(e?.trim(),"--step-owner")||void 0}function XL(e,t,n,r){QL(e,t,n),ZL(e,t),e.status=n,e.updated_at=r,eN(e,n,r)}function QL(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new l("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",m.USAGE)}function ZL(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=fm(t.stepOwner)),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let r=Me(t.file).map(lm),o=Me(t.test).map(mm),i=Me(t.doc).map(um);r.length>0&&(e.files=om(e.files,r)),o.length>0&&(e.tests=om(e.tests,o)),i.length>0&&(e.docs=om(e.docs,i))}function om(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let i=JSON.stringify(o);r.has(i)||(r.add(i),n.push(o))}return n}function eN(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function tN(e,t,n,r,o){let{document:i,itemId:s,resultStep:a}=await bt({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(d){let u=Er(d,r),p=d.filter(h=>h.id!==u.id),f=Math.max(1,Math.min(o,p.length+1));return p.splice(f-1,0,u),p.forEach((h,_)=>{h.order=_+1,h.updated_at=C()}),d.length=0,d.push(...p),{changedSteps:[u.id],resultStep:u}}}),c=Be(i.metadata,"standard");return{action:"reorder-step",plan:c,step:a,next_actions:We(s,c),warnings:[],generated_at:C()}}async function nN(e,t,n,r){let{document:o,itemId:i,resultStep:s}=await bt({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(c){let d=Er(c,r),u=c.filter(p=>p.id!==d.id);return u.forEach((p,f)=>{p.order=f+1}),c.length=0,c.push(...u),{changedSteps:[d.id],resultStep:d}}}),a=Be(o.metadata,"standard");return{action:"remove-step",plan:a,step:s,next_actions:We(i,a),warnings:[],generated_at:C()}}async function rN(e,t,n,r){let o=pm(t,rk(t.linkKind,"related"));if(o.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",m.USAGE);let i=t.promoteToItemDep===!0,{document:s,itemId:a,resultStep:c}=await bt({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Er(u,r),h=f.linked_items??[],_=y=>`${y.kind}:${y.id}`,g=new Set(h.map(_));for(let y of o){let w=_(y);g.has(w)||(h.push(y),g.add(w))}if(f.linked_items=h,f.updated_at=C(),i){let y=p.metadata.dependencies??[],w=k=>`${k.kind}:${k.id}`,v=new Set(y.map(w));for(let k of o){let S=k.kind==="depends_on"?"blocked_by":k.kind,T={id:k.id,kind:S,created_at:C(),author:R(t.author,n.settings.author_default)};v.has(w(T))||(y.push(T),v.add(w(T)))}p.metadata.dependencies=y}return{changedSteps:[f.id],resultStep:f}}}),d=Be(s.metadata,"standard");return{action:"link",plan:d,step:c,next_actions:We(a,d),warnings:[],generated_at:C()}}async function oN(e,t,n,r){let o=tt(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",m.USAGE);let{document:i,itemId:s,resultStep:a}=await bt({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(d){let u=Er(d,r),p=(u.linked_items??[]).filter(f=>!o.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=C(),{changedSteps:[u.id],resultStep:u}}}),c=Be(i.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:We(s,c),warnings:[],generated_at:C()}}async function im(e,t,n,r){let o=NL(r,t);if(!o){let d=`--${r}-text`,u=`--${r}`;throw new l(`pm plan ${r} requires ${d}`,m.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${d} "..."`,`pm plan ${r} <plan-id> ${u} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${d} <value>`}})}let i=R(t.author,n.settings.author_default),{document:s,itemId:a}=await bt({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(d,u){let p=C();if(r==="decision"){let h=u.metadata.plan_decisions??[];return h.push({ts:p,author:i,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=h,{changedSteps:[]}}if(r==="discovery"){let h=u.metadata.plan_discoveries??[];return h.push({ts:p,author:i,text:o}),u.metadata.plan_discoveries=h,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Be(s.metadata,"deep");return{action:r,plan:c,next_actions:We(a,c),warnings:[],generated_at:C()}}async function iN(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",m.USAGE);let{document:o,itemId:i}=await bt({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=r;let d=t.scope?.trim();return d&&(c.metadata.plan_scope=d),{changedSteps:[]}}}),s=Be(o.metadata,"brief");return{action:"resume",plan:s,next_actions:We(i,s),warnings:[],generated_at:C()}}async function sN(e,t,n){let r=nk(t.mode??"approved","approved"),{document:o,itemId:i}=await bt({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(a,c){c.metadata.plan_mode=r;let d=t.scope?.trim();return d&&(c.metadata.plan_scope=d),{changedSteps:[]}}}),s=Be(o.metadata,"brief");return{action:"approve",plan:s,next_actions:We(i,s),warnings:[],generated_at:C()}}function ck(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function aN(e,t){let n=Be(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:We(e.itemId,n),warnings:ck(t),generated_at:C()}}function cN(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let i=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${i}`)}return r}async function dN(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Me(e.options.field)){let i=o.indexOf("=");if(i<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,m.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,m.USAGE);let c=s.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,m.USAGE);let[d,...u]=c,p=`${d}${u.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(p))throw new l(`Invalid --field entry "${o}"; "${p}" is reserved by materialize and cannot be overridden`,m.USAGE);n[p]=a}for(let o of e.targets){let i={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:cN(e.parent,e.planItemId,o)};sk(e.options,i,["description",...Object.keys(n)]);let s=await rn(i,{path:e.pmRoot});t.push({id:s.item.id,title:s.item.title,type:e.resolvedTypeName,parent:s.item.parent,tags:s.item.tags??[],from_step:o.id})}return t}function lN(e,t,n){for(let r of t){let o=n.find(a=>a.from_step===r.id);if(!o)continue;let i=e.find(a=>a.id===r.id);if(!i)continue;let s=i.linked_items??[];s.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),i.linked_items=s,i.updated_at=C()}}async function mN(e,t,n){let r=tt(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",m.USAGE);let o=t.materializeType?.trim()||"Task",i=$(n.settings,I()),s=Ce(o,i);if(!s)throw new l(`Invalid --materialize-type "${o}"`,m.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,d=await ik(n,e),u=(d.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=LL(u,r);if(p.length===0){if(f.length>0)return aN(d,f);throw new l("No matching plan steps found for --steps",m.NOT_FOUND)}let h=await dN({targets:p,parent:a,planItemId:d.itemId,resolvedTypeName:s,tags:c,options:t,pmRoot:n.pmRoot}),{document:_,itemId:g}=await bt({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(w){return lN(w,p,h),{changedSteps:p.map(v=>v.id)}}}),y=Be(_.metadata,"standard");return{action:"materialize",plan:y,materialized:h,...f.length>0?{materialize_skipped:f}:{},next_actions:We(g,y),warnings:ck(f),generated_at:C()}}function uN(e){if(e.subcommand==="create")return e;let t=tk(e.options.step);if(t.length>1)throw new l(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,m.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:ue(e.options,{...e.options,stepTitle:t[0]})}:e}function Ut(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,m.USAGE);return e.id}function Un(e,t){let n=Ut(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,m.USAGE);return{id:n,stepRef:e.stepRef}}function pN(e){let t=Un(e,"reorder-step");if(e.reorderTo===void 0)throw new l("pm plan reorder-step requires <plan-id> <step> <new-order>",m.USAGE);return{...t,reorderTo:e.reorderTo}}var fN={create:(e,t)=>BL(e.options,e.global,t),show:(e,t)=>WL(Ut(e,"show"),e.options,t),"add-step":(e,t)=>YL(Ut(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=Un(e,"update-step");return rm(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=Un(e,"complete-step");return rm(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=Un(e,"block-step");return rm(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=pN(e);return tN(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=Un(e,"remove-step");return nN(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=Un(e,"link");return rN(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=Un(e,"unlink");return oN(n.id,e.options,t,n.stepRef)},decision:(e,t)=>im(Ut(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>im(Ut(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>im(Ut(e,"validation"),e.options,t,"validation"),resume:(e,t)=>iN(Ut(e,"resume"),e.options,t),approve:(e,t)=>sN(Ut(e,"approve"),e.options,t),materialize:(e,t)=>mN(Ut(e,"materialize"),e.options,t)};function _N(e){let t=fN[e];if(!t)throw Pe({command_path:"plan",token:e,allowed:EL});return t}async function dk(e){let t=await DL(e.global),n=uN(e),r=await _N(n.subcommand)(n,t);return r.action==="show"?r:{...r,mutation_receipt:Ia(r,t.pmRoot)}}import hN from"fast-json-patch";import _m from"node:fs/promises";function hm(e){return{schema:e.schema,extensionFieldNames:Ue(I())}}async function lk(e,t,n){let r=await uh(e,hm(t));return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:mk(n),recovered:!0}}function gN(e,t){return ch(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function mk(e){let t=ar(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:pt(_t(t))}async function yN(e,t,n,r){let o=await Sn(e,t,n,r),i=o.located?await Q_({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function wN(e,t){let n=eo(e),r=eo(t),o=hN.compare(n,r),i=new Set;for(let s of o){if(s.path==="/body"||s.path.startsWith("/body/")){i.add("body");continue}let a=s.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((s,a)=>s.localeCompare(a))}async function vN(e){let t=await oy({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>lk(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function bN(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:mk(t),originalRaw:null}}function kN(e){let t=e.document.metadata.assignee?.trim(),n=t&&t!==e.author&&!e.force,r=Vr(t);if(!n)return[];if(e.enforcement==="strict")throw new l(`Item ${e.resolvedId} is assigned to ${r}. Use --force to override.`,m.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${r}`]:[]}function SN(e){return Object.keys(e).length===0?void 0:e}async function AN(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await ae(e.existingItemPath,e.resolvedOriginalRaw),await _m.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await ae(e.existingItemPath,e.resolvedOriginalRaw);return}await _m.rm(e.restoredItemPath,{force:!0})}async function EN(e){return[...await Q({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await Q({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function gm(e,t,n,r){let o=E(process.cwd(),r.path);await O(o);let i=await A(o),s=$(i,I()),a=await yN(o,e,i,s.type_to_folder),c=a.id,{raw:d,entries:u}=await t_(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,m.NOT_FOUND);let p=gN(t,u),f=dh(ar(u,p.historyIndex),p),h=Zr(f,hm(i));if(h.metadata.id!==c)throw new l(`Restore target resolved to item ${h.metadata.id}, expected ${c}.`,m.GENERIC_FAILURE);let g=(a.located?await lk(a.located,i,u):null)?.raw??null,y=R(n.author,i.author_default),w=await ft(o,c,i.locks.ttl_seconds,y,!!n.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms,{waitPolicy:"progress"}),v=w.release;try{let{loadedItemUnderLock:k,existingItemPath:S}=await vN({pmRoot:o,subject:a,settings:i,typeRegistry:s,historyRawBeforeLock:d,currentItemRawBeforeLock:g,history:u}),T="toon",x=bN(k,u);k?.recovered===!0&&__(o,c,k.raw),g_(o,k?.document??Nu,c),h.metadata.pm_format_version=zc(Math.max(zi(h.metadata),zi(x.document.metadata))),lh(ai(o),zi(h.metadata));let F=kN({document:x.document,author:y,force:n.force,enforcement:i.governance.ownership_enforcement,resolvedId:c}),L=wN(x.document,h),H=await vn({pmRoot:o,settings:i,operation:"restore",author:y,before:x.document,after:h});await yn({pm_root:o,operation:"restore",before:x.document,after:h,changed_fields:L,author:y,sdk:bn({pmRoot:o,settings:i,typeToFolder:s.type_to_folder})});let B=ut(h,{format:T,...hm(i)}),Y=Et(o,h.metadata.type,c,T,s.type_to_folder),re=await w.fence(async()=>{let he=await Xt(o,y),qt;try{await ae(Y,B),S&&Y!==S&&await _m.rm(S);let cn=qe({nowIso:C(),author:y,op:"restore",before:x.document,after:h,message:n.message,context:SN({...H.decisions.length===0?{}:{workflow_policies:H.decisions},...w_(o,[c,x.document.metadata.id,h.metadata.id],"restore")})});try{await Bt(a.historyPath,cn)}catch(Ye){throw await AN({existingItemPath:S,resolvedOriginalRaw:x.originalRaw,restoredItemPath:Y}),Ye}qt=await Qt({pmRoot:o,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:Y,previousItemPath:S??void 0,document:h})}finally{await he()}return qt});y_(o,h,c);let J=await EN({restoredItemPath:Y,historyPath:a.historyPath,before:x.document,after:h});Qn({id:h.metadata.id,op:"restore",item_type:h.metadata.type,previous_status:x.document.metadata.status,status:h.metadata.status,previous:gn(x.document.metadata,L),current:gn(h.metadata,L),changed_fields:L});let Gt=u[p.historyIndex],G=wn(u,!0);return{item:h.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,version:G===null?null:G+p.historyIndex+1,entry_ts:Gt.ts,entry_op:Gt.op},changed_fields:L,warnings:[...H.warnings,...k?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...F,...re,...J]}}finally{await v()}}var pk=2,wm="update-many",CN=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),TN=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),RN={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},xN=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],fk=e=>{let t={};for(let[n,r]of Object.entries(e))CN.has(n)||r!==void 0&&(t[n]=r);return t},IN=e=>Object.keys(fk(e)).length>0,_k=e=>typeof e=="string"?e.trim():e,ON=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},ym=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},$N=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??_k(e)},PN={priority:ON,estimatedMinutes:ym,order:ym,rank:ym,regression:$N},LN=(e,t)=>{if(t!==void 0)return(PN[e]??_k)(t)},Oa=(e,t)=>ee(e,t),NN=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],FN=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,MN=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",uk=(e,t)=>t===void 0?void 0:e[t],Cr=e=>Array.isArray(e)?e.length:0,DN=(e,t,n)=>{let r=n[e.addKey],o=uk(n,e.removeKey),i=Cr(r),s=Cr(o),a=n[e.clearKey]===!0,c=uk(n,e.replaceKey)===!0;if(![a,c,i>0,s>0].includes(!0))return;let d=NN(e.field,t[e.field]);return{field:e.field,before:d,after:{operation:MN({replace:c,clear:a,removeCount:s}),clear:a,replace:c,add_count:i,remove_count:s,before_count:FN(e.field,d)}}},UN=(e,t)=>{let n=[];for(let r of xN){let o=DN(r,e,t);o!==void 0&&n.push(o)}return n},jN=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],GN=(e,t)=>{if(![t.tags!==void 0,Cr(t.addTags)>0,Cr(t.removeTags)>0].includes(!0))return;let n=jN(e.tags),r=t.tags===void 0?n:Wt(t.tags),o=rr(r,t.addTags),i=Zi(o,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),s=n.slice().sort((a,c)=>a.localeCompare(c));if(!Oa(s,i))return{field:"tags",before:n,after:i}},qN=(e,t)=>{let n=e.acceptance_criteria,r=Qi(nr(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let o=r.criteria.join("; ");if(!Oa(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},KN=(e,t,n)=>{for(let[r,o]of Object.entries(RN)){let i=n[r];if(i===void 0)continue;let s=t[o],a=LN(r,i);Oa(s,a)||e.push({field:o,before:s,after:a})}},zN=(e,t,n,r)=>{let o=Ki(n,r,["update_many"]);for(let[i,s]of Object.entries(o)){let a=t[i];Oa(a,s)||e.push({field:i,before:a,after:s})}},HN=(e,t,n,r)=>{if(n===void 0||n.length===0)return;let o=Hl(n,r,Ue(I()),["update_many"]);for(let i of o){let s=t[i];s!==void 0&&e.push({field:i,before:s,after:null})}},BN=(e,t,n={})=>{let r=e,o=[],i=GN(r,n);if(i&&o.push(i),KN(o,r,n),Cr(n.addAc)>0||Cr(n.removeAc)>0){let s=qN(r,n);s!==void 0&&o.push(s)}return o.push(...UN(r,n)),zN(o,r,n,t),HN(o,r,n.unset,t),{id:e.id,changes:o}},WN=(e,t)=>nh(e,t,{strict:!0,flagLabel:"--filter-status"}),VN=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",m.USAGE)},YN=[({update:e})=>{e.priority!==void 0&&Jt(e.priority)},({update:e,settings:t})=>{e.unset!==void 0&&e.unset.length>0&&Hl(e.unset,et(t.schema),Ue(I()),["update_many"])},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=$(t,I());if(!Ce(e.type,r))throw new l(zt(e.type,r.types,Ht(n,t.schema)),m.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!de(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid status value "${e.status}". Allowed: ${n.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e.status,allowed:n})}},({update:e})=>{e.deadline!==void 0&&se(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&or(e.estimatedMinutes,"estimated-minutes")}],JN=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let i of YN)i(o)},XN=async e=>{let t=await as(e.pmRoot,wm,e.rollbackId,pk),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await la(e.pmRoot,t,{author:e.options.update?.author,message:n,force:e.options.update?.force}),o=r.rows.filter(i=>i.status==="skipped").length;return{...kn({applied:r.restored_ids.length,skipped:o,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:r.restored_ids.length,skipped_count:o,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},QN=async e=>{let t={schema_version:pk,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:R(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await ss(e.pmRoot,wm,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},ZN=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},vm=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},eF=async e=>{let t=E(process.cwd(),e.path);await O(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:D(n.schema),runtimeFieldRegistry:et(n.schema)}},tF=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",m.USAGE);if(bo(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",m.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",m.USAGE);return XN({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},nF=async e=>{WN(e.options.status,e.runtime.statusRegistry);let t=await Lt(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let i=BN(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?i:{...i,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await Lt(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:ZN(e.options.list?.ids,r)}},rF=e=>({outcome:"effect",exit_code:m.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...vm(e)}),oF=e=>({...kn({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...vm(e)}),iF=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(i=>i.changes.length>0).map(i=>i.id));for(let i of e.items){if(!o.has(i.id)){t.push({id:i.id,status:"skipped"});continue}try{let s=_d(ue(e.options.update,{...e.options.update,message:r,runtimeFieldCommands:["update_many"]})),a=await ys({pmRoot:e.pmRoot,itemId:i.id,checkpointId:e.checkpointId},()=>ct(i.id,s,e.global));t.push({id:i.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(i.id)}catch(s){let a=await ma(s,i.id,e.pmRoot);if(a!==void 0){t.push({id:i.id,status:"updated",...a}),n.push(i.id);continue}t.push({id:i.id,status:"failed",error:mt(s),...await vt(s,e.pmRoot)})}}return{rows:t,updatedIds:n}},sF=async e=>{if(e.plan.actionable.length===0)return oF(e.plan);let t=C(),n=is(wm,t),r=new Set(e.plan.actionable.map(p=>p.id)),o=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),i=e.options.checkpoint===!1?void 0:await QN({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),s=await iF({pmRoot:e.runtime.pmRoot,items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=p=>s.rows.filter(f=>f.status===p).length,c=a("updated"),d=a("skipped"),u=a("failed");return{...kn({applied:c,skipped:d,failed:u,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...i?{checkpoint:i}:{},updated_count:c,skipped_count:d,failed_count:u,rows:s.rows,ids:s.updatedIds,...vm(e.plan)}},hk=async(e,t)=>{let n=os(e.rollback),r=await eF(t);n===void 0&&(e={...e,update:_d(await Vl(e.update))});let o=fk(e.update);if(VN(e.list),n!==void 0)return tF({runtime:r,rollbackId:n,options:e,global:t,updateSummary:o});if(!IN(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${TN}), or pass --dry-run for a filter-only preview.`,m.USAGE);JN(e.update,r.settings,r.statusRegistry,r.pmRoot),Yl(e.update);let i=await Ln({pmRoot:r.pmRoot,dependencies:xa(e.update.dep,r.settings.id_prefix,C(),R(e.update.author,r.settings.author_default)).additions,idPrefix:r.settings.id_prefix,itemFormat:r.settings.item_format,typeToFolder:$(r.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),s=await nF({options:e,global:t,runtime:r,updateSummary:o,dependencyWarnings:i});return await Ln({pmRoot:r.pmRoot,dependencies:xa(e.update.dep,r.settings.id_prefix,C(),R(e.update.author,r.settings.author_default)).additions,idPrefix:r.settings.id_prefix,itemFormat:r.settings.item_format,typeToFolder:$(r.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:s.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:r.settings.schema}),e.dryRun===!0?rF(s):sF({runtime:r,options:e,global:t,plan:s})};function aF(e){if(e===void 0)return;if(e.trim().length===0)throw new l("--add-json must contain a JSON value",m.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new l("--add-json must be valid JSON",m.USAGE,{code:"structured_event_json_invalid"})}return t}function cF(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function dF(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new l("--since must be a valid ISO timestamp",m.USAGE,{code:"structured_event_since_invalid"});return t}function gk(e){return Object.prototype.toString.call(e)==="[object Object]"?e:{}}async function yk(e,t,n){let r=aF(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",m.USAGE,{code:"structured_event_input_conflict"});let i=r===void 0?void 0:Ct(r),s=[t.since,t.eventType].some(_=>_!==void 0),a=dF(t.since),c=oo(t.limit),d=await hr(e,{...t,...s?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,s].includes(!0)},n,{input:await zs(i===void 0?t:{add:i},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:_=>_r(_),createEntry:_=>r===void 0?_:{..._,format:"json",data:r,event_type:cF(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm notes --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}}),u=t.eventType?.trim(),p=d.notes.filter(_=>{let g=gk(_),y=[g.format==="json",g.data!==void 0].every(Boolean),w=[a===void 0,Date.parse(g.created_at??"")>=(a??Number.POSITIVE_INFINITY)].includes(!0),v=[!u,g.event_type===u].includes(!0);return[!s,[y,w,v].every(Boolean)].includes(!0)}),f=s?Jd(p,c):p,h=f.filter(_=>gk(_).format==="json").length;return{...d,notes:f,count:f.length,...s?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:h}:t.includeMeta===!0?{structured_event_count:h}:{}}}import kF from"node:path";import lF from"node:fs/promises";import wk from"node:path";var mF="templates",uF=".json",pF=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,fF=Xi.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),_F=new Set(fF);function hF(e){let t=e.trim();if(!pF.test(t))throw new l(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,m.USAGE);return t}function vk(e){return wk.join(e,mF)}function bk(e,t){return wk.join(vk(e),`${t}${uF}`)}async function gF(e){await O(e)}function kk(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function yF(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(n==="priority"){t[n]=String(Jt(r));continue}if(_F.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(i=>typeof i=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return kk(t)}function wF(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new l(`Template "${t}" has invalid options payload.`,m.GENERIC_FAILURE);let n=e,r={};for(let[o,i]of Object.entries(n)){let s=o.trim();if(s.length===0)throw new l(`Template "${t}" contains an empty option key.`,m.GENERIC_FAILURE);if(typeof i=="string"){r[s]=i;continue}if(Array.isArray(i)&&i.every(a=>typeof a=="string")){r[s]=[...i];continue}throw new l(`Template "${t}" contains invalid value for option "${s}".`,m.GENERIC_FAILURE)}return kk(r)}function vF(e,t){let n;try{n=JSON.parse(e)}catch{throw new l(`Template "${t}" contains invalid JSON.`,m.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Template "${t}" has invalid document shape.`,m.GENERIC_FAILURE);let r=n,o=wF(r.options,t),i=C();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:i,updated_at:typeof r.updated_at=="string"?r.updated_at:i,options:o}}async function bF(e,t){let n=await oe(bk(e,t));if(n===null)throw new l(`Template "${t}" not found`,m.NOT_FOUND);return vF(n,t)}async function bm(e,t,n){let r=E(process.cwd(),n.path);await gF(r);let o=hF(e),i=yF(t);if(Object.keys(i).length===0)throw new l("templates save requires at least one create option flag",m.USAGE);let s=C(),a=bk(r,o),c=s;await W(a)&&(c=(await bF(r,o)).created_at);let d={name:o,created_at:c,updated_at:s,options:i},u=await A(r);return await lF.mkdir(vk(r),{recursive:!0}),await ot({pmRoot:r,filePath:a,raw:`${JSON.stringify(d,null,2)}
|
|
23
|
-
`,op:"templates:save",author:R(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:d.name,created_at:d.created_at,updated_at:d.updated_at,path:a,options:d.options}}var Ck=["list","show","apply","lint"],SF="schema-types",AF="schema-statuses",EF="schema-fields";function $a(){let e=I();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Tk(){let{profiles:e,warnings:t}=Tf($a());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:Pf(n.definition)})),warnings:t,generated_at:C()}}function Rk(e){let t;try{t=Mi(e,$a())}catch(r){throw new l(r instanceof Error?r.message:String(r),m.USAGE)}let{resolved:n}=t;return{action:"show",...Lf(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:C()}}function xk(e){let t;try{t=Mi(e,$a())}catch(o){throw new l(o instanceof Error?o.message:String(o),m.USAGE)}let{resolved:n}=t,r=G_(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:C()}}function CF(e,t){return kF.join(e,"templates",`${t}.json`)}async function TF(e,t){let n=await oe(CF(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function Sk(e,t,n,r){let o=new Map;for(let i of r.templates){let s=await TF(e,i.name);s!==void 0&&o.set(i.name,s)}return{typesRaw:await oe(Rt(e,t.files.types,Tt.types)),statusesRaw:await oe(Rt(e,t.files.statuses,Tt.statuses)),fieldsRaw:await oe(Rt(e,t.files.fields,Tt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Tr(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function Ak(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Tr(t.types.changes),statuses:Tr(t.statuses.changes),fields:Tr(t.fields.changes),workflows:Tr(t.workflows.changes.map(i=>({key:i.type,status:i.status}))),config:Tr(t.config.changes),templates:Tr(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(o)].sort((i,s)=>i.localeCompare(s)),generated_at:C()}}async function RF(e){await O(e)}function xF(e){try{let t=Mi(e,$a());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),m.USAGE)}}async function Ik(e,t,n){let r=E(process.cwd(),n.path);await RF(r);let o=xF(e),i=o.profile,s=o.warnings;for(let w of i.fields){let v;try{v=xf(w)}catch{continue}j_(v,w)}let a=t.dryRun===!0,c=await A(r),d=Di(c.schema);if(a){let w=await Sk(r,d,c,i),v=Ek(i,w);return Ak(i,v,!1,!0,[...s])}let u=R(t.author,c.author_default),p=ih(c),f=!!t.force,h=[...s],_=[],g=async w=>{_.push(await Yr(r,w,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},y;try{await g(SF),await g(AF),await g(EF);let w=await Sk(r,d,c,i);if(y=Ek(i,w),y.types.changed){let v=Rt(r,d.files.types,Tt.types);await ot({pmRoot:r,filePath:v,raw:Fi(y.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let k=new Set(i.types.map(T=>bf(T).name)),S=y.types.file.definitions.filter(T=>k.has(T.name));await bg(r,S,h,"profile:apply-type-folder"),h.push(...await Q({path:v,scope:"project",op:"profile:apply-types"}))}if(y.statuses.changed){let v=Rt(r,d.files.statuses,Tt.statuses);await ot({pmRoot:r,filePath:v,raw:$f(y.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),h.push(...await Q({path:v,scope:"project",op:"profile:apply-statuses"}))}if(y.fields.changed){let v=Rt(r,d.files.fields,Tt.fields);await ot({pmRoot:r,filePath:v,raw:If(y.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),h.push(...await Q({path:v,scope:"project",op:"profile:apply-fields"}))}if(y.config.changed||y.workflows.changed){for(let v of y.config.changes){if(v.status==="unchanged")continue;let k=Wr(v.key);k!==void 0&&ji(c,k,v.value)}c.schema.type_workflows=y.workflows.result,await xe(r,c,"profile:apply-config")}for(let v of y.templates.changes)v.status!=="unchanged"&&await bm(v.name,{...v.options},n)}finally{for(let w of _.reverse())try{await w()}catch{}}return Ak(i,y,y.changed,!1,h)}function Ek(e,t){try{return q_(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),m.USAGE)}}import FF from"node:fs/promises";import Am from"node:path";var $k=10,jn="https://schema.unbrained.dev/pm/eval-query-set/v1";var Pa={schema:jn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},dt=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},IF=new Set(["keyword","semantic","hybrid"]);function Ok(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function OF(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),o=Ok(r,n),i=Array.from({length:t.size},()=>1),s=Ok(i,n);return s===0?0:o/s}function $F(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function km(e,t,n){let r=Math.min(n,e.length),o=0;for(let i=0;i<r;i+=1)t.has(e[i])&&(o+=1);return o}function PF(e,t,n){return n<=0?0:km(e,t,n)/n}function LF(e,t,n){return t.size===0?0:km(e,t,n)/t.size}function Pk(e,t,n){return{ndcg:OF(e,t,n),mrr:$F(e,t,n),precision:PF(e,t,n),recall:LF(e,t,n),relevant_total:t.size,retrieved_relevant:km(e,t,n)}}function Lk(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function NF(e,t){if(typeof e!="object"||e===null)throw new dt(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new dt(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new dt(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(i=>typeof i!="string"))throw new dt(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new dt(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!IF.has(n.mode)))throw new dt(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.minimum===void 0?{}:{minimum:Ny(n.minimum)},...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Sm(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==jn)throw new dt(`Unsupported eval query set schema; expected "${jn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new dt('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new dt("Eval query set must contain at least one query");return{schema:jn,queries:n.map((r,o)=>NF(r,o))}}var MF=Am.join("search","eval-queries.json"),Em={schema:jn,examples:[JSON.stringify(Pa)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},DF=new Set(["keyword","semantic","hybrid"]),UF=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!DF.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",m.USAGE);return t},jF=e=>{if(e===void 0||e==="")return $k;let t=qu(e);if(t===null)throw new l("Eval --k must be a positive integer",m.USAGE);return t},GF=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new l("Eval --fail-under must be a number in the range [0, 1]",m.USAGE);return n},on=e=>Math.round(e*1e4)/1e4,qF=async e=>{try{return await FF.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,m.NOT_FOUND,{...Em,examples:[`echo '${JSON.stringify(Pa)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},KF=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new l(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,m.USAGE,Em)}},zF=e=>{try{return Sm(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),m.USAGE,Em)}},HF=async e=>zF(KF(await qF(e),e)),BF=async(e,t,n,r)=>{let o=e.mode??t,s=(await So(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=Pk(s,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:Fy(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:on(a.ndcg),mrr:on(a.mrr),precision:on(a.precision),recall:on(a.recall)}}},WF=(e,t,n,r)=>{let o=Lk(n);return{k:e,query_count:t.length,aggregate:{ndcg:on(o.ndcg),mrr:on(o.mrr),precision:on(o.precision),recall:on(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:(r===void 0||o.ndcg>=r)&&t.every(i=>(i.violations?.length??0)===0)}},Nk=async(e,t)=>{let n=E(process.cwd(),t.path);await O(n);let r=jF(e.k),o=UF(e.mode),i=GF(e.failUnder),s=e.queries?Am.resolve(process.cwd(),e.queries):Am.join(n,MF),a=await HF(s),c=[],d=[];for(let u of a.queries){let{report:p,metrics:f}=await BF(u,o,r,t);d.push(f),c.push(p)}return WF(r,c,d,i)};import{readFile as VF,writeFile as Dk}from"node:fs/promises";import YF from"node:path";var Fk=["item","history","relationship","json"];function JF(e){let t=e.trim().toLowerCase();if(Fk.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${Fk.join(", ")}.`,m.USAGE)}function XF(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new l(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,m.USAGE)}async function Cm(e,t){try{return await VF(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,m.NOT_FOUND)}}async function QF(e){let t=E(process.cwd(),e.path);return await W(ce(t))?A(t):null}function ZF(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Mk(e,t){try{return e()}catch(n){if(n instanceof l&&n.context?.code==="item_identity_conflict"){let r=o=>o.endsWith(`
|
|
20
|
+
`,{changedFields:["body"]}}});return{item:d.item,appended:c,changed_fields:d.changedFields}}function JI(e,t,n){let r={...t.metadata,body:t.body},o={...n.metadata,body:n.body};for(let i of new Set([...Object.keys(r),...Object.keys(o)])){if(i==="updated_at"||i==="pm_format_version")continue;let s=r[i],a=o[i];if(ee(s,a))continue;let c=e.get(i);if(c&&!ee(c.after,s))throw new l(`Rollback conflict on ${i}: the batch effects contain an intervening edit. Inspect pm history before resolving it.`,m.CONFLICT);e.set(i,{field:i,before:c?c.before:s,after:a})}}function XI(e,t,n){let r=new Map;for(let[o,i]of e.entries()){if(i.context?.bulk_checkpoint!==t)continue;let s=Zr(ar(e,o-1),{schema:n}),a=Zr(ar(e,o),{schema:n});JI(r,s,a)}return[...r.values()].filter(o=>!ee(o.before,o.after))}function QI(e,t){let n={...e.metadata,body:e.body},r=t.filter(o=>!ee(n[o.field],o.after));if(r.length>0)throw new l(`Rollback conflict on ${r.map(o=>o.field).join(", ")}: a later edit changed a batch field. Inspect pm get/history and reconcile it explicitly before retrying.`,m.CONFLICT);for(let o of t)o.field==="body"?e.body=o.before:o.before===void 0?delete e.metadata[o.field]:e.metadata[o.field]=structuredClone(o.before);return t.map(o=>o.field)}async function la(e,t,n){if(t.record.rollback_strategy!=="guarded_inverse")throw new l("This legacy checkpoint has no attributable inverse effects. Inspect pm history and use an explicit pm restore only after reviewing later edits.",m.CONFLICT);let r=await A(e),o=new Map,i=await eh(t.items,async a=>{try{return await ZI(e,r,t,a,n)}catch(c){throw o.set(a,c),c}}),s=[];for(let a of i.rows)s.push(a.status==="failed"?{...a,...await vt(o.get(a.id),e)}:a);return{...i,rows:s}}async function ZI(e,t,n,r,o){let i=await wh({pmRoot:e,settings:t,id:r,op:"restore",author:R(o.author,t.author_default),message:o.message,force:o.force,skipNoop:!0,historyContext:{bulk_rollback:n.id},async mutate(s){let a=await a_(Ze(e,r),r);if(!lg(a,s).ok)throw new l(`Cannot safely roll back ${r}: item/history verification failed. Inspect pm history --verify before recovery.`,m.CONFLICT);return a.some(d=>d.context?.bulk_rollback===n.id)?{changedFields:[]}:{changedFields:QI(s,XI(a,n.id,t.schema))}}});return{changed_fields:i.changedFields,warnings:i.warnings,skipped:i.changedFields.length===0}}var eO=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function Vv(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function No(e,t){return Sl(e,t,{operation:"close"})}function Sl(e,t,n){let r=Vv(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",m.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function Al(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],i=o.filter(d=>d.kind==="blocked_by"),s=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),s&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&i.length>0){let d=new Set(i),u=o.filter(p=>!d.has(p));u.length>0?e.dependencies=u:delete e.dependencies,a.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:a,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...i.length>0?[`closed_removed_predecessors:${e.id}:${i.map(d=>d.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${i.length}`]:[]]};let c=[...new Set([...n?[n]:[],...i.map(d=>d.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}var tO=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function nO(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new l(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,m.USAGE)}function Jv(e){let t=[];for(let n of tO){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function Xv(e,t,n={}){let r=Jv(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},i=r.map(a=>`--${a.key.replaceAll("_","-")}`),s=[...t,"update",e.id,...r.flatMap((a,c)=>[i[c],o[a.key]?.trim()||"<value>"])];return{missing:i,suggested_retry:L(s),suggested_retry_args:s}}async function rO(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let i=o.trim();if(i===n)return!0;if(r.has(i))return!1;r.add(i),o=(await e(i))?.duplicate_of}return!1}function oO(e){return typeof e!="string"||e.trim().length===0}async function iO(e,t,n,r){let o=n?.trim();if(!o)return;if(o===r)throw new l("An item cannot be closed as a duplicate of itself.",m.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let i=$(t,I()),s=new Map,a=async d=>{if(s.has(d))return s.get(d)??null;let u=await j(e,d,t.id_prefix,t.item_format,i.type_to_folder);if(!u)return s.set(d,null),null;let{document:p}=await te(u,{schema:t.schema});return s.set(d,p.metadata),p.metadata},c=await a(o);if(!c)throw new l(`Duplicate target "${o}" was not found. Create or locate the canonical item first.`,m.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await rO(a,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${o}" points back to "${r}".`,m.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new l(`Duplicate target "${o}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,m.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function sO(e,t,n){return e.filter(r=>r.parent===t&&!le(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function aO(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),o=ig(e),i=t.trim().toLowerCase(),s=n.blocked_statuses;return e.filter(a=>s.has(a.status)).map(a=>({item:a,blockerIds:o.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(i)).filter(({blockerIds:a})=>a.every(c=>{if(c===i)return!0;let d=r.get(c);return d!==void 0&&le(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function cO(e,t,n,r,o,i,s){let a=aO(n,r,i),c=[],d=[],u=[],p=[],f;for(let h of a)try{let _=await we({pmRoot:e,settings:t,id:h.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(g){let y=g.metadata.dependencies??[],w=y.filter(k=>{let S=k.id.trim().toLowerCase();return k.kind!=="blocked_by"||!h.blocker_ids.includes(S)});g.metadata.status=i.open_status,delete g.metadata.blocked_by,delete g.metadata.blocked_reason,g.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${h.blocker_ids.join(", ")}).`,w.length>0?g.metadata.dependencies=w:delete g.metadata.dependencies;let v=["status","blocked_by","blocked_reason","unblock_note"];return w.length!==y.length&&v.push("dependencies"),{changedFields:v}}});c.push(`auto_unblocked:${_.item.id}:resolved_blockers=${h.blocker_ids.join(",")}`),d.push(_.item.id)}catch(_){let g=_ instanceof Error?_.message.replace(/\s+/g," ").trim():"unknown";Cn(_)?(f??=_,u.push(h.id)):p.push({id:h.id,reason:g}),c.push(`auto_unblock_failed:${h.id}:${g}`)}if(f!==void 0){let h=await dy(f,e),_=[...i.blocked_statuses].sort().join(",");throw uO(h,{closedId:r,unblockedIds:d,conflictIds:u,failed:p,openStatus:i.open_status,blockedStatuses:_,commandScope:s})}return c}var Mt=10,El=20,dO=[{list:"auto_unblock_failed",omitted:"auto_unblock_failed_omitted",floor:0},{list:"changes_since",omitted:"changes_since_omitted",floor:0},{list:"pending_unblock",omitted:"pending_unblock_omitted",floor:1}];function lO(e){for(let t of dO){let n=e[t.list];if(Array.isArray(n))for(;n.length>t.floor&&!bd(e);)n.pop(),Reflect.set(e,t.omitted,Number(e[t.omitted])+1)}return e}function Yv(e){let t=e.length-Mt;return`${e.slice(0,Mt).join(", ")}${t>0?`, and ${t} more`:""}`}var mO="post_close_auto_unblock_refused";function uO(e,t){let{closedId:n,conflictIds:r,failed:o,commandScope:i}=t,s=String(e.context.item_id),a=_=>L([...i,"update",_,"--status",t.openStatus,"--unset","blocked_by","--unset","blocked_reason","--expect-hash",`${_}=<item_hash>`]),c=o.slice(0,Mt).map(_=>({id:_.id,reason:cp(_.reason,160)})),d=o.length===0?"":` Auto-unblocking also failed for ${Yv(o.map(_=>_.id))}; details.auto_unblock_failed gives the reasons it kept (auto_unblock_failed_omitted counts the rest; their get step shows the item). Fix that cause before unblocking it.`,u=L([...i,"list","--status",t.blockedStatuses,"--fields","id,title,blocked_by,dependencies","--limit","200"]),p=[...r.slice(0,Mt).flatMap(_=>[L([...i,"get",_,"--json"]),a(_)]),...c.map(_=>L([...i,"get",_.id,"--json"]))],f=r.length>Mt||o.length>Mt||p.length>El,h=p.slice(0,f?El-1:El);return new l(`${n} was closed, but auto-unblocking ${s} was refused. ${e.message}`,e.exitCode,{...e.context,reason:mO,examples:b_(s,!1,{scopeArgs:i}).examples,required:`The close of ${n} is complete; do not retry it. Only unblocking ${r.length===1?s:`the guarded dependents it refused (${Yv(r)})`} remains: re-read each one (pm get <id> --json reports item_hash), check that every blocker it declares is resolved, then unblock it with ${a(s)}${r.length===1?"":" for each id"}.${d}${f?` This refusal does not list a step for every dependent left blocked; list them with ${u}, and while it reports has_more, continue with --after <next_cursor>.`:""}`,nextSteps:f?[...h,u]:h,details:lO({...structuredClone(e.context.details),pending_unblock:r.slice(0,Mt),pending_unblock_omitted:Math.max(0,r.length-Mt),auto_unblock_failed:c,auto_unblock_failed_omitted:Math.max(0,o.length-Mt)}),side_effects:[{path:`history/${n}.jsonl`,op:"close"},...t.unblockedIds.map(_=>({path:`history/${_}.jsonl`,op:"update"}))]})}async function ma(e,t,n){if(!Cn(e)||!e.context.side_effects?.some(i=>`${i.op}:${i.path}`==`close:history/${t}.jsonl`))return;let r=String(e.context.item_id);return{warnings:[...e.context.side_effects.filter(i=>i.op==="update").map(i=>i.path.slice(8,-6)).map(i=>`auto_unblocked:${i}`),`auto_unblock_refused:${r}:item_revision_conflict`],dependent_revision_conflict:{item_id:r,error:mt(e),...await vt(e,n)}}}function pO(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:i}of r){if(typeof o!="string")continue;let s=o.trim();s.length!==0&&(e[i]=s,n.push(i))}return n}function fO(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:i}of r)oO(e[o])&&(e[o]=i,n.push(o));return n}function _O(e,t){let r=[["--resolution",e.resolution],["--expected-result",e.expectedResult],["--actual-result",e.actualResult],["--validate-close",e.validateClose],["--completed-at",e.completedAt],["--message",e.message],["--author",e.author]].flatMap(([o,i])=>t.has(o)||i===void 0||i.trim().length===0?[]:[`${o}=${i}`]);return e.force===!0?[...r,"--force"]:r}function hO(e,t,n){let r=t.map(y=>y.label),o=t.map(y=>`--${y.key.replaceAll("_","-")}`),i=o.flatMap(y=>[y,"<value>"]),s=[...n.commandScope,"update",e.id,...i],a=`Cannot close item ${e.id}: missing ${r.join(", ")}. Populate fields or use --validate-close warn.`,c="Use --validate-close warn only when governance permits an evidenced exception.",d=Object.entries(n.options.lifecyclePolicy??{}).filter(([,y])=>y!==void 0).map(([y])=>y),u=w_(n.pmRoot),p=typeof n.options.author=="string"&&n.options.author.trim().length===0,f=d.length>0?`its lifecyclePolicy override (${d.join(", ")}) has no CLI spelling`:p?"its explicitly blank author has no CLI spelling (pm close refuses an empty --author)":u===void 0?"its revision guards cannot be replayed as typed (nested revision guards expect different revisions of one item, or a write in the same operation advanced a guarded revision)":void 0;if(f!==void 0)return new l(a,m.USAGE,{code:"close_validation_missing_fields",required:`Pass ${t.map(y=>y.key).join(", ")} on the same SDK close; ${f}, so no CLI retry reproduces it.`,recovery:{missing:o,next_best_command:L(s)},nextSteps:["Retry the same SDK close with the missing evidence supplied, inside the same lifecycle policy and revision guards.",c]});let h=n.closeReason===void 0?[]:[`--reason=${n.closeReason}`],_=u.map(y=>`--expect-hash=${y}`),g=[...n.commandScope,"close",e.id,...h,..._O(n.options,new Set(o)),..._,...i];return new l(a,m.USAGE,{code:"close_validation_missing_fields",required:`Supply ${o.join(", ")}: pm close accepts them and records them in the same write as the closure.`,recovery:{missing:o,suggested_retry:L(g),suggested_retry_args:g,next_best_command:L(s)},nextSteps:["Run recovery.suggested_retry when it is present: the same close with the missing flags added, so one write records the evidence and the closure.","Without it, record the evidence with recovery.next_best_command, then repeat the original close.",c]})}function gO(e,t,n,r){let o=t.map(a=>Wc(a.field).flag),i=[...r.author?.trim()?[`--author=${r.author}`]:[],...r.force===!0?["--force"]:[]],s=[...n,"update",e.id,...i,...o.flatMap(a=>[a,"<value>"])];return new l(`Cannot close item ${e.id}: deferred fields still have no value (${t.map(a=>a.field).join(", ")}). Supply them or use --validate-close warn.`,m.USAGE,{code:"close_validation_deferred_fields",required:`Supply ${o.join(", ")}: each was deferred at create (${t.map(a=>`${a.field}: ${a.reason}`).join("; ")}).`,recovery:{missing:o,next_best_command:L(s)},nextSteps:["Record the now-known values with recovery.next_best_command; the update resolves each deferral, then repeat the close.","Use --validate-close warn only when governance permits closing with deferred values still unknown."]})}function yO(e,t,n){let r=Qf(e);if(r.length===0)return[];if(t==="strict")throw gO(e,r,n.commandScope,n.options);return[`close_validation_deferred_fields:${e.id}:${r.map(o=>o.field).join(",")}`]}function wO(e,t,n,r){let o=[];if(t!=="off"){o.push(...yO(e,t,r));let i=Jv(e);if(i.length>0){let s=i.map(a=>a.label);if(t==="strict")throw hO(e,i,r);o.push(`close_validation_missing_fields:${e.id}:${s.join(",")}`)}if(n.length>0){if(t==="strict")throw new l(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,m.USAGE);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function vO(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function bO(e){let t=["assignee","claim_principal"].filter(n=>e[n]!==void 0);for(let n of t)delete e[n];return[...t]}function kO(e,t){if(le(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,m.CONFLICT,{recovery:Xv(e,t.commandScope,t.options)});let n=pO(e,t.options),r=fO(e,t.duplicateOf),o=wO(e,t.validateCloseMode,t.activeChildIds,t);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let i=t.options.completedAt!==void 0||e.completed_at===void 0;i&&(e.completed_at=t.completedAt);let s=["status","closed_at",...i?["completed_at"]:[],...vO(e,t.closeReason),...n];if(Rh(e)&&(e.plan_mode="completed",s.push("plan_mode")),t.duplicateOf!==void 0){s.push("duplicate_of");for(let c of r)s.includes(c)||s.push(c)}s.push(...bO(e));let a=Al(e,t.lifecyclePolicy);return s.push(...a.changedFields),o.push(...a.warnings),{changedFields:s,...o.length>0?{warnings:o}:{}}}async function Qv(e,t,n,r){let o=E(process.cwd(),r.path),i=ke(r);await O(o);let s=await A(o),a=D(s.schema),c=R(n.author,s.author_default),d=$(s,I()).type_to_folder,u=await j(o,e,s.id_prefix,s.item_format,d);if(!u)throw await it(o,e,s.id_prefix,d);let p=await iO(o,s,n.duplicateOf,u.id),f={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},h=No({explicit:t,duplicateOf:p,resolution:n.resolution,message:n.message},f.requireCloseReason).closeReason,_=nO(n.validateClose)??s.governance.close_validation_default,g=await ye(o,s.item_format,d,void 0,s.schema),y=sO(g,u.id,a),w=C(),v=n.completedAt===void 0?w:se(n.completedAt,new Date(w),"completed-at"),k={timestamp:v,source:n.completedAt===void 0?"close_time":"asserted",...n.completedAt===void 0?{hint:`completed_at defaults to the close time. If work finished earlier, correct it with ${L([...i,"update",u.id,"--completed-at","<ISO>"])}.`}:{}},S=await en({pmRoot:o,settings:s,id:u.id,op:"close",author:c,message:n.message,force:n.force,resolveHistoryContext:()=>({completion:{timestamp:k.timestamp,source:k.source}}),mutate(x){return n.completedAt===void 0&&x.metadata.completed_at!==void 0&&(k={timestamp:x.metadata.completed_at,source:"existing"}),kO(x.metadata,{pmRoot:o,commandScope:i,statusRegistry:a,force:n.force,options:n,duplicateOf:p,validateCloseMode:_,activeChildIds:y,closeReason:h,closedAt:w,completedAt:v,lifecyclePolicy:f})}}),T=_==="warn"?Xv(S.item,i):void 0;return{item:S.item,changed_fields:S.changedFields,...T?{follow_up:{kind:"complete_close_evidence",missing:T.missing,suggested_command:T.suggested_retry,suggested_command_args:T.suggested_retry_args}}:{},warnings:[...S.warnings,...await cO(o,s,g,u.id,c,a,i)],completion:k}}function Dt(e,t,n,r){return Qv(e,t,n,r)}var eb=2,Cl="close-many",SO=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function AO(e,t){return bo(e,t,{includePagination:!1})}function EO(e,t){return bo(e,t)}function CO(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",m.USAGE)}function TO(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function RO(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new l("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",m.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function xO(e,t){let n=D(t.schema),r=$(t,I()),o=await ye(e,t.item_format,r.type_to_folder,void 0,t.schema),i=new Map,s=new Map;for(let a of o){if(typeof a.parent!="string"||a.parent.length===0||(s.set(a.id,a.parent),le(a.status,n)))continue;let c=i.get(a.parent);c?c.push(a.id):i.set(a.parent,[a.id])}for(let a of i.values())a.sort((c,d)=>c.localeCompare(d));return{childrenByParent:i,parentByChild:s}}function Zv(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,i=t.get(e),s=[],a=new Set,c=!1;for(;i!==void 0&&!a.has(i);){let d=n?.get(i);if(d!==void 0){o+=d+1;break}a.add(i),s.push(i),o+=1,i=t.get(i)}if(i!==void 0&&a.has(i)&&(c=!0),!c){n?.set(e,o);for(let[d,u]of s.entries())n?.set(u,o-d-1)}return o}async function IO(e){let t=await as(e.pmRoot,Cl,e.rollbackId,eb),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await la(e.pmRoot,t,{author:e.options.author,message:n,force:e.options.force}),o=r.rows.filter(i=>i.status==="skipped").length;return{...Sn({applied:r.restored_ids.length,skipped:o,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:r.restored_ids.length,skipped_count:o,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function OO(e,t,n,r,o){return e.map(i=>{let s=(t.get(i.id)??[]).filter(c=>!n.has(c)),a=!tb(i,r,o);return{id:i.id,title:typeof i.title=="string"?i.title:"",status:i.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...s.length>0?{active_child_ids:s}:{}}})}async function $O(e){let t=await ss(e.pmRoot,Cl,e.checkpointId,{schema_version:eb,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:R(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function LO(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await ys({pmRoot:e.pmRoot,itemId:r.id,checkpointId:e.checkpointId},()=>Dt(r.id,e.reason,e.closeOptions,e.global));t.push({id:r.id,status:"closed",completion:o.completion,changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){let i=await ma(o,r.id,e.pmRoot);if(i!==void 0){t.push({id:r.id,status:"closed",...i}),n.push(r.id);continue}t.push({id:r.id,status:"failed",error:mt(o),...await vt(o,e.pmRoot)})}}return{rows:t,closedIds:n}}function PO(e){return os(e.rollback)}function NO(e){if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",m.USAGE);if(EO(e.list,e.status))throw new l("Rollback mode does not accept filter options",m.USAGE)}function FO(e){if(!AO(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${SO}). Refusing to match every item.`,m.USAGE)}function MO(e,t){let n=new Map;return[...e].sort((r,o)=>{let i=Zv(o.id,t,n)-Zv(r.id,t,n);return i!==0?i:r.id.localeCompare(o.id)})}function tb(e,t,n){return n||!le(e.status,t)}function DO(e,t,n){return new Set(e.filter(r=>tb(r,t,n)).map(r=>r.id))}async function UO(e){FO(e.options);let t=D(e.settings.schema),n=RO(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await Pt(e.options.status,TO(e.options.list),e.global),{childrenByParent:i,parentByChild:s}=await xO(e.pmRoot,e.settings),a=MO(o.items,s),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],d=c.length===0?[]:(await Pt(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,u=new Set(d.map(f=>f.id)),p=DO(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!u.has(f)),planRows:OO(a,i,p,t,r)}}function jO(e){return{outcome:"effect",exit_code:m.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function GO(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return $O({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function nb(e,t){let n=PO(e),r=E(process.cwd(),t.path);await O(r);let o=await A(r),i=e.dryRun===!0;if(CO(e.list),n!==void 0)return NO(e),IO({pmRoot:r,rollbackId:n,options:e,global:t});let s=await UO({pmRoot:r,settings:o,options:e,global:t});if(i)return jO(s);let a=new Set(s.planRows.filter(w=>w.action==="close").map(w=>w.id)),c=C(),d=is(Cl,c),u=await GO({context:s,options:e,closableIds:a,checkpointId:d,nowValue:c}),p={author:e.author,message:e.message??`close-many apply ${d}`,completedAt:e.completedAt,validateClose:s.validateCloseMode,force:s.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:h}=await LO({pmRoot:r,checkpointId:d,matched:s.matched,closableIds:a,reason:s.reason,closeOptions:p,global:t}),_=f.filter(w=>w.status==="closed").length,g=f.filter(w=>w.status==="skipped").length,y=f.filter(w=>w.status==="failed").length;return{...Sn({applied:_,skipped:g,failed:y,unmatched:s.unmatchedIds?.length??0}),mode:"apply",matched_count:s.matched.length,dry_run:!1,...s.reason!==void 0?{reason:s.reason}:{},filters:s.listed.filters,...s.validateCloseMode?{validate_close:s.validateCloseMode}:{},...u?{checkpoint:u}:{},closed_count:_,skipped_count:g,failed_count:y,rows:f,ids:h,...s.unmatchedIds!==void 0?{unmatched_ids:s.unmatchedIds,unmatched_count:s.unmatchedIds.length}:{}}}function qO(e,t){return[...new Set([...ri.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,o)=>r.localeCompare(o))}function KO(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Tl(e,t,n){let r=E(process.cwd(),n.path);await O(r);let o=await A(r),i=$(o,I()),s=await j(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!s)throw await it(r,e,o.id_prefix,i.type_to_folder);let a=await te(s,{schema:o.schema}),c=a.document.metadata,d=C(),u=R(t.author,o.author_default),p=await ro(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:i.type_to_folder,probeExisting:!1}),f=D(o.schema),h=t.title?.trim();if(h!==void 0&&h.length===0)throw new l("Copy --title must not be empty",m.USAGE);let _={...c,id:p,title:h??c.title,status:f.open_status,created_at:d,updated_at:d};delete _.closed_at,delete _.completed_at,delete _.close_reason,delete _.test_runs;let g=Ue(I()),y=pt({metadata:_,body:a.document.body},{schema:o.schema,extensionFieldNames:g}),w=await ur({title:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[s.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=qO(y.metadata,y.body),k=Et(r,y.metadata.type,p,o.item_format,i.type_to_folder),S=Ze(r,p),T=await ft(r,p,o.locks.ttl_seconds,u,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),x={metadata:{},body:""},F,P,H;try{let B=await Qt(r,u,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await ur({title:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[s.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let Y=await j(r,p,o.id_prefix,o.item_format,i.type_to_folder);if(Y)throw new l(`Cannot copy to ${p}: an item with that id already exists at ${Y.itemPath}. Retry the copy to allocate a new id.`,m.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${Y.itemPath}.`,recovery:{suggested_retry:`pm copy ${s.id}`}});let re=await bn({pmRoot:r,settings:o,operation:"create",author:u,before:null,after:y});H=re.warnings,await wn({pm_root:r,operation:"create",before:null,after:y,changed_fields:v,author:u,sdk:kn({pmRoot:r,settings:o,typeToFolder:i.type_to_folder})}),await T.fence(async()=>{await ae(k,ut(y,{format:o.item_format,schema:o.schema,extensionFieldNames:g}));try{let J=qe({nowIso:d,author:u,op:"create",before:x,after:y,message:KO(s.id,t.message),context:re.decisions.length===0?void 0:{workflow_policies:re.decisions}});await Wt(S,J)}catch(J){throw await Hn(k),J}}),P=await Zt({pmRoot:r,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:k,document:y})}finally{await B()}F=[...await Q({path:k,scope:"project",op:"create",item_id:y.metadata.id,item_type:y.metadata.type,before:x,after:y,changed_fields:v}),...await Q({path:S,scope:"project",op:"create:history",item_id:y.metadata.id,item_type:y.metadata.type,before:x,after:y,changed_fields:v})],Qn({id:y.metadata.id,op:"create",item_type:y.metadata.type,status:y.metadata.status,current:yn(y.metadata,v),changed_fields:v})}finally{await T.release()}return{source_id:s.id,item:structuredClone(y.metadata),changed_fields:v,warnings:[...$s(w),...H,...P,...F],...w===void 0?{}:{similarity_advisory:w}}}function Rl(){return Hc.map(e=>e.field).join(", ")}var zO=Object.freeze({fields:[],reason:void 0,optionKeys:new Set});function HO(e){return(e??[]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function rb(e,t){let n=tr(t,"defer"),r=tr(t,"defer-reason"),o=HO(e.defer),i=e.deferReason?.trim();if(o.length===0){if(i!==void 0&&i.length>0)throw new l(`${r} needs ${n}: name the fields whose values are not known yet.`,m.USAGE,{code:"create_deferral_fields_required",required:`Pass ${n} with ${r}, or drop ${r}.`,nextSteps:[`Deferrable fields: ${Rl()}.`]});return zO}let s=new Map;for(let c of o){let d=Bc(c);if(d===void 0)throw new l(`${n} cannot defer "${c}". Deferrable fields: ${Rl()}.`,m.USAGE,{code:"create_deferral_field_unsupported",required:`Defer only ${Rl()}; supply every other field, or clear a repeatable option with its --clear-* flag.`});s.set(d.field,d)}if(i===void 0||i.length===0)throw new l(`${n} requires ${r}: record why the deferred values are not known yet.`,m.USAGE,{code:"create_deferral_reason_required",required:`Pass ${r} "<why>", for example the system the record was imported from.`});let a=Hc.filter(c=>s.has(c.field));return{fields:a,reason:i,optionKeys:new Set(a.map(c=>c.option))}}function xl(e,t,n,r,o={}){let i=e.fields.filter(c=>{let d=t[c.option];return typeof d=="string"&&d.trim().length>0||o[c.field]!==void 0||n.has(c.field)});if(i.length===0)return;let s=tr(r,"defer"),a=i.map(c=>c.field).join(", ");throw new l(`Cannot both defer and set ${a}: ${s} records a value as not known yet.`,m.USAGE,{code:"create_deferral_conflict",required:`Drop ${s} for ${a}, or drop the value (or unset) you supplied for it.`})}function ob(e){if(e.fields.length!==0)return Vc(e.fields.map(t=>({field:t.field,reason:e.reason})))}function ib(e,t=[]){let r=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(s=>typeof s=="string").flatMap(s=>s.split(",")).map(s=>Bc(s)).filter(s=>s!==void 0),o=new Set(r.map(s=>s.field)),i=t.filter(s=>s.commands.includes("create")&&o.has(s.metadata_key)).flatMap(s=>Yf(s));return[...r.map(s=>s.option),...i]}function sb(e,t,n,r,o={}){let i=new Set(t.fields.map(u=>u.field)),s=n.filter(u=>u.commands.includes("create")),a=u=>u.required!==!0&&i.has(u.metadata_key),c=new Set(s.filter(a).map(u=>`--${u.cli_flag}`)),d=new Set(s.filter(u=>!a(u)&&Jf(u,r)&&qi(o,u)===void 0).map(u=>`--${u.cli_flag}`));return e.filter(u=>!c.has(u)||d.has(u))}var BO="hierarchy-integrity";async function ua(e){let t=e.required?await Yr(e.pmRoot,BO,e.ttlSeconds,e.author,!1,!1,e.waitMs,{waitPolicy:"progress"}):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}function pa(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function fa(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function _a(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(vc.includes(t))return t;let n=ge(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new l("Confidence must be an integer 0..100 or one of low|med|medium|high",m.USAGE);return n}function ha(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new l("Regression must be one of true|false|1|0",m.USAGE)}var ab=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds","phase"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];var WO=["documentAnnotationSnapshot","runtimeFieldCommands","ownershipMetadataBypass","ownershipDependencyBypass"];function ga(e){let t=ab.find(([r])=>r===e)?.[1]??e.replaceAll(/_([a-z])/gu,(r,o)=>o.toUpperCase()),n=[["update",md],["create",ld]].flatMap(([r,o])=>o.flatMap(i=>{if(i.target!==t)return[];let s=i.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:r,flag:s}]}));return{recovery:{provided_fields:[e],...n.length>0?{suggested_flags:[...new Set(n.map(r=>r.flag))]}:{}},nextSteps:n.length>0?n.map(({command:r,flag:o})=>`Use the declared core mutation: pm ${r}${r==="update"?" <id>":""} ${o} <value>; inspect its help for other required options.`):[`No dedicated create/update CLI mutation flag is declared for "${e}". Use its owning lifecycle, evidence, or importer API; --field cannot mutate core metadata.`]}}var db={create:{name:"create",usage:"pm create",sdkScope:"create options"},update:{name:"update",usage:"pm update <id>",sdkScope:"update options"},update_many:{name:"update-many",usage:"pm update-many <selection flags>",sdkScope:"update options of the update-many request"}};function cb(e){return e.flatMap(t=>[t.flag,...t.short===void 0?[]:[t.short],...t.aliases??[]])}function lb(e){if(e==="update_many"){let o=lb("update"),i=cb(Ge("update-many"));return{options:new Set([...o.options,...i.map(s=>Kc(s))]),flags:new Set([...o.flags,...i])}}let t=e==="update"?md:ld,n=cb([...Ge(e),...Vn]),r=[...t.flatMap(o=>[o.target,...o.keys]),...n.map(o=>Kc(o)),...e==="update"?WO:[]];return{options:new Set(r),flags:new Set(n)}}function VO(e,t){let n=db[t];return e===void 0?`SDK: every option name for this field is shared with another declared field or an option of pm ${n.name}; no SDK option sets it alone.`:`SDK: pass ${e} in the ${n.sdkScope}.`}function YO(e,t,n,r){return e.definitions.some(o=>o.metadata_key===t.metadata_key&&o.commands.includes(n)&&qi(r,o)!==void 0)}function ya(e,t,n){let r=db[t],o=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([i])=>i!=="field"));return i=>{let s=Lf(i),a=e.definitions.filter(h=>h.metadata_key===s||h.key===s),c=a.find(h=>h.commands.includes(t))??a[0];if(c===void 0)return;let d=`Inspect the value contract with: pm schema show-field ${c.key}`;if(!c.commands.includes(t))return{recovery:{provided_fields:[i]},nextSteps:[`The project schema declares "${c.key}" for ${c.commands.join(", ")} only; ${r.name} cannot set it.`,d]};if(o!==void 0&&YO(e,c,t,o))return{recovery:{provided_fields:[i]},nextSteps:[`This invocation already sets "${c.key}" through a declared flag or option; drop the --field ${i} assignment so the field receives one value.`,d]};let u=lb(t),p=Vf(c,e,u,t),f=p===void 0?`Every CLI spelling of "${c.key}" is shared with another declared field or an option of pm ${r.name}; give it a distinct cli_flag in the project schema.`:`Use the declared project-schema flag: ${r.usage} ${qc(p)} <value>`;return{recovery:{provided_fields:[i],...p===void 0?{}:{suggested_flags:[qc(p)]}},nextSteps:[f,VO(Wf(c,e,u.options,t),t),d]}}}var JO=new Set(["event","meeting","reminder","milestone","decision","adr"]);function mb(e,t,n,r){if(JO.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=xt("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm claim ${e} --start`,to_status:o}}function pb(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,m.USAGE)}function Il(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function at(e,t,n,r=n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,m.USAGE,{field:r,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var fb=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function XO(e,t){return t==="defined"?e!==void 0:!!e}function ub(e,t,n){if(!XO(e,n))return;let r=ge(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,m.USAGE);return r}function QO(e,t,n){let r=e?se(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new l("--event recur_until must be at or after start",m.USAGE);return r}function ZO(e){return Array.from(new Set(Il(e).map(t=>at(t.toLowerCase(),Lu,"event weekday")))).sort((t,n)=>bc(t)-bc(n))}function e$(e){return Array.from(new Set(Il(e).map(t=>{let n=ge(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new l("--event recur_by_month_day values must be integers 1..31",m.USAGE);return n}))).sort((t,n)=>t-n)}function t$(e,t){return Array.from(new Set(Il(e).map(n=>se(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function _b(e,t,n,r){let o=e.recur_freq?.trim(),i=e.recur_interval?.trim(),s=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![o,i,s,a,c,d,u].some(k=>k!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",m.USAGE);let f=at(o.toLowerCase(),$u,"event recurrence frequency"),h=ub(i,"recur_interval",r),_=ub(s,"recur_count",r),g=QO(a,t,n),y=ZO(c),w=e$(d),v=t$(u,n);return{freq:f,interval:h,count:_,until:g,by_weekday:y.length>0?y:void 0,by_month_day:w.length>0?w:void 0,exdates:v.length>0?v:void 0}}function Ar(e,t=st()){let n=t.resolve(e);if(n)return n.kind;let r=new Set(ni),o=[...ni,...t.list().filter(({kind:i})=>!r.has(i)).flatMap(({kind:i,aliases:s})=>[i,...s])];throw new l(`Invalid dependency kind value "${e}". Allowed: ${o.join(", ")}`,m.USAGE,{field:"kind",value:e,recovery:{allowed_values:o},required:`dependency kind must be one of: ${o.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function Fo(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,m.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function Mo(e,t,n=st()){for(let r of t??[])try{ju(e,r.id,r.kind,n)}catch(o){throw new l(mt(o),m.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function hb(e,t){return(await te(e,{schema:t})).document.metadata.created_at}async function n$(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await j(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:hb(n,t.schema)}function r$(e){let t=e.registry.require(e.dependency.kind);return new l(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,m.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function o$(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:i})=>i===null?[]:[[o,i]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await hb(n.get(o),e.context.schema)])));for(let o of e.holders){let i=await n$(o,e.context);if(i!==void 0)for(let s of t){let a=r.get(s.id),c=Date.parse(i),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw r$({holder:o,dependency:s,sourceCreatedAt:i,targetCreatedAt:a,registry:e.registry})}}}async function Pn(e){let t=e.registry??st(),n=(e.dependencies??[]).filter(s=>!U_(s.source_kind)),r=[...new Set(n.map(s=>s.id))],o=await Promise.all(r.map(async s=>({target:s,located:await j(e.pmRoot,s,e.idPrefix,e.itemFormat,e.typeToFolder)}))),i=o.filter(({located:s})=>s===null).map(({target:s})=>s).sort((s,a)=>s<a?-1:1);if(i.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${i.length===1?"":"s"} not found: ${i.join(", ")}`,m.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:i,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${i.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:i,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${i[0]}" --limit 10`}});return await o$({dependencies:n,missingTargets:i,resolutions:o,holders:e.holders??[],registry:t,context:e}),i.map(s=>`dependency_target_unresolved:${s}`)}var i$={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function s$(e){return i$[e]}function Ol(e){return s$(e)!==void 0}var gb="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",a$="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",c$=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,d$=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,wb=1e3,$l=60*wb,l$=60*$l;function yb(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new l(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,m.USAGE);return n.toISOString()}function m$(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new l(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,m.USAGE);let o=r.replace(/^([+-]?\d+)mo$/i,"$1m"),i=c$.exec(r);if(i){let c=i[1]==="-"?-1:1,d=Number.parseInt(i[2],10)*c;return yb(n.getTime()+d*$l,r)}let s=d$.exec(r);if(s){let[,c,d,u,p]=s;if(d||u||p){let h=c==="-"?-1:1,_=Number.parseInt(d??"0",10),g=Number.parseInt(u??"0",10),y=Number.parseInt(p??"0",10),w=_*l$+g*$l+y*wb;return yb(n.getTime()+h*w,r)}}let a=o.startsWith("+")||o.startsWith("-")?o:`+${o}`;return se(a,n,"event.duration")}function vb(e,t,n,r){if(t&&n)throw new l(a$,m.USAGE);if(n){let i=m$(e,n);if(i<e)throw new l(gb,m.USAGE);return i===e?void 0:i}if(!t)return;let o=se(t,r,"event.end");if(o<e)throw new l(gb,m.USAGE);if(o!==e)return o}var u$=["at","date","text","title"],p$=["start","date","end","duration","title","description","location","timezone","all_day",...fb],f$=["key","value"];function bb(e,t){return t==="trimmed"?e?.trim():e}function _$(e,t){return t==="defined"?e!==void 0:!!e}function wa(e,t,n){return e.map(r=>{let o=_e(r,"--reminder");rt(o,"--reminder",u$);let i=bb(o.at??o.date,n.valueMode),s=bb(o.text??o.title,n.valueMode);if(!i||!s)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",m.USAGE);let a=s.trim();if(!a)throw new l("--reminder text must not be empty",m.USAGE);return{at:se(i,t,"reminder.at"),text:a}})}function va(e,t,n){return e.map(r=>{let o=_e(r,"--event");rt(o,"--event",p$);let i=(o.start??o.date)?.trim();if(!i)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",m.USAGE);let s=se(i,t,"event.start"),a=o.end?.trim(),c=o.duration?.trim(),d=vb(s,a,c,t),u=o.title,p=o.description,f=o.location,h=o.timezone,_=u?.trim(),g=p?.trim(),y=f?.trim(),w=h?.trim(),v=[["title",u,_],["description",p,g],["location",f,y],["timezone",h,w]];for(let[x,F,P]of v)if(F!==void 0&&!P)throw new l(`--event ${x} must not be empty`,m.USAGE);let k=o.all_day?.trim(),S=_b(o,s,t,n.recurrenceEmptyNumericGuard),T=_$(k,n.allDayEmptyGuard)?pb(k,"--event all_day"):void 0;return{start_at:s,end_at:d,title:_,description:g,location:y,all_day:T,timezone:w,recurrence:S}})}function ba(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new l("--type-option values must not be empty",m.USAGE);let o,i;if(r.includes(",")||r.includes(`
|
|
21
|
+
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=_e(r,"--type-option");rt(a,"--type-option",f$),o=a.key?.trim(),i=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),d=a;if(a<=0&&c>0&&(d=c),d<=0||d===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",m.USAGE);o=r.slice(0,d).trim(),i=r.slice(d+1).trim()}if(!o||!i)throw new l("--type-option requires key and value",m.USAGE);t[o]=i}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}var h$=["strict","progressive"],g$=["lightweight"],Eb=new Set(["Reminder","Meeting","Event"]),y$=new Set(["author","created_at","text"]),ka=new Map(Gh.map(e=>[e.optionKey,e.canonical]));function w$(e,t){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,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function v$(e,t){let n=e.default_status;if(n!==void 0){let r=de(n,t);if(r)return r}return t.open_status}function Ll(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid created_at timestamp "${e}"`,m.USAGE);return new Date(n).toISOString()}var b$=ks();function Cb(e){if(ht(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i};co(t.template)&&(t.template=void 0);let r=new Set([...ka.keys(),"rank"]);for(let o of r){if(ht(e,o))continue;let i=t[o];if(typeof i!="string"||!co(i))continue;let s=o==="rank"?"order":ka.get(o)??o;n(s),t[o]=void 0}return ue(e,As(t,b$))}function He(e){if(e!==void 0)return e}var kb=["id","kind","type","author","created_at","source_kind"],Sa=["path","scope","note"];function k$(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(i=>{let s=i.trim(),a=Aa(s,kb);Fo(s,a);let c=a?_e(i,"--dep"):{id:s,kind:"related"};a&&rt(c,"--dep",kb);let d=He(c.id),u=S$(He(c.kind??c.type));if(!d||!u)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",m.USAGE);if(d.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,m.USAGE);let p=_o(He(c.source_kind)),f=Xn(c.author,"--dep author");return{id:ho(d,n,p),kind:Ar(u),created_at:Ll(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function S$(e){return typeof e=="string"?st().resolve(e)?.kind??e.trim():e}function Aa(e,t){return Y_(e,t)?!0:es(e)}function Fn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Ne(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(s=>{let a=s.trim(),c=()=>{if(a.length===0)throw new l(`${e} requires text=<value>`,m.USAGE);return{created_at:n,author:r,text:a}},d;try{d=_e(s,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(d).filter(f=>!y$.has(f)).length>0)return{created_at:Ll(d.created_at,n),author:Xn(d.author,`${e} author`)??r,text:a};let p=d.text??"";if(p==="")throw new l(`${e} requires text=<value>`,m.USAGE);return{created_at:Ll(d.created_at,n),author:Xn(d.author,`${e} author`)??r,text:p}}),explicitEmpty:!1})}function Pl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),o=Aa(r,Sa);fd(r,"--file","file path",o);let i=o?_e(n,"--file"):{path:r};if(o&&rt(i,"--file",Sa),!i.path)throw new l("--file requires path=<value> or a bare file path",m.USAGE);return{path:i.path,scope:at(i.scope??"project",St,"file scope"),note:He(i.note)}}),explicitEmpty:!1})}function Nl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),o=Aa(r,$t);fd(r,"--test","test command",o);let i=o?rs(_e(n,"--test"),"--test"):{command:r},s=He(i.command),a=He(i.path);if(!s)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);let c=He(i.timeout_seconds),d=He(i.timeout);if(c&&d&&c!==d)throw new l("--test timeout and timeout_seconds must match when both are provided",m.USAGE);let u=c??d;return{command:s,path:a,scope:at(i.scope??"project",St,"test scope"),timeout_seconds:u?ge(u,"timeout_seconds"):void 0,pm_context_mode:ea(i.pm_context_mode,"--test"),workspace_context_mode:$n(i.workspace_context_mode,"--test"),env_set:Ro(i.env_set,"--test"),env_clear:xo(i.env_clear,"--test"),shared_host_safe:Zs(i.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Ln(i.assert_stdout_contains),assert_stdout_regex:Sr(i.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Ln(i.assert_stderr_contains),assert_stderr_regex:Sr(i.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:ta(i.assert_stdout_min_lines,"--test"),assert_json_field_equals:na(i.assert_json_field_equals,"--test"),assert_json_field_gte:ra(i.assert_json_field_gte,"--test"),note:He(i.note),phase:br(i.phase,"--test")}}),explicitEmpty:!1})}function Fl(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),o=Aa(r,Sa),i=o?_e(n,"--doc"):{path:r};if(o&&rt(i,"--doc",Sa),!i.path)throw new l("--doc requires path=<value> or a bare doc path",m.USAGE);return{path:i.path,scope:at(i.scope??"project",St,"doc scope"),note:He(i.note)}}),explicitEmpty:!1})}function A$(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--reminder","Use --clear-reminders to clear reminders."),{values:wa(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function E$(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--event","Use --clear-events to clear linked events."),{values:va(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function C$(e,t,n,r=[]){let o=[...ri.filter(i=>e[i]!==void 0),...r.filter(i=>e[i]!==void 0),...t.length>0?["body"]:[],...n.map(i=>`unset:${i}`)];return Array.from(new Set(o))}function T$(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Sb(e,t,n){let r=Mr("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,m.CONFLICT);return r}function R$(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function Tb(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function x$(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Sb(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Sb(r,e.name,"required_create_repeatables"));return n}function I$(e,t,n,r){for(let o of e)if(!(!Tb(t,o)&&!n.has(o)))throw new l(`Option ${Oe("create",o)} is disabled for type "${r}" by command_option_policies`,m.USAGE)}function O$(e,t,n){if(t!=="strict")return;let r=e.filter(i=>n.has(i)&&!Ol(i));if(r.length===0)return;let o=[...new Set(r.map(i=>Oe("create",i)))].sort((i,s)=>i.localeCompare(s));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset cannot satisfy a required scalar option (only repeatable options accept an explicit --clear-* empty set)`,m.USAGE)}function $$(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ne(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:ba(e),explicitEmpty:!1})}async function L$(e){return await ts(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function P$(e){return Ot(e)?await L$(e):e}function N$(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${h$.join(", ")}`,m.USAGE)}function F$(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new l("--schedule-preset must not be empty",m.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new l(`Invalid --schedule-preset value "${e}". Allowed: ${g$.join(", ")}`,m.USAGE)}function M$(e,t,n){let r=N$(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",m.USAGE);return"progressive"}function D$(e,t,n,r,o,i){let s=e.name,a=R$(t),c=x$(e,n),d=Bn(e,"create",c);if(d.errors.length>0)throw new l(d.errors.join("; "),m.CONFLICT);I$(d.disabled,a,r,s),O$(d.required,n,r);let u=f=>f==="author"&&o!=="unknown"||f==="status"&&e.default_status!==void 0||i.has(f)||r.has(f)&&Ol(f)?!0:Tb(a,f),p=d.required.filter(f=>!u(f));return[...new Set(p.map(f=>Oe("create",f)))].sort((f,h)=>f.localeCompare(h))}var Rb=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function U$(e,t){let n=[];for(let r of e){let o=r.match(Rb);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function j$(e,t){return e.filter(n=>{let r=n.match(Rb);return!r||r[2]!==t})}function G$(e,t,n,r){let o=j$(e,t);if(o.length===0)return;let i=xb(n,[],[],r.open_status);throw new l(o.join("; "),m.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[i],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function q$(e,t){let r=e.options.find(o=>o.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function K$(e,t,n){let r=e.split("/")[0];switch(r){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[r,'"<value>"']}}function xb(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],i=["--status","--priority","--message"],s=[...new Set([...i,...t])],a=new Set(["--title","--description","--type"]);for(let c of s){if(a.has(c))continue;let d=Ob[c];o.push(...d?[d]:K$(c,e.name,r)),a.add(c)}for(let c of n){let d=q$(e,c);o.push("--type-option",`${c}=${d}`)}return o.join(" ")}function Ml(e,t,n="cli"){let r=e?.trim();if(!r){let o=n==="sdk";throw t==="--title"?e!==void 0?new l(o?"Title cannot be empty or whitespace-only. Retry: pass a non-empty title.":"Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",m.USAGE):new l(o?'Missing required option title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass title (example: client.create({ type: "Issue", title: "Fix login bug" })).':'Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',m.USAGE):new l(`Missing required option ${o?tr("sdk",t.replace(/^--/u,"")):t}`,m.USAGE)}return r}function z$(e,t,n){let r={};for(let[o,i]of Object.entries(e))r[o]=Array.isArray(i)?[...i]:i;for(let[o,i]of Object.entries(t))i!==void 0&&(r[o]=Array.isArray(i)?[...i]:i);return H$(r,t,n),ue(t,r)}function H$(e,t,n){let r=[...Cd(t.unset,n).optionKeys,...ib(t.defer,n?.definitions)].flatMap(o=>o==="order"?[o,"rank"]:o==="tags"?[o,"addTags"]:[o]);for(let o of r)Reflect.get(t,o)===void 0&&Reflect.deleteProperty(e,o)}function B$(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function W$(){let e=I();return e?e.commands.some(t=>t.action==="templates-show"||B$(t.command)==="templates show"):!1}function V$(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new l(`Templates package returned invalid payload for template "${t}". Expected an options object.`,m.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Templates package returned invalid options for template "${t}".`,m.GENERIC_FAILURE);let r={};for(let[o,i]of Object.entries(n)){if(typeof i=="string"||typeof i=="number"||typeof i=="boolean"){r[o]=i;continue}if(Array.isArray(i)&&i.every(s=>typeof s=="string")){r[o]=[...i];continue}throw new l(`Templates package returned unsupported option value for "${o}" in template "${t}".`,m.GENERIC_FAILURE)}return r}async function Y$(e,t,n){if(!W$())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",m.USAGE);let r=await Vi({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled)throw Object.hasOwn(r,"cause")?vs("templates show",r):new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.`,m.USAGE);return V$(r.result,e)}function X(e,t,n){return e.has(t)||n===void 0?void 0:He(n)}function Nn(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var J$=new Set(["milestone","meeting","reminder","event"]);function Ib(e,t,n,r){let o=t!==void 0,i=n!==void 0&&n.length>0,s=r!==void 0&&r.length>0;return J$.has(e.toLowerCase())&&!o&&!i&&!s}function X$(e,t,n,r,o){let i=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&i.push(`event_without_schedule:${t}:no_time_set`),Ib(e,n,r,o)&&i.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),i}async function Q$(e,t,n,r){if(t.inheritFocus!==!0||e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await Hi(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function Z$(e,t,n,r,o,i,s){let a=lr(us(o,s),t.id_prefix);if(Ji(a))return{parent:a,warnings:[]};if(fs(r,a,t.id_prefix,s),await j(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let d=Pe(a,t.id_prefix);return{parent:a,warnings:ps(d,i,s).warnings}}async function eL(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await Z$(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy,e.audience)}async function tL(e){if(e.explicitId===void 0)return ro(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});yt(e.explicitId,"create","id");let t=e.explicitId.trim();if(t.length===0||sh(t))throw new l("--id must not be empty or use a placeholder token",m.USAGE);let n=Pe(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",m.USAGE);return n}function Ab(e,t,n,r,o,i){let s=X(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let a=_s(r,s,o,i);return{value:a.value,warnings:a.warnings}}async function nL(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:i,status:s,statusExplicit:a,nowValue:c,author:d}=e,u=e.dependencyValues;if(i===void 0)return{dependencyValues:u,status:s};let p=Pe(i,n.id_prefix),f=await j(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:s};if((u??[]).some(g=>g.id===f.id&&g.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:s};let _=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((g,y)=>g.localeCompare(y))[0]??o.open_status;return{dependencyValues:u,status:_}}function rL(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let o=t.governance.create_default_type?.trim();if(o&&o.length>0&&Ce(o,n)){e.type=o;return}Ce("Task",n)&&(e.type="Task")}function oL(e,t){return e.options.filter(n=>Mr("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,m.USAGE)})}async function iL(e,t,n,r,o){let i=e,s=[];if(i.template!==void 0){let _=i.template.trim();if(_.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",m.USAGE);let g=await Y$(_,t,n);i=Cb(mo("create",z$(g,i,et(r.schema))))}if(i.type===void 0&&rL(i,r,o),i.type===void 0)throw new l("Missing required option --type <value>",m.USAGE);let a=Ce(i.type,o);if(!a){let _=ch(i.type),g=_?Ce(_,o):void 0;if(g)s.push(`type_coercion:${i.type.trim()}:${g}`),i.type=g,a=g;else throw new l(Ht(i.type,o.types,Bt(n,r.schema)),m.USAGE)}let c=si(a,o);if(!c)throw new l(`Invalid type value "${i.type}"`,m.USAGE);let d=c.name,u=oL(c,i),p=u.map(_=>`${_.key}=${String(i[_.key])}`);if(p.length>0){i.typeOption=[...p,...i.typeOption??[]];for(let _ of u)delete i[_.key]}let f=F$(i.schedulePreset);if(f!==void 0&&!Eb.has(d))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,m.USAGE);let h=M$(i.createMode,f,r.governance.create_mode_default);return{resolvedOptions:i,typeDefinition:c,type:d,schedulePreset:f,createMode:h,warnings:s}}function sL(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let i of o)if(i.enabled){if(i.values&&i.values.length>0)throw new l(`Cannot combine ${i.clearFlag} with ${i.valueFlag}`,m.USAGE);n.add(i.metadataKey),r.add(i.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function aL(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=ka.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Oe("create",r)}`,m.USAGE)}}function cL(e){if(ht(e))return;let t=(n,r)=>{if(ht(e,r))return;let o=ka.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;Ss(n,Oe("create",r),i)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function dL(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,m.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,m.USAGE)}var Ob={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function lL(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:i,type:s,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(_=>{let g=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${g}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),u=[xb(n,r,o,i),...d.map(_=>_.example)].join(" "),p=[`Run "pm create --help --type ${s}" for type-aware required option guidance.`,...t.filter(_=>_==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+s+").")];a==="strict"&&(p.push('For staged onboarding, retry with "--create-mode progressive".'),Eb.has(s)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&p.push(`Required custom field formats: ${d.map(_=>_.description).join("; ")}.`);let f=[...new Set(t.flatMap(_=>{let g=_.split(" ",1)[0],y=Ob[g];return y?[y]:[]}))];f.length>0&&p.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let h=t.length===1?`Missing required option ${t[0]} for type "${s}"`:`Missing required options ${t.join(", ")} for type "${s}"`;throw new l(h,m.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${s}" in one invocation.`,examples:[...f.map(_=>`pm create --type ${s} ${_} ...`),u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function mL(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",m.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Vt(t.tags):[];return rr(n,t.addTags)}function uL(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new l("--order and --rank must match when both are provided",m.USAGE);let n=t.order??t.rank,r=Nn(e,"order",n,o=>ge(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",m.USAGE);return r}function pL(e,t,n,r,o,i){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",m.USAGE);let s=e!==t.close_status?void 0:r.completedAt===void 0?i:se(r.completedAt,new Date(i),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:s,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:Sl(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:s,warnings:[]}}async function fL(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:i,author:s,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:h,allowDuplicate:_}=e,g=Et(t,n,r,o.item_format,i.type_to_folder),y=Ze(t,r),w=st(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(x=>js(x.kind,w)),k=await ua({pmRoot:t,author:s,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:v}),S=v,T=[];try{let x=await ft(t,r,o.locks.ttl_seconds,s,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let F=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await ye(t,o.item_format,i.type_to_folder,void 0,o.schema):void 0,P=await j(t,r,o.id_prefix,o.item_format,i.type_to_folder);if(P)throw new l(`Item "${r}" already exists`,m.CONFLICT,{code:"item_already_exists",id:P.id,path:P.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${P.id}.`]});if(F){Gs(F,[...F,c.metadata],w);let re=D(o.schema);Is(F,[...F,c.metadata],r,J=>le(J,re),w)}let H=await bn({pmRoot:t,settings:o,operation:"create",author:s,before:null,after:c});await wn({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,author:s,sdk:kn({pmRoot:t,settings:o,typeToFolder:i.type_to_folder})});let B=await Qt(t,s,{required:o.governance.duplicate_detection_mode==="strict"&&_!==!0}),Y=[];try{o.governance.duplicate_detection_mode==="strict"&&_!==!0&&await ur(h,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await x.fence(async()=>{await ae(g,ut(c,{format:o.item_format,schema:o.schema,extensionFieldNames:a}));try{let re=qe({nowIso:f,author:s,op:"create",before:d,after:c,message:u,context:H.decisions.length===0?void 0:{workflow_policies:H.decisions}});await Wt(y,re)}catch(re){throw await Hn(g),re}}),S&&(await k(),S=!1),Y=await Zt({pmRoot:t,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:g,document:c})}finally{await B()}T=[...H.warnings,...F?Us(F,[...F,c.metadata],r):[],...Y,...await Q({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:p}),...await Q({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:p})],Qn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:yn(c.metadata,p),changed_fields:p})}finally{await x.release()}}finally{S&&await k()}return T}async function on(e,t){let n=mo("create",e),r=gt(n),o=Cb(await P$(n)),i=E(process.cwd(),t.path);await O(i);let s=await A(i),a=D(s.schema),c=et(s.schema),d=$(s,I()),u=await iL(o,t,i,s,d);o=u.resolvedOptions;let{typeDefinition:p,type:f,createMode:h}=u,_=Cd(o.unset,c),{explicitUnsets:g,clearOptionKeys:y}=sL(o,_);aL(o,_),cL(o);let w=rb(o,r);xl(w,o,_.metadataKeys,r);let v=R(He(o.author),s.author_default),k=D$(p,o,h,y,v,w.optionKeys),S=C(),T=k$(o.dep,S,s.id_prefix,v),x=Fn("--comment",o.comment,S,v),F=Fn("--note",o.note,S,v),P=Fn("--learning",o.learning,S,v),H=Pl(o.file),B=Nl(o.test);B.values=await fr(B.values,v,S);let Y=Fl(o.doc),re=A$(o.reminder,S),J=E$(o.event,S),Gt=$$(o.typeOption),G=Dr(f,Gt.values,d),he=I(),qt=Ue(he),dn=oi(o.field,he,ga,ya(c,"create",o)),Ye=Xf(o,c,f);xl(w,o,_.metadataKeys,r,Ye.values),Ye.missing_required_flags=sb(Ye.missing_required_flags,w,c.definitions,f,o);let Jo=new Set(Ye.missing_required_flags),ln=c.definitions.filter(ie=>Jo.has(`--${ie.cli_flag}`));dL(dn,Ye,_);let ic=U$(G.errors,f),Xo=ic.map(ie=>`--type-option ${ie}=<value>`),sc=[...new Set([...k,...Xo,...Ye.missing_required_flags])].sort((ie,hc)=>ie.localeCompare(hc));lL({combinedMissingFlags:sc,typeDefinition:p,missingRequiredCreateFlags:k,missingRequiredTypeOptionKeys:ic,openStatus:a.open_status,type:f,createMode:h,missingRequiredRuntimeFields:ln}),G$(G.errors,f,p,a);let Je=await tL({pmRoot:i,settings:s,typeRegistry:d,explicitId:o.id}),kt=o.status!==void 0?w$(o.status,a):v$(p,a),Xe=o.priority!==void 0?Xt(o.priority):2,N=_.metadataKeys,Qo=mL(N,o),nt=Nn(N,"deadline",o.deadline,ie=>se(ie,new Date(S),"deadline")),ac=Nn(N,"estimated_minutes",o.estimatedMinutes,ie=>or(ie,"estimated-minutes")),Qe=X(N,"acceptance_criteria",o.acceptanceCriteria),cc=X(N,"definition_of_ready",o.definitionOfReady),Zo=uL(N,o),dc=X(N,"goal",o.goal),ei=X(N,"objective",o.objective),aE=X(N,"value",o.value),cE=X(N,"impact",o.impact),dE=X(N,"outcome",o.outcome),lE=X(N,"why_now",o.whyNow),mE=X(N,"assignee",o.assignee),uE=N.has("author")?void 0:He(o.author)??v,pE=X(N,"parent",o.parent),hu=await Q$(pE,o,N,i),lc=hu.parent,fE=hu.parentSource,_E=X(N,"reviewer",o.reviewer),hE=Nn(N,"risk",o.risk,ie=>at(pa(ie),Pr,"risk")),gE=Nn(N,"confidence",o.confidence,ie=>_a(ie)),yE=o.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,gu=s.validation.sprint_release_format,mn=[...u.warnings,...X$(f,Je,nt,re.values,J.values)],yu=await eL({itemId:Je,parent:lc,pmRoot:i,settings:s,typeRegistry:d,policy:yE,audience:r});lc=yu.parent,mn.push(...yu.warnings);let wu=Ab(N,"sprint",o.sprint,"sprint",gu,r),wE=wu.value;mn.push(...wu.warnings);let vu=Ab(N,"release",o.release,"release",gu,r),vE=vu.value;mn.push(...vu.warnings);let bu=X(N,"blocked_by",o.blockedBy),ku=await nL({pmRoot:i,settings:s,typeRegistry:d,statusRegistry:a,blockedBy:bu,dependencyValues:T.values,status:kt,statusExplicit:o.status!==void 0,nowValue:S,author:v}),mc=ku.dependencyValues;Mo(Je,mc),mn.push(...await Pn({pmRoot:i,dependencies:mc,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:d.type_to_folder,allowUnresolved:o.allowUnresolvedDeps,holders:[{id:Je,createdAt:S}],schema:s.schema})),kt=ku.status;let bE=X(N,"blocked_reason",o.blockedReason),kE=X(N,"unblock_note",o.unblockNote),SE=X(N,"reporter",o.reporter),AE=Nn(N,"severity",o.severity,ie=>at(fa(ie),Nr,"severity")),EE=X(N,"environment",o.environment),CE=X(N,"repro_steps",o.reproSteps),Su=X(N,"resolution",o.resolution),TE=X(N,"expected_result",o.expectedResult),RE=X(N,"actual_result",o.actualResult),xE=X(N,"affected_version",o.affectedVersion),IE=X(N,"fixed_version",o.fixedVersion),OE=X(N,"component",o.component),$E=Nn(N,"regression",o.regression,ie=>ha(ie)),LE=X(N,"customer_impact",o.customerImpact),uc=Ml(o.title,"--title",r),pc=o.description??"",ti=o.body??"",Au=await ur({title:uc,description:pc,body:ti},{pmRoot:i,mode:s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:o.allowDuplicate});mn.push(...$s(Au));let fc=pL(kt,a,s,o,Su,S),PE=fc.closeReason,NE=kt===a.close_status?S:void 0,FE=fc.completedAt;mn.push(...fc.warnings);let zn=Yc({id:Je,title:uc,description:pc,type:f,type_options:G.normalized,status:kt,closed_at:NE,completed_at:FE,close_reason:PE,priority:Xe,tags:Qo,created_at:S,updated_at:S,deadline:nt,assignee:mE,author:uE,estimated_minutes:ac,acceptance_criteria:Qe,deferred_fields:ob(w),definition_of_ready:cc,order:Zo,goal:dc,objective:ei,value:aE,impact:cE,outcome:dE,why_now:lE,parent:lc,reviewer:_E,risk:hE,confidence:gE,sprint:wE,release:vE,blocked_by:bu,blocked_reason:bE,unblock_note:kE,reporter:SE,severity:AE,environment:EE,repro_steps:CE,resolution:Su,expected_result:TE,actual_result:RE,affected_version:xE,fixed_version:IE,component:OE,regression:$E,customer_impact:LE,dependencies:mc,comments:x.values,notes:F.values,learnings:P.values,files:H.values,tests:B.values,docs:Y.values,reminders:re.values,events:J.values,...dn,...Ye.values});Hf(zn),ii(zn,he),vd(zn,i);let ME=pt({metadata:zn,body:ti},{schema:s.schema,extensionFieldNames:qt}),DE={metadata:{},body:""},Eu=[...g].sort((ie,hc)=>ie.localeCompare(hc)),UE=T$(o.message,Eu),Cu=C$(zn,ti,Eu,[...Object.keys(dn),...Object.keys(Ye.values??{})]),jE=await fL({pmRoot:i,type:f,id:Je,settings:s,typeRegistry:d,author:v,extensionFieldNames:qt,afterDocument:ME,beforeDocument:DE,historyMessage:UE,changedFields:Cu,nowValue:S,similarityCandidate:{title:uc,description:pc,body:ti},allowDuplicate:o.allowDuplicate}),_c=structuredClone(zn);h==="strict"&&g.has("dependencies")&&(_c.dependencies=[]);let GE=mb(Je,f,kt,a);return Ib(f,nt,re.values,J.values)&&D_(`[pm] warning: ${f} '${Je}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Je} --deadline <ISO>' or 'pm update ${Je} --event "start=<ISO>,end=<ISO>"'.`),{item:_c,changed_fields:Cu,warnings:[...lo("create",o,r==="sdk",_c),...mn,...jE],...Object.fromEntries([["parent_source",fE],["next_transition",GE],["similarity_advisory",Au]].filter(ie=>ie[1]!==void 0))}}import Ea from"node:path";async function Dl(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=await vh({pmRoot:r,settings:o,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),a=s.targetPath?Ea.relative(r,s.targetPath).split(Ea.sep).join("/"):void 0;return{item:s.item,changed_fields:s.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:s.item.status,...a?{target_path:a}:{},history_retained:Ea.relative(r,Ze(r,s.item.id)).split(Ea.sep).join("/"),tombstone_retention:"retain_append_only",warnings:s.warnings}}async function _L(e){await O(e)}async function Ul(e,t,n){let r=E(process.cwd(),n.path);if(await _L(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",m.USAGE);let p=await A(r),f=gn(R(void 0,p.author_default));return await i_(r),await Kd({pmRoot:r,settings:p,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await Hi(r);if(p===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let f=await hL(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let i=await A(r),s=$(i,I()),a=await j(r,e,i.id_prefix,i.item_format,s.type_to_folder);if(!a)throw await it(r,e,i.id_prefix,s.type_to_folder);let c=Pe(a.id,i.id_prefix),d=await te(a,{schema:i.schema}),u=$b(d.document.metadata.title);return await o_(r,c),await Kd({pmRoot:r,settings:i,principal:gn(R(void 0,i.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function hL(e,t){let n=await A(e),r=$(n,I()),o=await j(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let i=await te(o,{schema:n.schema});return $b(i.document.metadata.title)}function $b(e){return e.trim().length>0?e:null}var Lb="terminal_state_unchanged";function Pb(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function gL(e,t){return de(e,t)===t.close_status}function yL(e){let t=n=>jh.includes(n.trim().toLowerCase());return qh(e.unset??[],t).some(t)}function Nb(e){!e.settings.governance.require_close_reason||!yL(e.options)||No({explicit:e.options.closeReason},!0)}function jl(e,t,n,r=!1){if(!gL(e.status,n))return!1;let o=Pb(t.closeReason);return r&&t.closeReason!==void 0&&o===void 0||o!==void 0&&o!==Pb(e.close_reason)?!1:t.completedAt===void 0||se(t.completedAt,new Date,"completed-at")===e.completed_at}async function Fb(e){let t=await j(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await it(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await te(t,{schema:e.settings.schema});return n.metadata}async function Mb(e,t,n,r,o){if(n.length===0)return{item:t,changed_fields:[],warnings:[...e.workflowTransitionWarnings,Lb]};let i=ue(e.options,{...e.options,status:void 0,closeReason:void 0,completedAt:void 0}),s=await r(e.id,i,e.global);return jl(s.item,e.options,e.statusRegistry,e.settings.governance.require_close_reason)?{item:s.item,changed_fields:s.changed_fields,warnings:[...e.workflowTransitionWarnings,...s.warnings,Lb]}:o(s)}function Ca(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),i=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,i].join("\0")}function Gl(e,t){return!(t.id!==void 0&&e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function Db(e,t,n){let r=t.filter(o=>!e.some(i=>Gl(i,o)));if(r.length!==0)throw new l(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,m.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r.map(o=>({...o,id:o.id??"*"})),available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function Ub(e,t){if(!Array.isArray(e)||e.length===0)return;let n=i=>(Array.isArray(i)?i:[]).filter(s=>typeof s=="object"&&s!==null&&typeof s.id=="string"),r=new Map;for(let i of n(t)){let s=Ca(i);r.set(s,(r.get(s)??0)+1)}let o=[];for(let i of n(e)){let s=Ca(i),a=r.get(s)??0;a>0?r.set(s,a-1):o.push(`${i.id}/${i.kind}`)}return o.length>0?o.join(","):void 0}var wL=(()=>{let e=new Map;for(let t of Es)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Ta=new Map(Es.map(e=>[e.optionKey,e.canonical])),vL=Es.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),bL=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),kL=ks({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Vb(e){if(ht(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i},r=new Set([...Ta.keys(),"rank"]);for(let o of r){if(ht(e,o))continue;let i=t[o];if(typeof i!="string"||!co(i))continue;let s=o==="rank"?"order":Ta.get(o)??o;n(s),t[o]=void 0}return ue(e,As(t,kL))}function Hl(e,t,n,r=["update"]){return[...Bl([...e],t,n,r).metadataKeys]}function Bl(e,t,n=[],r=["update"]){return Kh({raw:e,supportedFields:vL,resolveDefinition:o=>{let i=n.find(a=>{let c=a.toLowerCase();return c===o||c.replaceAll("_","-")===o||c.replaceAll("-","_")===o});return wL.get(o)??r.map(a=>Ed(o,a,t)).find(a=>a!==void 0)??(i?{optionKey:"field",metadataKey:i}:void 0)}})}var jb=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function Gb(e){let t=e.disallowedFlags.flatMap(r=>{let o=jb.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=jb.get(r);return o?[`Replace ${r} with: ${o(e.id)}`]:[]});return new l(e.message,m.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function SL(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new l("Choose only one package-provided ownership bypass mode.",m.USAGE);let i=(c,d,u)=>{c&&u.push(d)};if(o){let c=[];if(i(t.title!==void 0,"--title",c),i(t.description!==void 0,"--description",c),i(t.body!==void 0,"--body",c),i(t.status!==void 0,"--status",c),i(t.closeReason!==void 0,"--close-reason",c),i(t.priority!==void 0,"--priority",c),i(t.type!==void 0,"--type",c),i(t.tags!==void 0,"--tags",c),i(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),i(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),i(t.deadline!==void 0,"--deadline",c),i(t.estimatedMinutes!==void 0,"--estimate",c),i(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),i(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),i(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),i(t.definitionOfReady!==void 0,"--definition-of-ready",c),i(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),i(t.goal!==void 0,"--goal",c),i(t.objective!==void 0,"--objective",c),i(t.value!==void 0,"--value",c),i(t.impact!==void 0,"--impact",c),i(t.outcome!==void 0,"--outcome",c),i(t.whyNow!==void 0,"--why-now",c),i(t.assignee!==void 0,"--assignee",c),i(t.parent!==void 0,"--parent",c),i(t.reviewer!==void 0,"--reviewer",c),i(t.risk!==void 0,"--risk",c),i(t.confidence!==void 0,"--confidence",c),i(t.sprint!==void 0,"--sprint",c),i(t.release!==void 0,"--release",c),i(t.blockedBy!==void 0,"--blocked-by",c),i(t.blockedReason!==void 0,"--blocked-reason",c),i(t.unblockNote!==void 0,"--unblock-note",c),i(t.reporter!==void 0,"--reporter",c),i(t.severity!==void 0,"--severity",c),i(t.environment!==void 0,"--environment",c),i(t.reproSteps!==void 0,"--repro-steps",c),i(t.resolution!==void 0,"--resolution",c),i(t.expectedResult!==void 0,"--expected-result",c),i(t.actualResult!==void 0,"--actual-result",c),i(t.affectedVersion!==void 0,"--affected-version",c),i(t.fixedVersion!==void 0,"--fixed-version",c),i(t.component!==void 0,"--component",c),i(t.regression!==void 0,"--regression",c),i(t.customerImpact!==void 0,"--customer-impact",c),i(t.depRemove!==void 0,"--dep-remove",c),i(t.replaceDeps===!0,"--replace-deps",c),i(t.replaceTests===!0,"--replace-tests",c),i(t.replaceFiles===!0,"--replace-files",c),i(t.replaceDocs===!0,"--replace-docs",c),i(t.comment!==void 0,"--comment",c),i(t.note!==void 0,"--note",c),i(t.learning!==void 0,"--learning",c),i(t.file!==void 0,"--file",c),i(t.test!==void 0,"--test",c),i(t.doc!==void 0,"--doc",c),i(t.reminder!==void 0,"--reminder",c),i(t.event!==void 0,"--event",c),i(t.typeOption!==void 0,"--type-option",c),i(t.clearDeps===!0,"--clear-deps",c),i(t.clearComments===!0,"--clear-comments",c),i(t.clearNotes===!0,"--clear-notes",c),i(t.clearLearnings===!0,"--clear-learnings",c),i(t.clearFiles===!0,"--clear-files",c),i(t.clearTests===!0,"--clear-tests",c),i(t.clearDocs===!0,"--clear-docs",c),i(t.clearReminders===!0,"--clear-reminders",c),i(t.clearEvents===!0,"--clear-events",c),i(t.clearTypeOptions===!0,"--clear-type-options",c),i(t.force===!0,"--force",c),i(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",m.USAGE);if(c.length>0)throw Gb({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let s=[];i(t.status!==void 0,"--status",s),i(t.closeReason!==void 0,"--close-reason",s),i(t.assignee!==void 0,"--assignee",s),i(t.parent!==void 0,"--parent",s),i(t.blockedBy!==void 0,"--blocked-by",s),i(t.blockedReason!==void 0,"--blocked-reason",s),i(t.unblockNote!==void 0,"--unblock-note",s),i(t.dep!==void 0,"--dep",s),i(t.depRemove!==void 0,"--dep-remove",s),i(t.replaceDeps===!0,"--replace-deps",s),i(t.replaceTests===!0,"--replace-tests",s),i(t.replaceFiles===!0,"--replace-files",s),i(t.replaceDocs===!0,"--replace-docs",s),i(t.note!==void 0,"--note",s),i(t.learning!==void 0,"--learning",s),i(t.test!==void 0,"--test",s),i(t.reminder!==void 0,"--reminder",s),i(t.event!==void 0,"--event",s),i(t.clearDeps===!0,"--clear-deps",s),i(t.clearComments===!0,"--clear-comments",s),i(t.clearNotes===!0,"--clear-notes",s),i(t.clearLearnings===!0,"--clear-learnings",s),i(t.clearFiles===!0,"--clear-files",s),i(t.clearTests===!0,"--clear-tests",s),i(t.clearDocs===!0,"--clear-docs",s),i(t.clearReminders===!0,"--clear-reminders",s),i(t.clearEvents===!0,"--clear-events",s);let a=[...n].filter(c=>bL.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(s.push(...a),s.length>0)throw Gb({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${s.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:s})}function AL(e,t){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,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function EL(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:Yb(e)}function Yb(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new l(`Invalid dependency created_at timestamp "${e}"`,m.USAGE);return new Date(t).toISOString()}function Mn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var CL=["id","kind","type","author","created_at","source_kind"],TL=["id","kind","type","author","created_at","source_kind"];function Jb(e){return e.startsWith("```")||e.includes(`
|
|
22
|
+
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:es(e)}function Wl(e){return typeof e=="string"?st().resolve(e)?.kind??e.trim():e}function xa(e,t,n,r){return e?(Ne(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(i=>{let s=i.trim(),a=Jb(s);Fo(s,a);let c=a?_e(i,"--dep"):{id:s,kind:"related"};a&&rt(c,"--dep",CL);let d=c.id?.trim(),u=Wl((c.kind??c.type)?.trim());if(!d||!u)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",m.USAGE);if(d.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,m.USAGE);let p=_o(Mn(c.source_kind)),f=Mn(c.author);return{id:ho(d,t,p),kind:Ar(u),created_at:EL(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function RL(e,t){return e?(Ne(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new l("--dep-remove requires id or key/value selectors",m.USAGE);let o=Jb(r);if(Fo(r,o,"--dep-remove"),o){let i=_e(r,"--dep-remove");rt(i,"--dep-remove",TL);let s=i.id?.trim();if(i.id===void 0)return xL(i);if(!s)throw new l("--dep-remove key/value form requires a non-empty id=<value>",m.USAGE);if(s.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${s}"`,m.USAGE);let a=Wl(Mn(i.kind??i.type)),c=_o(Mn(i.source_kind)),d=Mn(i.author),u=Mn(i.created_at);return{id:ho(s,t,c),kind:a?Ar(a):void 0,source_kind:c,author:d,created_at:u?Yb(u):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,m.USAGE);return{id:Pe(r,t)}})):[]}function xL(e){let t=Wl(Mn(e.kind??e.type)),n=Object.keys(e).filter(r=>r!=="kind"&&r!=="type");if(!t||n.length>0||e.kind!==void 0&&e.type!==void 0)throw new l("--dep-remove key/value form requires id=<value>, or kind=<kind> alone to remove every row of that kind",m.USAGE);return{kind:Ar(t)}}function Ra(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function IL(e,t,n,r,o){let i=[...e??[]],s=!1;if(t===void 0){let a=i.filter(c=>o===void 0||!Qd(c,o.value,o.idPrefix));return a.length!==i.length&&(i=a,s=!0),s?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}return i.some(a=>a.kind==="blocked_by"&&a.id===t)||(i.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}async function OL(e,t,n,r,o,i){if(e===void 0||t)return{};let s=e.trim();if(s.length===0)return{};let a=await j(n,Pe(s,r),r,o,i);return a?{id:a.id}:{unresolved:s}}function $L(e,t,n,r,o,i){let s=IL(e.dependencies,t,n,r,i);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,o.includes("dependencies")||o.push("dependencies"))}function LL(e){return`${e.path}::${e.scope}`}function PL(e){return`${e.path}::${e.scope}`}function NL(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function qb(e,t){let n=Mr("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,m.CONFLICT);return n}function FL(e,t,n){let r=new Set,o=(i,s)=>{s&&r.add(i)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let i=Bl(e.unset,t,n,e.runtimeFieldCommands);for(let s of i.optionKeys)o(s,!0)}return r}function ML(e,t,n,r,o){let i=si(e,n);if(!i)throw new l(`Invalid type value "${e}"`,m.USAGE);let s=Bn(i,"update",[]);if(s.errors.length>0)throw new l(s.errors.join("; "),m.CONFLICT);let a=FL(t,r,o);for(let c of s.disabled)if(a.has(qb(c,e)))throw new l(`Option ${Oe("update",c)} is disabled for type "${e}" by command_option_policies`,m.USAGE);for(let c of s.required)if(!a.has(qb(c,e)))throw new l(`Missing required option ${Oe("update",c)} for type "${e}"`,m.USAGE)}var DL=new Set(["order","rank"]),UL=xc.filter(e=>!DL.has(e)),Xb=["tags","closeReason",...UL],jL=["title","description","body","status","closeReason","completedAt","priority","type",...xc,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],GL=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>se(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>or(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],qL=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>at(pa(e),Pr,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>_a(e)}],KL=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>at(fa(e),Nr,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>ha(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function zl(e,t,n){for(let r of e){let o=t[r.optionKey],i=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!i)){if(i){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new l(`${Oe("update",String(r.optionKey))} must be a string value`,m.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function zL(e){return Vb(await ts(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function Vl(e){let t=mo("update",e);return Ot(t)?await zL(t):Vb(t)}function HL(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function ql(e){if(e.enabled&&(!e.values||e.values.length===0))throw new l(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,m.USAGE);if(e.enabled&&e.clearEnabled)throw new l(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,m.USAGE)}function Yl(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new l("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",m.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new l("--replace-deps requires at least one --dep entry",m.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new l("--replace-deps cannot be combined with --dep-remove",m.USAGE);ql({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),ql({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),ql({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function BL(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new l(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,m.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function WL(e){let t={};for(let n of Xb)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function VL(e,t){let n=WL(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=Ta.get(r)??r;throw new l(`Cannot combine --unset ${i} with ${Oe("update",r)}`,m.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --add-ac",m.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --remove-ac",m.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",m.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new l("Cannot combine --unset tags with --remove-tags",m.USAGE)}}function YL(e){if(ht(e))return;let t=(n,r)=>{if(ht(e,r))return;let o=Ta.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;Ss(n,Oe("update",r),i)};for(let n of Xb)t(e[n],String(n));t(e.order??e.rank,"order"),Ne(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Ne(e.event,"--event","Use --clear-events to clear linked events.")}function JL(e,t){let n={};for(let r of jL)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function XL(e){let t=await j(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await it(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await te(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function QL(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return ye(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function ZL(e){e.before&&(Gs(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Is(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>le(t,e.statusRegistry),st()))}function eP(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new l("--order and --rank must match when both are provided",m.USAGE)}async function tP(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=gt(e.options),n=lr(us(e.options.parent,t),e.settings.id_prefix);if(Ji(n))return{resolvedParentValue:n,warnings:[]};if(fs(e.id,n,e.settings.id_prefix,t),await j(e.pmRoot,n,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:n,warnings:[]};let o=Pe(n,e.settings.id_prefix);return{resolvedParentValue:n,warnings:ps(o,e.parentReferencePolicy,t).warnings}}function nP(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function rP(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await j(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await it(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await te(t,{schema:e.settings.schema}),r=e.options.type!==void 0?Ce(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=gr({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function oP(e){if(!e.fieldFlags.status||de(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;Nb(e);let n=Object.entries(e.fieldFlags).filter(([i,s])=>s&&i!=="status"&&i!=="closeReason"&&i!=="completedAt").map(([i])=>i),r=await Fb(e);if(jl(r,e.options,e.statusRegistry,e.settings.governance.require_close_reason))return Mb(e,r,n,ct,i=>Kb(e,i));let o;if(n.length>0){let i=ue(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0});o=await ct(e.id,i,e.global)}return Kb(e,o)}async function Kb(e,t){let n=await Dt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),o=[...lo("update",e.options,gt(e.options)==="sdk",n.item),...e.workflowTransitionWarnings,...(t?.warnings??[]).filter(i=>!i.startsWith("literal_sentinel_stored:")),...n.warnings,"auto_routed_from_update_to_close"];return{item:n.item,changed_fields:[...t?.changed_fields??[],...n.changed_fields],warnings:o}}function iP(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Ml(t.title,"--title",gt(t)),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),de(e.metadata.status,n)??e.metadata.status}var sP=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function aP(e,t){for(let n of sP)e[n]!==void 0&&(delete e[n],t.push(n))}function cP(e,t,n,r,o){let i=AL(n,t.statusRegistry);if(e.metadata.status=i,o.push("status"),i===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!le(i,t.statusRegistry)&&le(r,t.statusRegistry)&&aP(e.metadata,o)}function dP(e,t,n,r){if(t.options.status!==void 0&&cP(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!le(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",m.USAGE);e.metadata.completed_at=se(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function lP(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new l(pd(gt(t.options),"close-reason"),m.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&le(n,t.statusRegistry)&&!le(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function mP(e,t,n,r){dP(e,t,n,r),lP(e,t,n,r)}function uP(e,t,n){let r=Ce(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=Xt(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=Ce(t.options.type,t.typeRegistry);if(!o)throw new l(Ht(t.options.type,t.typeRegistry.types,Bt(t.pmRoot,t.settings.schema)),m.USAGE);e.metadata.type=o,r=o,n.push("type")}return ML(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),pP(e,t,r,n),r}function pP(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let i=ba(t.options.typeOption??[]),s=Dr(n,i,t.typeRegistry);if(s.errors.length>0)throw new l(s.errors.join("; "),m.USAGE);e.metadata.type_options=s.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let o=Dr(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,m.USAGE);e.metadata.type_options=o.normalized}function fP(e,t){let n=new Set(t.map(o=>Ra(o))),r=new Set;return e.filter(o=>{if(!n.has(Ra(o)))return!0;let i=Ca(o);return r.has(i)?!1:(r.add(i),!0)})}function _P(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=fP(r,t.dependencyUpdates.additions);let o=new Set(r.map(i=>Ra(i)));for(let i of t.dependencyUpdates.additions){let s=Ra(i);o.has(s)||(r.push(i),o.add(s))}}t.dependencyRemovals.length>0&&(Db(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(i=>Gl(o,i)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function hP(e,t,n){Kl(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Kl(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Kl(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Kl(e,t,n,r,o,i){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],i.push(t))}function gP(e,t,n){zb(e,"files",t.options.file,t.fileUpdates.values,LL,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),yP(e,t,n),zb(e,"docs",t.options.doc,t.docUpdates.values,PL,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function zb(e,t,n,r,o,i,s,a){if(!(n===void 0&&!s.has(t))){if(i)e.metadata[t]=r;else if(s.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(u=>o(u)));for(let u of r){let p=o(u);d.has(p)||(c.push(u),d.add(p))}e.metadata[t]=c}a.push(t)}}function yP(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Hb(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Hb([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Hb(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=NL(r);n.has(o)||(t.push(r),n.add(o))}return t}function wP(e,t,n){let r=t.options.addTags,o=t.options.removeTags,i=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||i){let s=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Vt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Zi(rr(s,r),o),n.changedFields.push("tags")}zl(GL,t.options,n),bP(e,t,n.changedFields)}function vP(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let i=Qi(nr(e.metadata.acceptance_criteria),r,o);if(i.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${i.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:i.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let s=i.criteria.join("; ");e.metadata.acceptance_criteria!==s&&(s===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=s,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function bP(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=ge(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",m.USAGE);e.metadata.order=o}n.push("order")}}function kP(e,t,n,r){SP(e,t,n.changedFields),AP(e,t,n.changedFields),zl(qL,t.options,n),Bb(e,t,"sprint",r,n.changedFields),Bb(e,t,"release",r,n.changedFields),EP(e,t,n.changedFields),zl(KL,t.options,n)}function SP(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new l(pd(gt(t.options),"assignee",". Use --unset assignee to clear it."),m.USAGE);zf(r,"--assignee"),e.metadata.assignee=r}n.push("assignee")}}function AP(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function Bb(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let i=_s(n,t.options[n]??"",t.settings.validation.sprint_release_format,gt(t.options));e.metadata[n]=i.value,r.push(...i.warnings)}o.push(n)}}function EP(e,t,n){if(t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by"))return;let r=t.clearItemMetadataKeys.has("blocked_by")?e.metadata.blocked_by:void 0;t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&$L(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n,{value:r,idPrefix:t.settings.id_prefix})}function CP(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=wa(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=va(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function TP(e,t,n){Wb(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),Wb(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,i]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let s=o.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(d=>d.metadata_key===o)?.cli_flag??s;throw new l(`Cannot combine --unset ${s} with --${c}`,m.USAGE)}ee(e[o],i)||(e[o]=i,n.push(o))}let r=oi(t.options.field,t.extensionRegistrations,ga,ya(t.runtimeFieldRegistry,(t.options.runtimeFieldCommands??[]).includes("update_many")?"update_many":"update",t.options));for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new l(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,m.USAGE);for(let[o,i]of Object.entries(r))ee(e[o],i)||(e[o]=i,n.push(o))}function Wb(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function RP(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(o=>{let i=t[o];return i!==void 0&&(!Array.isArray(i)||!ee(i,n[o]??[]))});if(r!==void 0)throw new l(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,m.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${r}_requires_annotation_command`,required:`Use pm ${r} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${r} with pm ${r} ${e.metadata.id}.`,`Apply the correction with pm ${r} ${e.metadata.id} --edit <index> --add <text>.`]})}function xP(e,t){RP(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,o=[],i=[],s=iP(e,t.options,t.statusRegistry,o),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};mP(e,t,s,o),uP(e,t,o),_P(e,t,o),hP(e,t,o),gP(e,t,o),wP(e,t,c),vP(e,t,c),kP(e,t,c,i),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&Mo(e.metadata.id,e.metadata.dependencies),de(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),CP(e,t,o),TP(a,t,o),ii(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys});let d=e.metadata,u=[...new Set(o)].filter(f=>f==="body"?e.body!==r:!ee(n[f],d[f])),p=Ub(n.dependencies,d.dependencies);return p!==void 0&&i.push(`dependencies_removed:${e.metadata.id}:${p}`),t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&i.push(`acceptance_criteria_replaced:${nr(n.acceptance_criteria).length}:${nr(d.acceptance_criteria).length}`),{changedFields:u,warnings:i}}async function Qb(e,t,n,r={}){yt(e,"update","id");let o=await Vl(t),i=E(process.cwd(),n.path);await O(i);let s=await A(i),a=D(s.schema),c=et(s.schema),d=I(),u=Ue(d),p=$(s,d),f=s.governance.workflow_enforcement??"off",h=f==="off"?[]:Jn(s.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(o.allowMissingParent===!0)][s.validation.parent_reference],g=Bl(o.unset,c,u,o.runtimeFieldCommands),y=new Set(g.optionKeys),w=new Set(g.metadataKeys);Yl(o),BL({definitions:HL(o),options:o,clearOptionKeys:y,clearItemMetadataKeys:w}),SL(e,o,w),VL(o,g),YL(o);let v=R(o.author,s.author_default),k=new Date,S=k.toISOString(),T=xa(o.dep,s.id_prefix,S,v);Mo(e,T.additions);let x=await Pn({pmRoot:i,dependencies:T.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:p.type_to_folder,allowUnresolved:o.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),F=RL(o.depRemove,s.id_prefix),P=Fn("--comment",o.comment,S,v),H=o.ownershipMetadataBypass===!0&&P.values?{...P,values:P.values.map(Xe=>({...Xe,author:v}))}:P,B=Fn("--note",o.note,S,v),Y=Fn("--learning",o.learning,S,v),re=Pl(o.file),J=Nl(o.test);J.values=await fr(J.values,v,S);let Gt=Fl(o.doc),G=[],he=await tP({id:e,options:o,unsetTargets:g,pmRoot:i,settings:s,typeRegistry:p,parentReferencePolicy:_}),qt=await OL(o.blockedBy,w.has("blocked_by"),i,s.id_prefix,s.item_format,p.type_to_folder),dn=qt.id,Ye=[...he.warnings,...nP(qt)],Jo=Ki(o,c,o.runtimeFieldCommands),ln=JL(o,Jo);if(!Object.values(ln).some(Boolean))return XL({pmRoot:i,id:e,settings:s,typeRegistry:p});G.push(...await rP({options:o,fieldFlags:ln,workflowEnforcement:f,typeWorkflows:h,statusRegistry:a,typeRegistry:p,pmRoot:i,id:e,settings:s}));let Xo=await oP({options:o,fieldFlags:ln,statusRegistry:a,workflowTransitionWarnings:G,global:n,id:e,pmRoot:i,settings:s,typeRegistry:p});if(Xo)return Xo;eP(o);let sc=st(),Je=ln.parent&&!w.has("parent")||T.additions.some(Xe=>js(Xe.kind,sc)),kt=await ua({pmRoot:i,author:v,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Je});try{let Xe=await QL({fieldFlags:ln,clearedMetadataKeys:w,pmRoot:i,settings:s,typeToFolder:p.type_to_folder}),N,Qo,nt=await en({pmRoot:i,settings:s,typeToFolder:p.type_to_folder,id:e,op:IP(o,r),author:v,message:o.message,resolveHistoryContext:()=>Qo,force:o.force,bypassAssigneeConflict:o.ownershipMetadataBypass===!0||o.ownershipDependencyBypass===!0,extensionFieldNames:u,skipNoop:!0,async mutate(Qe){let cc=Qe.metadata.status;N=OP({document:Qe,recurrenceReason:r.recurrenceReason,requestedStatus:o.status,statusRegistry:a}),Qo=N?{recurrence:N}:void 0,Xe=Xe?.map(ei=>ei.id===Qe.metadata.id?structuredClone(Qe.metadata):ei);let Zo=xP(Qe,{options:o,settings:s,typeRegistry:p,statusRegistry:a,runtimeFieldRegistry:c,extensionRegistrations:d,extensionFieldNames:u,clearItemMetadataKeys:w,dependencyUpdates:T,dependencyRemovals:F,commentUpdates:H,noteUpdates:B,learningUpdates:Y,fileUpdates:re,testUpdates:J,docUpdates:Gt,resolvedParentValue:he.resolvedParentValue,resolvedBlockedByDependencyId:dn,runtimeFieldUpdates:Jo,nowValue:k,nowIso:S,author:v,pmRoot:i});ZL({before:Xe,document:Qe,statusRegistry:a});let dc=await Vs({pmRoot:i,settings:s,metadata:Qe.metadata,fromStatus:cc,registry:a,force:o.force===!0});return{...Zo,warnings:[...Zo.warnings,...dc]}}});await kt();let ac=Xe?Us(Xe,Xe.map(Qe=>Qe.id===nt.item.id?nt.item:Qe),nt.item.id):[];return{item:nt.item,changed_fields:nt.changedFields,warnings:[...lo("update",o,gt(o)==="sdk",nt.item),...G,...Ye,...x,...ac,...nt.warnings],...N===void 0?{}:{lifecycle_transition:N}}}finally{await kt()}}function IP(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function OP(e){if(e.recurrenceReason===void 0)return;let t=de(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!le(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,m.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=de(n,e.statusRegistry)??n,o=e.document.metadata,i=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(s=>{let a=o[s];return typeof a=="string"?[[s,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:i}}async function ct(e,t,n){return Qb(e,t,n)}async function Zb(e,t,n,r){yt(r,"reopen","reason");let o=await Qb(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,m.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}async function Jl(e,t,n,r){yt(e,"reopen","id"),yt(t,"reopen","reason"),Bh(n);let o=t.trim();if(o.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",m.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let i=E(process.cwd(),r.path),s=n.expectedResult?.trim();if(s!==void 0&&s.length===0)throw new l("Reopen expected result must describe the current active outcome.",m.USAGE);let a=D((await A(i)).schema),c=a.open_status,d=Nt(a),u=n.status??c,p=de(u,a)??u;if(p!==c&&p!==d)throw new l(`Reopen target status must be ${c} or ${d}; received ${u}.`,m.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([c,d])],suggested_retry:`pm item reopen ${e} "${o}" --status ${c}`,suggested_retry_args:["item","reopen",e,o,"--status",c]}});let f=await Zb(e,{status:p,expectedResult:s,unset:["close-reason","resolution",...s===void 0?["expected-result"]:[],"actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:f.item,changed_fields:f.changed_fields,warnings:f.warnings,recurrence:f.lifecycle_transition,...s===void 0?{recovery:{missing:["expected_result"],suggested_retry_args:["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"],suggested_retry:L(["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"])}}:{}}}async function Xl(e,t,n){try{return await n()}catch(r){let o=r instanceof l?r.context:{},i=new l(r instanceof Error?r.message:String(r),r instanceof l?r.exitCode:m.GENERIC_FAILURE,{...o,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${o.why?` ${o.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...o.nextSteps??[]]});throw i.cause=r,i}}async function Ql(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new l("--start cannot be combined with --next or --if-available for an explicit item",m.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let r=await A(E(process.cwd(),n.path)),o=Nt(D(r.schema));return tw(async()=>{let i=await Co(e,t.force===!0,n,wt(t,{},["start"])),s=i.item.id,a=await Xl(s,"claim",()=>ct(s,wt(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts","takeoverStale"]),n)).catch(async c=>{throw await $P(c,i,n,t.author)});return{id:s,action:"start_task",claim:i,update:a}})}async function $P(e,t,n,r){if(!(e instanceof l)||e.code!==Ws||t.previous_assignee!==null)return e;let o=String(t.item.id);try{await Wi({pmRoot:E(process.cwd(),n.path),id:o,validate:s=>{if(s.metadata.assignee!==t.claimed_by||s.metadata.claim_principal!==t.item.claim_principal)throw new l("The claim this start took is no longer its own.",m.CONFLICT)}},()=>wr(o,!1,n,{author:r,message:"Release the claim: a blocker opened before its start could be recorded"}))}catch{return e}let i=e.cause instanceof l?e.cause:e;return new l(i.message,i.exitCode,{...i.context,why:`${i.context.why??""} A blocker opened after this start's claim, so the claim was released and no ownership remains.`.trim()})}async function Zl(e,t,n){let r=await A(E(process.cwd(),n.path)),o=D(r.schema);Hs({...t,pause:!0},o);let i=await _w(e,n,t.author),s=o.open_status,a=await i(()=>ct(e,wt(t,{status:s},["assignee","pause"]),n)),c=a.item.id,d=await Xl(c,"update",()=>wr(c,t.force===!0,n,t));return{id:c,action:"pause_task",update:a,release:d}}async function em(e,t,n,r){let o=await Dt(e,t,n,r),i=o.item.id,s=await Xl(i,"close",()=>wr(i,n.force===!0,r,n));return{id:i,action:"close_task",close:o,release:s}}async function ek(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options),o=e.force===!0||r.force===!0,i={...e.args,...r},s=r.next===!0,a=e.id??b(r,"id");if(i.start===!0){if(a)return Dn(e,"start_task");lw(a,s,!0)}let c=s?await mw(o,e.global,i,i):await Co(Do(e,r),o,e.global,i);return Re(c,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Do(e,t){let n=e.id??b(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function tm(e,t){return b(e.args,"reason")??b(e.args,"text")??b(t,"reason")??b(t,"text")}async function tk(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return r.releaseAssignment===!0?Dn(e,"close_task"):Re(await Dt(Do(e,r),tm(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Dn(e,t){let{changedFields:n,idOnly:r,runnerOptions:o}=ve(e.args,e.options),i=Do(e,o),s=wt(o,{force:e.force===!0||o.force===!0}),a=t==="start_task"?await Ql(i,s,e.global):t==="pause_task"?await Zl(i,s,e.global):await em(i,tm(e,o),s,e.global);return Re(a,{changedFields:n,idOnly:r,compactEnvelope:n==="compact"&&!r})}async function nk(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options),o=wt(r,{message:b(Object.hasOwn(r,"message")?r:e.args,"message")});if(o.pause===!0)return Dn({...e,options:o},"pause_task");let i=await wr(Do(e,o),e.force===!0||o.force===!0,e.global,o);return Re(i,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function rk(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return Re(await Jl(Do(e,r),tm(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Ia(e,t){let n=L(["plan","show",e.plan.id,"--depth","deep",...t===void 0?[]:["--pm-path",t]]);return{kind:"plan_mutation",action:e.action,id:e.plan.id,status:e.plan.status,mode:e.plan.mode,steps_summary:e.plan.steps_summary,...e.step===void 0?{}:{step:{id:e.step.id,order:e.step.order,status:e.step.status}},materialized_count:e.materialized?.length??0,skipped_count:e.materialize_skipped?.length??0,warning_count:e.warnings.length,warnings:e.warnings.slice(0,3).map(r=>r.slice(0,160)),warnings_truncated:e.warnings.length>3||e.warnings.some(r=>r.length>160),next_action:e.next_actions?.[0]===void 0?n:t===void 0?e.next_actions[0]:`${e.next_actions[0]} --pm-path ${Kf(t)}`,inspection_command:n,omission_receipt:{has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"plan_detail",restore_with:n}]}}}var LP=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"];var sk="plan-step-",am="draft",sm=["bug-investigation","feature-implementation","refactoring-sprint"],ok={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function PP(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(ok,t)?ok[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${sm.join(", ")}`,m.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${sm[0]}`]});return n.map(r=>({...r}))}function NP(e,t){return t>0?Math.round(e/t*100):0}function ak(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function tt(e){return Array.isArray(e)?e.flatMap(t=>cr(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?cr(e,{unique:!1}):[]}function Me(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function ck(e,t=am){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=kc.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${kc.join(", ")}`,m.USAGE);return r}function cm(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Sc.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${Sc.join(", ")}`,m.USAGE);return r}function dk(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ec.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${Ec.join(", ")}`,m.USAGE);return r}function FP(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ac.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${Ac.join(", ")}`,m.USAGE);return n}function MP(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=Pc.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${Pc.join(", ")}`,m.USAGE);return n}function DP(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new l("Plan --fields requires a comma-separated list of plan field names",m.USAGE);return t}var nm=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function UP(e,t){let n=e,r={},o=[];for(let i of t){let s=i.startsWith("plan.")?i.slice(5):i;if(s.length!==0){if(!nm.has(s)){o.push(i);continue}Object.prototype.hasOwnProperty.call(n,s)&&(r[s]=n[s])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,m.USAGE,{nextSteps:[`Use --fields ${[...nm].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...nm].join(",")}`}});return r}function dm(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let i=o.indexOf("=");if(i<=0)throw new l(`Invalid ${t} entry "${o}"; expected key=value`,m.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[o.slice(0,i).trim().toLowerCase()]=o.slice(i+1).trim()}return n}function lm(e){let t=dm(e,"--file");if(!t.path)throw new l("--file requires path=<value>",m.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function mm(e){let t=dm(e,"--test");if(!t.command&&!t.path)throw new l("--test requires at least command=<value> or path=<value>",m.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function um(e){let t=dm(e,"--doc");if(!t.path)throw new l("--doc requires path=<value>",m.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function jP(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=NP(t.completed,t.total),t}function GP(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${sk}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new l("Could not allocate step id (limit reached)",m.GENERIC_FAILURE)}function Er(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",m.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),i=e.find(s=>s.order===o);if(i)return i}throw new l(`Step "${t}" not found in plan`,m.NOT_FOUND)}function ik(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function qP(e,t){let n=t.filter(s=>s.trim().toLowerCase()==="all"),r=[],o=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",m.USAGE);for(let s of e.slice().sort((a,c)=>a.order-c.order)){let a=ik(s);if(a){o.push({from_step:s.id,...a});continue}r.push(s)}return{targets:r,skipped:o}}let i=new Set;for(let s of t){let a=Er(e,s);if(i.has(a.id))continue;i.add(a.id);let c=ik(a);if(c){o.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:o}}function KP(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function zP(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function HP(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function Be(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((s,a)=>s.order-a.order),r=jP(n),o=zP(n),i={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??am,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:HP(n),linked_items:(e.dependencies??[]).map(s=>({id:s.id,kind:s.kind}))};return(t==="standard"||t==="deep")&&(i.steps=n),t==="deep"&&(i.decisions=e.plan_decisions??[],i.discoveries=e.plan_discoveries??[],i.validation=e.plan_validation??[]),i}function We(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!kd(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function lk(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new l(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,m.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function BP(e){let t=E(process.cwd(),e.path);await O(t);let n=await A(t);return{pmRoot:t,settings:n}}async function mk(e,t){let n=$(e.settings,I()),r=await j(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,m.NOT_FOUND);let o=await te(r,{schema:e.settings.schema});return lk(o.document.metadata),{document:o.document,itemId:r.id}}function WP(e){let t=[];for(let n of tt(e.related))t.push(`id=${n},kind=related`);for(let n of tt(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of tt(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function VP(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function YP(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||tt(e.dependsOn).length>0||tt(e.link).length>0}function JP(e){let t=e.stepTitle?.trim()||void 0,n=ak(e.step),r=e.template?.trim()?PP(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function XP(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",m.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${sm[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",m.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function QP(e,t){let n=cm(e.stepStatus,"pending"),r=pm(e,"depends_on"),o=Me(e.file).map(lm),i=Me(e.test).map(mm),s=Me(e.doc).map(um),a=C();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:fm(e.stepOwner),evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function ZP(e){let t=JP(e),n=YP(e);if(XP(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[QP(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=C();return{steps:t.stepTitles.map((o,i)=>({id:`${sk}${String(i+1).padStart(3,"0")}`,order:i+1,title:o,body:t.templateSteps[i]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function uk(e,t,n=[]){ue(e,t),n.length>0&&X_(t,n)}async function eN(e,t,n){let r=e.title?.trim();if(!r)throw new l("pm plan create requires --title",m.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let o=ck(e.mode,am),i=FP(e.harness),s=e.fromSearch?.trim(),a=VP(e),{steps:c,hasPerStepDetailOptions:d}=ZP(e);if(c.length===0&&d)throw new l("pm plan create step options require --step-title (or a single --step)",m.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?R(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:Me(e.file),test:Me(e.test),doc:Me(e.doc),field:Me(e.field),assignee:R(e.author,n.settings.author_default),blockedBy:void 0,dep:WP(e),message:e.message??(s?`plan create (search: ${s})`:"plan create")};uk(e,f);let h=await on(f,t),_=await we({pmRoot:n.pmRoot,settings:n.settings,id:h.item.id,op:"plan_create_metadata",author:R(e.author,n.settings.author_default),message:"seed plan metadata",mutate(y){let w=["plan_mode"];y.metadata.plan_mode=o,i&&(y.metadata.plan_harness=i,w.push("plan_harness"));let v=e.scope?.trim();v&&(y.metadata.plan_scope=v,w.push("plan_scope"));let k=e.resumeContext?.trim();return k&&(y.metadata.plan_resume_context=k,w.push("plan_resume_context")),y.metadata.plan_steps=c,w.push("plan_steps"),a&&(y.metadata.plan_validation=[...y.metadata.plan_validation??[],a],w.push("plan_validation")),p&&(y.metadata.assignee=p,w.push("assignee")),{changedFields:w}}}),g=Be(_.item,"brief");return{action:"create",plan:g,step:c[0],next_actions:We(h.item.id,g),warnings:[...h.warnings],generated_at:C()}}async function tN(e,t,n){let r=MP(t.depth),o=DP(t.fields),{document:i,itemId:s}=await mk(n,e),a=Be(i.metadata,o===null?r:"deep");return{action:"show",plan:o===null?a:UP(a,o),next_actions:We(s,a),warnings:[],generated_at:C()}}function nN(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function bt(e){let t=R(e.options.author,e.ctx.settings.author_default),n,r=await we({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){lk(o.metadata);let i=D(e.ctx.settings.schema);if(le(o.metadata.status,i)||kd(o.metadata.plan_mode))throw new l(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.metadata.plan_mode??"unset"}) and cannot be mutated.`,m.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let s=(o.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(o.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(s,o);n=c.resultStep;let d=s.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));o.metadata.plan_steps=d;let u=nN(a,o.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function rN(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",m.USAGE);let o=cm(t.stepStatus,"pending"),i=t.allowMultipleActive===!0,{document:s,resultStep:a,itemId:c}=await bt({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;pk(u,void 0,o,i);let f=oN(u,t,{order:p,title:r,status:o});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),d=Be(s.metadata,"standard");return{action:"add-step",plan:d,step:a,next_actions:We(c,d),warnings:[],generated_at:C()}}function pk(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(i=>i.id!==t&&i.status==="in_progress");if(o)throw new l(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,m.CONFLICT)}function oN(e,t,n){let r=pm(t,"depends_on"),o=Me(t.file).map(lm),i=Me(t.test).map(mm),s=Me(t.doc).map(um),a=C();return{id:GP(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:fm(t.stepOwner),evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function pm(e,t){let n=tt(e.dependsOn).map(u=>({id:u,kind:t})),r=tt(e.related).map(u=>({id:u,kind:"related"})),o=tt(e.blocks).map(u=>({id:u,kind:"blocks"})),i=tt(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),s=tt(e.link),a=dk(e.linkKind,t),c=e.linkNote?.trim(),d=s.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...o,...i,...d]}async function rm(e,t,n,r){let{document:o,resultStep:i,itemId:s}=await bt({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,d){let u=Er(c,r.stepRef),p=C(),f=r.finalStatus??cm(t.stepStatus,u.status),h=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return pk(c,u.status==="in_progress"?u.id:void 0,f,h),iN(u,t,f,p),d.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Be(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:i,next_actions:We(s,a),warnings:[],generated_at:C()}}function fm(e){return Xn(e?.trim(),"--step-owner")||void 0}function iN(e,t,n,r){sN(e,t,n),aN(e,t),e.status=n,e.updated_at=r,cN(e,n,r)}function sN(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new l("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",m.USAGE)}function aN(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=fm(t.stepOwner)),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let r=Me(t.file).map(lm),o=Me(t.test).map(mm),i=Me(t.doc).map(um);r.length>0&&(e.files=om(e.files,r)),o.length>0&&(e.tests=om(e.tests,o)),i.length>0&&(e.docs=om(e.docs,i))}function om(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let i=JSON.stringify(o);r.has(i)||(r.add(i),n.push(o))}return n}function cN(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function dN(e,t,n,r,o){let{document:i,itemId:s,resultStep:a}=await bt({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(d){let u=Er(d,r),p=d.filter(h=>h.id!==u.id),f=Math.max(1,Math.min(o,p.length+1));return p.splice(f-1,0,u),p.forEach((h,_)=>{h.order=_+1,h.updated_at=C()}),d.length=0,d.push(...p),{changedSteps:[u.id],resultStep:u}}}),c=Be(i.metadata,"standard");return{action:"reorder-step",plan:c,step:a,next_actions:We(s,c),warnings:[],generated_at:C()}}async function lN(e,t,n,r){let{document:o,itemId:i,resultStep:s}=await bt({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(c){let d=Er(c,r),u=c.filter(p=>p.id!==d.id);return u.forEach((p,f)=>{p.order=f+1}),c.length=0,c.push(...u),{changedSteps:[d.id],resultStep:d}}}),a=Be(o.metadata,"standard");return{action:"remove-step",plan:a,step:s,next_actions:We(i,a),warnings:[],generated_at:C()}}async function mN(e,t,n,r){let o=pm(t,dk(t.linkKind,"related"));if(o.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",m.USAGE);let i=t.promoteToItemDep===!0,{document:s,itemId:a,resultStep:c}=await bt({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Er(u,r),h=f.linked_items??[],_=y=>`${y.kind}:${y.id}`,g=new Set(h.map(_));for(let y of o){let w=_(y);g.has(w)||(h.push(y),g.add(w))}if(f.linked_items=h,f.updated_at=C(),i){let y=p.metadata.dependencies??[],w=k=>`${k.kind}:${k.id}`,v=new Set(y.map(w));for(let k of o){let S=k.kind==="depends_on"?"blocked_by":k.kind,T={id:k.id,kind:S,created_at:C(),author:R(t.author,n.settings.author_default)};v.has(w(T))||(y.push(T),v.add(w(T)))}p.metadata.dependencies=y}return{changedSteps:[f.id],resultStep:f}}}),d=Be(s.metadata,"standard");return{action:"link",plan:d,step:c,next_actions:We(a,d),warnings:[],generated_at:C()}}async function uN(e,t,n,r){let o=tt(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",m.USAGE);let{document:i,itemId:s,resultStep:a}=await bt({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(d){let u=Er(d,r),p=(u.linked_items??[]).filter(f=>!o.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=C(),{changedSteps:[u.id],resultStep:u}}}),c=Be(i.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:We(s,c),warnings:[],generated_at:C()}}async function im(e,t,n,r){let o=KP(r,t);if(!o){let d=`--${r}-text`,u=`--${r}`;throw new l(`pm plan ${r} requires ${d}`,m.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${d} "..."`,`pm plan ${r} <plan-id> ${u} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${d} <value>`}})}let i=R(t.author,n.settings.author_default),{document:s,itemId:a}=await bt({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(d,u){let p=C();if(r==="decision"){let h=u.metadata.plan_decisions??[];return h.push({ts:p,author:i,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=h,{changedSteps:[]}}if(r==="discovery"){let h=u.metadata.plan_discoveries??[];return h.push({ts:p,author:i,text:o}),u.metadata.plan_discoveries=h,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Be(s.metadata,"deep");return{action:r,plan:c,next_actions:We(a,c),warnings:[],generated_at:C()}}async function pN(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",m.USAGE);let{document:o,itemId:i}=await bt({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=r;let d=t.scope?.trim();return d&&(c.metadata.plan_scope=d),{changedSteps:[]}}}),s=Be(o.metadata,"brief");return{action:"resume",plan:s,next_actions:We(i,s),warnings:[],generated_at:C()}}async function fN(e,t,n){let r=ck(t.mode??"approved","approved"),{document:o,itemId:i}=await bt({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(a,c){c.metadata.plan_mode=r;let d=t.scope?.trim();return d&&(c.metadata.plan_scope=d),{changedSteps:[]}}}),s=Be(o.metadata,"brief");return{action:"approve",plan:s,next_actions:We(i,s),warnings:[],generated_at:C()}}function fk(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function _N(e,t){let n=Be(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:We(e.itemId,n),warnings:fk(t),generated_at:C()}}function hN(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let i=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${i}`)}return r}async function gN(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Me(e.options.field)){let i=o.indexOf("=");if(i<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,m.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,m.USAGE);let c=s.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new l(`Invalid --field entry "${o}"; expected name=value`,m.USAGE);let[d,...u]=c,p=`${d}${u.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(p))throw new l(`Invalid --field entry "${o}"; "${p}" is reserved by materialize and cannot be overridden`,m.USAGE);n[p]=a}for(let o of e.targets){let i={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:hN(e.parent,e.planItemId,o)};uk(e.options,i,["description",...Object.keys(n)]);let s=await on(i,{path:e.pmRoot});t.push({id:s.item.id,title:s.item.title,type:e.resolvedTypeName,parent:s.item.parent,tags:s.item.tags??[],from_step:o.id})}return t}function yN(e,t,n){for(let r of t){let o=n.find(a=>a.from_step===r.id);if(!o)continue;let i=e.find(a=>a.id===r.id);if(!i)continue;let s=i.linked_items??[];s.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),i.linked_items=s,i.updated_at=C()}}async function wN(e,t,n){let r=tt(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",m.USAGE);let o=t.materializeType?.trim()||"Task",i=$(n.settings,I()),s=Ce(o,i);if(!s)throw new l(`Invalid --materialize-type "${o}"`,m.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,d=await mk(n,e),u=(d.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=qP(u,r);if(p.length===0){if(f.length>0)return _N(d,f);throw new l("No matching plan steps found for --steps",m.NOT_FOUND)}let h=await gN({targets:p,parent:a,planItemId:d.itemId,resolvedTypeName:s,tags:c,options:t,pmRoot:n.pmRoot}),{document:_,itemId:g}=await bt({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(w){return yN(w,p,h),{changedSteps:p.map(v=>v.id)}}}),y=Be(_.metadata,"standard");return{action:"materialize",plan:y,materialized:h,...f.length>0?{materialize_skipped:f}:{},next_actions:We(g,y),warnings:fk(f),generated_at:C()}}function vN(e){if(e.subcommand==="create")return e;let t=ak(e.options.step);if(t.length>1)throw new l(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,m.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:ue(e.options,{...e.options,stepTitle:t[0]})}:e}function Ut(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,m.USAGE);return e.id}function Un(e,t){let n=Ut(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,m.USAGE);return{id:n,stepRef:e.stepRef}}function bN(e){let t=Un(e,"reorder-step");if(e.reorderTo===void 0)throw new l("pm plan reorder-step requires <plan-id> <step> <new-order>",m.USAGE);return{...t,reorderTo:e.reorderTo}}var kN={create:(e,t)=>eN(e.options,e.global,t),show:(e,t)=>tN(Ut(e,"show"),e.options,t),"add-step":(e,t)=>rN(Ut(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=Un(e,"update-step");return rm(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=Un(e,"complete-step");return rm(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=Un(e,"block-step");return rm(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=bN(e);return dN(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=Un(e,"remove-step");return lN(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=Un(e,"link");return mN(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=Un(e,"unlink");return uN(n.id,e.options,t,n.stepRef)},decision:(e,t)=>im(Ut(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>im(Ut(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>im(Ut(e,"validation"),e.options,t,"validation"),resume:(e,t)=>pN(Ut(e,"resume"),e.options,t),approve:(e,t)=>fN(Ut(e,"approve"),e.options,t),materialize:(e,t)=>wN(Ut(e,"materialize"),e.options,t)};function SN(e){let t=kN[e];if(!t)throw Le({command_path:"plan",token:e,allowed:LP});return t}async function _k(e){let t=await BP(e.global),n=vN(e),r=await SN(n.subcommand)(n,t);return r.action==="show"?r:{...r,mutation_receipt:Ia(r,t.pmRoot)}}import AN from"fast-json-patch";import _m from"node:fs/promises";function hm(e){return{schema:e.schema,extensionFieldNames:Ue(I())}}async function hk(e,t,n){let r=await gh(e,hm(t));return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:gk(n),recovered:!0}}function EN(e,t){return ph(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function gk(e){let t=ar(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:pt(_t(t))}async function CN(e,t,n,r){let o=await An(e,t,n,r),i=o.located?await rh({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function TN(e,t){let n=eo(e),r=eo(t),o=AN.compare(n,r),i=new Set;for(let s of o){if(s.path==="/body"||s.path.startsWith("/body/")){i.add("body");continue}let a=s.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((s,a)=>s.localeCompare(a))}async function RN(e){let t=await ly({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>hk(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function xN(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:gk(t),originalRaw:null}}function IN(e){let t=e.document.metadata.assignee?.trim(),n=t&&t!==e.author&&!e.force,r=Vr(t);if(!n)return[];if(e.enforcement==="strict")throw new l(`Item ${e.resolvedId} is assigned to ${r}. Use --force to override.`,m.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${r}`]:[]}function ON(e){return Object.keys(e).length===0?void 0:e}async function $N(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await ae(e.existingItemPath,e.resolvedOriginalRaw),await _m.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await ae(e.existingItemPath,e.resolvedOriginalRaw);return}await _m.rm(e.restoredItemPath,{force:!0})}async function LN(e){return[...await Q({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await Q({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function gm(e,t,n,r){let o=E(process.cwd(),r.path);await O(o);let i=await A(o),s=$(i,I()),a=await CN(o,e,i,s.type_to_folder),c=a.id,{raw:d,entries:u}=await s_(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,m.NOT_FOUND);let p=EN(t,u),f=fh(ar(u,p.historyIndex),p),h=Zr(f,hm(i));if(h.metadata.id!==c)throw new l(`Restore target resolved to item ${h.metadata.id}, expected ${c}.`,m.GENERIC_FAILURE);let g=(a.located?await hk(a.located,i,u):null)?.raw??null,y=R(n.author,i.author_default),w=await ft(o,c,i.locks.ttl_seconds,y,!!n.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms,{waitPolicy:"progress"}),v=w.release;try{let{loadedItemUnderLock:k,existingItemPath:S}=await RN({pmRoot:o,subject:a,settings:i,typeRegistry:s,historyRawBeforeLock:d,currentItemRawBeforeLock:g,history:u}),T="toon",x=xN(k,u);k?.recovered===!0&&v_(o,c,k.raw),k_(o,k?.document??Nu,c),h.metadata.pm_format_version=zc(Math.max(zi(h.metadata),zi(x.document.metadata))),_h(ai(o),zi(h.metadata));let F=IN({document:x.document,author:y,force:n.force,enforcement:i.governance.ownership_enforcement,resolvedId:c}),P=TN(x.document,h),H=await bn({pmRoot:o,settings:i,operation:"restore",author:y,before:x.document,after:h});await wn({pm_root:o,operation:"restore",before:x.document,after:h,changed_fields:P,author:y,sdk:kn({pmRoot:o,settings:i,typeToFolder:s.type_to_folder})});let B=ut(h,{format:T,...hm(i)}),Y=Et(o,h.metadata.type,c,T,s.type_to_folder),re=await w.fence(async()=>{let he=await Qt(o,y),qt;try{await ae(Y,B),S&&Y!==S&&await _m.rm(S);let dn=qe({nowIso:C(),author:y,op:"restore",before:x.document,after:h,message:n.message,context:ON({...H.decisions.length===0?{}:{workflow_policies:H.decisions},...A_(o,[c,x.document.metadata.id,h.metadata.id],"restore")})});try{await Wt(a.historyPath,dn)}catch(Ye){throw await $N({existingItemPath:S,resolvedOriginalRaw:x.originalRaw,restoredItemPath:Y}),Ye}qt=await Zt({pmRoot:o,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:Y,previousItemPath:S??void 0,document:h})}finally{await he()}return qt});S_(o,h,c);let J=await LN({restoredItemPath:Y,historyPath:a.historyPath,before:x.document,after:h});Qn({id:h.metadata.id,op:"restore",item_type:h.metadata.type,previous_status:x.document.metadata.status,status:h.metadata.status,previous:yn(x.document.metadata,P),current:yn(h.metadata,P),changed_fields:P});let Gt=u[p.historyIndex],G=vn(u,!0);return{item:h.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,version:G===null?null:G+p.historyIndex+1,entry_ts:Gt.ts,entry_op:Gt.op},changed_fields:P,warnings:[...H.warnings,...k?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...F,...re,...J]}}finally{await v()}}var wk=2,wm="update-many",PN=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),NN=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),FN={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},MN=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],vk=e=>{let t={};for(let[n,r]of Object.entries(e))PN.has(n)||r!==void 0&&(t[n]=r);return t},DN=e=>Object.keys(vk(e)).length>0,bk=e=>typeof e=="string"?e.trim():e,UN=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},ym=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},jN=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??bk(e)},GN={priority:UN,estimatedMinutes:ym,order:ym,rank:ym,regression:jN},qN=(e,t)=>{if(t!==void 0)return(GN[e]??bk)(t)},Oa=(e,t)=>ee(e,t),KN=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],zN=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,HN=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",yk=(e,t)=>t===void 0?void 0:e[t],Cr=e=>Array.isArray(e)?e.length:0,BN=(e,t,n)=>{let r=n[e.addKey],o=yk(n,e.removeKey),i=Cr(r),s=Cr(o),a=n[e.clearKey]===!0,c=yk(n,e.replaceKey)===!0;if(![a,c,i>0,s>0].includes(!0))return;let d=KN(e.field,t[e.field]);return{field:e.field,before:d,after:{operation:HN({replace:c,clear:a,removeCount:s}),clear:a,replace:c,add_count:i,remove_count:s,before_count:zN(e.field,d)}}},WN=(e,t)=>{let n=[];for(let r of MN){let o=BN(r,e,t);o!==void 0&&n.push(o)}return n},VN=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],YN=(e,t)=>{if(![t.tags!==void 0,Cr(t.addTags)>0,Cr(t.removeTags)>0].includes(!0))return;let n=VN(e.tags),r=t.tags===void 0?n:Vt(t.tags),o=rr(r,t.addTags),i=Zi(o,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),s=n.slice().sort((a,c)=>a.localeCompare(c));if(!Oa(s,i))return{field:"tags",before:n,after:i}},JN=(e,t)=>{let n=e.acceptance_criteria,r=Qi(nr(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let o=r.criteria.join("; ");if(!Oa(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},XN=(e,t,n)=>{for(let[r,o]of Object.entries(FN)){let i=n[r];if(i===void 0)continue;let s=t[o],a=qN(r,i);Oa(s,a)||e.push({field:o,before:s,after:a})}},QN=(e,t,n,r)=>{let o=Ki(n,r,["update_many"]);for(let[i,s]of Object.entries(o)){let a=t[i];Oa(a,s)||e.push({field:i,before:a,after:s})}},ZN=(e,t,n,r)=>{if(n===void 0||n.length===0)return;let o=Hl(n,r,Ue(I()),["update_many"]);for(let i of o){let s=t[i];s!==void 0&&e.push({field:i,before:s,after:null})}},eF=(e,t,n={})=>{let r=e,o=[],i=YN(r,n);if(i&&o.push(i),XN(o,r,n),Cr(n.addAc)>0||Cr(n.removeAc)>0){let s=JN(r,n);s!==void 0&&o.push(s)}return o.push(...WN(r,n)),QN(o,r,n,t),ZN(o,r,n.unset,t),{id:e.id,changes:o}},tF=(e,t)=>ah(e,t,{strict:!0,flagLabel:"--filter-status"}),nF=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",m.USAGE)},rF=[({update:e})=>{e.priority!==void 0&&Xt(e.priority)},({update:e,settings:t})=>{e.unset!==void 0&&e.unset.length>0&&Hl(e.unset,et(t.schema),Ue(I()),["update_many"])},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=$(t,I());if(!Ce(e.type,r))throw new l(Ht(e.type,r.types,Bt(n,t.schema)),m.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!de(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid status value "${e.status}". Allowed: ${n.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e.status,allowed:n})}},({update:e})=>{e.deadline!==void 0&&se(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&or(e.estimatedMinutes,"estimated-minutes")}],oF=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let i of rF)i(o)},iF=async e=>{let t=await as(e.pmRoot,wm,e.rollbackId,wk),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await la(e.pmRoot,t,{author:e.options.update?.author,message:n,force:e.options.update?.force}),o=r.rows.filter(i=>i.status==="skipped").length;return{...Sn({applied:r.restored_ids.length,skipped:o,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:r.restored_ids.length,skipped_count:o,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},sF=async e=>{let t={schema_version:wk,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:R(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await ss(e.pmRoot,wm,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},aF=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},vm=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},cF=async e=>{let t=E(process.cwd(),e.path);await O(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:D(n.schema),runtimeFieldRegistry:et(n.schema)}},dF=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",m.USAGE);if(bo(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",m.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",m.USAGE);return iF({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},lF=async e=>{tF(e.options.status,e.runtime.statusRegistry);let t=await Pt(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let i=eF(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?i:{...i,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await Pt(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:aF(e.options.list?.ids,r)}},mF=e=>({outcome:"effect",exit_code:m.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...vm(e)}),uF=e=>({...Sn({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...vm(e)}),pF=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(i=>i.changes.length>0).map(i=>i.id));for(let i of e.items){if(!o.has(i.id)){t.push({id:i.id,status:"skipped"});continue}try{let s=_d(ue(e.options.update,{...e.options.update,message:r,runtimeFieldCommands:["update_many"]})),a=await ys({pmRoot:e.pmRoot,itemId:i.id,checkpointId:e.checkpointId},()=>ct(i.id,s,e.global));t.push({id:i.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(i.id)}catch(s){let a=await ma(s,i.id,e.pmRoot);if(a!==void 0){t.push({id:i.id,status:"updated",...a}),n.push(i.id);continue}t.push({id:i.id,status:"failed",error:mt(s),...await vt(s,e.pmRoot)})}}return{rows:t,updatedIds:n}},fF=async e=>{if(e.plan.actionable.length===0)return uF(e.plan);let t=C(),n=is(wm,t),r=new Set(e.plan.actionable.map(p=>p.id)),o=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),i=e.options.checkpoint===!1?void 0:await sF({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),s=await pF({pmRoot:e.runtime.pmRoot,items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=p=>s.rows.filter(f=>f.status===p).length,c=a("updated"),d=a("skipped"),u=a("failed");return{...Sn({applied:c,skipped:d,failed:u,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...i?{checkpoint:i}:{},updated_count:c,skipped_count:d,failed_count:u,rows:s.rows,ids:s.updatedIds,...vm(e.plan)}},kk=async(e,t)=>{let n=os(e.rollback),r=await cF(t);n===void 0&&(e={...e,update:_d(await Vl(e.update))});let o=vk(e.update);if(nF(e.list),n!==void 0)return dF({runtime:r,rollbackId:n,options:e,global:t,updateSummary:o});if(!DN(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${NN}), or pass --dry-run for a filter-only preview.`,m.USAGE);oF(e.update,r.settings,r.statusRegistry,r.pmRoot),Yl(e.update);let i=await Pn({pmRoot:r.pmRoot,dependencies:xa(e.update.dep,r.settings.id_prefix,C(),R(e.update.author,r.settings.author_default)).additions,idPrefix:r.settings.id_prefix,itemFormat:r.settings.item_format,typeToFolder:$(r.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),s=await lF({options:e,global:t,runtime:r,updateSummary:o,dependencyWarnings:i});return await Pn({pmRoot:r.pmRoot,dependencies:xa(e.update.dep,r.settings.id_prefix,C(),R(e.update.author,r.settings.author_default)).additions,idPrefix:r.settings.id_prefix,itemFormat:r.settings.item_format,typeToFolder:$(r.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:s.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:r.settings.schema}),e.dryRun===!0?mF(s):fF({runtime:r,options:e,global:t,plan:s})};function _F(e){if(e===void 0)return;if(e.trim().length===0)throw new l("--add-json must contain a JSON value",m.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new l("--add-json must be valid JSON",m.USAGE,{code:"structured_event_json_invalid"})}return t}function hF(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function gF(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new l("--since must be a valid ISO timestamp",m.USAGE,{code:"structured_event_since_invalid"});return t}function Sk(e){return Object.prototype.toString.call(e)==="[object Object]"?e:{}}async function Ak(e,t,n){let r=_F(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",m.USAGE,{code:"structured_event_input_conflict"});let i=r===void 0?void 0:Ct(r),s=[t.since,t.eventType].some(_=>_!==void 0),a=gF(t.since),c=oo(t.limit),d=await hr(e,{...t,...s?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,s].includes(!0)},n,{input:await zs(i===void 0?t:{add:i},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:_=>_r(_),createEntry:_=>r===void 0?_:{..._,format:"json",data:r,event_type:hF(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm notes --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}}),u=t.eventType?.trim(),p=d.notes.filter(_=>{let g=Sk(_),y=[g.format==="json",g.data!==void 0].every(Boolean),w=[a===void 0,Date.parse(g.created_at??"")>=(a??Number.POSITIVE_INFINITY)].includes(!0),v=[!u,g.event_type===u].includes(!0);return[!s,[y,w,v].every(Boolean)].includes(!0)}),f=s?Jd(p,c):p,h=f.filter(_=>Sk(_).format==="json").length;return{...d,notes:f,count:f.length,...s?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:h}:t.includeMeta===!0?{structured_event_count:h}:{}}}import IF from"node:path";import yF from"node:fs/promises";import Ek from"node:path";var wF="templates",vF=".json",bF=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,kF=Xi.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),SF=new Set(kF);function AF(e){let t=e.trim();if(!bF.test(t))throw new l(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,m.USAGE);return t}function Ck(e){return Ek.join(e,wF)}function Tk(e,t){return Ek.join(Ck(e),`${t}${vF}`)}async function EF(e){await O(e)}function Rk(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function CF(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(n==="priority"){t[n]=String(Xt(r));continue}if(SF.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(i=>typeof i=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return Rk(t)}function TF(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new l(`Template "${t}" has invalid options payload.`,m.GENERIC_FAILURE);let n=e,r={};for(let[o,i]of Object.entries(n)){let s=o.trim();if(s.length===0)throw new l(`Template "${t}" contains an empty option key.`,m.GENERIC_FAILURE);if(typeof i=="string"){r[s]=i;continue}if(Array.isArray(i)&&i.every(a=>typeof a=="string")){r[s]=[...i];continue}throw new l(`Template "${t}" contains invalid value for option "${s}".`,m.GENERIC_FAILURE)}return Rk(r)}function RF(e,t){let n;try{n=JSON.parse(e)}catch{throw new l(`Template "${t}" contains invalid JSON.`,m.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Template "${t}" has invalid document shape.`,m.GENERIC_FAILURE);let r=n,o=TF(r.options,t),i=C();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:i,updated_at:typeof r.updated_at=="string"?r.updated_at:i,options:o}}async function xF(e,t){let n=await oe(Tk(e,t));if(n===null)throw new l(`Template "${t}" not found`,m.NOT_FOUND);return RF(n,t)}async function bm(e,t,n){let r=E(process.cwd(),n.path);await EF(r);let o=AF(e),i=CF(t);if(Object.keys(i).length===0)throw new l("templates save requires at least one create option flag",m.USAGE);let s=C(),a=Tk(r,o),c=s;await W(a)&&(c=(await xF(r,o)).created_at);let d={name:o,created_at:c,updated_at:s,options:i},u=await A(r);return await yF.mkdir(Ck(r),{recursive:!0}),await ot({pmRoot:r,filePath:a,raw:`${JSON.stringify(d,null,2)}
|
|
23
|
+
`,op:"templates:save",author:R(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:d.name,created_at:d.created_at,updated_at:d.updated_at,path:a,options:d.options}}var $k=["list","show","apply","lint"],OF="schema-types",$F="schema-statuses",LF="schema-fields";function $a(){let e=I();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Lk(){let{profiles:e,warnings:t}=$f($a());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:Df(n.definition)})),warnings:t,generated_at:C()}}function Pk(e){let t;try{t=Mi(e,$a())}catch(r){throw new l(r instanceof Error?r.message:String(r),m.USAGE)}let{resolved:n}=t;return{action:"show",...Uf(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:C()}}function Nk(e){let t;try{t=Mi(e,$a())}catch(o){throw new l(o instanceof Error?o.message:String(o),m.USAGE)}let{resolved:n}=t,r=B_(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:C()}}function PF(e,t){return IF.join(e,"templates",`${t}.json`)}async function NF(e,t){let n=await oe(PF(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function xk(e,t,n,r){let o=new Map;for(let i of r.templates){let s=await NF(e,i.name);s!==void 0&&o.set(i.name,s)}return{typesRaw:await oe(Rt(e,t.files.types,Tt.types)),statusesRaw:await oe(Rt(e,t.files.statuses,Tt.statuses)),fieldsRaw:await oe(Rt(e,t.files.fields,Tt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Tr(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function Ik(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Tr(t.types.changes),statuses:Tr(t.statuses.changes),fields:Tr(t.fields.changes),workflows:Tr(t.workflows.changes.map(i=>({key:i.type,status:i.status}))),config:Tr(t.config.changes),templates:Tr(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(o)].sort((i,s)=>i.localeCompare(s)),generated_at:C()}}async function FF(e){await O(e)}function MF(e){try{let t=Mi(e,$a());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),m.USAGE)}}async function Fk(e,t,n){let r=E(process.cwd(),n.path);await FF(r);let o=MF(e),i=o.profile,s=o.warnings;for(let w of i.fields){let v;try{v=Pf(w)}catch{continue}H_(v,w)}let a=t.dryRun===!0,c=await A(r),d=Di(c.schema);if(a){let w=await xk(r,d,c,i),v=Ok(i,w);return Ik(i,v,!1,!0,[...s])}let u=R(t.author,c.author_default),p=lh(c),f=!!t.force,h=[...s],_=[],g=async w=>{_.push(await Yr(r,w,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},y;try{await g(OF),await g($F),await g(LF);let w=await xk(r,d,c,i);if(y=Ok(i,w),y.types.changed){let v=Rt(r,d.files.types,Tt.types);await ot({pmRoot:r,filePath:v,raw:Fi(y.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let k=new Set(i.types.map(T=>Cf(T).name)),S=y.types.file.definitions.filter(T=>k.has(T.name));await Tg(r,S,h,"profile:apply-type-folder"),h.push(...await Q({path:v,scope:"project",op:"profile:apply-types"}))}if(y.statuses.changed){let v=Rt(r,d.files.statuses,Tt.statuses);await ot({pmRoot:r,filePath:v,raw:Mf(y.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),h.push(...await Q({path:v,scope:"project",op:"profile:apply-statuses"}))}if(y.fields.changed){let v=Rt(r,d.files.fields,Tt.fields);await ot({pmRoot:r,filePath:v,raw:Nf(y.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),h.push(...await Q({path:v,scope:"project",op:"profile:apply-fields"}))}if(y.config.changed||y.workflows.changed){for(let v of y.config.changes){if(v.status==="unchanged")continue;let k=Wr(v.key);k!==void 0&&ji(c,k,v.value)}c.schema.type_workflows=y.workflows.result,await xe(r,c,"profile:apply-config")}for(let v of y.templates.changes)v.status!=="unchanged"&&await bm(v.name,{...v.options},n)}finally{for(let w of _.reverse())try{await w()}catch{}}return Ik(i,y,y.changed,!1,h)}function Ok(e,t){try{return W_(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),m.USAGE)}}import zF from"node:fs/promises";import Am from"node:path";var Dk=10,jn="https://schema.unbrained.dev/pm/eval-query-set/v1";var La={schema:jn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},dt=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},DF=new Set(["keyword","semantic","hybrid"]);function Mk(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function UF(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),o=Mk(r,n),i=Array.from({length:t.size},()=>1),s=Mk(i,n);return s===0?0:o/s}function jF(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function km(e,t,n){let r=Math.min(n,e.length),o=0;for(let i=0;i<r;i+=1)t.has(e[i])&&(o+=1);return o}function GF(e,t,n){return n<=0?0:km(e,t,n)/n}function qF(e,t,n){return t.size===0?0:km(e,t,n)/t.size}function Uk(e,t,n){return{ndcg:UF(e,t,n),mrr:jF(e,t,n),precision:GF(e,t,n),recall:qF(e,t,n),relevant_total:t.size,retrieved_relevant:km(e,t,n)}}function jk(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function KF(e,t){if(typeof e!="object"||e===null)throw new dt(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new dt(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new dt(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(i=>typeof i!="string"))throw new dt(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new dt(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!DF.has(n.mode)))throw new dt(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.minimum===void 0?{}:{minimum:Gy(n.minimum)},...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Sm(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==jn)throw new dt(`Unsupported eval query set schema; expected "${jn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new dt('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new dt("Eval query set must contain at least one query");return{schema:jn,queries:n.map((r,o)=>KF(r,o))}}var HF=Am.join("search","eval-queries.json"),Em={schema:jn,examples:[JSON.stringify(La)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},BF=new Set(["keyword","semantic","hybrid"]),WF=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!BF.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",m.USAGE);return t},VF=e=>{if(e===void 0||e==="")return Dk;let t=qu(e);if(t===null)throw new l("Eval --k must be a positive integer",m.USAGE);return t},YF=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new l("Eval --fail-under must be a number in the range [0, 1]",m.USAGE);return n},sn=e=>Math.round(e*1e4)/1e4,JF=async e=>{try{return await zF.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,m.NOT_FOUND,{...Em,examples:[`echo '${JSON.stringify(La)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},XF=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new l(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,m.USAGE,Em)}},QF=e=>{try{return Sm(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),m.USAGE,Em)}},ZF=async e=>QF(XF(await JF(e),e)),eM=async(e,t,n,r)=>{let o=e.mode??t,s=(await So(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=Uk(s,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:qy(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:sn(a.ndcg),mrr:sn(a.mrr),precision:sn(a.precision),recall:sn(a.recall)}}},tM=(e,t,n,r)=>{let o=jk(n);return{k:e,query_count:t.length,aggregate:{ndcg:sn(o.ndcg),mrr:sn(o.mrr),precision:sn(o.precision),recall:sn(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:(r===void 0||o.ndcg>=r)&&t.every(i=>(i.violations?.length??0)===0)}},Gk=async(e,t)=>{let n=E(process.cwd(),t.path);await O(n);let r=VF(e.k),o=WF(e.mode),i=YF(e.failUnder),s=e.queries?Am.resolve(process.cwd(),e.queries):Am.join(n,HF),a=await ZF(s),c=[],d=[];for(let u of a.queries){let{report:p,metrics:f}=await eM(u,o,r,t);d.push(f),c.push(p)}return tM(r,c,d,i)};import{readFile as nM,writeFile as zk}from"node:fs/promises";import rM from"node:path";var qk=["item","history","relationship","json"];function oM(e){let t=e.trim().toLowerCase();if(qk.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${qk.join(", ")}.`,m.USAGE)}function iM(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new l(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,m.USAGE)}async function Cm(e,t){try{return await nM(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,m.NOT_FOUND)}}async function sM(e){let t=E(process.cwd(),e.path);return await W(ce(t))?A(t):null}function aM(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Kk(e,t){try{return e()}catch(n){if(n instanceof l&&n.context?.code==="item_identity_conflict"){let r=o=>o.endsWith(`
|
|
24
24
|
`)?o:`${o}
|
|
25
|
-
`;throw await
|
|
25
|
+
`;throw await zk(t.outputPath,`<<<<<<< pm ours
|
|
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 Uk(e,t){let n=JF(e.artifact),r=XF(e.prefer),o=YF.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 Mk(()=>Kg(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 _=zg(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 QF(t),g=ZF(e.itemPath??o,_),y=Ue(I()),w=await Mk(()=>Hg(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,qg(T==="body"?v.body:k[T])])),decisions:w.conflict_decisions,operation:await Wg(process.cwd(),e.itemPath,s)}}}else{let _=Bg(i,s,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await Dk(o,c,"utf8"),d!==void 0){let _=await Yg(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 jk(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await Vg(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 Ps(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as eM}from"node:fs/promises";import tM from"node:path";var nM=4;function Gk(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 rM(e,t){let n=[];for(let r of t){let o;try{o=await eM(tM.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=ty(s,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!ey(a)||a.eventTimestamp===void 0||Gi(a.eventTimestamp,Zg)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function oM(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 iM(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 sM(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 aM(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=>Ps(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}function cM(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 dM(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-FEJT2UCG.js"),i=await o(t),s=await La({...n,dryRun:!0},i);return r({preview:s,dryRun:e.dryRun===!0,global:i,apply:()=>La({...n,dryRun:!1},i)})}async function La(e,t){return e.stage===!0?dM(e,t):lM(e,t)}async function lM(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=Gk(o),s=await rM(r,i.coordinates),a=await Os(r),c=a??r,d=await Jg(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"}});Xg(d.receipts.map(G=>G.id),d,n);let u=await oM({candidates:s,options:e,global:t}),p=d.receipts,f=await jk({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 Ns({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 wh(k,nM,G=>iM({id:G,dryRun:n,options:e,global:t,auditContext:g[G],mergeReceiptProof:y[G]}));sM({receiptOnlyIds:k,results:S,repair:w});let T=await aM({dryRun:n,pendingReceipts:p,repair:w,receiptWorkspaceRoot:c}),x=await Ds({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),F=u===0?o:await wo(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),L=Gk(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=cM(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 mM}from"node:crypto";var Hk=1,Bk=/^[A-Za-z0-9_-]+$/,uM=100,qk=1e3;var QX=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 pM(e){return mM("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 Kk(e,t){let n={version:Hk,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 fM(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Hk,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 _M(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Bk.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(!fM(r,t))throw new l("Mutation event cursor does not match this query.",m.USAGE,{code:"event_cursor_query_mismatch"});return r}function hM(e){let t=e??uM;if(!Number.isSafeInteger(t)||t<0||t>qk)throw new l(`Mutation event limit must be an integer from 0 to ${qk}.`,m.USAGE,{code:"invalid_event_limit"});return t}function gM(e,t){let n=e?.trim();if(!n)return{};if(Bk.test(n))return{cursor:_M(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 yM(e,t){if(t.verify)return zk(e,t);let n=await Zc(e,t),r=n.result;if(r===null&&n.repair_needed)try{await a_(e,{lockWaitMs:0})&&(r=(await Zc(e,t)).result)}catch{}return r===null?zk(e,t):{...r,source:"derived_index"}}async function zk(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 wM(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 Na(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=hM(e.limit),r=wM(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=Ry(o.agent_identity.harness_signals),a=xy({provenance:e.provenanceFilter},s),c=lt(e.harness),d=pM(e),{cursor:u,sinceTimestamp:p}=gM(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 yM(t,f),_=h.events.map(g=>({...r==="row"?{cursor:Kk(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:Iy(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:Kk(h.events[h.events.length-1],d)},source:h.source,...e.provenanceSummary===!0?{provenance_summary:Oy(h.events.map(g=>g.entry),i,s)}:{}}}var vM="1h",bM="now",kM="+1d";function sn(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Wk(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 Vk(e,t,n,r){let o=Wk(e,t,n),i=[];return sn(i,"start",n.start??bM),n.end!==void 0?sn(i,"end",n.end):sn(i,"duration",n.duration??vM),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 Yk(e,t,n){return Vk("Meeting",e,t,n)}function Jk(e,t,n){return Vk("Event",e,t,n)}function Xk(e,t,n){let r=Wk("Reminder",e,t),o=[];return sn(o,"at",t.at??kM),sn(o,"text",t.text??e),r.reminder=[o.join(",")],rn(r,n)}import Uo from"node:crypto";import{cp as Qk,lstat as SM,mkdir as Gn,readFile as xr,readdir as Rm,rename as tS,rm as Im,writeFile as Fa}from"node:fs/promises";import U from"node:path";var nS="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var rS=U.join("runtime","workspace-snapshots"),AM=new Set(["checkpoints","locks","runtime","search","transactions"]),EM=/^[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"}},oS={renameEntry:tS,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
|
-
`)}finally{await t()}}};async function
|
|
31
|
-
`).filter(t=>t.trim().length>0).length}async function
|
|
32
|
-
`,"utf8"),await Gn(U.dirname(i),{recursive:!0})}),s=await
|
|
33
|
-
`,"utf8"),await tS(d,U.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:s}}async function jo(e,t){let n=await xM(e,t),r=await dS(U.join(qn(e),"objects",n,"manifest.json"),t);if(r.schema!==nS||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,m.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function Pm(e){let t=qn(e),n=await Rm(U.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&je(o))return[];throw o}),r=await Rm(U.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&je(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>jo(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await xr(U.join(t,"refs",o),"utf8"))))}}async function Lm(e,t){let n=await jo(e,t),{manifest:r,contents:o}=await sS(e),i=new Map(r.files.map((p,f)=>[p,o[f]])),s=await CM(U.join(qn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),d=new Set([...a,...c]);for(let p of d){let f=i.get(p),h=s.get(p);f!==void 0&&h!==void 0&&f.equals(h)&&d.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=Zk(i.get(p)),h=Zk(s.get(p));return{path:p,current_entries:f,target_entries:h,removed_entries:Math.max(0,f-h)}}).filter(p=>p.removed_entries>0).sort((p,f)=>p.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(p=>!c.has(p)).length,added_file_count:[...c].filter(p=>!a.has(p)).length,removed_item_count:[...a].filter(p=>p.endsWith(".toon")&&!c.has(p)).length,affected_history_stream_count:u.length,removed_history_entry_count:u.reduce((p,f)=>p+f.removed_entries,0),affected_history_streams:u,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function lS(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",m.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",o=n.lockTtlSeconds??60,i=n.lockWaitMs??5e3,s=await ft(e,Rr,o,r,!1,!1,i),a=s.release,c=new xm(ci(e,Rr),r,o);c.start(),await c.refreshNow();let d,u=!1,p=!1;try{let f=await Lm(e,t),h=await jo(e,t),_=await $m(e),g=h.fingerprint,y=qn(e),w=U.join(y,"objects",g,"files"),v=U.dirname(e),k=U.basename(e);d=U.join(v,`.${k}.restore-${Uo.randomUUID()}`);let S=U.join(v,`.${k}.backup-${Uo.randomUUID()}`);await aS("restore_stage",async()=>{await Gn(d,{recursive:!0}),await Qk(w,d,{recursive:!0,force:!1}),await Gn(U.join(d,"runtime"),{recursive:!0}),await Qk(y,U.join(d,rS),{recursive:!0,force:!1})});let T=await eh({pmRoot:d,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:f.changed_file_count,removed_file_count:f.removed_file_count,removed_item_count:f.removed_item_count,affected_history_stream_count:f.affected_history_stream_count,removed_history_entry_count:f.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:i}),x=U.relative(d,T.historyPath).replaceAll("\\","/");await c.stop(),p=!0;let F=ci(d,Rr),L=d;return await s.fence(async()=>{await Gn(U.dirname(F),{recursive:!0}),await Fa(F,await xr(ci(e,Rr)),{flag:"wx"}),u=!0,await RM(L,e,S,oS,async()=>{c.start(),p=!1,await c.refreshNow()})}),await c.stop(),p=!0,{manifest:h,plan:f,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:x,audit_operation:"workspace_snapshot_restore"}}catch(f){throw d!==void 0&&!u&&await Promise.allSettled([Im(d,{recursive:!0,force:!0})]),f}finally{try{p||await c.stop()}catch{}finally{await a()}}}async function mS(e,t){Om(t);let n=qn(e);if(!/^[a-f0-9]{64}$/.test(t))return await eS(U.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Pm(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await eS(U.join(n,"objects",t),t,!0),{deleted:"object",target:t}}function Go(e){let t={...e.args,...e.options};return ue(e.options,t)}function jt(e,t){let n=b(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,m.USAGE)}function Ir(e){return typeof e=="string"?[e]:Se(e)}function uS(e){return Nk(Go(e),e.global)}function pS(e){let t=Go(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",m.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Na({cwd:b(t,"cwd"),pmRoot:b(t,"path"),since:b(t,"since"),type:Ir(t.type),author:Ir(t.author),item:Ir(t.item),limit:t.limit===void 0?void 0:Ke(t.limit,"limit"),full:t.full===!0,...t.verify===!0?{verify:!0}:{},...r===void 0?{}:{cursorMode:r},...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Ir(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Ir(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Ir(t.provenanceFilter)}})}function fS(e){let t=Go(e),n=jt(t,"subcommand");if(n==="install")return fg({dryRun:t.dryRun===!0,preCommitHook:t.preCommitHook===!0},e.global);if(n==="reconcile")return La({dryRun:t.dryRun===!0,author:b(t,"author"),message:b(t,"message"),force:t.force===!0,stage:t.stage===!0},e.global);if(n==="report")return Qg({includeReconciled:t.includeReconciled===!0,cwd:b(t,"cwd")});if(n==="driver")return Uk({artifact:jt(t,"artifact"),basePath:jt(t,"basePath"),oursPath:jt(t,"oursPath"),theirsPath:jt(t,"theirsPath"),outputPath:b(t,"outputPath")??b(t,"output"),itemPath:b(t,"itemPath"),prefer:b(t,"prefer")},e.global);throw Pe({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function _S(e){let t=Go(e),n=jt(t,"subcommand");if(n==="position")return My(e.global);if(n!=="snapshot")throw Pe({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=b(t,"snapshotAction")??jt(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return $m(o,{name:b(t,"name")});if(r==="list")return Pm(o);let i=jt(t,"target");if(r==="inspect")return jo(o,i);if(r==="delete")return mS(o,i);if(r==="restore")return t.dryRun===!0?Lm(o,i):lS(o,i,{force:t.force===!0,author:b(t,"author"),message:b(t,"message"),lockTtlSeconds:Ke(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Ke(t.lockWaitMs,"lockWaitMs")});throw Pe({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Ma(e){let t=Go(e),n=jt(t,"title");return e.action==="meet"?Yk(n,t,e.global):e.action==="event"?Jk(n,t,e.global):Xk(n,t,e.global)}function hS(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:b(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:Se(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:b(e,"measurementSource"),measurementItem:b(e,"measurementItem"),measurementRevision:b(e,"measurementRevision"),author:b(e,"author"),message:b(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:b(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import a0 from"node:fs/promises";import PS from"node:path";function Da(e,t,n,r,o,i="min"){let s=o==="min"?e-t:t-e,a=i==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return s<0||s===0&&r!==null&&a<0}function IM(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,i=null,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;r+=1;let u;try{u=JSON.parse(d)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(Da(f,s,p,o,"min")&&(s=f,o=p),Da(f,a,p,i,"max","max")&&(a=f,i=p))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:i}}function gS(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:h,raw:_})=>IM(h,_)),i=0,s=0,a=null,c=null,d=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let h of o){if(i+=h.lines,s+=h.bytes,h.oldest_ts!==null){let _=Date.parse(h.oldest_ts);Da(_,d,h.id,a?.id??null,"min")&&(d=_,a={id:h.id,ts:h.oldest_ts})}if(h.newest_ts!==null){let _=Date.parse(h.newest_ts);Da(_,u,h.id,c?.id??null,"max")&&(u=_,c={id:h.id,ts:h.newest_ts})}}let p=r===0?[]:[...o].sort((h,_)=>_.bytes-h.bytes||h.id.localeCompare(_.id)).slice(0,r),f=r===0?[]:[...o].sort((h,_)=>_.lines-h.lines||h.id.localeCompare(_.id)).slice(0,r);return{total_streams:e.length,total_lines:i,total_bytes:s,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as $M}from"node:crypto";import{execFile as PM}from"node:child_process";import vS from"node:path";import{promisify as LM}from"node:util";var yS=1;function OM(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Nm(e){if(e===null)return{format_version:yS,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==yS||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!OM(r))throw new l("Improvement ledger contains an invalid observation.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}var NM=LM(PM),FM=50,wS=1e3,MM=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function bS(e){let t=e.trim().toLowerCase();if(!MM.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,m.USAGE,{code:"invalid_improvement_metric"});return t}function DM(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",m.USAGE,{code:"invalid_improvement_observation"});return t}function qo(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,m.USAGE,{code:"invalid_improvement_observation"});return n}}function UM(e){let t=e??FM;if(!Number.isSafeInteger(t)||t<0||t>wS)throw new l(`Improvement observation limit must be an integer from 0 to ${wS}.`,m.USAGE,{code:"invalid_improvement_observation_limit"});return t}function kS(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,m.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function jM(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",m.USAGE,{code:"invalid_improvement_observation"});let r=bS(n.metric),o=DM(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",m.USAGE,{code:"invalid_improvement_observation"});let i=await qM(e,n.revision),s=qo(n.source,"source"),a=qo(n.itemId,"itemId"),c=qo(n.unit,"unit"),d=qo(n.idempotencyKey,"idempotencyKey")??(i.revision_source==="unversioned"?void 0:[i.revision,r,s??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:kS(n.observedAt??C(),"observedAt"),...i,author:R(n.author,t.author_default),...a===void 0?{}:{item_id:a},...s===void 0?{}:{source:s},...d===void 0?{}:{idempotency_key:d}};return{id:$M("sha256").update(Ct(u)).digest("hex").slice(0,24),...u}}function GM(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,m.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,m.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function qM(e,t){let n=qo(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await NM("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:ai(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function KM(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function SS(e,t={}){let n=E(process.cwd(),t.path);await O(n);let r=await A(n),o=await jM(n,r,e),i=vS.join(n,"improvement-ledger.json"),s=await ls({pmRoot:n,filePath:i,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Nm(a),d=GM(c,o);return d?{raw:a,result:d}:(c.observations.push(o),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${Ct(c)}
|
|
34
|
-
`,result:o})}});return{changed:s.changed,observation:s.result,ledger_path:"improvement-ledger.json"}}async function AS(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=e.metric===void 0?void 0:bS(e.metric),r=e.since===void 0?void 0:kS(e.since,"since"),o=UM(e.limit),s=Nm(await oe(vS.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of s){let d=a.get(c.metric)??[];d.push(c),a.set(c.metric,d)}return{observations:[...s].reverse().slice(0,o),total:s.length,truncated:s.length>o,trends:[...a].map(([,c])=>KM(c)).sort((c,d)=>c.metric.localeCompare(d.metric)),source:"audited_workspace_singleton"}}var zM=1e4,ES=1e5,HM=1e3,BM=30,WM=["append","comment","docs","file","learning","note","test_run"];function VM(e){let t=e??zM;if(!Number.isSafeInteger(t)||t<1||t>ES)throw new l(`History analytics event limit must be an integer from 1 to ${ES}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return t}function CS(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function YM(e){let t=e?.trim();if(!t)return new Date(Date.now()-BM*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),i=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*i).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function TS(e,t){let n=VM(t.eventLimit),r=YM(t.since),o=[],i=r,s=!1;for(;o.length<n;){let a=await Na({pmRoot:e,since:i,limit:Math.min(HM,n-o.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(o.push(...c),s=a.has_more,i=a.next_cursor,!a.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:s,...s?{next_cursor:i}:{},source:"history_event_index"}}}function JM(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function XM(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function QM(e){return WM.some(t=>e.startsWith(t))}function RS(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function ZM(e,t,n){let r=new Map,o=new Map,i=new Map;for(let s of t){let a=JM(s.entry,e),c=XM(s.entry),d=o.get(s.item_id)===!0,u=c===void 0?d:n.has(c);if(c!==void 0&&o.set(s.item_id,u),!a)continue;let p=RS(r,a);p.events+=1,QM(s.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!d&&u?(p.closes+=1,i.set(s.item_id,a)):c!==void 0&&d&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:i}}function e0(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(i=>i.kind==="discovered_from").map(i=>i.id));for(let i of o){let s=t.get(i);s&&(RS(e,s).defectEscapes+=1)}}}function t0(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function n0(e,t,n,r,o,i){let{buckets:s,lastCloseValue:a}=ZM(e,t,r);return e0(s,a,n),{dimension:e,status:s.size===0?"unavailable":"available",rows:[...s].map(([c,d])=>t0(c,d,o,i)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function r0(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),i=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(i)?1:Math.max(1,(i-o)/864e5)}function o0(e,t,n){let r=lw(t),o=mw(e,Jr,n),i=o.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),s=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:o,inert:i,undeclared:s,warnings:[...i.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...s.map(a=>`provenance_dimension_undeclared:${a}`)]}}function xS(e,t=Bi,n={}){let r=CS(n.minimumSample);return{...o0(e.events.map(o=>o.entry),t,r),window:e.receipt}}function IS(e,t,n,r={}){let o=CS(r.minimumSample),i=r0(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(s=>n0(s,e.events,t,n,o,i)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}var i0=32;function s0(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let i=o.slice(0,o.indexOf("=")).trim();r.length>0&&i!=="unit"&&i!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Ko(e,t){let n=s0(e).map(o=>{let[i,...s]=o.split(","),a=i.indexOf("="),c=i.slice(0,a).trim(),d=i.slice(a+1).trim(),u=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${o}"; expected name=value[,unit=...][,threshold=...]`,m.USAGE);let p,f;for(let h of s){let _=h.indexOf("="),g=h.slice(0,_).trim(),y=h.slice(_+1).trim();if(g==="unit"&&y.length>0)p=y;else if(g==="threshold"&&y.length>0&&Number.isFinite(Number(y)))f=Number(y);else throw new l(`Invalid --measure attribute "${h}"`,m.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(o=>[o.name,o])).values()].sort((o,i)=>o.name.localeCompare(i.name)).slice(0,i0)}function OS(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function $S(e,t){let n=e.flatMap(i=>i.measurements??[]).filter(i=>i.name===t).sort((i,s)=>s.recorded_at.localeCompare(i.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}function c0(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function d0(e,t,n,r,o){let i=fo(e,"type",r),s=new Set(i.rows.map(f=>f.key)),a=t.filter(f=>!s.has(f)),d=(o?[...i.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:i.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=c0([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>o||f>0));return{byType:d,byStatus:p,omitted:o?0:a.length+Object.values(u).filter(f=>f===0).length}}function l0(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function m0(e){let t=PS.join(e,"history");if(!await W(t))return[];await Zn({path:t,scope:"project"});let n=(await a0.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,i)=>o.localeCompare(i)),r=[];for(let o of n){let i=PS.join(t,o),s=await oe(i);s!==null&&(await Zn({path:i,scope:"project"}),r.push({id:o.slice(0,-6),raw:s}))}return r}async function u0(e,t){let n=[],r=C();for(let o of Ko(t.observe,r))n.push(await SS({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function p0(e,t,n){let r={};return t.byAssignee&&(r.assignee=fo(e,"assignee",n)),t.byTag&&(r.tag=fo(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=fo(e,"priority",n)),r}async function f0(e,t,n,r,o){let i={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},s=o.provenanceCoverage||o.fleetAttribution?await TS(e,i):void 0;return{provenanceCoverage:o.provenanceCoverage&&s?xS(s,n.agent_identity?.harness_signals,i):void 0,fleetAttribution:o.fleetAttribution&&s?IS(s,t,r,i):void 0}}function _0(e,t,n,r,o){let i=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...i?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:C()}}async function Fm(e,t={}){let n=E(process.cwd(),e.path);await O(n);let r=await A(n),o=await u0(e,t),i=$(r,I()),s=D(r.schema),a=t.fieldUtilization?await ph(n,r.item_format,i.type_to_folder,void 0,r.schema):await ye(n,r.item_format,i.type_to_folder,void 0,r.schema);await Z_({pmRoot:n,settings:r,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=xs(s),d=d0(a,i.types,s.definitions.map(k=>k.id),c,t.includeEmpty===!0),u=await m0(n),p=0;for(let k of u)p+=l0(k.raw);let f=t.storage?gS(u):void 0,h=t.metadataCoverage?eg(a,c):void 0,_=p0(a,t,c),g=t.fieldUtilization?tg(a):void 0,y=t.measurements===!0||o.length>0?await AS({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:v}=await f0(n,a,r,s.terminal_statuses,t);return _0({items:a.length,history_streams:u.length,history_entries:p},d.byType,d.byStatus,d.omitted,{metadataCoverage:h,breakdowns:_,storage:f,fieldUtilization:g,improvementLedger:y,recordedObservations:o,provenanceCoverage:w,fleetAttribution:v})}import h0 from"node:fs/promises";import an from"node:path";var g0=an.join("runtime","telemetry","state.json"),zo=an.join("runtime","telemetry"),y0=20,US=un.filter(e=>e.lifecycle==="deprecated"),LS=["status","flush","stats","clear"],NS=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Mm=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,FS=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},w0=e=>({command:Mm(e.event.command,"<unknown>"),eventType:Mm(e.event.event_type,"unknown"),eventSchemaVersion:FS(e.event.schema_version),clientSchemaVersion:FS(e.client_schema_version)}),v0=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),b0=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},k0=e=>{let t=e?.command_resolution;return Mm(t,"")||void 0},jS=(e,t)=>{e[t]=(e[t]??0)+1},S0=(e,t)=>{let n=b0(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=k0(t);r!==void 0&&jS(e.resolution_counts,r)},A0=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,MS=(e,t)=>{t!==void 0&&e.add(t)},E0=(e,t)=>{let n=w0(t),r=e.get(n.command)??v0();r.count+=1,r.max_attempts=Math.max(r.max_attempts,A0(t.attempts)),jS(r.event_type_counts,n.eventType),MS(r.event_schema_versions,n.eventSchemaVersion),MS(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&S0(r,t.event.payload),e.set(n.command,r)},C0=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((i,s)=>i-s),o=Object.entries(t.resolution_counts).sort((i,s)=>i[0].localeCompare(s[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((i,s)=>i[0].localeCompare(s[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((i,s)=>i-s),client_schema_versions:[...t.client_schema_versions].sort((i,s)=>i-s),...r.length>0?{duration_p50_ms:NS(r,.5),duration_p95_ms:NS(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},T0=e=>{let t=(e??"status").trim().toLowerCase();if(LS.includes(t))return t;throw Pe({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:LS,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Um=()=>{throw new l("--limit must be a positive integer",m.USAGE)},GS=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Um():e,R0=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Um():GS(Number.parseInt(t,10))},x0=e=>e===void 0?y0:typeof e=="number"?GS(e):typeof e=="string"?R0(e):Um(),I0=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},O0=e=>{try{let t=JSON.parse(e);return I0(t)?t:void 0}catch{return}},$0=e=>e===null?[]:e.split(`
|
|
35
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),
|
|
36
|
-
`)},e,250)}catch{}return i}var Ua=e=>e??null,ja=async e=>{let t=await A(e),n=
|
|
37
|
-
${t}`;for(let r of
|
|
38
|
-
`))return!1}finally{await r.close()}let i=o.match(/^#![ \t]*(\/[^ \t\n]+)(?:[ \t\n]|$)/u)?.[1];if(!i)return!1;try{return await lD(i),!1}catch(s){return At(s)}}catch{return!1}}async function tA(e,t,n,r){if(/[;&|<>()`$\r\n]/u.test(e))return!1;let o=fD(e);if(!o||!_D(o,t.exitCode,t.stderr))return!1;let i=process.platform==="win32",s=i?eA.join(n.SystemRoot??"C:\\Windows","System32","where.exe"):"/bin/sh",a=i?[o]:["-c",'command -v "$1"',"pm-linked-test-resolution",o];try{let{stdout:c}=await pD(s,a,{env:n,cwd:r,timeout:1e3,windowsHide:!0});return!i&&hD(c,r)}catch(c){let d=c;if(d.killed||d.signal)return!1;let u=d.code;return u===1||!i&&u===127}}import{spawn as gD}from"node:child_process";import{cp as oA,mkdir as Ym,mkdtemp as gA,open as Bm,readdir as Wm,rm as Wo,symlink as yD}from"node:fs/promises";import{tmpdir as yA}from"node:os";import me from"node:path";function nA(e,t,n,r,o){if((t.measure?.length??0)===0||o.some(s=>s.phase!=="setup"&&typeof s.stdout=="string"&&s.failure_category!=="spawn_error"&&s.failure_category!=="empty_run"&&qa(s.stdout,s.stderr??"")===null))return;let i=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[],"test",e,"--list","--json"];throw new l("--measure requires an executed linked test",m.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:P(i),suggested_retry_args:i}})}function Hm(e,t,n,r,o=!1){if((t.measure?.length??0)===0||t.run===!0)return;let i=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[]],s=[...i,...qh(e,t),...t.list?["--list"]:[],...o?["--background"]:[]],a=t.acknowledgeLinkedTests?[...i,"test",e,"--help"]:s,c=[...i,"test",e,"--acknowledge-linked-tests",...t.author?["--author",t.author]:[]];throw new l("--measure requires --run",m.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...t.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${P([...i,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${P(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${P(s)}`]}:{},recovery:{missing:["--run"],suggested_retry:P(a),suggested_retry_args:a}})}var rA={taskkillTimeoutMs:null},Va=20*1024*1024,wD=3e3,vD=1e4,bD=5e3,iA=120,kD=new Set(["locks","extensions","runtime"]),SD=new Set(["history","index","search","extensions","locks","runtime"]),AD=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],ED=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,CD=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,TD=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Jm(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function RD(){return Jm("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",wD)}function xD(){return Jm("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",vD)}function ID(){return Jm("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",bD)}function OD(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function $D(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}}function Xm(e){let t=0,n=0,r=0,o=0;for(let i of e){let s=i.execution_context;!s||s.is_pm_command!==!0||(t+=1,s.is_pm_tracker_read_command===!0&&(n+=1),s.mismatch_detected===!0&&(r+=1),s.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function PD(e){let t=e??"project";if(!St.includes(t))throw new l(`Invalid scope "${e}"`,m.USAGE);return t}function Ja(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(xn.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${xn.join(", ")}`,m.USAGE)}function wA(e){return On(e??"source","--workspace-context")}function vA(e,t,n){return n?t:On(e.workspace_context_mode,"linked test")??t}function bA(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Ja(e.pm_context_mode)}function kA(e,t){return e==="auto"?t?"tracker":"schema":e}function LD(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function ND(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function FD(e,t){let n={};if(!e)return n;for(let r of e){let o=Ro(r,t);if(o)for(let[i,s]of Object.entries(o))n[i]=s}return n}function MD(e,t){if(!e)return[];let n=[];for(let r of e){let o=xo(r,t);o&&n.push(...o)}return[...new Set(n)]}function DD(e){let t=Ms(e);return Fs(t).some(n=>jd(n)!==null)}function SA(e){let t=Ms(e);return Fs(t).some(n=>{let r=jd(n);if(!r)return!1;let o=_y(r);return o?TD.has(o.subcommand):!1})}function Ba(e){if(e)return ly.has(e.subcommand)?pr(e.args,my)?.subcommand:e.subcommand}function sA(e,t){if(e==="npx"||e==="bunx")return Gd(t)?.command;if(e==="pnpm")return Ba(pr(t,sy));if(e==="npm")return Ba(pr(t,ay));if(e==="yarn")return Ba(pr(t,cy));if(e==="bun")return Ba(pr(t,dy))}function Wa(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function AA(e){let t=e.split(" ").filter(s=>s.length>0),n=uy(t);if(n.length===0)return!1;let[r,...o]=n,i=hy.get(r);if(i){let s=o.findIndex(a=>i.test(a));return s>=0&&AA(o.slice(s+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?UD(o):jD(r,o)}function UD(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function jD(e,t){return e==="npx"||e==="bunx"?Wa(Gd(t)?.command):e==="pnpm"||e==="npm"?Wa((e==="pnpm"?py(t):fy(t))?.command)||Wa(sA(e,t)):(e==="yarn"||e==="bun")&&Wa(sA(e,t))}function GD(e){if(gy(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function qD(e){return e?e.map(KD):[]}function KD(e){let t=e.trim(),n=V_(t)?rs(_e(e,"--add"),"--add"):{command:t},r=be(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);return vo(r),{command:r,path:be(n.path),scope:PD(n.scope),timeout_seconds:zD(be(n.timeout_seconds),be(n.timeout)),pm_context_mode:ea(be(n.pm_context_mode),"--add"),workspace_context_mode:On(be(n.workspace_context_mode),"--add"),env_set:Ro(be(n.env_set),"--add"),env_clear:xo(be(n.env_clear),"--add"),shared_host_safe:Zs(be(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:$n(be(n.assert_stdout_contains)),assert_stdout_regex:Sr(be(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:$n(be(n.assert_stderr_contains)),assert_stderr_regex:Sr(be(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:ta(be(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:na(be(n.assert_json_field_equals),"--add"),assert_json_field_gte:ra(be(n.assert_json_field_gte),"--add"),note:be(n.note),phase:br(n.phase,"--add")}}function be(e){let t=e?.trim();return t&&t.length>0?t:void 0}function zD(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",m.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(ge(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",m.USAGE);return r}function HD(e){return e?e.flatMap(t=>{let n=Io(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",m.USAGE);vo(o)}return n}):[]}function BD(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",m.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",m.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",m.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=_e(n,"--remove"),i=o.path!==void 0?"path":"command",s=o.path??o.command;if(!s?.trim())throw new l("--remove requires command=<value> and/or path=<value>",m.USAGE);return{kind:i,value:s.trim()}}return{kind:"either",value:n}}):[]}function WD(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",m.USAGE);return n}))]:[]}function VD(e){try{e.stdin?.end()}catch{}}function EA(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=iA?t:`${t.slice(0,iA-3)}...`}function CA(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Vm(e){try{process.stderr.write(`${e}
|
|
39
|
-
`)}catch{}}function
|
|
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 Hk(e,t){let n=oM(e.artifact),r=iM(e.prefer),o=rM.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 Kk(()=>Yg(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 _=Jg(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 sM(t),g=aM(e.itemPath??o,_),y=Ue(I()),w=await Kk(()=>Xg(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=n_(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,Vg(T==="body"?v.body:k[T])])),decisions:w.conflict_decisions,operation:await Zg(process.cwd(),e.itemPath,s)}}}else{let _=Qg(i,s,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await zk(o,c,"utf8"),d!==void 0){let _=await ty(d);_!==null&&(p.receipt=En(_))}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 Bk(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await ey(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await tn(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await tn(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:[{...En(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await Ls(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as cM}from"node:fs/promises";import dM from"node:path";var lM=4;function Wk(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 mM(e,t){let n=[];for(let r of t){let o;try{o=await cM(dM.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=ay(s,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!sy(a)||a.eventTimestamp===void 0||Gi(a.eventTimestamp,iy)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function uM(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 tn(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 pM(e){try{return{status:"fulfilled",value:await tn(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 fM(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 _M(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=>Ls(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}function hM(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 gM(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-QBZIK3T5.js"),i=await o(t),s=await Pa({...n,dryRun:!0},i);return r({preview:s,dryRun:e.dryRun===!0,global:i,apply:()=>Pa({...n,dryRun:!1},i)})}async function Pa(e,t){return e.stage===!0?gM(e,t):yM(e,t)}async function yM(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=Wk(o),s=await mM(r,i.coordinates),a=await Os(r),c=a??r,d=await ny(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"}});ry(d.receipts.map(G=>G.id),d,n);let u=await uM({candidates:s,options:e,global:t}),p=d.receipts,f=await Bk({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(En)}}])),y=Object.fromEntries([..._].map(([G,he])=>[G,{gitWorkspaceRoot:a,receipts:he}])),w=await Ns({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 Ah(k,lM,G=>pM({id:G,dryRun:n,options:e,global:t,auditContext:g[G],mergeReceiptProof:y[G]}));fM({receiptOnlyIds:k,results:S,repair:w});let T=await _M({dryRun:n,pendingReceipts:p,repair:w,receiptWorkspaceRoot:c}),x=await Ds({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),F=u===0?o:await wo(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),P=Wk(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,P.count===0,!P.truncated].every(Boolean),re=i.truncated||P.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=hM(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(En),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:P.count},validation:x,guidance:Gt,generated_at:x.generated_at}}import{createHash as wM}from"node:crypto";var Xk=1,Qk=/^[A-Za-z0-9_-]+$/,vM=100,Vk=1e3;var a4=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 bM(e){return wM("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 Yk(e,t){let n={version:Xk,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 kM(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Xk,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 SM(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Qk.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(!kM(r,t))throw new l("Mutation event cursor does not match this query.",m.USAGE,{code:"event_cursor_query_mismatch"});return r}function AM(e){let t=e??vM;if(!Number.isSafeInteger(t)||t<0||t>Vk)throw new l(`Mutation event limit must be an integer from 0 to ${Vk}.`,m.USAGE,{code:"invalid_event_limit"});return t}function EM(e,t){let n=e?.trim();if(!n)return{};if(Qk.test(n))return{cursor:SM(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 CM(e,t){if(t.verify)return Jk(e,t);let n=await Zc(e,t),r=n.result;if(r===null&&n.repair_needed)try{await u_(e,{lockWaitMs:0})&&(r=(await Zc(e,t)).result)}catch{}return r===null?Jk(e,t):{...r,source:"derived_index"}}async function Jk(e,t){try{return{...await p_(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 TM(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 Na(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=AM(e.limit),r=TM(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=Py(o.agent_identity.harness_signals),a=Ny({provenance:e.provenanceFilter},s),c=lt(e.harness),d=bM(e),{cursor:u,sinceTimestamp:p}=EM(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 CM(t,f),_=h.events.map(g=>({...r==="row"?{cursor:Yk(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:Fy(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:Yk(h.events[h.events.length-1],d)},source:h.source,...e.provenanceSummary===!0?{provenance_summary:My(h.events.map(g=>g.entry),i,s)}:{}}}var RM="1h",xM="now",IM="+1d";function an(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Zk(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 eS(e,t,n,r){let o=Zk(e,t,n),i=[];return an(i,"start",n.start??xM),n.end!==void 0?an(i,"end",n.end):an(i,"duration",n.duration??RM),an(i,"location",n.location),an(i,"timezone",n.timezone),n.allDay===!0&&an(i,"all_day","true"),o.event=[i.join(",")],on(o,r)}function tS(e,t,n){return eS("Meeting",e,t,n)}function nS(e,t,n){return eS("Event",e,t,n)}function rS(e,t,n){let r=Zk("Reminder",e,t),o=[];return an(o,"at",t.at??IM),an(o,"text",t.text??e),r.reminder=[o.join(",")],on(r,n)}import Uo from"node:crypto";import{cp as oS,lstat as OM,mkdir as Gn,readFile as xr,readdir as Rm,rename as aS,rm as Im,writeFile as Fa}from"node:fs/promises";import U from"node:path";var cS="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var dS=U.join("runtime","workspace-snapshots"),$M=new Set(["checkpoints","locks","runtime","search","transactions"]),LM=/^[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"}},lS={renameEntry:aS,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 r_(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
|
+
`)}finally{await t()}}};async function mS(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&&$M.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 mS(e,i));else if(o.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function uS(e){let t=await mS(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:cS,fingerprint:i,files:t,bytes:o},contents:r}}function iS(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
|
|
31
|
+
`).filter(t=>t.trim().length>0).length}async function PM(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(!LM.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 pS(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,dS)}function fS(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 _S(e,t){try{return JSON.parse(await xr(e,"utf8"))}catch(n){throw je(n)?fS(t):n}}async function sS(e,t,n){try{await Im(e,{recursive:n})}catch(r){throw je(r)?fS(t):r}}async function NM(e,t,n=lS){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 FM(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 MM(e,t){return Om(t),/^[a-f0-9]{64}$/.test(t)?t:(await _S(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 uS(e),o=qn(e),i=U.join(o,"objects",n.fingerprint),s=!1;try{s=(await OM(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 pS("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 Fa(u,r[c])}await Fa(U.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
|
|
32
|
+
`,"utf8"),await Gn(U.dirname(i),{recursive:!0})}),s=await NM(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 Fa(d,`${JSON.stringify(a,null,2)}
|
|
33
|
+
`,"utf8"),await aS(d,U.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:s}}async function jo(e,t){let n=await MM(e,t),r=await _S(U.join(qn(e),"objects",n,"manifest.json"),t);if(r.schema!==cS||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,m.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function Lm(e){let t=qn(e),n=await Rm(U.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&je(o))return[];throw o}),r=await Rm(U.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&je(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>jo(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await xr(U.join(t,"refs",o),"utf8"))))}}async function Pm(e,t){let n=await jo(e,t),{manifest:r,contents:o}=await uS(e),i=new Map(r.files.map((p,f)=>[p,o[f]])),s=await PM(U.join(qn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),d=new Set([...a,...c]);for(let p of d){let f=i.get(p),h=s.get(p);f!==void 0&&h!==void 0&&f.equals(h)&&d.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=iS(i.get(p)),h=iS(s.get(p));return{path:p,current_entries:f,target_entries:h,removed_entries:Math.max(0,f-h)}}).filter(p=>p.removed_entries>0).sort((p,f)=>p.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(p=>!c.has(p)).length,added_file_count:[...c].filter(p=>!a.has(p)).length,removed_item_count:[...a].filter(p=>p.endsWith(".toon")&&!c.has(p)).length,affected_history_stream_count:u.length,removed_history_entry_count:u.reduce((p,f)=>p+f.removed_entries,0),affected_history_streams:u,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function hS(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",m.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",o=n.lockTtlSeconds??60,i=n.lockWaitMs??5e3,s=await ft(e,Rr,o,r,!1,!1,i),a=s.release,c=new xm(ci(e,Rr),r,o);c.start(),await c.refreshNow();let d,u=!1,p=!1;try{let f=await Pm(e,t),h=await jo(e,t),_=await $m(e),g=h.fingerprint,y=qn(e),w=U.join(y,"objects",g,"files"),v=U.dirname(e),k=U.basename(e);d=U.join(v,`.${k}.restore-${Uo.randomUUID()}`);let S=U.join(v,`.${k}.backup-${Uo.randomUUID()}`);await pS("restore_stage",async()=>{await Gn(d,{recursive:!0}),await oS(w,d,{recursive:!0,force:!1}),await Gn(U.join(d,"runtime"),{recursive:!0}),await oS(y,U.join(d,dS),{recursive:!0,force:!1})});let T=await ih({pmRoot:d,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:f.changed_file_count,removed_file_count:f.removed_file_count,removed_item_count:f.removed_item_count,affected_history_stream_count:f.affected_history_stream_count,removed_history_entry_count:f.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:i}),x=U.relative(d,T.historyPath).replaceAll("\\","/");await c.stop(),p=!0;let F=ci(d,Rr),P=d;return await s.fence(async()=>{await Gn(U.dirname(F),{recursive:!0}),await Fa(F,await xr(ci(e,Rr)),{flag:"wx"}),u=!0,await FM(P,e,S,lS,async()=>{c.start(),p=!1,await c.refreshNow()})}),await c.stop(),p=!0,{manifest:h,plan:f,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:x,audit_operation:"workspace_snapshot_restore"}}catch(f){throw d!==void 0&&!u&&await Promise.allSettled([Im(d,{recursive:!0,force:!0})]),f}finally{try{p||await c.stop()}catch{}finally{await a()}}}async function gS(e,t){Om(t);let n=qn(e);if(!/^[a-f0-9]{64}$/.test(t))return await sS(U.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Lm(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await sS(U.join(n,"objects",t),t,!0),{deleted:"object",target:t}}function Go(e){let t={...e.args,...e.options};return ue(e.options,t)}function jt(e,t){let n=b(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,m.USAGE)}function Ir(e){return typeof e=="string"?[e]:Se(e)}function yS(e){return Gk(Go(e),e.global)}function wS(e){let t=Go(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",m.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Na({cwd:b(t,"cwd"),pmRoot:b(t,"path"),since:b(t,"since"),type:Ir(t.type),author:Ir(t.author),item:Ir(t.item),limit:t.limit===void 0?void 0:Ke(t.limit,"limit"),full:t.full===!0,...t.verify===!0?{verify:!0}:{},...r===void 0?{}:{cursorMode:r},...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Ir(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Ir(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Ir(t.provenanceFilter)}})}function vS(e){let t=Go(e),n=jt(t,"subcommand");if(n==="install")return vg({dryRun:t.dryRun===!0,preCommitHook:t.preCommitHook===!0},e.global);if(n==="reconcile")return Pa({dryRun:t.dryRun===!0,author:b(t,"author"),message:b(t,"message"),force:t.force===!0,stage:t.stage===!0},e.global);if(n==="report")return oy({includeReconciled:t.includeReconciled===!0,cwd:b(t,"cwd")});if(n==="driver")return Hk({artifact:jt(t,"artifact"),basePath:jt(t,"basePath"),oursPath:jt(t,"oursPath"),theirsPath:jt(t,"theirsPath"),outputPath:b(t,"outputPath")??b(t,"output"),itemPath:b(t,"itemPath"),prefer:b(t,"prefer")},e.global);throw Le({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function bS(e){let t=Go(e),n=jt(t,"subcommand");if(n==="position")return Ky(e.global);if(n!=="snapshot")throw Le({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=b(t,"snapshotAction")??jt(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return $m(o,{name:b(t,"name")});if(r==="list")return Lm(o);let i=jt(t,"target");if(r==="inspect")return jo(o,i);if(r==="delete")return gS(o,i);if(r==="restore")return t.dryRun===!0?Pm(o,i):hS(o,i,{force:t.force===!0,author:b(t,"author"),message:b(t,"message"),lockTtlSeconds:Ke(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Ke(t.lockWaitMs,"lockWaitMs")});throw Le({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Ma(e){let t=Go(e),n=jt(t,"title");return e.action==="meet"?tS(n,t,e.global):e.action==="event"?nS(n,t,e.global):rS(n,t,e.global)}function kS(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:b(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:Se(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:b(e,"measurementSource"),measurementItem:b(e,"measurementItem"),measurementRevision:b(e,"measurementRevision"),author:b(e,"author"),message:b(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:b(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import _0 from"node:fs/promises";import US from"node:path";function Da(e,t,n,r,o,i="min"){let s=o==="min"?e-t:t-e,a=i==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return s<0||s===0&&r!==null&&a<0}function DM(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,i=null,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;r+=1;let u;try{u=JSON.parse(d)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(Da(f,s,p,o,"min")&&(s=f,o=p),Da(f,a,p,i,"max","max")&&(a=f,i=p))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:i}}function SS(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:h,raw:_})=>DM(h,_)),i=0,s=0,a=null,c=null,d=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let h of o){if(i+=h.lines,s+=h.bytes,h.oldest_ts!==null){let _=Date.parse(h.oldest_ts);Da(_,d,h.id,a?.id??null,"min")&&(d=_,a={id:h.id,ts:h.oldest_ts})}if(h.newest_ts!==null){let _=Date.parse(h.newest_ts);Da(_,u,h.id,c?.id??null,"max")&&(u=_,c={id:h.id,ts:h.newest_ts})}}let p=r===0?[]:[...o].sort((h,_)=>_.bytes-h.bytes||h.id.localeCompare(_.id)).slice(0,r),f=r===0?[]:[...o].sort((h,_)=>_.lines-h.lines||h.id.localeCompare(_.id)).slice(0,r);return{total_streams:e.length,total_lines:i,total_bytes:s,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as jM}from"node:crypto";import{execFile as GM}from"node:child_process";import CS from"node:path";import{promisify as qM}from"node:util";var AS=1;function UM(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Nm(e){if(e===null)return{format_version:AS,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==AS||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!UM(r))throw new l("Improvement ledger contains an invalid observation.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}var KM=qM(GM),zM=50,ES=1e3,HM=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function TS(e){let t=e.trim().toLowerCase();if(!HM.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,m.USAGE,{code:"invalid_improvement_metric"});return t}function BM(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",m.USAGE,{code:"invalid_improvement_observation"});return t}function qo(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,m.USAGE,{code:"invalid_improvement_observation"});return n}}function WM(e){let t=e??zM;if(!Number.isSafeInteger(t)||t<0||t>ES)throw new l(`Improvement observation limit must be an integer from 0 to ${ES}.`,m.USAGE,{code:"invalid_improvement_observation_limit"});return t}function RS(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,m.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function VM(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",m.USAGE,{code:"invalid_improvement_observation"});let r=TS(n.metric),o=BM(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",m.USAGE,{code:"invalid_improvement_observation"});let i=await JM(e,n.revision),s=qo(n.source,"source"),a=qo(n.itemId,"itemId"),c=qo(n.unit,"unit"),d=qo(n.idempotencyKey,"idempotencyKey")??(i.revision_source==="unversioned"?void 0:[i.revision,r,s??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:RS(n.observedAt??C(),"observedAt"),...i,author:R(n.author,t.author_default),...a===void 0?{}:{item_id:a},...s===void 0?{}:{source:s},...d===void 0?{}:{idempotency_key:d}};return{id:jM("sha256").update(Ct(u)).digest("hex").slice(0,24),...u}}function YM(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,m.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,m.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function JM(e,t){let n=qo(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await KM("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:ai(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function XM(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function xS(e,t={}){let n=E(process.cwd(),t.path);await O(n);let r=await A(n),o=await VM(n,r,e),i=CS.join(n,"improvement-ledger.json"),s=await ls({pmRoot:n,filePath:i,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Nm(a),d=YM(c,o);return d?{raw:a,result:d}:(c.observations.push(o),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${Ct(c)}
|
|
34
|
+
`,result:o})}});return{changed:s.changed,observation:s.result,ledger_path:"improvement-ledger.json"}}async function IS(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=e.metric===void 0?void 0:TS(e.metric),r=e.since===void 0?void 0:RS(e.since,"since"),o=WM(e.limit),s=Nm(await oe(CS.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of s){let d=a.get(c.metric)??[];d.push(c),a.set(c.metric,d)}return{observations:[...s].reverse().slice(0,o),total:s.length,truncated:s.length>o,trends:[...a].map(([,c])=>XM(c)).sort((c,d)=>c.metric.localeCompare(d.metric)),source:"audited_workspace_singleton"}}var QM=1e4,OS=1e5,ZM=1e3,e0=30,t0=["append","comment","docs","file","learning","note","test_run"];function n0(e){let t=e??QM;if(!Number.isSafeInteger(t)||t<1||t>OS)throw new l(`History analytics event limit must be an integer from 1 to ${OS}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return t}function $S(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function r0(e){let t=e?.trim();if(!t)return new Date(Date.now()-e0*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),i=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*i).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function LS(e,t){let n=n0(t.eventLimit),r=r0(t.since),o=[],i=r,s=!1;for(;o.length<n;){let a=await Na({pmRoot:e,since:i,limit:Math.min(ZM,n-o.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(o.push(...c),s=a.has_more,i=a.next_cursor,!a.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:s,...s?{next_cursor:i}:{},source:"history_event_index"}}}function o0(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function i0(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function s0(e){return t0.some(t=>e.startsWith(t))}function PS(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function a0(e,t,n){let r=new Map,o=new Map,i=new Map;for(let s of t){let a=o0(s.entry,e),c=i0(s.entry),d=o.get(s.item_id)===!0,u=c===void 0?d:n.has(c);if(c!==void 0&&o.set(s.item_id,u),!a)continue;let p=PS(r,a);p.events+=1,s0(s.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!d&&u?(p.closes+=1,i.set(s.item_id,a)):c!==void 0&&d&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:i}}function c0(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(i=>i.kind==="discovered_from").map(i=>i.id));for(let i of o){let s=t.get(i);s&&(PS(e,s).defectEscapes+=1)}}}function d0(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function l0(e,t,n,r,o,i){let{buckets:s,lastCloseValue:a}=a0(e,t,r);return c0(s,a,n),{dimension:e,status:s.size===0?"unavailable":"available",rows:[...s].map(([c,d])=>d0(c,d,o,i)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function m0(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),i=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(i)?1:Math.max(1,(i-o)/864e5)}function u0(e,t,n){let r=hw(t),o=gw(e,Jr,n),i=o.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),s=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:o,inert:i,undeclared:s,warnings:[...i.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...s.map(a=>`provenance_dimension_undeclared:${a}`)]}}function NS(e,t=Bi,n={}){let r=$S(n.minimumSample);return{...u0(e.events.map(o=>o.entry),t,r),window:e.receipt}}function FS(e,t,n,r={}){let o=$S(r.minimumSample),i=m0(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(s=>l0(s,e.events,t,n,o,i)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}var p0=32;function f0(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let i=o.slice(0,o.indexOf("=")).trim();r.length>0&&i!=="unit"&&i!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Ko(e,t){let n=f0(e).map(o=>{let[i,...s]=o.split(","),a=i.indexOf("="),c=i.slice(0,a).trim(),d=i.slice(a+1).trim(),u=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${o}"; expected name=value[,unit=...][,threshold=...]`,m.USAGE);let p,f;for(let h of s){let _=h.indexOf("="),g=h.slice(0,_).trim(),y=h.slice(_+1).trim();if(g==="unit"&&y.length>0)p=y;else if(g==="threshold"&&y.length>0&&Number.isFinite(Number(y)))f=Number(y);else throw new l(`Invalid --measure attribute "${h}"`,m.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(o=>[o.name,o])).values()].sort((o,i)=>o.name.localeCompare(i.name)).slice(0,p0)}function MS(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function DS(e,t){let n=e.flatMap(i=>i.measurements??[]).filter(i=>i.name===t).sort((i,s)=>s.recorded_at.localeCompare(i.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}function h0(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function g0(e,t,n,r,o){let i=fo(e,"type",r),s=new Set(i.rows.map(f=>f.key)),a=t.filter(f=>!s.has(f)),d=(o?[...i.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:i.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=h0([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>o||f>0));return{byType:d,byStatus:p,omitted:o?0:a.length+Object.values(u).filter(f=>f===0).length}}function y0(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function w0(e){let t=US.join(e,"history");if(!await W(t))return[];await Zn({path:t,scope:"project"});let n=(await _0.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,i)=>o.localeCompare(i)),r=[];for(let o of n){let i=US.join(t,o),s=await oe(i);s!==null&&(await Zn({path:i,scope:"project"}),r.push({id:o.slice(0,-6),raw:s}))}return r}async function v0(e,t){let n=[],r=C();for(let o of Ko(t.observe,r))n.push(await xS({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function b0(e,t,n){let r={};return t.byAssignee&&(r.assignee=fo(e,"assignee",n)),t.byTag&&(r.tag=fo(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=fo(e,"priority",n)),r}async function k0(e,t,n,r,o){let i={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},s=o.provenanceCoverage||o.fleetAttribution?await LS(e,i):void 0;return{provenanceCoverage:o.provenanceCoverage&&s?NS(s,n.agent_identity?.harness_signals,i):void 0,fleetAttribution:o.fleetAttribution&&s?FS(s,t,r,i):void 0}}function S0(e,t,n,r,o){let i=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...i?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:C()}}async function Fm(e,t={}){let n=E(process.cwd(),e.path);await O(n);let r=await A(n),o=await v0(e,t),i=$(r,I()),s=D(r.schema),a=t.fieldUtilization?await yh(n,r.item_format,i.type_to_folder,void 0,r.schema):await ye(n,r.item_format,i.type_to_folder,void 0,r.schema);await oh({pmRoot:n,settings:r,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=xs(s),d=g0(a,i.types,s.definitions.map(k=>k.id),c,t.includeEmpty===!0),u=await w0(n),p=0;for(let k of u)p+=y0(k.raw);let f=t.storage?SS(u):void 0,h=t.metadataCoverage?sg(a,c):void 0,_=b0(a,t,c),g=t.fieldUtilization?ag(a):void 0,y=t.measurements===!0||o.length>0?await IS({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:v}=await k0(n,a,r,s.terminal_statuses,t);return S0({items:a.length,history_streams:u.length,history_entries:p},d.byType,d.byStatus,d.omitted,{metadataCoverage:h,breakdowns:_,storage:f,fieldUtilization:g,improvementLedger:y,recordedObservations:o,provenanceCoverage:w,fleetAttribution:v})}import A0 from"node:fs/promises";import cn from"node:path";var E0=cn.join("runtime","telemetry","state.json"),zo=cn.join("runtime","telemetry"),C0=20,HS=pn.filter(e=>e.lifecycle==="deprecated"),jS=["status","flush","stats","clear"],GS=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Mm=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,qS=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},T0=e=>({command:Mm(e.event.command,"<unknown>"),eventType:Mm(e.event.event_type,"unknown"),eventSchemaVersion:qS(e.event.schema_version),clientSchemaVersion:qS(e.client_schema_version)}),R0=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),x0=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},I0=e=>{let t=e?.command_resolution;return Mm(t,"")||void 0},BS=(e,t)=>{e[t]=(e[t]??0)+1},O0=(e,t)=>{let n=x0(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=I0(t);r!==void 0&&BS(e.resolution_counts,r)},$0=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,KS=(e,t)=>{t!==void 0&&e.add(t)},L0=(e,t)=>{let n=T0(t),r=e.get(n.command)??R0();r.count+=1,r.max_attempts=Math.max(r.max_attempts,$0(t.attempts)),BS(r.event_type_counts,n.eventType),KS(r.event_schema_versions,n.eventSchemaVersion),KS(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&O0(r,t.event.payload),e.set(n.command,r)},P0=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((i,s)=>i-s),o=Object.entries(t.resolution_counts).sort((i,s)=>i[0].localeCompare(s[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((i,s)=>i[0].localeCompare(s[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((i,s)=>i-s),client_schema_versions:[...t.client_schema_versions].sort((i,s)=>i-s),...r.length>0?{duration_p50_ms:GS(r,.5),duration_p95_ms:GS(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},N0=e=>{let t=(e??"status").trim().toLowerCase();if(jS.includes(t))return t;throw Le({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:jS,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Um=()=>{throw new l("--limit must be a positive integer",m.USAGE)},WS=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Um():e,F0=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Um():WS(Number.parseInt(t,10))},M0=e=>e===void 0?C0:typeof e=="number"?WS(e):typeof e=="string"?F0(e):Um(),D0=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},U0=e=>{try{let t=JSON.parse(e);return D0(t)?t:void 0}catch{return}},j0=e=>e===null?[]:e.split(`
|
|
35
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),VS=e=>{let t=j0(e),n=[],r=0;for(let o of t){let i=U0(o);i===void 0?r+=1:n.push(i)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},G0=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),q0=e=>{try{let t=JSON.parse(e);return G0(t)?t:{}}catch{return{}}},Dm=async e=>{let t=await oe(e);return t===null||t.trim().length===0?{}:q0(t)};function K0(e){let t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-Math.max(1,Math.trunc(e))+1)).toISOString().slice(0,10)}function z0(e,t,n){let r=Object.create(null);for(let[o,i]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(o)||o<t||o>n||typeof i!="object"||i===null||Array.isArray(i))continue;let s=i;!Number.isSafeInteger(s.count)||s.count<1||typeof s.last_seen!="string"||!s.last_seen.startsWith(o)||(r[o]={count:s.count,last_seen:s.last_seen})}return r}function zS(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,o=new Date().toISOString().slice(0,10);for(let i of HS){let s=r[i.alias];if(typeof s!="object"||s===null||Array.isArray(s))continue;let a=s;if(a.canonical!==i.canonical||typeof a.days!="object"||a.days===null||Array.isArray(a.days))continue;let c=z0(a.days,t,o);Object.keys(c).length>0&&(n[i.alias]={canonical:i.canonical,days:c})}return n}async function H0(e,t,n){let r=K0(n),o=await Dm(t),i=zS(o.alias_usage,r);if(JSON.stringify(o.alias_usage??{})===JSON.stringify(i))return i;try{await Sd(async()=>{let s=await Dm(t);if(s.alias_usage===void 0)return;let a=zS(s.alias_usage,r);JSON.stringify(s.alias_usage)!==JSON.stringify(a)&&await ae(t,`${JSON.stringify({...s,alias_usage:a},null,2)}
|
|
36
|
+
`)},e,250)}catch{}return i}var Ua=e=>e??null,ja=async e=>{let t=await A(e),n=cn.join(e,zo,io("events.jsonl")),r=cn.join(e,zo,io("state.json")),o=await oe(n),i=VS(o),s=await Dm(r),a=ws();return{enabled:t.telemetry.enabled&&!a.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:a,endpoint:bh(kh(t.telemetry.endpoint)),queue_path:n,state_path:r,queue_rows_total:i.rows_total,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:Ua(s.last_attempted_flush_at),last_successful_flush_at:Ua(s.last_successful_flush_at),last_failed_flush_at:Ua(s.last_failed_flush_at),last_failed_flush_error:Ua(s.last_failed_flush_error)}},B0=e=>{let t=new Map;for(let n of e)L0(t,n);return[...t.entries()].map(([n,r])=>P0(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},W0=async(e,t)=>({action:"telemetry",subcommand:"status",status:await ja(t.globalPmRoot),generated_at:C()}),V0=async(e,t)=>{let n=await ja(t.globalPmRoot);await Oh(t.globalPmRoot);let r=await ja(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),i=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:i,queue_drained:i,status:r,generated_at:C()}},Y0=async(e,t)=>{let n=M0(e.limit),r=await oe(t.queuePath),o=VS(r),i=B0(o.entries),s=i.slice(0,n),a=await A(t.globalPmRoot),c=await H0(t.globalPmRoot,cn.join(t.globalPmRoot,E0),a.telemetry.retention_days),d=Object.entries(c).map(([u,p])=>{let f=Object.values(p.days);return{alias:u,canonical:p.canonical,count:f.reduce((h,_)=>Math.min(Number.MAX_SAFE_INTEGER,h+_.count),0),last_seen:f.map(h=>h.last_seen).sort().at(-1)}}).sort((u,p)=>p.count-u.count||u.alias.localeCompare(p.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:i.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:i.length>s.length,stats:s,alias_usage:d,zero_use_aliases:HS.map(u=>u.alias).filter(u=>c[u]===void 0),alias_usage_retention_days:a.telemetry.retention_days,generated_at:C()}},J0=async(e,t)=>Sd(async()=>{let n=await A(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await xe(t.globalPmRoot,n,"telemetry:clear");let o=cn.join(t.globalPmRoot,zo),i=await W(o);return await A0.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:i&&!await W(o),queue_exists_after:await W(t.queuePath),state_exists_after:await W(t.statePath),status:await ja(t.globalPmRoot),generated_at:C()}},t.globalPmRoot),X0={status:W0,flush:V0,stats:Y0,clear:J0};async function YS(e,t){let n=N0(e.subcommand),r=$e(process.cwd());return X0[n](e,{globalPmRoot:r,queuePath:cn.join(r,zo,io("events.jsonl")),statePath:cn.join(r,zo,io("state.json"))})}var JS=20;function Q0(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return JS;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?JS:t}function jm(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let i=Gi(r.recorded_at,o.recorded_at);if(i!==0)return i;let s=r.run_id.localeCompare(o.run_id);return s!==0?s:r.kind.localeCompare(o.kind)}),n=Q0();return t.length>n?t.slice(t.length-n):t}async function Ga(e){await we({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=jm([...n,e.entry]),{changedFields:["test_runs"]}}})}function XS(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(o))return[];t.push(o);continue}t.push(r)}return t}function Gm(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=XS(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let i of r){if(typeof o!="object"||o===null)return{found:!1,value:void 0};if(typeof i=="number"&&(!Array.isArray(o)||i>=o.length))return{found:!1,value:void 0};let s=Object.getOwnPropertyDescriptor(o,i);if(!s||!Object.hasOwn(s,"value"))return{found:!1,value:void 0};o=s.value}return{found:!0,value:o}}var Z0=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],eD=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function qa(e,t){let n=`${e}
|
|
37
|
+
${t}`;for(let r of Z0)if(r.regex.test(n))return{code:r.code};return null}function QS(e,t){for(let[n,r]of[["stdout",e],["stderr",t]]){let o=eD.find(i=>i.regex.test(r));if(o)return{code:o.receiptCode,stream:n}}}function ZS(e,t){return{trackerPath:e.path?.trim()||(process.env.PM_PATH?.trim()?t:void 0),noExtensions:e.noExtensions}}function eA(e,t={}){let n=t.trackerPath?.trim();return L(["test",e,"--list",...t.noExtensions===!0?["--no-extensions"]:[],...n?["--pm-path",n]:[]],t.platform)}import{cp as sD,lstat as aD,mkdir as cD,readlink as dD,realpath as zm,stat as lD,symlink as rA}from"node:fs/promises";import{execFile as mD}from"node:child_process";import K from"node:path";import{promisify as uD}from"node:util";import{execFile as tD}from"node:child_process";import{readdir as nD,realpath as rD}from"node:fs/promises";import oD from"node:path";import{promisify as iD}from"node:util";var qm=iD(tD),tA=".agents/pm/merge-receipts";async function nA(e,t,n){let r=oD.join(n,"merge-receipts"),o=(await nD(r).catch(c=>{if(je(c))return[];throw c})).filter(c=>c.endsWith(".json")),{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-EUYZJR5R.js"),s=o.length===0?new Map:await i(e,r,o,wg,await rD(r),{failOnReadError:!0}),a={cwd:t,env:yg(),timeout:1e4,maxBuffer:1024*1024,windowsHide:!0};await qm("git",["rm","-q","-r","--cached","--ignore-unmatch","--",tA],a);for(let[c,d]of s){let u=qm("git",["hash-object","-w","--stdin"],a),p=u.child.stdin;p!==null&&(p.on("error",()=>{u.child.kill()}),p.end(d));let f=(await u).stdout.trim();if(!/^(?:[a-f\d]{40}|[a-f\d]{64})$/u.test(f))throw new Error("Invalid snapshot receipt object identity.");await qm("git",["update-index","--add","--cacheinfo","100644",f,`${tA}/${c}`],a)}}var pD=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),Ka=uD(mD);async function fD(e,t){let n=await za(K.join(e,".git"));if(!n||n.isDirectory()&&!await za(K.join(e,".git/HEAD")))return!1;let r=Object.fromEntries(Object.entries(process.env).filter(([o])=>!o.toUpperCase().startsWith("GIT_")));await Ka("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:r,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await Ka("git",["-C",t,"remote","remove","origin"],{env:r,timeout:1e4,windowsHide:!0});try{await Ka("git",["-C",t,"rev-parse","--verify","--quiet","HEAD"],{env:r,timeout:1e4,windowsHide:!0})}catch(o){if(o.code===1)return!0;throw o}return await Ka("git",["-C",t,"read-tree","HEAD"],{env:r,timeout:1e4,windowsHide:!0}),!0}async function _D(e,t,n,r){await fD(e,t)&&n&&r!==!1&&await nA(e,t,n)}function Km(e){return e.split(K.sep).some(t=>pD.has(t.toLowerCase()))}function Ho(e){return e===".."||e.startsWith(`..${K.sep}`)||K.isAbsolute(e)}async function za(e){try{return await lD(e)}catch(t){if(!je(t))throw t;return}}async function Ha(e){let t=[],n=e;for(;K.dirname(n)!==n;)try{return K.join(await zm(n),...t)}catch(r){if(!je(r))throw r;t.unshift(K.basename(n)),n=K.dirname(n)}return K.join(await zm(n),...t)}async function hD(e,t,n){let r=K.relative(t,await Ha(e));if(!Ho(r))return r;let o=[],i=e;for(;K.dirname(i)!==i;){let s=await Ha(i),a=n.find(([,c])=>c===s);if(a)return K.join(a[0],...o);o.unshift(K.basename(i)),i=K.dirname(i)}return r}async function oA(e,t,n,r){let o=[],i=[],s=await zm(e),a=await Ha(K.resolve(t));if(![K.relative(s,a),K.relative(a,s)].every(Ho))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await cD(K.dirname(t),{recursive:!0}),await _D(s,t,n,r),await sD(s,t,{recursive:!0,force:!0,async filter(c){let d=K.relative(s,c);if(!d)return!0;if(Km(d))return!1;if(K.basename(c).toLowerCase()==="node_modules"){if((await za(c))?.isDirectory()){let u=await Ha(c),p=K.relative(s,u);if(!Ho(K.relative(u,s))||!Ho(p)&&(Km(p)||!p.split(K.sep).some(f=>f.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${d}`);o.push([d,u])}return!1}return(await aD(c)).isSymbolicLink()?(i.push([d,K.resolve(K.dirname(c),await dD(c)),(await za(c))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[c]of o)await rA(K.resolve(s,c),K.join(t,c),"junction");for(let[c,d,u]of i){let p=await hD(d,s,o);if(Ho(p)||Km(p))throw new Error(`Source symlink must target included workspace source: ${c}`);await rA(K.resolve(t,p),K.join(t,c),u)}}import{execFile as gD}from"node:child_process";import{constants as iA}from"node:fs";import{access as yD,open as wD}from"node:fs/promises";import sA from"node:path";import{promisify as vD}from"node:util";var bD=vD(gD);function kD(e){let t=e.match(/^\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([\w./\\:-]+))(?=\s|$)/u),n=t?.[1]??t?.[2]??t?.[3];return n&&!/[$`%&|<>^;]/u.test(n)?n:void 0}function SD(e,t,n){return process.platform==="win32"?(t===1||t===9009)&&n.split(/\r?\n/u).some(r=>r.trim()===`'${e}' is not recognized as an internal or external command,`):t!==126&&t!==127?!1:n.split(/\r?\n/u).some(r=>t===127&&(r.endsWith(`: ${e}: not found`)||r.endsWith(`: ${e}: command not found`))||t===126&&r.includes(`: ${e}: `)&&r.endsWith(": bad interpreter: No such file or directory"))}async function AD(e,t){let n=e.trim();if(!n||/[\r\n]/u.test(n))return!1;try{let r=await wD(sA.resolve(t,n),iA.O_RDONLY|iA.O_NONBLOCK),o;try{let s=Buffer.alloc(256),{bytesRead:a}=await r.read(s,0,s.length,0);if(o=s.toString("utf8",0,a),a===s.length&&!o.includes(`
|
|
38
|
+
`))return!1}finally{await r.close()}let i=o.match(/^#![ \t]*(\/[^ \t\n]+)(?:[ \t\n]|$)/u)?.[1];if(!i)return!1;try{return await yD(i),!1}catch(s){return At(s)}}catch{return!1}}async function aA(e,t,n,r){if(/[;&|<>()`$\r\n]/u.test(e))return!1;let o=kD(e);if(!o||!SD(o,t.exitCode,t.stderr))return!1;let i=process.platform==="win32",s=i?sA.join(n.SystemRoot??"C:\\Windows","System32","where.exe"):"/bin/sh",a=i?[o]:["-c",'command -v "$1"',"pm-linked-test-resolution",o];try{let{stdout:c}=await bD(s,a,{env:n,cwd:r,timeout:1e3,windowsHide:!0});return!i&&AD(c,r)}catch(c){let d=c;if(d.killed||d.signal)return!1;let u=d.code;return u===1||!i&&u===127}}import{spawn as ED}from"node:child_process";import{cp as lA,mkdir as Ym,mkdtemp as SA,open as Bm,readdir as Wm,rm as Wo,symlink as CD}from"node:fs/promises";import{tmpdir as AA}from"node:os";import me from"node:path";function cA(e,t,n,r,o){if((t.measure?.length??0)===0||o.some(s=>s.phase!=="setup"&&typeof s.stdout=="string"&&s.failure_category!=="spawn_error"&&s.failure_category!=="empty_run"&&qa(s.stdout,s.stderr??"")===null))return;let i=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[],"test",e,"--list","--json"];throw new l("--measure requires an executed linked test",m.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:L(i),suggested_retry_args:i}})}function Hm(e,t,n,r,o=!1){if((t.measure?.length??0)===0||t.run===!0)return;let i=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[]],s=[...i,...Wh(e,t),...t.list?["--list"]:[],...o?["--background"]:[]],a=t.acknowledgeLinkedTests?[...i,"test",e,"--help"]:s,c=[...i,"test",e,"--acknowledge-linked-tests",...t.author?["--author",t.author]:[]];throw new l("--measure requires --run",m.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...t.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${L([...i,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${L(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${L(s)}`]}:{},recovery:{missing:["--run"],suggested_retry:L(a),suggested_retry_args:a}})}var dA={taskkillTimeoutMs:null},Va=20*1024*1024,TD=3e3,RD=1e4,xD=5e3,mA=120,ID=new Set(["locks","extensions","runtime"]),OD=new Set(["history","index","search","extensions","locks","runtime"]),$D=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],LD=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,PD=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,ND=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Jm(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function FD(){return Jm("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",TD)}function MD(){return Jm("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",RD)}function DD(){return Jm("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",xD)}function UD(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function jD(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}}function Xm(e){let t=0,n=0,r=0,o=0;for(let i of e){let s=i.execution_context;!s||s.is_pm_command!==!0||(t+=1,s.is_pm_tracker_read_command===!0&&(n+=1),s.mismatch_detected===!0&&(r+=1),s.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function GD(e){let t=e??"project";if(!St.includes(t))throw new l(`Invalid scope "${e}"`,m.USAGE);return t}function Ja(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(In.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${In.join(", ")}`,m.USAGE)}function EA(e){return $n(e??"source","--workspace-context")}function CA(e,t,n){return n?t:$n(e.workspace_context_mode,"linked test")??t}function TA(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Ja(e.pm_context_mode)}function RA(e,t){return e==="auto"?t?"tracker":"schema":e}function qD(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function KD(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function zD(e,t){let n={};if(!e)return n;for(let r of e){let o=Ro(r,t);if(o)for(let[i,s]of Object.entries(o))n[i]=s}return n}function HD(e,t){if(!e)return[];let n=[];for(let r of e){let o=xo(r,t);o&&n.push(...o)}return[...new Set(n)]}function BD(e){let t=Ms(e);return Fs(t).some(n=>jd(n)!==null)}function xA(e){let t=Ms(e);return Fs(t).some(n=>{let r=jd(n);if(!r)return!1;let o=by(r);return o?ND.has(o.subcommand):!1})}function Ba(e){if(e)return hy.has(e.subcommand)?pr(e.args,gy)?.subcommand:e.subcommand}function uA(e,t){if(e==="npx"||e==="bunx")return Gd(t)?.command;if(e==="pnpm")return Ba(pr(t,uy));if(e==="npm")return Ba(pr(t,py));if(e==="yarn")return Ba(pr(t,fy));if(e==="bun")return Ba(pr(t,_y))}function Wa(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function IA(e){let t=e.split(" ").filter(s=>s.length>0),n=yy(t);if(n.length===0)return!1;let[r,...o]=n,i=ky.get(r);if(i){let s=o.findIndex(a=>i.test(a));return s>=0&&IA(o.slice(s+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?WD(o):VD(r,o)}function WD(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function VD(e,t){return e==="npx"||e==="bunx"?Wa(Gd(t)?.command):e==="pnpm"||e==="npm"?Wa((e==="pnpm"?wy(t):vy(t))?.command)||Wa(uA(e,t)):(e==="yarn"||e==="bun")&&Wa(uA(e,t))}function YD(e){if(Sy(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function JD(e){return e?e.map(XD):[]}function XD(e){let t=e.trim(),n=Z_(t)?rs(_e(e,"--add"),"--add"):{command:t},r=be(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);return vo(r),{command:r,path:be(n.path),scope:GD(n.scope),timeout_seconds:QD(be(n.timeout_seconds),be(n.timeout)),pm_context_mode:ea(be(n.pm_context_mode),"--add"),workspace_context_mode:$n(be(n.workspace_context_mode),"--add"),env_set:Ro(be(n.env_set),"--add"),env_clear:xo(be(n.env_clear),"--add"),shared_host_safe:Zs(be(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Ln(be(n.assert_stdout_contains)),assert_stdout_regex:Sr(be(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Ln(be(n.assert_stderr_contains)),assert_stderr_regex:Sr(be(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:ta(be(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:na(be(n.assert_json_field_equals),"--add"),assert_json_field_gte:ra(be(n.assert_json_field_gte),"--add"),note:be(n.note),phase:br(n.phase,"--add")}}function be(e){let t=e?.trim();return t&&t.length>0?t:void 0}function QD(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",m.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(ge(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",m.USAGE);return r}function ZD(e){return e?e.flatMap(t=>{let n=Io(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",m.USAGE);vo(o)}return n}):[]}function eU(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",m.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",m.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",m.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=_e(n,"--remove"),i=o.path!==void 0?"path":"command",s=o.path??o.command;if(!s?.trim())throw new l("--remove requires command=<value> and/or path=<value>",m.USAGE);return{kind:i,value:s.trim()}}return{kind:"either",value:n}}):[]}function tU(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",m.USAGE);return n}))]:[]}function nU(e){try{e.stdin?.end()}catch{}}function OA(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=mA?t:`${t.slice(0,mA-3)}...`}function $A(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Vm(e){try{process.stderr.write(`${e}
|
|
39
|
+
`)}catch{}}function rU(e,t){if(!$A(t))return null;let n=OA(e.command),r=Date.now();Vm(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let i=Date.now()-r;Vm(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${i} command="${n}"`)},MD());return o.unref?.(),o}function oU(e,t,n,r){if(!$A(r))return;let o=OA(e.command),i=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let d=t.exitCode===null?"null":String(t.exitCode),u=c.length>0?` ${c.join(" ")}`:"";Vm(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${d} elapsed_ms=${i}${u} command="${o}"`)}function iU(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function sU(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid,o={alive:()=>e.exitCode===null&&e.signalCode===null,kill:()=>{e.exitCode===null&&e.signalCode===null&&e.kill("SIGKILL")}};if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await $d(r,o,dA);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{$d(r,o,dA)},FD()),t.forceKillTimer.unref?.()}}function aU(e){return new Promise(t=>{let n=!1,r=null,o=(i,s=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),s&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(i))};e.on("exit",(i,s)=>{n||(r=setTimeout(()=>{o({code:i,signal:s},!0)},DD()),r.unref?.())}),e.on("close",(i,s)=>{o({code:i,signal:s})})})}function cU(e,t,n,r,o){return ED(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function pA(e){let t=await Bm(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,Va),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>Va}}finally{await t.close()}}async function dU(e,t,n,r,o,i=process.cwd()){let s=Date.now(),a=await SA(me.join(AA(),"pm-linked-test-output-"));try{let c=me.join(a,"stdout.log"),d=me.join(a,"stderr.log"),[u,p]=await Promise.all([Bm(c,"w"),Bm(d,"w")]),f;try{f=cU(e,n,u.fd,p.fd,i)}catch(H){throw await Promise.all([u.close(),p.close()]),H}let h=aU(f),_;f.on("error",H=>{_=H.message}),await Promise.all([u.close(),p.close()]),nU(f);let g={heartbeat:rU(r,o),forceKillTimer:null,timedOutTimer:null},y=sU(f,g),w=!1;g.timedOutTimer=setTimeout(()=>{w=!0,y()},t),g.timedOutTimer.unref?.();let{code:v,signal:k}=await h;iU(g);let[S,T]=await Promise.all([pA(c),pA(d)]),x=S.truncated||T.truncated,F=x?`
|
|
40
40
|
[pm linked-test output truncated at ${Va} bytes per stream; the child process continued to completion]
|
|
41
|
-
`:"";!_&&await
|
|
42
|
-
`);return AD.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>ED.test(n)&&CD.test(n))}function oU(e){return rU(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function cA(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 iU(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 sU(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 TA(e,t,n){return{env_set:FD(e,"--env-set"),env_clear:MD(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 oA(e,t,{recursive:!0,force:!0});return}await oA(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 dA(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 lA(e,t){if(!await W(e))return;let n=await Wm(e,{withFileTypes:!0});for(let r of n){if(kD.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 mA(e,t){let n=await oe(ce(e));if(n===null||await W(gd(e)))return;let r=await A(t);await Wo(gd(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()||SD.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 aU(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function cU(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 dU(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?ee(e,t):Object.is(e,t)}function lU(e,t,n){let r=[];r.push(...uA("stdout",t,e.assert_stdout_contains)),r.push(...pA("stdout",t,e.assert_stdout_regex)),r.push(...uA("stderr",n,e.assert_stderr_contains)),r.push(...pA("stderr",n,e.assert_stderr_regex)),r.push(...mU(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=cU(d);dU(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 uA(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function pA(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 mU(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 uU(e){let t=Ms(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Fs(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&AA(n))}function pU(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 fU(e,t,n){return e.some(r=>vA(r,t,n)==="snapshot")}async function _U(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 yD(t,r,process.platform==="win32"?"junction":"dir")}async function hU(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 gU(e,t,n){t&&(await dA(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await dA(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await lA(t.projectPmRoot,e.trackerProjectPmPath),await lA(t.globalPmRoot,e.trackerGlobalPmPath),await mA(t.projectPmRoot,e.trackerProjectPmPath),await mA(t.globalPmRoot,e.trackerGlobalPmPath)))}function yU(e,t,n){return e.some(r=>{let o=r.command??"",i=o.length>0&&SA(o),s=n?.autoPmContext===!0&&i?"auto":bA(r,t,n?.overrideLinkedPmContext===!0);return kA(s,i)==="tracker"})}async function wU(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 vU(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 bU(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Ja(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?DD(n):!1,o=r&&n?SA(n):!1,i=e.options?.autoPmContext===!0&&o,s=i?"auto":bA(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=kA(s,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await _U(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:vU({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 fA(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function kU(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 SU(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 AU(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 SU(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 EU(e){if(!e.linkedTest.command)return fA(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=GD(e.linkedTest.command);return t?fA(e.linkedTest,e.executionContext,t):null}function CU(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Ya(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?Ya(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 Ya(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 TU(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=ND({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 Ya(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 RU(e){let t=EU(e);if(t)return t;let n=AU(e);if(n)return n;let r=CU(e);if(r)return r;let o=TU(e);return o||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!LD(e.linkedTest)?Ya(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function xU(e){let t=sU(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return cA(n,e.runtimeDirectives),cA(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&iU(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 IU(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 _A(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 OU(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:aU(e.execution),failure_category:oU(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:nU(e.execution,e.timeoutMs)}}function $U(e){let t=BS(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&uU(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){let o=qa(e.execution.stdout,e.execution.stderr);if(o)return _A({...e,emptyRunSignal:o});if(n&&!t)return _A({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let r=lU(e.linkedTest,e.execution.stdout,e.execution.stderr);return r.length>0?kU(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${r.join("; ")}`,e.execution):IU(e.linkedTest,e.executionContext,e.execution,t)}async function PU(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await tU(t,n,xU(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?$U({...e,execution:r}):OU({...e,execution:r,timeoutMs:n})}async function Qm(e,t,n){let r=Ys(e);for(let y of r)to(y.command);let o=[],i=await gA(me.join(yA(),"pm-linked-test-")),s=pU(i),a=Ja(n?.pmContext),c=wA(n?.workspaceContext),d=n?.progress===!0?"always":"auto",u=TA(n?.envSet,n?.envClear,n?.sharedHostSafe),p=n?.sourceRoots,f=wy(),h=yU(r,a,n),_=fU(r,c,n?.overrideLinkedWorkspaceContext===!0),g=await yy(f);try{await hU(s,Lo,h),await Ym(s.workspaceIsolatedRoot,{recursive:!0}),await gU(s,p,h),_&&await QS(f,s.workspaceSnapshotRoot,p?.projectPmRoot,h);let y=await wU(s,p),w=To(),v=T=>vA(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=hw(T,L,k);if(H)return H;let B=await bU({linkedTest:T,layout:s,counts:y,sourceRoots:p,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:c,workspaceContextMode:L,currentSourceRef:g,sourceWorkspaceRoot:f});return RU({linkedTest:T,executionContext:B.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:B.linkedOverridePmContextMode,options:F})??await PU({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 LU(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 NU(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 FU(e,t){let n=[...e];for(let r of t)n.some(o=>no(o,r))||n.push(r);return n}function MU(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 DU(e,t,n,r){return MU(FU(e,t),n,r)}function UU(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 RA(e){if(UU(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 jU(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 NU({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=DU(_,s,a,c);if(hd(()=>xA(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:ee(_,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?Mg(u,f):[],storedRemoved:LU(u,f)}}function xA(e,t){let n=Ja(e.pmContext);wA(e.workspaceContext),TA(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);RA(e);let i=e.run===!0?_w(fw(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 GU(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 qU(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 KU(e){let t=$D(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:OD("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 zU(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=KU({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 Ga({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 hA(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=OS(t,i,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:$S(t,e.metricDiff)}}async function HU(e,t,n){if(e.acknowledgeLinkedTests===!0)return vy(t,n,C())}function BU(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:i,warnings:s,recording:a,measurementProjection:c,restoreScope:d}=e,u=VU(t,e.fullHistory),p=WU(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 WU(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:VS(e.itemId,r)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function VU(e,t){if(e.written!==void 0)return Nd({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function YU(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 Xa(e,t,n){let r=ww(t);if(r){vw(t),RA(t),Hm(e,t,n,E(process.cwd(),n.path));let B=await kw(e,{...r,author:t.author,message:t.message,force:t.force},n);return YU(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"),hA(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=[...qD(c),...HD(d)],f=await fr(p,R(t.author,s.author_default),C())??[],h=BD(u),_=WD(t.removeIndex),g=await jU({id:e,options:t,pmRoot:i,settings:s,typeToFolder:a.type_to_folder,adds:f,removes:h,removeIndexes:_}),y=hd(()=>xA(t,g.tests)),w=await HU(t,i,g.tests),v=t.run===!0?C():void 0,k=await GU({options:t,runOptions:y,pmRoot:i,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests});nA(e,t,n,i,k);let S=kr(k),T=t.run===!0&&t.failOnSkipped===!0&&k.some(B=>B.status==="skipped"),x=qU(t,k);w&&x.push(`linked_test_trust_acknowledged:${w.acknowledged}`);let F=await zU({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=hA(t,L,F?.entry);return BU({item:g,runResults:k,failureCategories:S,runSelection:y.runSelection,failOnSkippedTriggered:T,warnings:x,recording:F,measurementProjection:H,restoreScope:WS(n,i),ran:t.run===!0,fullHistory:t.fullHistory===!0})}var JU=(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},XU=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},IA=(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},QU=e=>e instanceof Error?e.message:String(e),ZU=()=>{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)}`},ej=e=>e.trim().replaceAll(/\s+/g," "),tj=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),nj=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),rj=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},oj=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Qa=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),OA=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),ij=e=>typeof e=="number"?e:void 0,sj=e=>{let t={assert_stdout_contains:Qa(e.assert_stdout_contains),assert_stdout_regex:Qa(e.assert_stdout_regex),assert_stderr_contains:Qa(e.assert_stderr_contains),assert_stderr_regex:Qa(e.assert_stderr_regex),assert_stdout_min_lines:ij(e.assert_stdout_min_lines),assert_json_field_equals:OA(e.assert_json_field_equals),assert_json_field_gte:OA(e.assert_json_field_gte)};return JSON.stringify(t)},aj=e=>{let t=eu(e.command);return t!==void 0?`command:${e.scope}:${ej(t)}`:`path:${e.scope}:${eu(e.path)??""}`},Zm=e=>{let t=tj(e.env_set),n=nj(e.env_clear),r=rj(e.pm_context_mode),o=oj(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",s=sj(e);return`${aj(e)}:${t}:${n}:${r}:${o}:${i}:${s}`},cj=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,dj=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}},lj=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Za=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
43
|
-
`)}catch{}},mj=async(e,t,n)=>{let r=[],o=0;for(let i of e){let s=await Xa(i.id,{run:!1},{...t,path:n});o+=s.tests.length,r.push({item:i,tests:s.tests})}return{itemTests:r,linkedTests:o}},uj=async e=>{let t=D(e.settings.schema),n=$(e.settings,I()),r=JU(e.options.status,t),o=IA(e.options.limit,"--limit"),i=IA(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}},$A=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)},PA=(e,t)=>t.length===0?Zm(e):`${Zm(e)}:setup[${t}]`,pj=e=>{let t=new Map;for(let{tests:n}of e){let r=$A(n);for(let o of n){if(Ie(o))continue;let i=PA(o,r);if(!t.has(i)){t.set(i,o.timeout_seconds);continue}t.set(i,cj(t.get(i),o.timeout_seconds))}}return t};function fj(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 _j=(e,t)=>{let n=[],r=[],o=Ys(e.tests),i=$A(o),s=To();return{plans:o.map(c=>{let d=Ie(c),u=d?Zm(c):PA(c,i),p=s.blocked(c);if(p)return{test:c,key:u,duplicate:!1,refusal:p};let f=fj(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}},hj=(e,t,n)=>{if(e.some(r=>r.phase==="setup"&&r.status!=="passed"))for(let r of t)n.seenTestKeys.delete(r)},gj=async(e,t)=>{let{plans:n,testsToRun:r,reservedKeys:o}=_j(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}):[];hj(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=dj(c),u=kr(c),p=await vj(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}}},yj=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),wj=e=>e?!0:void 0,vj=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=yj(t,r.options);await Ga({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:wj(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}:${QU(o)}`]}return[]},bj=()=>{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},kj=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:pj(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:R(e.options.author,e.settings.author_default),trackingRunId:ZU(),trackingAttempt:bj(),trackingResumedFrom:eu(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),Sj=(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}},Aj=async(e,t,n)=>{for(let[o,i]of e.entries()){Za(t.options,`item ${o+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let s=await gj(i,t);lj(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),Za(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},Ej=(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}`)},Cj=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}),Tj=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(" "),Rj=async(e,t)=>{let n=E(process.cwd(),t.path);await O(n);let r=await A(n),o=await uj({pmRoot:n,settings:r,options:e}),i=XU(e.timeout),s=C(),a=await mj(o.filteredItems,t,n);return Za(e,Tj({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:i,runStartedAt:s}},xj=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}},LA=async(e,t)=>{let n=await Rj(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=Sj(e,n.linkedTests,n.filteredItems),i=kj({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await Aj(n.itemTests,i,r),Ej(e,r);let s=xj({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Za(e,`end status=${s.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),Cj({ok:s.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:s.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};function NA(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 Ij(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 Oj(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=Kn({list:()=>Ag(t.global),show:()=>Eg(r,t.global),"show-status":()=>Cg(r,t.global),"list-fields":()=>xg(t.global),"show-field":()=>Ig(r,t.global),"remove-type":()=>vg(r,{author:o,force:i},t.global),"remove-field":()=>Rg(r,{author:o,force:i},t.global),"remove-status":()=>Sg(r,{author:o,force:i},t.global),"apply-preset":()=>Og(b(t.args,"typePreset")??b(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function $j(e,t){return[e.args[t],e.options[t]].find(n=>typeof n=="string")}function Pj(e){let{ctx:t,name:n,author:r,force:o}=e,i=t.args.alias??t.options.alias,s=Array.isArray(i)?i.map(d=>String(d)):e.aliases,a=t.args.commands??t.options.commands,c=t.args.requiredTypes??t.options.requiredTypes;return Tg(n,{type:b(t.args,"fieldType")??b(t.options,"fieldType"),commands:a===void 0?void 0:Se(a),description:b(t.args,"description")??b(t.options,"description"),cliFlag:$j(t,"cliFlag"),alias:s,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:c===void 0?void 0:Se(c),author:r,force:o},t.global)}function Lj(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.role??t.options.role;return kg(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 Nj(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return wg(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 Fj(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 gg(d,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function FA(e){let t=Ij(e);K_(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Wn.find(o=>o===t.subcommand);if(n)return hg(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=Oj(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return Fj(t);if(t.subcommand==="add-field")return Pj(t);if(t.subcommand==="add-status")return Lj(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?$g({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):Nj(t);throw Pe({command_path:"schema",token:t.subcommand,allowed:yg,exit_code:64})}function ec(e){return b(e.args,"target")??b(e.options,"target")}function Ee(e,t=e.options){return e.id??De(t,"id")}async function Mj(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 Dj(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 Uj(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 jj(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 Gj(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 qj(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),av(Ee(e),t,e.global)}function MA(e,t){return jg(NA(e.options,t,Ke),e.global)}function Kj(e){let t=Se(e.options.lookupPath);if(t&&t.length>0)return MA(e,t);let n=Ee(e);return e.options.discover===!0?Ud(n,Cs(e.options),e.global):Ug(n,po(Tn(e.options)),e.global)}function zj(e){return KS({subcommand:b(e.args,"subcommand")??b(e.options,"subcommand"),limit:Hh(e.args,e.options)},e.global)}function Hj(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 Bj(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 Rv(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 Wj(e){let t=e.options;return Py($y(t),e.global)}function Vj(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 Yj(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 dk({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:Jj(e),reorderTo:Vj(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&Td(e.args)&&(i.mutation_receipt=Ia(i,void 0)),t==="show"?i:Re(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function Jj(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function Xj(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:()=>Tk(),show:()=>Rk(r),lint:()=>xk(r),apply:()=>Ik(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:Ck,exit_code:64});return i()}async function Qj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return Re(await Gv(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Zj(e){let{changedFields:t,runnerOptions:n}=ve(e.args,e.options);return Re(await hk(Rs(n,!Td(e.args)),e.global),{changedFields:t})}async function eG(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 Jv(Ts(o),e.global),{changedFields:t})}async function tG(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 nG(e){let t={...e.args,...e.options};return Gg(De(t,"subcommand"),b(t,"id")??e.id,b(t,"target"),Jh(t),e.global)}function rG(e){return Ng(E(process.cwd(),e.global.path),{...e.args,...e.options})}var DA={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:uS,events:pS,merge:fS,workspace:_S,meet:Ma,event:Ma,remind:Ma,list:Mj,get:e=>{let t=Ee(e);return Wd(t,e.global,er("get",e.options,[t]))},search:Dj,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:Uj,copy:jj,focus:e=>Ul(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:Gj,"item-reopen":Xb,restore:tG,claim:Vb,release:Jb,"start-task":e=>Dn(e,"start_task"),"pause-task":e=>Dn(e,"pause_task"),"close-task":e=>Dn(e,"close_task"),close:Yb,comments:qj,notes:e=>yk(Ee(e),Tn(e.options),e.global),learnings:e=>jv(Ee(e),Tn(e.options),e.global),files:Kj,docs:e=>Dg(Ee(e),po(Tn(e.options)),e.global),test:e=>Xa(Ee(e),Tn(e.options),e.global),"test-all":e=>LA(e.options,e.global),telemetry:zj,validate:e=>Ds(e.options,e.global,{runUpdate:(t,n,r)=>ct(t,n,r)}),health:Hj,assurance:e=>by(e.args,e.options,e.global),contracts:e=>sl(e.options,e.global),config:Bj,activity:Wj,aggregate:e=>Bd(e.options,e.global),extension:e=>mr(ec(e),e.options,e.global),package:e=>mr(ec(e),e.options,e.global),install:e=>mr(ec(e),{...e.options,install:!0},e.global),upgrade:e=>Sy(ec(e),e.options,e.global),delete:e=>Dl(Ee(e),e.options,e.global),deps:e=>Fg(Ee(e),e.options,e.global),graph:nG,"files-discover":e=>Ud(Ee(e),e.options,e.global),"files-lookup":e=>MA(e,Se(e.options.paths)),history:e=>Ly(Ee(e),{...e.options,compact:e.options.full===!0||e.options.provenance===!0?!1:e.options.compact!==!1},e.global),"history-redact":e=>Uv(Ee(e),e.options,e.global),"history-repair":Lv,"history-compact":Nv,"history-attest":e=>Ay(e.options,e.global),"history-author-acknowledge":rG,plan:Yj,schema:FA,profile:Xj,stats:e=>Fm(e.global,hS(e.options)),append:Qj,"update-many":Zj,"close-many":eG,gc:e=>ky(e.global,e.options)};var oG=new Map;function tu(){oG.clear()}var jA=[{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:Ph().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"]}],UA=new Map;for(let e of jA){UA.set(e.id,e);for(let t of e.aliases)UA.set(t,e)}function nu(){return jA.map(e=>e.id)}var I8=[...gc],O8=[...yc],ru=new Set(un.filter(e=>e.hidden).map(e=>e.alias)),GA=$h("full").filter(e=>!e.includes(" ")&&!ru.has(e)),iG=M(li),sG=M(mi),aG=M(yi),cG=M(Si),qA=ao("restore",Ge("restore")),KA=ao("history-attest",Ge("history-attest")),dG=M(Ai),lG=M(sf),mG=M(af),uG=M(ki),pG=M(Ri),fG=M(Ei),_G=M(Ci),hG=M(gi),ou=[...new Set(Te.map(e=>e.canonical_argv[0]))],zA=[...new Set(Te.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],$8=new Set(di.filter(e=>e.disposition==="package_owned").map(e=>V(e.command))),HA=Te.filter(e=>e.canonical_argv[0]==="history"),gG=HA.map(e=>e.canonical_argv[1]).join(" ");var yG=HA.map(e=>({...e,flags:M(Ge(e.alias))})),wG=M(ui),vG=M(pi,!1),bG=M(Ti),kG=M(Hr),SG=M(Br),AG=M($i),EG=M(Ii),CG=M(vi),TG=M(Oi),RG=M(xi),xG=M(Pi),IG=M(wi),OG=M(bi),$G=M(_i),PG=M(Li),LG=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 NG=M(Ni),FG=`${NG} bash zsh fish`,su=nc(nu()),tc="init scaffold install uninstall list inventory explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",au=`${tc} upgrade`,MG=M(hi),DG=M(qr),UG=M(zr);var jG=M(Ge("close")),GG=M(Ge("close-task")),qG=M(Ge("release")),KG=M(Ge("claim"));var BA=Vn.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),cu=[...Yi].join("|"),du=[...Yi].map(e=>`${e}=*`).join("|"),lu=[...BA.split(" ").filter(e=>!Yi.has(e)),"-h","-V"].join("|");function nc(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 oq({...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=()=>QA(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=()=>ZA({...this.defaults,cwd:s,path:r},o);return n?ir(r,a):a()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-YZ2PUPGM.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-YZ2PUPGM.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,r)=>this.withItemTransactionContext(async o=>(await import("./item-transaction-YZ2PUPGM.js")).abandonItemTransaction({...r,...o,transactionId:n}));return{status:n=>this.withItemTransactionContext(async r=>(await import("./item-transaction-YZ2PUPGM.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-YH5R7YPW.js")).readItemRevision(t,{pmRoot:n}))}async withExpectedItemRevisions(t,n){let r=await import("./item-revision-YH5R7YPW.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 rv(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 Uh(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 U7(e={},t={}){return new z(t).context(e)}function j7(e={},t={}){return new z(t).list(e)}function G7(e={},t={}){return new z(t).listAllComplete(e)}function q7(e,t={},n={}){return new z(n).search(e,t)}function K7(e,t={},n={}){return new z(n).get(e,t)}function z7(e={},t={}){return new z(t).next(e)}function H7(e={},t={}){return new z(t).aggregate(e)}function B7(e,t={},n={}){return new z(n).comments(e,t)}function W7(e,t={},n={}){return new z(n).notes(e,t)}function V7(e,t={},n={}){return new z(n).learnings(e,t)}function Y7(e,t={},n={}){return new z(n).files(e,t)}function J7(e,t={},n={}){return new z(n).filesDiscover(e,t)}function X7(e,t={},n={}){return new z(n).docs(e,t)}function Q7(e,t={},n={}){return new z(n).deps(e,t)}function Z7(e,t={},n={},r={}){return new z(r).graph(e,t,n)}function eee(e,t,n={},r={}){return new z(r).append(e,t,n)}function tee(e={},t={}){return new z(t).create(e)}function nee(e,t={},n={}){return new z(n).update(e,t)}function ree(e,t,n={},r={}){return new z(r).reopen(e,t,n)}function oee(e,t,n={},r={}){return new z(r).close(e,t,n)}function iee(e,t={},n={}){return new z(n).claim(e,t)}function see(e={},t={}){return new z(t).claimNext(e)}function aee(e,t={},n={}){return new z(n).release(e,t)}function cee(e,t={},n={}){return new z(n).copy(e,t)}function dee(e,t={},n={}){return new z(n).delete(e,t)}function lee(e,t,n={},r={}){return new z(r).restore(e,t,n)}function mee(e,t={},n={}){return new z(n).focus(e,t)}var JA=v_(),oc=new XG;function Yo(e){try{return QG(e)}catch{return uu.resolve(e)}}function Pr(){let e=oc.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 oc.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===oc.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):td(()=>$r(e,null,()=>mu(t,n,a=>$r(e,a,()=>r(a))),!1))}function QA(e,t,n,r,o){let i=oc.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 rc(){nd(ep()),rd(tp()),od(np()),id(rp()),sd(op()),ad(ip()),cd(sp())}async function _u(e,t,n,r){return td(()=>t===void 0?JA.read(()=>mu(e,n,r)):JA.write(()=>tq(t,()=>mu(e,n,r))))}async function ZA(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 uee(e,t){return ZA({path:e},t)}function ZG(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:yh(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 rc(),Yd({pmRoot:r},()=>n(null));if(!await W(ce(r)))return rc(),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},nd(c.hooks),rd(c.commands),od(c.parsers),id(c.preflight),sd(c.services),ad(c.renderers),cd(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(s){rc(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",ZG(s))}try{return await Yd({pmRoot:r,packages:o?.packages},()=>n(o))}finally{rc(),i&&await Pc(i.loadResult,i.activationResult).catch(()=>{})}}function eE(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 eq(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,m.USAGE);let i=eE(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=Rh(Id(t,n),Th(o.registrations,a),a,Xw(a)),d=await Vi({command:a,args:Se(n.args??t.args),options:c,global:{...r,author:s},pm_root:o.pmRoot,sdk:Jw(o.pmRoot,z.forActiveExtensionHost({pmRoot:o.pmRoot,author:s}),s,a)});if(!d.handled){if(Object.hasOwn(d,"cause"))throw vs(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 tq(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function nq(e){let t=De(e,"action"),n=dr(t),r=Kn(iv,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 rq(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 oq(e){let t=nq(e),n=uo(t.args);b_(n);let r=Vh(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}=Qh(t.args),c=async d=>{if(s===void 0)return XA(t.action,a,n,d);let{dispatchWithExpectedItemRevisions:u}=await import("./item-revision-YH5R7YPW.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:rq(e,n,o,i),...n.outputFormat===void 0?{}:{outputArgs:["--output-format",n.outputFormat]}},run:()=>XA(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 QA(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 XA(e,t,n,r){let o=Kn(DA,e),i=Rd(t,e,{nativeAction:o!==void 0});if(e==="create"||e==="update"){let{assertNativeMutationOptions:u}=await import("./mutation-admission-3SECKVKY.js");await u(e,t,i,n.path,Bh[e])}if(e==="update-many"){let{assertNativeUpdateManyOptions:u}=await import("./mutation-admission-3SECKVKY.js");await u(t,i,n.path)}let s=o?void 0:eE(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 eq(e,t,i,n,r);if(e==="history-attest")return d;{let u=$_(a,i,d);return await Vw(E(process.cwd(),n.path),u),u}}var iq={closeManyOptionsFromFlat:Ts,extensionOptionsFromArgs:Id,globalOptions:uo,mutationListOptions:Yh,normalizeActionName:dr,normalizeCommandPath:xd,normalizeMcpUpdateOptions:Xh,normalizeMcpOptionsArrays:Wh,optionsWithAuthor:Rd,readRequiredString:De,readScalarString:Kh,readScalarStringAllowBlank:zh,readStringArray:Se,updateManyOptionsFromFlat:Rs,withAddNoteOption:po,withFilesDiscoveryOptions:Cs,withMutationCompaction:ve};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=iq);export{Vd as a,lC as b,TC as c,lw as d,AK as e,mw as f,EK as g,CK as h,kw as i,ZC as j,z as k,U7 as l,j7 as m,G7 as n,q7 as o,K7 as p,z7 as q,H7 as r,B7 as s,W7 as t,V7 as u,Y7 as v,J7 as w,X7 as x,Q7 as y,Z7 as z,eee as A,tee as B,nee as C,ree as D,oee as E,iee as F,see as G,aee as H,cee as I,dee as J,lee as K,mee as L,ZA as M,uee as N,oq as O};
|
|
44
|
-
//# sourceMappingURL=chunk-
|
|
41
|
+
`:"";!_&&await aA(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 P={stdout:`${S.text}${F}`,stderr:T.text,exitCode:v,signal:k,timedOut:w,maxBufferExceeded:!1,outputTruncated:x,spawnError:_};return oU(r,P,s,o),P}finally{await Wo(a,{recursive:!0,force:!0})}}function lU(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Va} 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 mU(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
42
|
+
`);return $D.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>LD.test(n)&&PD.test(n))}function uU(e){return mU(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function fA(e,t){for(let[n,r]of Object.entries(t.env_set))On.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)On.has(n.toUpperCase())||delete e[n]}function pU(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 fU(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 LA(e,t,n){return{env_set:zD(e,"--env-set"),env_clear:HD(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 lA(e,t,{recursive:!0,force:!0});return}await lA(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 _A(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 hA(e,t){if(!await W(e))return;let n=await Wm(e,{withFileTypes:!0});for(let r of n){if(ID.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 gA(e,t){let n=await oe(ce(e));if(n===null||await W(gd(e)))return;let r=await A(t);await Wo(gd(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()||OD.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 _U(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function hU(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 gU(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?ee(e,t):Object.is(e,t)}function yU(e,t,n){let r=[];r.push(...yA("stdout",t,e.assert_stdout_contains)),r.push(...wA("stdout",t,e.assert_stdout_regex)),r.push(...yA("stderr",n,e.assert_stderr_contains)),r.push(...wA("stderr",n,e.assert_stderr_regex)),r.push(...wU(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=hU(d);gU(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 yA(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function wA(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 wU(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 vU(e){let t=Ms(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Fs(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&IA(n))}function bU(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 kU(e,t,n){return e.some(r=>CA(r,t,n)==="snapshot")}async function SU(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 CD(t,r,process.platform==="win32"?"junction":"dir")}async function AU(e,t=Po,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 EU(e,t,n){t&&(await _A(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await _A(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await hA(t.projectPmRoot,e.trackerProjectPmPath),await hA(t.globalPmRoot,e.trackerGlobalPmPath),await gA(t.projectPmRoot,e.trackerProjectPmPath),await gA(t.globalPmRoot,e.trackerGlobalPmPath)))}function CU(e,t,n){return e.some(r=>{let o=r.command??"",i=o.length>0&&xA(o),s=n?.autoPmContext===!0&&i?"auto":TA(r,t,n?.overrideLinkedPmContext===!0);return RA(s,i)==="tracker"})}async function TU(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 RU(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 xU(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Ja(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?BD(n):!1,o=r&&n?xA(n):!1,i=e.options?.autoPmContext===!0&&o,s=i?"auto":TA(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=RA(s,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await SU(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:RU({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 vA(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function IU(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 OU(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 $U(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 OU(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 LU(e){if(!e.linkedTest.command)return vA(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=YD(e.linkedTest.command);return t?vA(e.linkedTest,e.executionContext,t):null}function PU(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?Ya(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?Ya(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 Ya(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 NU(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=KD({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 Ya(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 FU(e){let t=LU(e);if(t)return t;let n=$U(e);if(n)return n;let r=PU(e);if(r)return r;let o=NU(e);return o||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!qD(e.linkedTest)?Ya(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function MU(e){let t=fU(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return fA(n,e.runtimeDirectives),fA(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&pU(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 DU(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 bA(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 UU(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:_U(e.execution),failure_category:uU(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:lU(e.execution,e.timeoutMs)}}function jU(e){let t=QS(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&vU(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){let o=qa(e.execution.stdout,e.execution.stderr);if(o)return bA({...e,emptyRunSignal:o});if(n&&!t)return bA({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let r=yU(e.linkedTest,e.execution.stdout,e.execution.stderr);return r.length>0?IU(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${r.join("; ")}`,e.execution):DU(e.linkedTest,e.executionContext,e.execution,t)}async function GU(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await dU(t,n,MU(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?jU({...e,execution:r}):UU({...e,execution:r,timeoutMs:n})}async function Qm(e,t,n){let r=Ys(e);for(let y of r)to(y.command);let o=[],i=await SA(me.join(AA(),"pm-linked-test-")),s=bU(i),a=Ja(n?.pmContext),c=EA(n?.workspaceContext),d=n?.progress===!0?"always":"auto",u=LA(n?.envSet,n?.envClear,n?.sharedHostSafe),p=n?.sourceRoots,f=Ey(),h=CU(r,a,n),_=kU(r,c,n?.overrideLinkedWorkspaceContext===!0),g=await Ay(f);try{await AU(s,Po,h),await Ym(s.workspaceIsolatedRoot,{recursive:!0}),await EU(s,p,h),_&&await oA(f,s.workspaceSnapshotRoot,p?.projectPmRoot,h);let y=await TU(s,p),w=To(),v=T=>CA(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),P=v(T),H=kw(T,P,k);if(H)return H;let B=await xU({linkedTest:T,layout:s,counts:y,sourceRoots:p,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:c,workspaceContextMode:P,currentSourceRef:g,sourceWorkspaceRoot:f});return FU({linkedTest:T,executionContext:B.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:B.linkedOverridePmContextMode,options:F})??await GU({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 qU(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 KU(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 zU(e,t){let n=[...e];for(let r of t)n.some(o=>no(o,r))||n.push(r);return n}function HU(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 BU(e,t,n,r){return HU(zU(e,t),n,r)}function WU(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 PA(e){if(WU(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 VU(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 KU({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=BU(_,s,a,c);if(hd(()=>NA(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:ee(_,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?Kg(u,f):[],storedRemoved:qU(u,f)}}function NA(e,t){let n=Ja(e.pmContext);EA(e.workspaceContext),LA(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);PA(e);let i=e.run===!0?bw(vw(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 YU(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 JU(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 XU(e){let t=jD(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:UD("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 QU(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=XU({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 Ga({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(Cn(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 kA(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=MS(t,i,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:DS(t,e.metricDiff)}}async function ZU(e,t,n){if(e.acknowledgeLinkedTests===!0)return Cy(t,n,C())}function ej(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:i,warnings:s,recording:a,measurementProjection:c,restoreScope:d}=e,u=nj(t,e.fullHistory),p=tj(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 tj(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:eA(e.itemId,r)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function nj(e,t){if(e.written!==void 0)return Nd({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function rj(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 Xa(e,t,n){let r=Ew(t);if(r){Cw(t),PA(t),Hm(e,t,n,E(process.cwd(),n.path));let B=await Rw(e,{...r,author:t.author,message:t.message,force:t.force},n);return rj(B,t.fullHistory===!0)}let o=Yt(),i=E(process.cwd(),n.path);await O(i);let s=await A(i);Hm(e,t,n,i),Ko(t.measure,"validation"),kA(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=[...JD(c),...ZD(d)],f=await fr(p,R(t.author,s.author_default),C())??[],h=eU(u),_=tU(t.removeIndex),g=await VU({id:e,options:t,pmRoot:i,settings:s,typeToFolder:a.type_to_folder,adds:f,removes:h,removeIndexes:_}),y=hd(()=>NA(t,g.tests)),w=await ZU(t,i,g.tests),v=t.run===!0?C():void 0,k=await YU({options:t,runOptions:y,pmRoot:i,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests});cA(e,t,n,i,k);let S=kr(k),T=t.run===!0&&t.failOnSkipped===!0&&k.some(B=>B.status==="skipped"),x=JU(t,k);w&&x.push(`linked_test_trust_acknowledged:${w.acknowledged}`);let F=await QU({options:t,pmRoot:i,settings:s,itemId:g.itemId,runStartedAt:v,runResults:k,failOnSkippedTriggered:T,warnings:x}),P=F?.receipt.recorded?jm([...g.testRuns,F.entry]):g.testRuns,H=kA(t,P,F?.entry);return ej({item:g,runResults:k,failureCategories:S,runSelection:y.runSelection,failOnSkippedTriggered:T,warnings:x,recording:F,measurementProjection:H,restoreScope:ZS(n,i),ran:t.run===!0,fullHistory:t.fullHistory===!0})}var oj=(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},ij=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},FA=(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},sj=e=>e instanceof Error?e.message:String(e),aj=()=>{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)}`},cj=e=>e.trim().replaceAll(/\s+/g," "),dj=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),lj=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),mj=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},uj=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Qa=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),MA=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),pj=e=>typeof e=="number"?e:void 0,fj=e=>{let t={assert_stdout_contains:Qa(e.assert_stdout_contains),assert_stdout_regex:Qa(e.assert_stdout_regex),assert_stderr_contains:Qa(e.assert_stderr_contains),assert_stderr_regex:Qa(e.assert_stderr_regex),assert_stdout_min_lines:pj(e.assert_stdout_min_lines),assert_json_field_equals:MA(e.assert_json_field_equals),assert_json_field_gte:MA(e.assert_json_field_gte)};return JSON.stringify(t)},_j=e=>{let t=eu(e.command);return t!==void 0?`command:${e.scope}:${cj(t)}`:`path:${e.scope}:${eu(e.path)??""}`},Zm=e=>{let t=dj(e.env_set),n=lj(e.env_clear),r=mj(e.pm_context_mode),o=uj(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",s=fj(e);return`${_j(e)}:${t}:${n}:${r}:${o}:${i}:${s}`},hj=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,gj=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}},yj=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Za=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
43
|
+
`)}catch{}},wj=async(e,t,n)=>{let r=[],o=0;for(let i of e){let s=await Xa(i.id,{run:!1},{...t,path:n});o+=s.tests.length,r.push({item:i,tests:s.tests})}return{itemTests:r,linkedTests:o}},vj=async e=>{let t=D(e.settings.schema),n=$(e.settings,I()),r=oj(e.options.status,t),o=FA(e.options.limit,"--limit"),i=FA(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}},DA=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)},UA=(e,t)=>t.length===0?Zm(e):`${Zm(e)}:setup[${t}]`,bj=e=>{let t=new Map;for(let{tests:n}of e){let r=DA(n);for(let o of n){if(Ie(o))continue;let i=UA(o,r);if(!t.has(i)){t.set(i,o.timeout_seconds);continue}t.set(i,hj(t.get(i),o.timeout_seconds))}}return t};function kj(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 Sj=(e,t)=>{let n=[],r=[],o=Ys(e.tests),i=DA(o),s=To();return{plans:o.map(c=>{let d=Ie(c),u=d?Zm(c):UA(c,i),p=s.blocked(c);if(p)return{test:c,key:u,duplicate:!1,refusal:p};let f=kj(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}},Aj=(e,t,n)=>{if(e.some(r=>r.phase==="setup"&&r.status!=="passed"))for(let r of t)n.seenTestKeys.delete(r)},Ej=async(e,t)=>{let{plans:n,testsToRun:r,reservedKeys:o}=Sj(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}):[];Aj(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=gj(c),u=kr(c),p=await Rj(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}}},Cj=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),Tj=e=>e?!0:void 0,Rj=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=Cj(t,r.options);await Ga({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:Tj(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 Cn(o)?(r.revisionConflicts.push(o),[]):[`test_result_tracking_failed:${e.item.id}:${sj(o)}`]}return[]},xj=()=>{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},Ij=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:bj(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:R(e.options.author,e.settings.author_default),trackingRunId:aj(),trackingAttempt:xj(),trackingResumedFrom:eu(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),Oj=(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}},$j=async(e,t,n)=>{for(let[o,i]of e.entries()){Za(t.options,`item ${o+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let s=await Ej(i,t);yj(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),Za(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},Lj=(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}`)},Pj=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}),Nj=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(" "),Fj=async(e,t)=>{let n=E(process.cwd(),t.path);await O(n);let r=await A(n),o=await vj({pmRoot:n,settings:r,options:e}),i=ij(e.timeout),s=C(),a=await wj(o.filteredItems,t,n);return Za(e,Nj({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:i,runStartedAt:s}},Mj=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}},jA=async(e,t)=>{let n=await Fj(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=Oj(e,n.linkedTests,n.filteredItems),i=Ij({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await $j(n.itemTests,i,r),Lj(e,r);let s=Mj({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Za(e,`end status=${s.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),Pj({ok:s.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:s.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};function GA(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 Dj(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 Uj(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=Kn({list:()=>Ig(t.global),show:()=>Og(r,t.global),"show-status":()=>$g(r,t.global),"list-fields":()=>Ng(t.global),"show-field":()=>Fg(r,t.global),"remove-type":()=>Cg(r,{author:o,force:i},t.global),"remove-field":()=>Pg(r,{author:o,force:i},t.global),"remove-status":()=>xg(r,{author:o,force:i},t.global),"apply-preset":()=>Mg(b(t.args,"typePreset")??b(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function jj(e,t){return[e.args[t],e.options[t]].find(n=>typeof n=="string")}function Gj(e){let{ctx:t,name:n,author:r,force:o}=e,i=t.args.alias??t.options.alias,s=Array.isArray(i)?i.map(d=>String(d)):e.aliases,a=t.args.commands??t.options.commands,c=t.args.requiredTypes??t.options.requiredTypes;return Lg(n,{type:b(t.args,"fieldType")??b(t.options,"fieldType"),commands:a===void 0?void 0:Se(a),description:b(t.args,"description")??b(t.options,"description"),cliFlag:jj(t,"cliFlag"),alias:s,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:c===void 0?void 0:Se(c),author:r,force:o},t.global)}function qj(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.role??t.options.role;return Rg(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 Kj(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return Eg(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 zj(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 Sg(d,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function qA(e){let t=Dj(e);V_(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=Wn.find(o=>o===t.subcommand);if(n)return kg(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=Uj(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return zj(t);if(t.subcommand==="add-field")return Gj(t);if(t.subcommand==="add-status")return qj(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Dg({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):Kj(t);throw Le({command_path:"schema",token:t.subcommand,allowed:Ag,exit_code:64})}function ec(e){return b(e.args,"target")??b(e.options,"target")}function Ee(e,t=e.options){return e.id??De(t,"id")}async function Hj(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 Pt(b(e.args,"status")??b(t,"status"),t,e.global),t)}async function Bj(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 Wj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return Re(await on(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Vj(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 Yj(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 Jj(e){let t=Rn(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),pv(Ee(e),t,e.global)}function KA(e,t){return Bg(GA(e.options,t,Ke),e.global)}function Xj(e){let t=Se(e.options.lookupPath);if(t&&t.length>0)return KA(e,t);let n=Ee(e);return e.options.discover===!0?Ud(n,Cs(e.options),e.global):Hg(n,po(Rn(e.options)),e.global)}function Qj(e){return YS({subcommand:b(e.args,"subcommand")??b(e.options,"subcommand"),limit:Jh(e.args,e.options)},e.global)}function Zj(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 eG(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 Pv(b(e.args,"scope")??b(e.options,"scope")??nh(o),t,o,r,e.global,b(e.options,"policy")===void 0?n:void 0)}function tG(e){let t=e.options;return Uy(Dy(t),e.global)}function nG(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 rG(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 _k({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:oG(e),reorderTo:nG(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&Td(e.args)&&(i.mutation_receipt=Ia(i,void 0)),t==="show"?i:Re(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function oG(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function iG(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:()=>Lk(),show:()=>Pk(r),lint:()=>Nk(r),apply:()=>Fk(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 Le({command_path:"profile",token:t,allowed:$k,exit_code:64});return i()}async function sG(e){let{changedFields:t,idOnly:n,runnerOptions:r}=ve(e.args,e.options);return Re(await Wv(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function aG(e){let{changedFields:t,runnerOptions:n}=ve(e.args,e.options);return Re(await kk(Rs(n,!Td(e.args)),e.global),{changedFields:t})}async function cG(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 nb(Ts(o),e.global),{changedFields:t})}async function dG(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 lG(e){let t={...e.args,...e.options};return Wg(De(t,"subcommand"),b(t,"id")??e.id,b(t,"target"),tg(t),e.global)}function mG(e){return Gg(E(process.cwd(),e.global.path),{...e.args,...e.options})}var zA={init:e=>Po(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:yS,events:wS,merge:vS,workspace:bS,meet:Ma,event:Ma,remind:Ma,list:Hj,get:e=>{let t=Ee(e);return Wd(t,e.global,er("get",e.options,[t]))},search:Bj,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:Wj,copy:Vj,focus:e=>Ul(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:Yj,"item-reopen":rk,restore:dG,claim:ek,release:nk,"start-task":e=>Dn(e,"start_task"),"pause-task":e=>Dn(e,"pause_task"),"close-task":e=>Dn(e,"close_task"),close:tk,comments:Jj,notes:e=>Ak(Ee(e),Rn(e.options),e.global),learnings:e=>Bv(Ee(e),Rn(e.options),e.global),files:Xj,docs:e=>zg(Ee(e),po(Rn(e.options)),e.global),test:e=>Xa(Ee(e),Rn(e.options),e.global),"test-all":e=>jA(e.options,e.global),telemetry:Qj,validate:e=>Ds(e.options,e.global,{runUpdate:(t,n,r)=>ct(t,n,r)}),health:Zj,assurance:e=>Ty(e.args,e.options,e.global),contracts:e=>sl(e.options,e.global),config:eG,activity:tG,aggregate:e=>Bd(e.options,e.global),extension:e=>mr(ec(e),e.options,e.global),package:e=>mr(ec(e),e.options,e.global),install:e=>mr(ec(e),{...e.options,install:!0},e.global),upgrade:e=>xy(ec(e),e.options,e.global),delete:e=>Dl(Ee(e),e.options,e.global),deps:e=>qg(Ee(e),e.options,e.global),graph:lG,"files-discover":e=>Ud(Ee(e),e.options,e.global),"files-lookup":e=>KA(e,Se(e.options.paths)),history:e=>jy(Ee(e),{...e.options,compact:e.options.full===!0||e.options.provenance===!0?!1:e.options.compact!==!1},e.global),"history-redact":e=>Hv(Ee(e),e.options,e.global),"history-repair":jv,"history-compact":Gv,"history-attest":e=>Iy(e.options,e.global),"history-author-acknowledge":mG,plan:rG,schema:qA,profile:iG,stats:e=>Fm(e.global,kS(e.options)),append:sG,"update-many":aG,"close-many":cG,gc:e=>Ry(e.global,e.options)};var uG=new Map;function tu(){uG.clear()}var BA=[{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:Dh().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"]}],HA=new Map;for(let e of BA){HA.set(e.id,e);for(let t of e.aliases)HA.set(t,e)}function nu(){return BA.map(e=>e.id)}var U8=[...gc],j8=[...yc],ru=new Set(pn.filter(e=>e.hidden).map(e=>e.alias)),WA=Mh("full").filter(e=>!e.includes(" ")&&!ru.has(e)),pG=M(li),fG=M(mi),_G=M(yi),hG=M(Si),VA=ao("restore",Ge("restore")),YA=ao("history-attest",Ge("history-attest")),gG=M(Ai),yG=M(mf),wG=M(uf),vG=M(ki),bG=M(Ri),kG=M(Ei),SG=M(Ci),AG=M(gi),ou=[...new Set(Te.map(e=>e.canonical_argv[0]))],JA=[...new Set(Te.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],G8=new Set(di.filter(e=>e.disposition==="package_owned").map(e=>V(e.command))),XA=Te.filter(e=>e.canonical_argv[0]==="history"),EG=XA.map(e=>e.canonical_argv[1]).join(" ");var CG=XA.map(e=>({...e,flags:M(Ge(e.alias))})),TG=M(ui),RG=M(pi,!1),xG=M(Ti),IG=M(Hr),OG=M(Br),$G=M($i),LG=M(Ii),PG=M(vi),NG=M(Oi),FG=M(xi),MG=M(Li),DG=M(wi),UG=M(bi),jG=M(_i),GG=M(Pi),qG=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 KG=M(Ni),zG=`${KG} bash zsh fish`,su=nc(nu()),tc="init scaffold install uninstall list inventory explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",au=`${tc} upgrade`,HG=M(hi),BG=M(qr),WG=M(zr);var VG=M(Ge("close")),YG=M(Ge("close-task")),JG=M(Ge("release")),XG=M(Ge("claim"));var QA=Vn.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),cu=[...Yi].join("|"),du=[...Yi].map(e=>`${e}=*`).join("|"),lu=[...QA.split(" ").filter(e=>!Yi.has(e)),"-h","-V"].join("|");function nc(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 uq({...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=()=>oE(r,uo({path:r}),void 0,c,o);return n?ir(r,d):d()}let i=Lr()!==void 0;i&&pu(this.defaults.cwd);let s=i?void 0:this.defaults.cwd,a=()=>iE({...this.defaults,cwd:s,path:r},o);return n?ir(r,a):a()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-2K4SFLJ7.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-2K4SFLJ7.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,r)=>this.withItemTransactionContext(async o=>(await import("./item-transaction-2K4SFLJ7.js")).abandonItemTransaction({...r,...o,transactionId:n}));return{status:n=>this.withItemTransactionContext(async r=>(await import("./item-transaction-2K4SFLJ7.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-723XCQPS.js")).readItemRevision(t,{pmRoot:n}))}async withExpectedItemRevisions(t,n){let r=await import("./item-revision-723XCQPS.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 dv(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Pd(await this.list(Ld(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 zh(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 V7(e={},t={}){return new z(t).context(e)}function Y7(e={},t={}){return new z(t).list(e)}function J7(e={},t={}){return new z(t).listAllComplete(e)}function X7(e,t={},n={}){return new z(n).search(e,t)}function Q7(e,t={},n={}){return new z(n).get(e,t)}function Z7(e={},t={}){return new z(t).next(e)}function eee(e={},t={}){return new z(t).aggregate(e)}function tee(e,t={},n={}){return new z(n).comments(e,t)}function nee(e,t={},n={}){return new z(n).notes(e,t)}function ree(e,t={},n={}){return new z(n).learnings(e,t)}function oee(e,t={},n={}){return new z(n).files(e,t)}function iee(e,t={},n={}){return new z(n).filesDiscover(e,t)}function see(e,t={},n={}){return new z(n).docs(e,t)}function aee(e,t={},n={}){return new z(n).deps(e,t)}function cee(e,t={},n={},r={}){return new z(r).graph(e,t,n)}function dee(e,t,n={},r={}){return new z(r).append(e,t,n)}function lee(e={},t={}){return new z(t).create(e)}function mee(e,t={},n={}){return new z(n).update(e,t)}function uee(e,t,n={},r={}){return new z(r).reopen(e,t,n)}function pee(e,t,n={},r={}){return new z(r).close(e,t,n)}function fee(e,t={},n={}){return new z(n).claim(e,t)}function _ee(e={},t={}){return new z(t).claimNext(e)}function hee(e,t={},n={}){return new z(n).release(e,t)}function gee(e,t={},n={}){return new z(n).copy(e,t)}function yee(e,t={},n={}){return new z(n).delete(e,t)}function wee(e,t,n={},r={}){return new z(r).restore(e,t,n)}function vee(e,t={},n={}){return new z(n).focus(e,t)}var nE=E_(),oc=new iq;function Yo(e){try{return sq(e)}catch{return uu.resolve(e)}}function Lr(){let e=oc.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:Lr(),ready:r};try{return await oc.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=Lr();if(o===void 0)return;let i=o===oc.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):td(()=>$r(e,null,()=>mu(t,n,a=>$r(e,a,()=>r(a))),!1))}function oE(e,t,n,r,o){let i=oc.getStore();if(i===void 0)return o(null);let s=Lr(),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 rc(){nd(ep()),rd(tp()),od(np()),id(rp()),sd(op()),ad(ip()),cd(sp())}async function _u(e,t,n,r){return td(()=>t===void 0?nE.read(()=>mu(e,n,r)):nE.write(()=>dq(t,()=>mu(e,n,r))))}async function iE(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});Lr()!==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 bee(e,t){return iE({path:e},t)}function aq(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:Sh(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 rc(),Yd({pmRoot:r},()=>n(null));if(!await W(ce(r)))return rc(),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},nd(c.hooks),rd(c.commands),od(c.parsers),id(c.preflight),sd(c.services),ad(c.renderers),cd(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(s){rc(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",aq(s))}try{return await Yd({pmRoot:r,packages:o?.packages},()=>n(o))}finally{rc(),i&&await Lc(i.loadResult,i.activationResult).catch(()=>{})}}function sE(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 cq(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,m.USAGE);let i=sE(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=Lh(Id(t,n),$h(o.registrations,a),a,rv(a)),d=await Vi({command:a,args:Se(n.args??t.args),options:c,global:{...r,author:s},pm_root:o.pmRoot,sdk:nv(o.pmRoot,z.forActiveExtensionHost({pmRoot:o.pmRoot,author:s}),s,a)});if(!d.handled){if(Object.hasOwn(d,"cause"))throw vs(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 dq(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function lq(e){let t=De(e,"action"),n=dr(t),r=Kn(mv,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 mq(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 uq(e){let t=lq(e),n=uo(t.args);C_(n);let r=Zh(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}=rg(t.args),c=async d=>{if(s===void 0)return rE(t.action,a,n,d);let{dispatchWithExpectedItemRevisions:u}=await import("./item-revision-723XCQPS.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:mq(e,n,o,i),...n.outputFormat===void 0?{}:{outputArgs:["--output-format",n.outputFormat]}},run:()=>rE(t.action,a,n,d)})};try{if(t.action==="history-attest")return await c(null);let d=E(i,n.path);if(Lr()!==void 0&&pu(o),e[Vo]===!0)return await oE(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 rE(e,t,n,r){let o=Kn(zA,e),i=Rd(t,e,{nativeAction:o!==void 0});if(e==="create"||e==="update"){let{assertNativeMutationOptions:u}=await import("./mutation-admission-SDWQVVHN.js");await u(e,t,i,n.path,Xh[e])}if(e==="update-many"){let{assertNativeUpdateManyOptions:u}=await import("./mutation-admission-SDWQVVHN.js");await u(t,i,n.path)}let s=o?void 0:sE(e,r),a=s===void 0?e:`extension:${s}`;O_(a,i),L_(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 cq(e,t,i,n,r);if(e==="history-attest")return d;{let u=M_(a,i,d);return await ev(E(process.cwd(),n.path),u),u}}var pq={closeManyOptionsFromFlat:Ts,extensionOptionsFromArgs:Id,globalOptions:uo,mutationListOptions:eg,normalizeActionName:dr,normalizeCommandPath:xd,normalizeMcpUpdateOptions:ng,normalizeMcpOptionsArrays:Qh,optionsWithAuthor:Rd,readRequiredString:De,readScalarString:Vh,readScalarStringAllowBlank:Yh,readStringArray:Se,updateManyOptionsFromFlat:Rs,withAddNoteOption:po,withFilesDiscoveryOptions:Cs,withMutationCompaction:ve};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=pq);export{Vd as a,hC as b,LC as c,hw as d,$K as e,gw as f,LK as g,PK as h,Rw as i,iT as j,z as k,V7 as l,Y7 as m,J7 as n,X7 as o,Q7 as p,Z7 as q,eee as r,tee as s,nee as t,ree as u,oee as v,iee as w,see as x,aee as y,cee as z,dee as A,lee as B,mee as C,uee as D,pee as E,fee as F,_ee as G,hee as H,gee as I,yee as J,wee as K,vee as L,iE as M,bee as N,uq as O};
|
|
44
|
+
//# sourceMappingURL=chunk-PT7RT3T6.js.map
|