@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,23 +1,23 @@
|
|
|
1
|
-
import{A as mn,B as ie,D as Fi,G as Di,H as vf,Ha as Lf,Ia as Mf,J as oa,Ja as ir,K as kf,Ka as ua,M as bf,Na as Ff,Oc as t_,Rc as n_,U as Sf,_a as sr,bb as gn,eb as yn,l as gf,lb as ji,o as yf,oa as $f,p as tr,pa as Nf,pb as Qf,qb as Zf,s as wf,wb as e_,y as nr,yb as ha,z as rr}from"./chunk-KCR4NF2A.js";import{a as Xo,d as Jo,e as Wp,f as Qo,g as Bp}from"./chunk-X5D5YUHR.js";import{a as Df}from"./chunk-4QA5O64H.js";import{J as hf,a as Oi,b as Jn,c as $i,d as ke,e as Ni,f as mf,g as pf,h as Li,i as Qn,j as ff,k as _f,l as ra,m as ia,n as Zn,r as er,t as Mi,u as X,y as sa}from"./chunk-VI3A7UZ2.js";import{C as qf,E as Gi,F as Gf,G as Kf,H as ma,I as pa,N as zf,O as Wf,P as Bf,Q as Hf,R as Vf,S as fa,T as _a,U as Yf,V as Xf,W as Jf,Z as r_,a as Tf,aa as i_,da as s_,ia as o_,ja as a_,m as hn,q as If,r as Of,t as Pi,u as Ui,v as Pf,w as Uf,x as jf,z as qi}from"./chunk-WNB62BGK.js";import{Aa as Rf,j as Hp,oa as ca,pa as Cf,qa as da,ra as la,u as xf,va as Ef}from"./chunk-JFPCL45G.js";import{a as pm,l as aa}from"./chunk-JQHLOSSS.js";import{i as kt,k as pn,l as fn,m as _n}from"./chunk-3TK2YOVB.js";import{c as Af}from"./chunk-OGVSGXQX.js";import{N as rf,O as Ti,P as sf,Q as ta,S as of,T as af,V as cf,W as df,X as Ii,Y as lf,a as Vp,b as Yp,c as Xp,ca as na,d as Jp,f as Qp,ga as uf,j as Zo,k as Zp,l as ef,m as ea,n as tf,o as nf}from"./chunk-R6M5OGJH.js";import{d as cm,j as dm,r as lm,s as Vn,t as um,w as mm}from"./chunk-4EBHZBM2.js";import{$b as Hn,A as Zd,Ad as am,B as Re,C as Wr,E as bl,H as Sl,Ha as Si,J as Al,Jb as Hu,Ka as ln,La as $u,Ma as Nu,Na as Du,Nc as Po,Ob as Vu,Oc as Uo,Pc as jo,Qb as Yu,Qc as qo,R as ti,Tb as Do,U as Eu,Ua as Pu,Vb as Xu,Xb as Ju,Yb as yt,Zb as Qu,_b as wt,ab as Uu,ac as Dt,c as Be,ca as gi,cc as Zu,e as He,eb as qu,f as tn,fb as Gu,fd as nm,g as ho,ga as De,h as Xd,ha as Tu,i as jr,ib as Ku,j as qr,ja as yi,jb as Ai,k as Jd,ka as Iu,kb as zu,l as Gr,la as wi,lc as em,m as Qd,ma as vi,mb as V,na as ki,nb as le,nd as rm,o as _e,p as Kr,pb as xi,pc as tm,q as go,qb as he,r as Ne,ra as bi,rb as rt,sb as Wu,sd as im,tb as Ft,td as sm,ua as Ou,ud as Ci,v as Ve,vb as un,vd as om,wb as Ie,x as Tt,xa as Bn,yb as Fo,z as zr,zb as Bu,zd as Ei}from"./chunk-PY6A7ULK.js";import{B as ju,H as z,a as Mt,b as Ru,e as cn,f as dn,j as Lu,t as Mu,u as R,v as Fu}from"./chunk-3E53F7QY.js";import{A as _o,Aa as si,Bb as Zl,Da as oi,Ea as re,Fa as Nt,Ga as ae,Ha as No,Hb as ui,Hc as ru,Ia as Lo,Ib as H,If as _u,Ja as jl,Jd as ou,Jg as _i,Kd as au,Kf as hu,La as ai,Lg as hi,Mf as Wn,Na as ql,Nb as Lt,O as Ao,Oa as an,Of as gu,Pa as Gl,Q as Ye,Qa as Kl,Qd as cu,Rf as yu,Sa as zl,T as Ot,Ua as ci,Ub as eu,Ug as vu,Va as Wl,Ve as lu,Wa as Bl,X as te,_ as Zr,a as jd,ab as Hl,ah as M,bb as Vl,bd as iu,cb as Yl,db as Xl,eb as Jl,fa as Rl,fb as di,fd as su,ga as on,gb as li,ha as Ro,hg as gt,hh as ku,ia as ei,ig as pi,ih as bu,kd as Mo,kg as fi,l as qd,lh as nt,m as Gd,mf as uu,n as Kd,nb as Ql,nf as mu,o as zd,oa as Tl,of as mi,oh as Su,p as Wd,ph as Te,q as Bd,qb as Kn,qg as wu,r as We,rb as zn,rh as Au,s as Hd,sh as xu,tf as pu,th as Cu,vc as tu,wc as nu,xa as ii,xe as du,y as Vd,ya as Gn,yf as fu,z as Yd}from"./chunk-RWHS77ME.js";import{A as pl,B as fl,C as _l,D as hl,E as gl,F as yl,b as ko,c as Un,d as ve,g as F,h as et,i as Yr,j as rn,k as jn,l as qn,o as I,p as _t,q as tt,r as sn,s as ll,t as ul,u as Me,v as Xr,x as ml,y as bo,z as So}from"./chunk-GSLOAEY2.js";import{g as zp}from"./chunk-CNZOC6JD.js";import{$ as qm,$a as Yo,Aa as up,Ba as mp,C as zo,Ca as pp,D as Wo,E as vm,F as Ri,G as km,Ga as fp,H as bm,Ha as _p,I as Sm,Ia as hp,J as Am,Ja as gp,K as xm,Ka as yp,L as Cm,La as wp,M as Em,Ma as vp,N as Rm,Na as kp,O as Tm,Oa as bp,P as Im,Pa as Sp,Q as Om,Qa as Ap,R as $m,Ra as xp,S as Nm,Sa as Cp,T as Lm,Ta as Ep,U as Mm,Ua as Rp,V as Fm,Va as Tp,W as Dm,Wa as Ip,X as Pm,Xa as Op,Y as Um,Ya as Vo,Z as jm,Za as $p,_a as Np,aa as Bo,ab as Lp,ba as Gm,bb as Mp,c as fm,ca as Km,cb as Fp,d as _m,da as zm,db as Dp,e as hm,ea as Wm,eb as Pp,fa as Yn,fb as vt,ga as Bm,gb as Up,ha as Hm,hb as jp,ia as Vm,ib as qp,ja as Ym,jb as Gp,ka as Xm,la as Jm,lb as Kp,ma as Qm,na as Zm,nb as Xn,oa as ep,p as Go,pa as tp,q as gm,qa as np,ra as Ho,sa as rp,t as ym,ta as ip,u as Ko,ua as sp,v as Pt,va as op,wa as ap,x as wm,xa as cp,ya as dp,za as lp}from"./chunk-NRCGGNOE.js";import{$ as Oo,A as It,B as xo,C as wl,D as Qr,E as vl,F as Co,I as kl,K as xl,Q as O,S as Eo,T as Cl,U as El,W as se,_ as Ll,a as Z,aa as Ml,b as Pn,ba as $o,ca as Fl,da as ri,fa as Dl,ga as Pl,ha as Ul,i as ze,k as j,l as Ur,m as Rt,v as Jr,x as L}from"./chunk-JV7LREUF.js";import{E as dl,I as Il,P as To,T as Ol,W as $l,X as Nl,Z as Io,_ as ni,ba as q,ca as Fe,d as yo,da as $t,fa as ht,h as wo,i as Br,j as Hr,k as Vr,l as nl,n as rl,o as il,p as sl,q as ol,s as al,t as cl,u as vo}from"./chunk-TE6FBDHP.js";import{A as p,C as f,D as nn,E as me,F as el,G as B,H as ee,L as Le,N as tl,a as Ld,m as Md,p as Fd,s as Dd,u as Pd,w as Ud,x as Pr,y as Et}from"./chunk-K672XXGQ.js";var qb=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file, or from stdin when set to -.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),Gb=new Set(["--add","--body","--comment","--dep","--dep-remove","--description","--doc","--event","--field","--file","--learning","--note","--remove","--reminder","--test","--type-option"]),Kb=new Set(["append","comments","create","docs","files","learnings","notes","test","update","update-many"]),zb=new Set(["close-many:--ids","comments:--file","create:--body-file","history-compact:--ids","learnings:--file","notes:--file","update:--body-file","update-many:--ids"]),Wb=new Set(["close-many:--ids","history-compact:--ids","update-many:--ids"]),Bb=["--allow-","--check-","--dry-run","--explain","--fail-","--fix-","--full","--has-","--include-","--json","--no-","--prune-","--quiet","--refresh-","--require-","--runtime-only","--schema-only","--skip-","--stream","--strict-","--summary","--today","--verbose"],Hb=new Set(["--activate","--active-only","--adopt","--adopt-all","--all","--all-actionable","--all-affected-ids","--all-day","--all-streams","--acknowledge-linked-tests","--append-stable","--auto-fix","--auto-pm-context","--availability-only","--background","--brief","--by-assignee","--by-priority","--by-tag","--catalog","--claim","--clear","--clear-comments","--clear-criteria","--clear-deps","--clear-docs","--clear-events","--clear-files","--clear-learnings","--clear-notes","--clear-reminders","--clear-tests","--clear-type-options","--cli-only","--closed","--compact","--completion","--count","--counts","--deactivate","--declarative","--defaults","--describe","--diff","--doctor","--empty-body","--explore","--field-utilization","--filter-empty-body","--flags-only","--follow","--force","--global","--highlight","--hybrid","--id-only","--if-available","--ignore-global","--include_unparented","--infer","--init","--install","--isolated","--lean","--list","--local","--manage","--markdown","--metadata-coverage","--next","--normalize-provenance","--only","--only-last","--output-row-contract","--override-linked-pm-context","--override-linked-workspace-context","--packages-only","--past","--phrase-exact","--profile","--progress","--project","--promote-to-item-dep","--provenance","--provenance-summary","--raw","--ready-only","--ready_only","--rebuild","--recent","--reload","--repair","--replace-deps","--replace-docs","--replace-files","--replace-tests","--required","--required-on-create","--run","--runtime-probe","--save-baseline","--scaffold","--semantic","--shared-host-safe","--storage","--takeover-stale","--title-exact","--token-accounting","--trace","--tree","--unbounded","--uninstall","--validate-paths","--verify","--watch","--with-packages"]),Vb=new Set(["--only-index"]),Yb=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),Xb=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),Jb=new Set(["--regression"]);function Qb(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:zb.has(`${e}:${t}`)?["argv","file","stdin"]:t.endsWith("-file")?["argv","file"]:Gb.has(t)&&Kb.has(e)?["argv","stdin"]:["argv"]}function Zb(e,t){let n=Yb.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,r=t.value_type==="boolean"||t.flag==="--stdin"||t.flag==="--stdin-json"||t.flag.startsWith("--filter-")&&(t.flag.endsWith("-missing")||t.flag.startsWith("--filter-has-")||t.flag.startsWith("--filter-no-"))||Bb.some(i=>t.flag.startsWith(i));return n||Vb.has(t.flag)||!Hb.has(t.flag)&&!r}function eS(e,t){return t.value_arity!==void 0?t.value_arity:Zb(e,t)?Jb.has(t.flag)||Xb.has(`${e}:${t.flag}`)?"optional":"required":"none"}function tS(e,t){let n=Ur(e),r=eS(n,t),i=r!=="none",s=Qb(n,t.flag),o=t.description??qb[t.flag]??`${i?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:o,takes_value:i,value_required:r==="required",...i?{value_name:t.value_name??"value"}:{},value_type:i?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:s,...s.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{},...Wb.has(`${n}:${t.flag}`)?{file_token_prefix:"@"}:{}}}function c_(e,t){return t.map(n=>tS(e,n))}function CF(e,t,n){let r=e.trim().toLowerCase(),i=[],s=new Map,o=0;for(let c of n)if(c.command.trim().toLowerCase()===r){if(o+=1,s.has(c.flag)){i.push({code:"duplicate_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} was observed more than once.`});continue}s.set(c.flag,c)}let a=new Set(t.map(({flag:c})=>c));for(let c of t){let d=s.get(c.flag);if(!d){i.push({code:"missing_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} has no executable option observation.`});continue}for(let[l,u]of[["takes_value","takes_value_mismatch"],["value_required","value_required_mismatch"],["repeatable","repeatable_mismatch"]])c[l]!==d[l]&&i.push({code:u,command:r,flag:c.flag,detail:`${r} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of s.values())a.has(c.flag)||i.push({code:"undeclared_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} is executable but absent from invocation contracts.`});return i.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:i.length===0,declared_count:t.length,observed_count:o,findings:i}}import{readFile as nS}from"node:fs/promises";function BF(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Ve(e,t)}function f_(e){return Object.prototype.toString.call(e)==="[object Object]"}function rS(e,t,n,r){let i=O();if(!f_(e))return{...r({created_at:i,author:n,text:t}),text:t,edited_at:i};let s=o=>typeof o=="string"&&o!=="";return{...e,...s(e.created_at)?{}:{created_at:i},...s(e.author)?{}:{author:n},text:t,edited_at:i}}function d_(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new f(`Structured context events are append-only and cannot be ${t}.`,p.USAGE,{code:"structured_event_immutable"})}function iS(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Ut(e,t){let n=e[t];return Array.isArray(n)?n:[]}function HF(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let s=_e(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function sS(e){return typeof e=="object"&&e!==null&&"code"in e}function l_(e,t){if(!Tt(e))throw new f(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,p.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function oS(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new f(`Specify ${t} text using only one input source: --add, --stdin, or --file`,p.USAGE);let r=Zd(),i=Tt(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",i)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return l_(e,"--stdin"),{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new f("--file path cannot be empty",p.USAGE);if(s==="-")return l_(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await nS(s,"utf8"),emptyFlag:"--file"}}catch(o){if(sS(o)&&el(o))throw new f(`--file path not found: ${s}. Use --file - to read stdin.`,p.USAGE);let a=o instanceof Error?o.message:String(o);throw new f(`Failed to read --file path "${s}": ${a}. Use --file - to read stdin.`,p.USAGE)}}async function VF(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new f("Specify only one of --edit or --delete",p.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new f("--delete cannot be combined with replacement text",p.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new f("--delete must be a positive integer",p.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new f("--edit must be a positive integer",p.USAGE);let n=await oS(e,t);if(e.edit!==void 0){if(!n)throw new f("--edit requires replacement text from --add, --stdin, or --file",p.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function or(e,t){throw e instanceof f&&e.exitCode===p.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new f(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function __(e){return e==="comments"?"--stdin":"--add -"}var YF="annotation_flag_like_value";function aS(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function cS(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function dS(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=cS(t),i=__(e.collectionKey),s=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 o=r.split(/[ =]/,1)[0],a=o==="--file"?"that file":"stdin",c=e.conflictingOperand===void 0?"":` "${e.conflictingOperand}" was read as positional text, which ${o} cannot be combined with: drop it, or pass it as the text without ${o}.`;return new f(`${e.textFlag} value "${t}" looks like an option, not annotation text: ${e.textFlag} took ${o} as its value. Drop ${e.textFlag} and pass ${r} on its own.${c}`,p.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}`],...s})}return new f(`${e.textFlag} value "${t}" looks like an option, not annotation text. Use ${i} to read stdin, or use text=${t} for literal dash-leading text.`,p.USAGE,{code:"annotation_flag_like_value",required:`Use ${i} for stdin input, pass plain text, or use text=${t} when the text really starts with "-".`,examples:[`${e.commandPrefix} ${i}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...s})}function lS(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!aS(e)))throw dS({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function uS(e,t,n,r,i){if(n.input.mode!=="edit")return;let s=nu(t);if(s===void 0)return;let o=n.collectionKey.replace(/s$/,""),a=n.input.index,c=Ye(r)[0]==="--pm-path"?["--pm-path",i]:[];throw new f(`Replacement text for ${o} ${a} on ${e} ends with the read-output compaction marker, so it was copied from a compacted read that left out ${s} characters. Nothing was written.`,p.USAGE,{code:"annotation_text_compacted",item_id:e,details:{collection:n.collectionKey,entry_index:a,omitted_characters:s},required:`Read the whole ${o} 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 mS(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new f(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,p.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(pS(e,t),e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new f(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,p.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> ${__(e.collectionKey)}`]})}function pS(e,t){if(t.expectAt!==void 0){if(e.input.mode!=="edit"&&e.input.mode!=="delete")throw new f(`--expect-at guards an --edit or --delete of one ${e.collectionKey.replace(/s$/,"")}`,p.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 f("--expect-at must be the non-empty created_at timestamp of the entry you read",p.USAGE,{code:"annotation_expectation_invalid",required:"Pass the created_at value of the row you read at that index, as a string."})}}function u_(e,t,n,r,i){if(i===void 0)return;let s=t[n]?.created_at,o=typeof s=="string"?s:null;if(o===i)return;let a=t.flatMap((m,_)=>m?.created_at===i?[_+1]:[]),c=r.collectionKey.replace(/s$/,""),d=r.input.mode==="delete"?"--delete":"--edit",l=n+1,u=a.length===1?` The ${c} created at ${i} is at index ${a[0]}.`:a.length>1?` ${a.length} ${r.collectionKey} were created at ${i}: indexes ${a.join(", ")}.`:` No ${c} on ${e} was created at ${i}.`;throw new f(`${c.charAt(0).toUpperCase()}${c.slice(1)} ${l} on ${e} was created at ${o||"an unrecorded time (malformed entry)"}, not ${i}; refusing ${d} of an entry the caller did not read. Nothing was written.${u}`,p.CONFLICT,{code:"annotation_entry_mismatch",item_id:e,details:{collection:r.collectionKey,entry_index:l,expected_created_at:i,actual_created_at:o,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 ${i}${d==="--edit"?' --add "<text>"':""}`]})}function fS(e,t,n,r,i,s){let o=Ut(e.metadata,t),a=i?o.findIndex(c=>f_(c)&&c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],written:o,position:a}:(o.push(s({created_at:O(),author:n,text:r})),e.metadata[t]=o,{changedFields:[t],written:o,position:o.length-1})}function m_(e,t,n){return Gl.has(e)?t.map((i,s)=>s).sort((i,s)=>Kl(t[i],t[s])||i-s).indexOf(n)+1:n+1}async function XF(e,t,n,r){mS(r,t);let i=I(process.cwd(),n.path);await z(i);let s=await R(i),o=F(s,M()),a=Bn(t.limit);if(r.input.mode==="list"){let h=await V(i,e,s.id_prefix,s.item_format,o.type_to_folder);if(!h)throw new f(`Item ${e} not found`,p.NOT_FOUND);let g=await le(h,{schema:s.schema}),y=Ut(g.document.metadata,r.collectionKey);return Ki(h.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=H(t.author,s.author_default);if(r.input.mode==="delete"){let h=r.deleteOp??r.op,g;try{g=await Ie({pmRoot:i,settings:s,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let v=Ut(w.metadata,r.collectionKey),k=p_(r.input.index,v.length,r.collectionKey);return u_(e,v,k,r,t.expectAt),d_(v[k],"deleted"),v.splice(k,1),w.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(w){or(w,r.conflictGuidance)}let y=Ut(g.item,r.collectionKey);return Ki(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??"";lS(d,r);let l=r.parseText(r.input.value??"");if(!l.trim())throw new f(`${r.input.emptyFlag??"--add"} text cannot be empty`,p.USAGE);if(uS(e,l,r,n,i),r.input.mode==="edit"){let h=r.editOp??r.op,g,y=0;try{g=await Ie({pmRoot:i,settings:s,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(k){let b=Ut(k.metadata,r.collectionKey),A=p_(r.input.index,b.length,r.collectionKey);u_(e,b,A,r,t.expectAt);let C=b[A];return d_(C,"edited"),b[A]=rS(C,l,c,r.createEntry),y=m_(r.collectionKey,b,A),k.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(k){or(k,r.conflictGuidance)}let w=Ut(g.item,r.collectionKey),v=y;return Ki(g.item.id,r.collectionKey,w,a,t.includeMeta===!0,{action:"edit",entryIndex:v,entry:w[v-1]},t.fullHistory===!0)}let u,m=0;try{u=await Ie({pmRoot:i,settings:s,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(h){let g=fS(h,r.collectionKey,c,l,t.ifAbsent===!0,r.createEntry);return m=m_(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(h){or(h,r.conflictGuidance)}let _=Ut(u.item,r.collectionKey);return Ki(u.item.id,r.collectionKey,_,a,t.includeMeta===!0,{action:"add",entryIndex:m,entry:_[m-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function p_(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),i=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,s=t===1?`1 ${r}`:`${t} ${n}`;throw new f(`${i} index ${e??"(missing)"} out of range (item has ${s})`,p.USAGE)}return e-1}function _S(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 h_(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function hS(e,t){let n=e.length-t.length;return t.map((r,i)=>h_(r,n+i+1))}function Ki(e,t,n,r,i,s,o=!1){let a=s===void 0||o?hS(n,iS(n,s!==void 0&&o?void 0:r)):s.entry===void 0?[]:[h_(s.entry,s.entryIndex)],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...s?.changedCount===void 0?{}:{changed:s.changedCount===1},...[i,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},..._S(t,s,c)}}import{isDeepStrictEqual as b_}from"node:util";var gS=new Set(["__proto__","prototype","constructor"]),ar=Symbol("looseOptionOccurrences");function it(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,r)=>r.toUpperCase())}function yS(e,t,n){let r=e[t];if(r===void 0){e[t]=n;return}if(Array.isArray(r)){r.push(n),e[t]=r;return}e[t]=[r,n]}function ga(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(1,o).trim(),value:n.slice(o+1),attached:!0};let a=n.slice(1).trim(),c=e[t+1];return typeof c=="string"&&!c.startsWith("-")?{consumed:2,key:a,value:c}:{consumed:1,key:a,value:!0}}let r=n.indexOf("=");if(r>=0)return{consumed:1,key:n.slice(2,r).trim(),value:n.slice(r+1),attached:!0};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let i=n.slice(2).trim(),s=e[t+1];return typeof s=="string"&&!s.startsWith("-")?{consumed:2,key:i,value:s}:{consumed:1,key:i,value:!0}}function Wi(e){return gS.has(e)}function Hi(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return Rl(t)}function wn(e){let t=[],n=Ot(e.long)??"",r=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let i=it(n.slice(2));i.length>0&&!Wi(i)&&t.push(i)}if(r.startsWith("-")&&!r.startsWith("--")){let i=it(r.slice(1));i.length>0&&!Wi(i)&&t.push(i)}return[...new Set(t)]}function nD(e){let t=new Set;for(let n of e)for(let r of wn(n))t.add(r);return t}function jt(e){let t=Ot(e.long)??"";if(t.startsWith("--")){let n=it(t.slice(2));if(n.length>0&&!Wi(n))return n}return wn(e)[0]??null}function vn(e){let t=Ot(e.long)??"";if(t.startsWith("--")&&t.length>2)return t;let n=typeof e.short=="string"?e.short.trim():"";return n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function S_(e,t){return[...(t.definitions??e).map(r=>vn(r)).filter(r=>r!==null),...t.inheritedFlags??[]]}function rD(e,t,n,r={}){if(t.length===0)return;let i=new Set,s=new Map,o=[],a=S_(t,r);for(let c of t){let d=wn(c),l=vn(c);for(let u of d)i.add(u),c.enabled===!1&&s.set(u,l);c.required===!0&&c.enabled!==!1&&d.length>0&&o.push({keys:d,label:l,definition:c})}for(let c of Object.keys(e)){i.has(c)||A_(`--${c}`,`--${c}`,n,a);let d=s.get(c);d&&x_(d,n)}for(let c of o){let d=l=>Object.hasOwn(e,l)&&(c.definition.list!==!0||wa(c.definition,e[l]));c.keys.some(d)||C_(c.definition,c.keys[0],c.label,n)}}function A_(e,t,n,r){let i=r.length>0?` Expected one of: ${[...new Set(r)].join(", ")}.`:"";throw new f(`Unknown option '${e}' for extension command '${n}'.${i}`,p.USAGE,{code:"unknown_option",flag:t,required:`Use a flag the command accepts; run pm contracts --command ${n} --flags-only --json to list them.`})}function x_(e,t){throw new f(`Option '${e}' is disabled for extension command '${t}'.`,p.USAGE,{code:"extension_option_disabled",flag:e,required:`Remove ${e}; the command declares it with enabled: false.`,why:"A disabled declaration keeps the flag in the contract while refusing every value for it.",examples:[`pm ${t} --help`],nextSteps:[`Run pm contracts --command ${t} --flags-only --json to list the flags this command accepts.`]})}function C_(e,t,n,r){let i=on(e),s=i.value_arity==="none"?n:i.value_arity==="optional"?`${n} [${i.value_name}]`:`${n} <${i.value_name}>`;throw new f(`Missing required option '${n}' for extension command '${r}'.`,p.USAGE,{code:"missing_required_option",flag:n,field:t,required:`Pass ${s}.`,why:"The command declares this flag as required, so pm refuses the invocation before the extension handler runs.",examples:[`pm ${r} ${s}`],nextSteps:[`Run pm contracts --command ${r} --flags-only --json to read each flag's sdk_option key.`],recovery:{missing:[n]}})}function wS(e){return typeof e=="string"||e==null?e:String(e)}function vS(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);return Number.isFinite(t)?t:e}return e}function E_(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return e}var kS={string:wS,number:vS,boolean:E_};function qt(e,t){return Array.isArray(e)?e.map(n=>qt(n,t)):kS[t](e)}function ya(e,t,n){let r=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(i=>i!=null&&i!==""):Ro(e);return t?r.map(i=>qt(i,t)):r}function wa(e,t){return ya(t,null,e.repeatable===!0).length>0}function bS(e,t,n,r){return n?ya(e,t,r):t?qt(e,t):e}function SS(e,t,n){let r=T_(e,t);return r.length===0?n:r.map(i=>i.value)}function R_(e){return on(e).value_arity==="none"}function va(e,t,n,r,i){let s=vn(e),o=i?` for extension command '${i}'`:"",a=n===!0?"no value":JSON.stringify(n);throw new f(`Option '${s}'${o} expects ${r}; received ${a}.`,p.USAGE,{code:"extension_flag_value_invalid",flag:s,required:`Pass ${s} ${t==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${t} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${t} value for ${s}.`,`Run pm ${i??"<command>"} --help to review the declared flag contract.`]})}function ka(e,t){return e.value_validation==="strict"&&t!=="string"}function T_(e,t){let n=e[ar];if(!n)return[];let r=new Set(t);return n.filter(i=>r.has(i.key))}function AS(e,t,n,r){if(R_(e))for(let i of T_(n,t)){if(i.attached!==!0)continue;let s=e.list===!0&&e.repeatable!==!0?Ro(i.value):[i.value];for(let o of s){let a=ei(qt(o,"boolean"),"boolean");a!==null&&va(e,"boolean",o,a.expected,r)}}}function xS(e,t,n,r,i){let s=Array.isArray(n)?n.flat(1/0):[n],o=r?s:s.flatMap(a=>typeof a=="string"?a.split(","):[a]);for(let a of o)if(typeof a=="string"&&a.trim().length===0){let c=ei(a,t);va(e,t,a,c.expected,i)}}function ba(e,t,n,r){if(!ka(e,n))return t;let i=n==="boolean"&&R_(e),s=o=>{let a=ei(o,n);return a===null?o:i&&typeof o=="string"?!0:va(e,n,o,a.expected,r)};return Array.isArray(t)?t.map(s):s(t)}function CS(e,t,n,r){for(let i of n)if(!(i===t||!Object.hasOwn(e,i))){if(Object.hasOwn(e,t)){if(r){let s=e[t],o=e[i];e[t]=[...Array.isArray(s)?s:[s],...Array.isArray(o)?o:[o]].filter(a=>a!=null)}delete e[i];continue}e[t]=e[i],delete e[i]}}function I_(e,t,n=e,r){if(t.length===0)return e;let i=Object.create(null);for(let[o,a]of Object.entries(e))i[o]=a;let s=new Set(t.map(o=>jt(o)).filter(o=>o!==null));for(let o of t){let a=jt(o);if(a){let c=wn(o).filter(d=>d===a||!s.has(d));ES(i,o,a,c,n,r)}}return i}function ES(e,t,n,r,i,s){let o=t.list===!0,a=Hi(t);a&&!o&&RS(e,t,n,r,a,s),CS(e,n,r,o);let c=t.repeatable===!0;if(!Object.hasOwn(e,n)){t.default!==void 0&&(e[n]=bS(t.default,a,o,c));return}if(a==="boolean"&&ka(t,a)&&AS(t,r,i,s),o){e[n]=TS(t,r,i,e[n],a,c,s);return}a&&(e[n]=ba(t,qt(e[n],a),a,s))}function RS(e,t,n,r,i,s){for(let o of r)o!==n&&Object.hasOwn(e,o)&&ba(t,qt(e[o],i),i,s)}function TS(e,t,n,r,i,s,o){let a=SS(n,t,r);i&&ka(e,i)&&xS(e,i,a,s,o);let c=ya(a,i,s);return i?ba(e,c,i,o):c}function iD(e){let t=Object.create(null),n=[];Object.defineProperty(t,ar,{value:n});let r=0;for(;r<e.length;){let i=ga(e,r);if(!i){r+=1;continue}let s=it(i.key);if(s.length===0||Wi(s)){r+=i.consumed;continue}yS(t,s,i.value),n.push({...i,key:s}),r+=i.consumed}return t}function sD(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let r=ga(e,n);if(r){n+=Math.max(1,r.consumed);continue}t.push(e[n]),n+=1}return t}function oD(e,t){if(t.length===0)return[...e];let n=new Set,r=new Set;for(let o of t){let a=Hi(o);for(let c of wn(o))n.add(c),a==="boolean"&&r.add(c)}if(n.size===0)return[...e];let i=[],s=0;for(;s<e.length;){if(e[s]==="--"){i.push(...e.slice(s+1));break}let o=ga(e,s);if(o){let a=it(o.key);if(n.has(a)){let c=e[s],d=r.has(a)&&!c.includes("=")?1:o.consumed;s+=d;continue}}i.push(e[s]),s+=1}return i}function Sa(e){return jt(e)}function g_(e){return e.trim().toLowerCase().split(/\s+/u).filter(t=>t.length>0).join(" ")}function aD(e,t){let n=g_(t);if(n.length===0)return[];let r=j(n);return e.flags.filter(i=>j(g_(i.target_command))===r).flatMap(i=>[...i.flags])}function O_(e,t,n,r){let i=vn(e),[s,o]=n;throw new f(`Options '${s}' and '${o}' both set ${i} for extension command '${r}' with different values.`,p.USAGE,{code:"extension_option_spelling_conflict",required:`Pass ${i} once, under the handler key '${t}'.`,why:`'${s}' and '${o}' are spellings of the same declared flag, and pm refuses to choose between two different values.`,nextSteps:[`Remove '${s}' or '${o}' and pass one value as '${t}'.`,`Run pm contracts --command ${r} --flags-only --json to read each flag's sdk_option key.`]})}function cD(e,t,n,r={}){if(t.length===0)return e;let i=t.map(l=>l.repeatable===!0&&l.list!==!0?{...l,list:!0}:l),s=L_(i),o=LS(e,s,n),a=new Set([...s.long.values()].map(({handlerKey:l})=>l)),c=Object.create(null),d=Object.create(null);for(let[l,u]of Object.entries(o))a.has(l)?c[l]=u:u===void 0||r.undeclaredKeys==="pass"||OS(l)?d[l]=u:A_(l,$S(l),n,S_(i,{}));return N_(c,i,n),Object.assign(d,I_(c,i,$_(c,s),n))}function $_(e,t){let n=new Set([...t.long.values()].map(({handlerKey:s})=>s)),r=Object.entries(e).filter(([s])=>n.has(s)).flatMap(([s,o])=>(Array.isArray(o)?o.flat(1/0):[o]).map(a=>({consumed:1,key:s,value:a,attached:!0}))),i=Object.create(null);return Object.defineProperty(i,ar,{value:r}),i}function N_(e,t,n){for(let r of t){let i=jt(r);if(i===null)continue;let s=vn(r),o=e[i],a=Object.hasOwn(e,i);r.enabled===!1&&a&&x_(s,n);let c=a&&(r.list!==!0||wa(r,o));r.required===!0&&r.enabled!==!1&&!c&&C_(r,i,s,n),r.list!==!0&&Array.isArray(o)&&IS(s,n)}}function IS(e,t){throw new f(`Option '${e}' for extension command '${t}' takes one value; received an array.`,p.USAGE,{code:"extension_flag_value_invalid",flag:e,required:`Pass one value for ${e}, or ask the package to declare it with list: true or repeatable: true.`,why:"The flag is not declared list or repeatable, so pm refuses an array before the extension handler runs instead of handing it a value of the wrong shape.",nextSteps:[`Run pm contracts --command ${t} --flags-only --json to read each flag's value contract.`]})}var y_=new Set([...[...xl].flatMap(e=>{let t=e.replace(/^--/u,"");return[t,...t.startsWith("no-")?[t.slice(3)]:[]].flatMap(r=>[it(r),r.replaceAll("-","_")])}),"force","subcommand","inputResponses","requestState"]);function OS(e){return y_.has(e)||y_.has(it(e.replace(/^-{1,2}/u,"")))}function $S(e){return`--${e.replace(/^-+/u,"").replace(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`}function L_(e){let t={long:new Map,short:new Map},n=(r,i,s)=>{i.length>0&&!r.has(i)&&r.set(i,s)};for(let r of e){let i=jt(r);if(i===null)continue;let s={handlerKey:i,definition:r};n(t.long,i,s);let o=typeof r.short=="string"?r.short.trim():"";o.startsWith("-")&&!o.startsWith("--")&&n(t.short,o.slice(1),s)}return t}function Bi(e,t){return e.long.get(t)??e.short.get(t.replace(/^-(?!-)/u,""))??e.long.get(it(t.replace(/^-{1,2}/u,"")))}function M_(e,t,n,r){let i=/^(?:--)?no-(.+)$/u.exec(t)?.[1];if(i===void 0||Bi(e,t)!==void 0)return{spelling:t,value:n};let s=Bi(e,i);return s===void 0||Hi(s.definition)!=="boolean"?{spelling:t,value:n}:(s.definition.list===!0||s.definition.repeatable===!0)&&Array.isArray(n)?{spelling:i,value:n.flat(1/0).map(o=>w_(t,s.definition,o,r))}:s.definition.list===!0&&n!==void 0?{spelling:i,value:w_(t,s.definition,n,r)}:{spelling:i,value:n===void 0?n:zi(t,s.definition,n,r)}}function dD(e,t,n){let r=L_(e);try{let i=M_(r,t,n,"");if(i.spelling===t)return;let s=Bi(r,i.spelling);return(s.definition.list===!0||s.definition.repeatable===!0)&&!wa(s.definition,i.value)?void 0:{key:s.handlerKey,value:i.value}}catch{return}}function w_(e,t,n,r){let i=s=>s.trim().length===0?s:String(zi(e,t,s.trim(),r));return n==null?n:typeof n!="string"?zi(e,t,n,r):n.trim().length===0?n:t.repeatable===!0||!n.includes(",")?zi(e,t,n,r):n.split(",").map(i).join(",")}function zi(e,t,n,r){let i=E_(n);return typeof i=="boolean"?!i:NS(e,t,n,r)}function NS(e,t,n,r){let i=vn(t);throw new f(`Option '${e}' for extension command '${r}' negates ${i} and expects true, false, 1, or 0; received ${JSON.stringify(n)}.`,p.USAGE,{code:"extension_flag_value_invalid",flag:i,required:`Pass ${i} as true or false, or '${e}' as true.`,why:`'${e}' is the negated spelling of the boolean ${i}, so only a boolean value can be inverted before the extension handler runs.`,nextSteps:[`Run pm contracts --command ${r} --flags-only --json to read each flag's value contract.`]})}function LS(e,t,n){let r=Object.create(null),i=new Map;for(let[s,o]of Object.entries(e)){let{spelling:a,value:c}=M_(t,s,o,n),d=Bi(t,a);if(d===void 0)r[a]=c;else if(c!==void 0){let l=i.get(d.handlerKey);l===void 0?(i.set(d.handlerKey,a),r[d.handlerKey]=c):b_(v_(d.definition,d.handlerKey,r[d.handlerKey],t,n),v_(d.definition,d.handlerKey,c,t,n))||O_(d.definition,d.handlerKey,[l,a],n)}}return r}function v_(e,t,n,r,i){let s={[t]:n};return N_(s,[e],i),I_(s,[e],$_(s,r),i)[t]}function F_(e){let t=new Map;for(let n of e){let r=jt(n);if(r===null)continue;let i={definition:n,handlerKey:r,kind:Hi(n),arity:on(n).value_arity,scalar:n.list!==!0},s=[Ot(n.long),typeof n.short=="string"?n.short.trim():""];for(let o of s.filter(a=>a?.startsWith("-")===!0))t.has(o)||t.set(o,i)}return t}function D_(e,t,n,r=KS){let i=e.optionOf(n),s=t.get(n),o=s!==void 0&&r(s)?s:void 0;if(i!==void 0){let a={arity:i.arity,...i.variadic===!0?{variadic:!0}:{}};if(o?.handlerKey===i.key)return{...a,declared:o};if(s!==void 0)return a;let c=GS(t,n,i,r);return c===void 0?a:{...a,declared:c,negates:!0}}if(!(!e.includesLooseFlags||s===void 0))return o===void 0?{arity:s.arity,loose:!0}:{arity:s.arity,declared:o,loose:!0}}function Aa(e){return e.length>1&&e.startsWith("-")}var P_=/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/u;function U_(e,t,n){let{tokens:r}=e,i=0,s,o=!1,a=!1;for(;i<r.length||s!==void 0;){let c=s??r[i++];if(c==="--")return;if(a&&s===void 0&&MS(e,c))continue;let d=Aa(c)?DS(e,c,r[i],t,n):{consumedByCommander:!1,consumed:0};if(i+=d.consumed,s=d.group,a=d.variadic===!0,!d.consumedByCommander){if(FS(e.stop,c,o))return;o=!0}}}function MS(e,t){return!Aa(t)||e.negativeNumbersAreValues&&P_.test(t)}function FS(e,t,n){return e!==void 0&&(e.atFirstUnrecognized||!n&&e.atSubcommand(t))}function DS(e,t,n,r,i){let s=PS(t,n,r);if(s!==void 0)return i(s.spelling,s.entry,s.value,"loose"),{consumedByCommander:!1,consumed:s.consumed};let o=r(t);if(o!==void 0){let a=o.arity==="required"||o.arity==="optional"&&n!==void 0&&(!Aa(n)||e.negativeNumbersAreValues&&P_.test(n));return i(t,o,o.negates===!0?!1:a?n:!0,"commander"),{consumedByCommander:!0,consumed:a?1:0,variadic:o.variadic===!0}}return t[1]!=="-"?{consumed:0,...US(t,r,i)}:{consumedByCommander:jS(t,r,i,e.includesLooseFlags?i:()=>{}),consumed:0}}function PS(e,t,n){let r=e.indexOf("="),i=r>1?e.slice(0,r):e,s=n(i);if(s?.loose===!0)return r>1?{spelling:i,entry:s,value:e.slice(r+1),consumed:0}:t!==void 0&&!t.startsWith("-")?{spelling:i,entry:s,value:t,consumed:1}:{spelling:i,entry:s,value:!0,consumed:0};let o=r<0&&e.startsWith("--no-")?n(`--${e.slice(5)}`):void 0;return o?.loose===!0&&o.declared?.kind==="boolean"?{spelling:e,entry:o,value:!1,consumed:0}:void 0}function US(e,t,n){let r=e.slice(0,2),i=e.length>2?t(r):void 0;return i===void 0||i.loose===!0?{consumedByCommander:!1}:i.arity!=="none"?(n(r,i,e.slice(2),"commander"),{consumedByCommander:!0}):(n(r,i,!0,"commander"),{consumedByCommander:!0,group:`-${e.slice(2)}`})}function jS(e,t,n,r){let i=e.indexOf("=");if(i>2){let o=e.slice(0,i),a=t(o);return a!==void 0&&a.arity!=="none"?(n(o,a,e.slice(i+1),"commander"),!0):(a?.declared?.kind==="boolean"&&r(o,a,e.slice(i+1),"loose"),!1)}let s=e.startsWith("--no-")?t(`--${e.slice(5)}`):void 0;return s?.declared?.kind==="boolean"&&r(e,s,!1,"loose"),!1}function lD(e,t,n){let r=F_(t),i=new Map;for(let s of e)U_(s,o=>D_(s,r,o),(o,a,c)=>{a.declared!==void 0&&qS(i,a.declared,o,c,n)})}function qS(e,t,n,r,i){let{definition:s,handlerKey:o,kind:a}=t,c=a?qt(r,a):r,d=e.get(o)??new Map,l=[...d].find(([u,m])=>u!==n&&!b_(m,c));l!==void 0&&O_(s,o,[l[0],n],i),d.set(n,c),e.set(o,d)}function GS(e,t,n,r){let i=t.startsWith("--no-")?e.get(`--${t.slice(5)}`):void 0;return i!==void 0&&r(i)&&i.kind==="boolean"&&i.handlerKey===n.key?i:void 0}function KS(e){return e.scalar}function k_(e){return!e.scalar&&e.kind==="boolean"&&e.arity==="none"}function uD(e,t,n){let r=F_(n),i=[...new Set(r.values())].filter(k_);if(i.length===0)return e;let s=new Set(n.map(m=>jt(m)).filter(m=>m!==null)),o=m=>wn(m.definition).filter(_=>_===m.handlerKey||!s.has(_)),a=new Map([...i].reverse().flatMap(m=>o(m).map(_=>[_,m]))),c=new Map;for(let m of t)U_(m,_=>D_(m,r,_,k_)??zS(m,a,_),(_,h,g,y)=>{if(h.declared===void 0)return;let w=c.get(h.declared)??[];w.push(y==="commander"?{value:g}:null),c.set(h.declared,w)});let d=[...c].filter(([,m])=>m.some(_=>_!==null));if(d.length===0)return e;let l=e[ar]??[];for(let[m,_]of d){let h=new Set(o(m)),g=l.filter(({key:k})=>h.has(k));if(g.length===0)continue;let y=k=>({consumed:0,key:m.handlerKey,value:k.value}),w=0,v=_.filter(k=>k===null).length===g.length?_.map(k=>k===null?g[w++]:y(k)):[...g,..._.filter(k=>k!==null).map(y)];l=[...l.filter(({key:k})=>!h.has(k)),...v]}let u=Object.assign(Object.create(null),e);return Object.defineProperty(u,ar,{value:l}),u}function zS(e,t,n){let r=!n.startsWith("--")&&e.optionOf(n.slice(0,2))!==void 0;if(!e.includesLooseFlags||r)return;let i=t.get(it(n.replace(/^-+/u,"")));return i===void 0?void 0:{arity:i.arity,declared:i,loose:!0}}var WS=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate","workspace"]),BS=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),HS=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),VS=new Set(["extension","install","package","packages","upgrade"]);function YS(e){let t=j(e.trim().toLowerCase());if(t==="ops")return"quality";for(let[n,r]of Object.entries(HS))if(r.has(t))return n;return VS.has(t)?"extensions":"internal"}var kn=Object.freeze([...We.flatMap(e=>e==="item"?["item","item-reopen"]:[e,...ze.filter(t=>t.alias===e).map(t=>t.canonical)]).map(e=>({command:e,tier:WS.has(j(e))?"core":BS.has(j(e))?"standard":"full",family:YS(e)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]),XS=kn,j_=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),_D=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function hD(e){let t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=j_.max_lines&&n<=j_.max_utf8_bytes}}var q_={core:0,standard:1,full:2,internal:3},G_=new Map(XS.map(({command:e,tier:t})=>[e,t]));function xa(e,t="standard"){return G_.get(e.trim().toLowerCase())??G_.get(j(e.trim().toLowerCase()))??t}function gD(e){return K_(e,kn)}function K_(e,t){let n=q_[e];return t.filter(r=>r.tier!=="internal"&&q_[r.tier]<=n).map(r=>r.command)}function yD(e){return z_(e,kn)}function z_(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}var JS=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],QS=new Set([...Rt.filter(e=>e.hidden).map(e=>e.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function wD(e=kn){return JS.map(t=>({family:t,commands:z_(t,e).filter(n=>e.find(r=>r.command===n)?.tier!=="internal"&&!QS.has(n))})).filter(({commands:t})=>t.length>0)}var ZS=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function vD(e,t){return eA(e,t,kn)}function eA(e,t,n){if(t==="full")return[...e];let r=new Set(K_(t,n));return e.filter(i=>{let s=ZS[i];return s!==void 0&&r.has(s)})}var kD=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),bD=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function SD(){return tA(kn)}function tA(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:n,tier:r,family:i})=>`| \`${n}\` | ${r} | ${i} |`),""].join(`
|
|
2
|
-
`)}var Ca=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],nA=new Map(Ca.map(e=>[e.exit_code,e.class]));function Vi(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function rA(e){if(!e)return[];let t=new Set,n=new Set;return e.map(r=>{let i=r.state.trim(),s=r.probe_id.trim(),o=Vi(r.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(i)||!/^[a-z][a-z0-9-]*$/.test(s)||o.length===0||t.has(i)||n.has(s))throw new TypeError("Invalid pm refusal state contract");return t.add(i),n.add(s),{state:i,probe_id:s,entrypoints:o,expected_exit_class:r.expected_exit_class}}).sort((r,i)=>r.state.localeCompare(i.state))}function iA(e,t,n,r,i){return![[1,2,3,4,5].includes(e.exit_code),e.meaning.trim().length>0,e.recovery.trim().length>0,t.length>0,n.length>0,/^[a-z][a-z0-9_]*$/.test(r),i.every(s=>/^[a-z][a-z0-9_]*$/.test(s)),nA.get(e.exit_code)===e.class].includes(!1)}function sA(e,t){let n=e,r=new Set;for(;n.canonical_code!==n.code;){if(r.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);r.add(n.code);let i=t.get(n.canonical_code);if(!i)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=i}return n}function oA(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let r=sA(n,t);if(r.exit_code!==n.exit_code||r.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let i=e.filter(s=>s.code!==r.code&&s.canonical_code===r.code).map(s=>s.code).sort();if(n.code===r.code?JSON.stringify(n.aliases)!==JSON.stringify(i):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function B_(e){let t=new Set,n=e.map(r=>{let i=r.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(i))throw new TypeError(`Invalid pm error code: ${JSON.stringify(r.code)}`);if(t.has(i))throw new TypeError(`Duplicate pm error code: ${i}`);t.add(i);let s=Vi(r.sources),o=Vi(r.emitting_commands),a=(r.canonical_code??i).trim(),c=Vi(r.aliases??[]),d=rA(r.owned_states);if(!iA(r,s,o,a,c))throw new TypeError(`Invalid pm error code contract: ${i}`);if(d.some(l=>l.expected_exit_class!==r.class))throw new TypeError(`Invalid pm refusal state exit class: ${i}`);return Object.freeze({...r,code:i,meaning:r.meaning.trim(),recovery:r.recovery.trim(),sources:s,emitting_commands:o,canonical_code:a,aliases:c,owned_states:d})});return oA(n),Object.freeze(n.sort((r,i)=>r.code.localeCompare(i.code)))}function xD(e,t){let n=W_(e,t);return W_(n.canonical_code??n.code,t)}function W_(e,t){let n=e.trim(),r=t.find(i=>i.code===n);if(!r)throw new TypeError(`Unknown pm error code "${n}"`);return r}var aA="Inspect the structured error guidance, then retry the suggested command when one is present.",cA=new Map(Ca.map(e=>[e.exit_code,e.class]));function H_(e){return e.map(t=>{let n=`${t.code.replaceAll("_"," ")} condition.`,r={code:t.code,meaning:`${n.charAt(0).toUpperCase()}${n.slice(1)}`,stability:t.stable?"stable":"provisional",exit_code:t.exit_code,class:cA.get(t.exit_code),recovery:aA,sources:t.sources,emitting_commands:t.emitting_commands??["*"],canonical_code:t.canonical_code??t.code,aliases:t.aliases??[]};return t.owned_states&&(r.owned_states=t.owned_states),r})}var V_=[{code:"acceptance_criteria_mutation_conflict",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_remove_unmatched",exit_code:3,sources:["sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_semicolon_forbidden",exit_code:2,stable:!0,sources:["core/item/parse.ts"]},{code:"accepted_rejected_value",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"alias_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"alias_target_missing",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"already_claimed_by",exit_code:4,stable:!0,sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"ambiguous_option_combination",exit_code:2,stable:!0,sources:["sdk/lifecycle/claim.ts","sdk/lifecycle/plan.ts"],emitting_commands:["claim","plan"]},{code:"annotation_alias_conflict",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"annotation_entry_mismatch",exit_code:4,sources:["sdk/annotations.ts"]},{code:"annotation_expectation_invalid",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_expectation_without_target",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_flag_like_value",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_if_absent_without_append",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_message_without_text",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_text_compacted",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_text_source_conflict",exit_code:2,sources:["sdk/runtime-input.ts"]},{code:"annotation_transposed_subcommand",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"append_empty_body",exit_code:2,stable:!0,sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"]},{code:"assurance_registry_invalid",exit_code:1,sources:["sdk/governance/assurance.ts"]},{code:"bare_comma_entry_ambiguous",exit_code:2,sources:["core/item/parse.ts"]},{code:"blocker_identity_read_failed",exit_code:1,sources:["sdk/query/declared-blockers.ts"]},{code:"body_file_conflicts_with_body",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_missing_path",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_unreadable",exit_code:3,stable:!0,sources:["core/io/body-file.ts"]},{code:"budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"bulk_create_route",exit_code:2,sources:["cli/register-mutation.ts"]},{code:"bulk_ids_input_empty",exit_code:2,sources:["core/io/bulk-ids-input.ts","sdk/history-compact.ts","sdk/history-mcp.ts"],owned_states:[{state:"bulk_ids_stdin_contains_no_nonempty_ids",probe_id:"bulk-ids-stdin-empty",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_missing_path",exit_code:2,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_token_omits_its_path",probe_id:"bulk-ids-file-path-missing",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_unreadable",exit_code:3,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_path_cannot_be_read",probe_id:"bulk-ids-file-unreadable",entrypoints:["update-many"],expected_exit_class:"not_found"}]},{code:"bundle_integrity_torn_install",exit_code:1,stable:!0,sources:["cli/bundle-integrity.ts"]},{code:"capability_undeclared",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"capability_unused",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"child_projection_item_bound_exceeded",exit_code:1,stable:!0,sources:["sdk/item-children.ts"]},{code:"close_reason_required",exit_code:2,stable:!0,sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"]},{code:"close_through_update",exit_code:1,stable:!0,sources:["core/telemetry/observability.ts"]},{code:"close_validation_deferred_fields",exit_code:2,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"close_validation_missing_fields",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"collected_zero_items",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"collection_transposed_subcommand",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"command_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"command_namespace",exit_code:2,stable:!0,sources:["sdk/cli-contracts/runtime-contracts.ts"]},{code:"command_override_conflict",exit_code:4,stable:!0,sources:["sdk/compose.ts"]},{code:"config_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"config_key_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts","sdk/config.ts"]},{code:"config_value_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"conflicting_lifecycle_owner",exit_code:2,stable:!0,sources:["cli/register-operations.ts"]},{code:"context_evaluation_read_incomplete",exit_code:2,sources:["sdk/context-relevance.ts"]},{code:"context_signal_store_invalid",exit_code:2,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_stale",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_write_failed",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_takes_no_item_argument",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"core_item_field_requires_dedicated_flag",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"create_deferral_conflict",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_field_unsupported",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_fields_required",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_reason_required",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_positional_type_without_title",exit_code:2,stable:!0,sources:["cli/register-mutation.ts"]},{code:"dependency_cardinality_created",exit_code:2,sources:["sdk/graph/cardinality-integrity.ts"]},{code:"dependency_edge_not_allowed",exit_code:2,stable:!0,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_flag_value_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_remove_no_match",exit_code:3,sources:["sdk/lifecycle/dependency-removal.ts"],emitting_commands:["update"]},{code:"dependency_target_not_found",exit_code:3,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_temporal_order_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"duplicate_canonical_flag",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"duplicate_command",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"duplicate_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"duplicate_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"duplicate_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"duplicate_probe",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"duplicate_sweep_cost_limit",exit_code:4,stable:!0,sources:["sdk/query/duplicate-candidates.ts"],emitting_commands:["duplicate-candidates"]},{code:"duplicate_target_circular",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_is_duplicate",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_missing",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_self",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"empty_corpus",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"empty_surface",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"event_cursor_query_mismatch",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"event_history_integrity_failed",exit_code:1,sources:["core/history/event-index.ts"]},{code:"event_index_unavailable",exit_code:1,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"exit_code_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"expect_hash_background_unsupported",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invalid",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invocation_rewritten",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_requires_mutation",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_target_required",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expected_revision_duplicate",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"expected_revision_scope_conflict",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"extension_command_activation_failed",exit_code:1,stable:!0,sources:["cli/commander-usage.ts"]},{code:"extension_dependency_name_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_spec_invalid",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_version_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_flag_value_invalid",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_install_incomplete_source_scan",exit_code:2,sources:["sdk/extension/install-plan.ts"]},{code:"extension_install_rollback_failed",exit_code:1,sources:["sdk/extension/install-snapshot.ts"]},{code:"extension_install_soft_failed",exit_code:1,stable:!0,sources:["cli/register-setup.ts"]},{code:"extension_install_source_contains_destination",exit_code:2,stable:!0,sources:["sdk/extension/install-runtime.ts"]},{code:"extension_item_field_reserved",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_type_conflict",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_unknown",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_mutation_guard_failed",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_decision",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_denial",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_timed_out",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_option_disabled",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_option_spelling_conflict",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_read_output_invalid",exit_code:2,sources:["sdk/read-output/extension.ts"]},{code:"extension_update_health_partial_coverage",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"extensions_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"field_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_flag_invalid",exit_code:2,sources:["core/profile/profile-lint.ts"]},{code:"field_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_mcp_input_collision",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_option_collision",exit_code:1,sources:["core/profile/profile-lint.ts"]},{code:"finalization_invalid_document",exit_code:2,sources:["sdk/transactions/item-finalization.ts"]},{code:"github_source_entry_unbuilt",exit_code:2,stable:!0,sources:["sdk/extension/shared.ts"]},{code:"hierarchy_cardinality_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_cycle_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_parent_divergence_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"history_append_only_repair_unavailable",exit_code:4,sources:["sdk/history/append-only-repair.ts"]},{code:"history_author_acknowledge_plan_conflict",exit_code:4,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_plan_fingerprint_required",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_preview_limit_invalid",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_required_values_missing",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_conflict",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_required",exit_code:2,stable:!0,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_not_actionable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_unreadable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_baseline_unavailable",exit_code:1,sources:["core/history/projection.ts"]},{code:"history_compact_boundary_bridged",exit_code:2,sources:["sdk/history-compact.ts"]},{code:"history_drift_chain_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_chain_mismatches"]},{code:"history_drift_chain_unbridgeable",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_hash_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_hash_mismatches"]},{code:"history_drift_merge_receipt",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_missing_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_missing_streams"]},{code:"history_drift_unreadable_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_unreadable_streams"]},{code:"history_drift_unrepairable_stream",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_version_skew",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_version_skews"]},{code:"history_json_invalid",exit_code:1,sources:["core/history/read.ts"]},{code:"history_merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/history/read.ts"],canonical_code:"merge_conflict_markers_detected"},{code:"history_record_integrity_invalid",exit_code:4,sources:["sdk/history/reanchor-refusal.ts"]},{code:"history_record_invalid",exit_code:1,sources:["core/history/read.ts"]},{code:"history_record_version_unsupported",exit_code:4,sources:["sdk/history/reanchor-refusal.ts"]},{code:"history_redact_bridge_unlocated",exit_code:1,sources:["sdk/history-redact.ts"]},{code:"history_replay_invalid",exit_code:1,sources:["core/history/projection.ts","core/history/tombstone.ts"]},{code:"history_salvage_refused",exit_code:4,sources:["sdk/history/salvage.ts"]},{code:"history_stream_over_compact_threshold",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"history_target_out_of_range",exit_code:1,stable:!0,sources:["core/history/projection.ts"]},{code:"history_timestamp_invalid",exit_code:1,sources:["core/history/event-index.ts","core/history/history.ts"]},{code:"history_union_rebase_conflict",exit_code:4,sources:["sdk/merge/history-scalar-rebase.ts"]},{code:"history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_unknown_author_events"]},{code:"history_version_mapping_unavailable",exit_code:2,sources:["core/history/version-address.ts"]},{code:"history_version_pruned",exit_code:2,sources:["core/history/projection.ts"]},{code:"history_version_unreconstructable",exit_code:2,sources:["core/history/projection.ts"]},{code:"host_environment_capacity_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_operation_invalid",exit_code:2,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_permission_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_resource_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"improvement_metric_contract_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"improvement_observation_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"in_progress_idle",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"in_progress_unowned",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"incomplete_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"inconsistent_concept_kind",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"init_existing_settings_requires_force",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_gitignore_unwritable",exit_code:1,stable:!0,sources:["sdk/workspace.ts"]},{code:"init_id_prefix_conflict",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_id_prefix_path_like",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"integrity_history_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_history_conflict_markers"]},{code:"integrity_history_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_history_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_ahead_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_ahead_items"]},{code:"integrity_item_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_outdated_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_outdated_items"]},{code:"integrity_item_parse_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"invalid_argument_value",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/item/priority.ts","core/shared/url-credentials.ts","core/telemetry/observability.ts","sdk/config.ts","sdk/context-intent-contracts.ts","sdk/dependencies.ts","sdk/extension/listing-fields.ts","sdk/extension/static-inventory.ts","sdk/governance/assurance-mutation-error.ts","sdk/history-redact.ts","sdk/lifecycle/create.ts","sdk/lifecycle/task-composition.ts","sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts","sdk/linked-artifacts.ts","sdk/query/next.ts","sdk/runtime-input.ts","sdk/runtime.ts","sdk/runtime/mutation-admission.ts","sdk/runtime/mutation-value-validation.ts","sdk/runtime/schema-preview.ts","sdk/test/run-phases.ts","sdk/workspace.ts"],emitting_commands:["*","create","next","task-composition","update","update-many"]},{code:"invalid_command_usage",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"invalid_event_cursor",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_cursor_mode",exit_code:2,sources:["cli/register-list-query.ts","sdk/mutation-events.ts","sdk/runtime-extended-actions.ts"]},{code:"invalid_event_follow_interval",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_limit",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_since",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_history_analytics_limit",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_minimum_sample",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_since",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_improvement_ledger",exit_code:1,sources:["sdk/improvement-ledger-validation.ts"]},{code:"invalid_improvement_metric",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_limit",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_timestamp",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_provenance_predicate",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"invalid_query_cursor",exit_code:2,stable:!0,sources:["sdk/pagination.ts","sdk/query/window-pagination.ts"]},{code:"invalid_read_output_session",exit_code:2,sources:["sdk/read-output-session.ts"]},{code:"invalid_reproducible_process_environment",exit_code:2,sources:["sdk/reproducibility/process.ts"]},{code:"invalid_workspace_snapshot_target",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"item_already_active",exit_code:4,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"item_already_exists",exit_code:4,stable:!0,sources:["sdk/lifecycle/create.ts"],emitting_commands:["create"]},{code:"item_deleted",exit_code:3,sources:["core/history/tombstone.ts"]},{code:"item_document_encoding_invalid",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_document_invalid",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_document_roundtrip_failed",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_format_version_unsupported",exit_code:4,sources:["core/item/item-format.ts"]},{code:"item_id_collision",exit_code:4,stable:!0,sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"]},{code:"item_identity_ambiguous",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_identity_conflict",exit_code:4,sources:["sdk/governance/validate-history-drift.ts","sdk/lifecycle/item-revision.ts","sdk/merge/three-way.ts","sdk/query/declared-blockers.ts"]},{code:"item_identity_reserved",exit_code:4,sources:["core/history/history.ts"]},{code:"item_not_found",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/item-store.ts","core/telemetry/observability.ts","sdk/governance/validate-history-drift.ts"]},{code:"item_revision_conflict",exit_code:4,sources:["core/store/item-mutation-precondition.ts"]},{code:"likely_duplicate",exit_code:4,stable:!0,sources:["sdk/similarity.ts"]},{code:"linked_artifact_mutation_conflict",exit_code:2,sources:["sdk/linked-artifacts.ts"]},{code:"linked_artifact_note_conflict",exit_code:4,sources:["sdk/linked-artifacts.ts"]},{code:"linked_artifact_note_key_misread",exit_code:2,sources:["sdk/linked-artifacts.ts"]},{code:"linked_resource_positional_value",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"linked_resource_value_list",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"linked_test_command_immutable",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_command_not_executable",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_context_invalid",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_patch_fields_unsupported",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_remove_no_match",exit_code:3,sources:["sdk/test/execution.ts"]},{code:"linked_test_update_ambiguous",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_update_no_match",exit_code:3,sources:["sdk/test/update.ts"]},{code:"linked_test_value_not_quoted",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"list_source_incomplete",exit_code:1,stable:!0,sources:["sdk/query/list.ts"],emitting_commands:["list"]},{code:"local_package_archive_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"local_source_not_found_bare_name",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"lock_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"]},{code:"lock_lost",exit_code:4,sources:["core/lock/lock.ts"]},{code:"lock_path_unsafe",exit_code:4,sources:["core/lock/lock-confinement.ts"]},{code:"locks_stale_count",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"locks_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"malformed_plan_step_evidence",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"managed_state_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"managed_state_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_capabilities_absent",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"manifest_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_unknown_key",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_declares_an_unknown_top_level_key",probe_id:"author-manifest-unknown-key",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"manifest_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"mcp_annotation_file_unavailable",exit_code:2,sources:["sdk/runtime-input.ts"]},{code:"mcp_stdin_unavailable",exit_code:2,sources:["sdk/annotations.ts"]},{code:"mcp_task_not_found_or_not_authorized",exit_code:3,sources:["sdk/mcp/tasks.ts"]},{code:"merge_artifacts_ignored",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_bun_launcher_unavailable",exit_code:5,sources:["sdk/merge/install.ts"]},{code:"merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/item/item-format.ts"],aliases:["history_merge_conflict_markers_detected"]},{code:"merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_driver_configuration_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_driver_configuration_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]}];var Y_=[{code:"merge_fence_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_fence_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_git_config_unwritable",exit_code:5,stable:!0,sources:["sdk/merge/install.ts"]},{code:"merge_receipt_evidence_invalid",exit_code:4,sources:["core/diagnostics/remediation.ts","sdk/merge/reconcile.ts"]},{code:"merge_receipt_history_reference_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_receipt_not_portable",exit_code:4,sources:["sdk/merge/receipts.ts"]},{code:"merge_receipts_pending",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_reconcile_receipt_evidence_untrusted",exit_code:4,sources:["sdk/history-repair.ts"]},{code:"merge_root_not_found",exit_code:3,stable:!0,sources:["sdk/merge/install.ts"]},{code:"merge_settlement_hook_conflict",exit_code:4,sources:["sdk/merge/settlement-hook.ts"]},{code:"merge_settlement_review_required",exit_code:4,sources:["sdk/merge/ignored-artifacts.ts","sdk/merge/reconcile.ts","sdk/merge/stage.ts"]},{code:"missing_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"missing_cli_flag",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_directory",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"missing_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_lifecycle_target",exit_code:2,stable:!0,sources:["sdk/extension.ts"]},{code:"missing_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"missing_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_parameter_alias",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_positive_execution_receipt",exit_code:1,sources:["sdk/test/execution.ts"]},{code:"missing_probe",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_required_argument",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","cli/schema/registration.ts","core/telemetry/observability.ts","sdk/governance/assurance-action.ts","sdk/history-redact.ts","sdk/invocation-author.ts","sdk/lifecycle/claim.ts","sdk/linked-artifacts.ts"],emitting_commands:["*","claim"]},{code:"missing_required_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/extension/command-options.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"]},{code:"missing_suggested_retry",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_suggested_retry_args",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"module_import_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"multi_target_github_install_ambiguous",exit_code:2,stable:!0,sources:["cli/register-setup.ts"]},{code:"mutation_author_required",exit_code:2,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"mutation_document_unreadable",exit_code:2,sources:["cli/register-structured-mutation.ts"]},{code:"mutation_option_value_invalid",exit_code:2,sources:["sdk/lifecycle/mutation-option-validation.ts"],emitting_commands:["item mutate"]},{code:"mutation_secret_guard_blocked",exit_code:4,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"no_matching_tests",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_projects_matched_filters",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_test_files_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_tests_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_update_fields",exit_code:1,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"no_version_bounds_declared",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_omits_canonical_pm_version_bounds",probe_id:"author-manifest-version-bounds-missing",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"non_refusal_exit",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"npm_pack_json_shape_unsupported",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_missing",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_unsafe",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_not_found",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"npm_source_shorthand_ambiguous",exit_code:2,sources:["sdk/extension/install-sources.ts"]},{code:"output_budget_exceeded",exit_code:2,sources:["sdk/testing.ts"]},{code:"ownership_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"]},{code:"ownership_dependency_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"ownership_metadata_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"package_spec_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"package_upgrade_modes_mutually_exclusive",exit_code:2,sources:["sdk/governance/upgrade.ts"]},{code:"positional_shape_budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"positional_signature_mismatch",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"profile_name_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_name_not_normalized",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_summary_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_title_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"project_runtime_history_epoch_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_item_format_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_mutation",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_read",exit_code:1,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_schema_field_requires_declared_flag",exit_code:2,sources:["core/extensions/item-fields.ts"]},{code:"projection_options_mutually_exclusive",exit_code:2,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"provenance_value_domain_invalid",exit_code:2,sources:["core/diagnostics/remediation.ts"]},{code:"read_output_cursor_command_mismatch",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_invalid",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_stale",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_mutation_conflict",exit_code:2,sources:["sdk/read-output-contracts.ts"]},{code:"read_output_surface_unsupported",exit_code:2,sources:["sdk/extension/static-inventory.ts","sdk/read-output-contracts.ts"]},{code:"recovery_kind_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"redundant_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"refusal_allowed_values_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_exit_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_mutated_state",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_probe_missing",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_recovery_failed",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"reindex_already_running",exit_code:4,stable:!0,sources:["sdk/governance/reindex.ts"]},{code:"removed_canonical_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"removed_compatibility_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"reopen_reason_required",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reopen_receipt_missing",exit_code:1,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"reopen_target_status_invalid",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reported_zero_passes",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reported_zero_tests",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reserved_item_field",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"retry_failed",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"schema_field_flag_invalid",exit_code:2,sources:["sdk/schema/field-option-collisions.ts"]},{code:"schema_field_option_collision",exit_code:2,sources:["sdk/schema/field-option-collisions.ts"]},{code:"schema_migration_input_required",exit_code:2,stable:!0,sources:["cli/migration-gates.ts"]},{code:"semantic_spelling_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"settings_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_read_fs_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_schema",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_merge_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_section_document_malformed",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_document_missing",exit_code:3,sources:["core/store/settings-sections.ts"]},{code:"settings_section_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_name_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_reserved",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_revision_conflict",exit_code:4,sources:["core/store/settings-sections.ts"]},{code:"settings_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_write_assigned_path_invalid",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_json",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_schema",exit_code:2,sources:["core/store/settings.ts"]},{code:"stale_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"stale_claim_takeover_refused",exit_code:4,sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"stale_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_in_progress_items",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"stale_lock_requires_override",exit_code:4,sources:["core/lock/lock.ts"]},{code:"stale_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_revision",exit_code:4,sources:["core/store/item-store.ts"]},{code:"start_blocked_by_open_dependency",exit_code:4,sources:["sdk/lifecycle/start-blockers.ts"],emitting_commands:["claim","start-task","update"]},{code:"status_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_lifecycle_role_required",exit_code:2,sources:["sdk/schema.ts"]},{code:"stdin_json_invalid",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"stdin_json_persisted_annotation_changed",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"stdin_json_unknown_key",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"structured_entry_key_repeated",exit_code:2,sources:["core/item/parse.ts"]},{code:"structured_event_immutable",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"structured_event_input_conflict",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_empty",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_since_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"suggested_retry_args_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"telemetry_endpoint_probe_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_endpoint_probe_http_status",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_otel_export_failing",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_high_retries",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_invalid_rows",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_pending",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_schema_version_behind",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_state_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"template_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"terminal_plan_mutation",exit_code:4,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"terminal_state_conflict",exit_code:4,stable:!0,sources:["core/telemetry/observability.ts","sdk/lifecycle/claim.ts"],emitting_commands:["*","claim"]},{code:"test_measure_requires_execution",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"test_measure_requires_run",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"text_unpaired_surrogate",exit_code:2,sources:["core/item/item-format.ts","core/shared/output-unicode.ts"]},{code:"tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_tracked_runtime_cache_files"]},{code:"tracker_not_initialized",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/tracker-preflight.ts","core/telemetry/observability.ts"],owned_states:[{state:"selected_tracker_root_exists_without_settings",probe_id:"tracker-root-settings-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_missing",exit_code:3,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_does_not_exist",probe_id:"tracker-root-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_not_directory",exit_code:2,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_a_regular_file",probe_id:"tracker-root-not-directory",entrypoints:["list"],expected_exit_class:"usage"}]},{code:"tracker_root_unreadable",exit_code:1,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_not_readable",probe_id:"tracker-root-unreadable",entrypoints:["list"],expected_exit_class:"generic_failure"}]},{code:"transaction_abandoned",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_committed",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_create_compensated",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_journal_invalid",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_partial_mutation",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_plan_mismatch",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_preview_external_schema",exit_code:2,sources:["sdk/item-transaction.ts"]},{code:"transaction_preview_non_regular_file",exit_code:2,sources:["core/fs/fs-utils.ts"]},{code:"transaction_preview_snapshot_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_recovery_plan_missing",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"type_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"type_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"undeclared_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"unexpected_refusal_probe",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"unknown_command",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"]},{code:"unknown_context_intent",exit_code:2,stable:!0,sources:["sdk/context-intent-contracts.ts"]},{code:"unknown_error",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"unknown_field",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_field_projection",exit_code:2,stable:!0,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"unknown_item_type",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_lifecycle_action",exit_code:2,stable:!0,sources:["sdk/agent/subcommand-recovery.ts"],canonical_code:"unknown_subcommand"},{code:"unknown_noun",exit_code:2,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"unknown_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/runtime/invocation-options.ts","core/telemetry/observability.ts","sdk/extension/command-options.ts"],owned_states:[{state:"declared_option_is_rejected_on_the_selected_command_path",probe_id:"cross-command-unknown-option",entrypoints:["deps"],expected_exit_class:"usage"}]},{code:"unknown_plan_template",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"unknown_provenance_dimension",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"unknown_status",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_subcommand",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","sdk/agent/subcommand-recovery.ts"],aliases:["unknown_lifecycle_action"],owned_states:[{state:"config_action_token_is_not_declared",probe_id:"config-unknown-action",entrypoints:["config"],expected_exit_class:"usage"},{state:"graph_command_token_is_not_declared",probe_id:"graph-unknown-subcommand",entrypoints:["graph"],expected_exit_class:"usage"},{state:"nested_command_token_is_not_declared_by_its_family",probe_id:"schema-unknown-subcommand",entrypoints:["schema"],expected_exit_class:"usage"},{state:"package_lifecycle_token_is_not_declared",probe_id:"package-unknown-action",entrypoints:["package"],expected_exit_class:"usage"}]},{code:"unsafe_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"unsupported_update_option",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"upsert_key_ambiguous",exit_code:4,sources:["sdk/structured-mutations.ts"]},{code:"upsert_key_conflict",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"upsert_key_duplicate",exit_code:2,sources:["sdk/item-transaction.ts","sdk/structured-mutations.ts"]},{code:"upsert_key_missing",exit_code:2,sources:["sdk/structured-mutations.ts"]},{code:"upsert_match_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"validate_command_references_stale_pm_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_missing_linked_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_orphaned_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_tracked_all_strict_forces_pm_internals",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_format_version_ahead_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_ahead_format_version"},{code:"validate_format_version_outdated_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_outdated_format_version"},{code:"validate_hierarchy_parent_cycle",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_hierarchy_parent_cycle_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_history_drift_chain_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_chain_mismatch"},{code:"validate_history_drift_hash_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_hash_mismatch"},{code:"validate_history_drift_missing_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_missing_stream"},{code:"validate_history_drift_unreadable_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_unreadable_stream"},{code:"validate_history_drift_version_skews",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_version_skew"},{code:"validate_history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_unknown_author_events"},{code:"validate_lifecycle_active_closure_like_metadata",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_active_terminal_parent",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_stale_blockers",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_driver_configuration",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_fence_drift",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_custom_profile_missing_required_fields",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_duplicate_issue_codes",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_acceptance_criteria",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_close_reason",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_closed_at",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_confidence",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_estimate",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_release",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_reviewer",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_risk",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_sprint",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_resolution_missing_fields",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_schema_field_option_collision",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_duplicate_item_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_history_conflict_markers",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_history_conflict_marker"},{code:"validate_storage_resurrected_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"tracked_runtime_cache_files"},{code:"validate_storage_unparseable_config",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unparseable_history",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unreadable_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_embedding_identity_changed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_stale_items_remaining",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"visible_surface_ceiling_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"workflow_duplicate_type",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_policy_approval_history_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_audit_failed",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_input_unreadable",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_invalid",exit_code:2,sources:["core/policy/workflow-policy.ts"]},{code:"workflow_policy_refused",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_registry_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_status_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_transition_malformed",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workspace_history_chain_invalid",exit_code:4,sources:["core/history/workspace-history.ts"]},{code:"workspace_history_state_conflict",exit_code:4,stable:!0,sources:["core/history/workspace-history.ts"]},{code:"workspace_root_pm_path",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"workspace_snapshot_force_required",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_manifest_mismatch",exit_code:4,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_name_reserved_fingerprint",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_not_found",exit_code:3,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_permission_denied",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_resource_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_storage_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"wrong_item_type",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]}];var X_=B_(H_([...V_,...Y_]));var dA=["mutation_receipt","entity","collection","diagnostic","stream"],lA=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),uA=new Set(["close-many","update-many"]),mA=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),pA=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function cr(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!dA.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function J_(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return uA.has(n)?cr({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):lA.has(n)?cr({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):mA.has(n)?cr({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):pA.has(n)?cr({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):cr({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var fA=We.map(e=>J_(e)),_A=new Map(fA.map(e=>[e.command,e]));function Q_(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=Ur(t).split(" "),r=_A.get(n);return r?{...r,command:t}:J_(t)}function hA(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gA(e){return hA(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function PD(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!gA(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}var Ea=[{exit_code:p.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:p.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:p.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:p.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:p.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:p.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:p.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:p.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],Z_=[p.SUCCESS,p.GENERIC_FAILURE,p.USAGE,p.NOT_FOUND,p.CONFLICT,p.DEPENDENCY_FAILED],yA=new Set(["close-many","update-many"]),th=We.map(e=>({command:e,exit_codes:yA.has(e)?[...Z_,p.NO_EFFECT,p.PARTIAL_EFFECT]:[...Z_]})),eh=new Map(th.map(e=>[e.command,e])),wA=[p.SUCCESS,p.NO_EFFECT,p.PARTIAL_EFFECT];function GD(e){return wA.includes(e)}function KD(e){return Ea.some(t=>t.exit_code===e)}function nh(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return eh.get(t)??eh.get(t.split(" ")[0])}function zD(e,t=We,n=th){let r=new Map(n.map(d=>[d.command,d])),i=t.filter(d=>!r.has(d)),s=e.filter(d=>{let l=r.get(d.command)??r.get(d.command.split(" ")[0]);return l===void 0||!l.exit_codes.includes(d.exit_code)}),o=new Set(e.map(d=>d.exit_code)),c=[...new Set(n.flatMap(d=>d.exit_codes))].filter(d=>!o.has(d)).sort((d,l)=>d-l);return{ok:i.length===0&&s.length===0&&c.length===0,missing_commands:i,undeclared_observations:s,unreachable_exit_codes:c}}function WD(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:p.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:p.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:p.PARTIAL_EFFECT}:{outcome:"effect",exit_code:p.SUCCESS}}var N=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},be=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Xe=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function bn(e){try{return await e()}catch(t){throw t instanceof N?new f(t.message,p.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Ra(e){try{return await e()}catch(t){throw t instanceof be?new f(t.message,p.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as vA}from"node:crypto";import kA from"node:path";var ih=1,st=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],dr=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],bA=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],SA=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Yi=30,Xi=5e3,sh=4,AA=50;function ot(e,t){if(!SA.test(e))throw new N(`${t} must be a stable lowercase id`)}function xA(e,t){if(!Number.isFinite(e)||e<0)throw new N(`${t} must be a finite non-negative number`)}function ur(e){let t=bA.filter(i=>e[i]!==void 0);if(t.length!==1)throw new N(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function Ia(e,t){return Z(e)===Z(t)}function oh(e,t){if(t.polarity==="equals")return Ia(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function ah(e){let t=ur(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>oh(r.observed,t)===(r.expected==="pass"))}function CA(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!Ia(e.value,t.value)}function EA(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||Z(e.scope)!==Z(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return CA(ur(e),ur(t))||n[t.enforcement]<n[e.enforcement]||r}function RA(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new N("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new N("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new N("items source equals/state requires field")}function TA(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new N("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(n=>n!==void 0).length>1)throw new N("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new N("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new N("dependency_kind source source_kind_state must be present or missing")}function IA(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new N("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new N("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new N("prose_edge_gap exemption selectors must not be empty")}}function Oa(e){ot(e.id,"measurement.id"),e.max_cost!==void 0&&xA(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new N(`measurement.source.kind must be one of ${dr.join(", ")}`);let n=Reflect.get(t,"kind");if(!dr.includes(n))throw new N(`measurement.source.kind must be one of ${dr.join(", ")}`);let r=t;if(r.kind==="items"&&RA(r),r.kind==="dependency_kind"&&TA(r),r.kind==="prose_edge_gap"&&IA(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new N(`${r.kind} source requires field`);return r.kind==="provider"&&(ot(r.provider,"provider source provider"),ot(r.key,"provider source key")),e}function $a(e){if(ot(e.id,"assertion.id"),ot(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new N("assertion.owner_item_id is required");let t=ur(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new N(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new N("retired assertion requires retire_reason");e.scope.kind==="filter"&&ot(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new N("assertion negative control requires pass and fail cases");if(!ah(e))throw new N(`assertion ${e.id} negative control does not prove its bound`);return e}function OA(e){if(!Array.isArray(e.allowed_providers))throw new N("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)ot(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new N("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!st.includes(t))throw new N(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new N(`gate provider policy trigger ${t} is invalid`)}}function ch(e){if(ot(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new N("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new N("gate requires at least one assertion");for(let t of e.assertion_ids)ot(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new N(`gate.triggers is required and must be an array of ${st.join(", ")}`);if(e.triggers.length===0)throw new N("gate requires at least one trigger");for(let t of e.triggers)if(!st.includes(t))throw new N(`gate trigger must be one of ${st.join(", ")}`);return e.provider_policy&&OA(e.provider_policy),e}function Sn(e){if(e.version!==ih)throw new N(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Oa(r),t.has(`measurement:${r.id}`))throw new N(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if($a(r),t.has(`assertion:${r.id}`))throw new N(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){ch(r);let i=r.assertion_ids.filter(s=>!e.assertions.some(o=>o.id===s));if(i.length>0)throw new N(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new N(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of dh(e))if(!n.has(r))throw new N(`${i.join(", ")} references missing measurement ${r}`);return e}function Na(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)Na(n,t)}function dh(e){let t=new Map,n=(r,i)=>{let s=t.get(r)??[];s.push(i),t.set(r,s)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];Na(r.source.expression,i);for(let s of i)n(s,`derived measurement ${r.id}`)}return t}function $A(e,t){let n=e.assertion_ids.flatMap(s=>{let o=t.assertions.find(a=>a.id===s);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let s=n.pop();if(r.has(s))continue;r.add(s);let o=t.measurements.find(a=>a.id===s);o.source.kind==="provider"?i.add(o.source.provider):o.source.kind==="derived"&&Na(o.source.expression,n)}return i}function mr(){return{version:ih,measurements:[],assertions:[],gates:[]}}function NA(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let s=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?s:!s}return Ia(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function LA(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function MA(e,t){let n=[],r=Wn(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let s of i.dependencies??[]){let o=Wn(s.kind)??s.kind.trim().toLowerCase(),a=s.source_kind?.trim();o===r&&LA(e,a)&&n.push(`${i.id}->${s.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function FA(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let s=Reflect.get(i,"text");typeof s=="string"&&t.push(s)}}}return t}function DA(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function Ta(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function PA(e){let t=new Map,n=new Set,r=[],i=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,s=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let a of o.dependencies??[])n.add(Ta(o.id,a.id));for(let a of[o.parent,o.blocked_by])typeof a=="string"&&n.add(Ta(o.id,a));for(let a of FA(o)){let c=[...a.matchAll(i)].map(d=>d[0]);s+=c.length,r.push({holder_id:o.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:s}}function UA(e,t){let n=PA(t.items),r=new Map;for(let o of n.prose_mentions){let a=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(a)];for(let d of c){let l=Ta(o.holder_id,d);if(n.linked_pairs.has(l)||DA(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],s=i.map(o=>o.contributor).sort();return{value:s.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:s.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(o=>o.explicit).length,implicit_subject:i.filter(o=>!o.explicit).length}}}function jA(e,t){return{value:t.history.filter(r=>(e.op===void 0||r.op===e.op)&&(e.author===void 0||r.author===e.author)&&(e.harness===void 0||r.agent_harness===e.harness)&&(e.model===void 0||r.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function qA(e,t){let n=t.items.filter(r=>{let i=r[e.link],s=Array.isArray(i)&&i.length>0;return e.state==="present"?s:!s});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function GA(e,t){let n=e.source;return n.kind==="items"?NA(n,t):n.kind==="dependency_kind"?MA(n,t):n.kind==="prose_edge_gap"?UA(n,t):n.kind==="history"?jA(n,t):n.kind==="links"?qA(n,t):null}function lh(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function KA(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function uh(e,t,n){let r=new Array(e.length),i=0,s=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o],o)}});return await Promise.all(s),r}async function mh(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await ph(o,t,n,r,i);if(typeof a.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=i.charged.has(o.id)?[]:[a.cost];return i.charged.add(o.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let s=await uh(e.operands,sh,o=>mh(o,t,n,r,i));return{value:KA(e.operator,s.map(o=>o.value)),costs:s.flatMap(o=>o.costs),population_size:Math.max(0,...s.map(o=>o.population_size)),contributors:[...new Set(s.flatMap(o=>o.contributors))]}}async function zA(e,t,n,r,i){Oa(e);let s=Date.now(),o,a=[],c=0;if(e.source.kind==="derived"){let u=await mh(e.source.expression,t,n,[...r,e.id],i);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=GA(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let d={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-s},l=lh([...a,d],Date.now()-s);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new be(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${vA("sha256").update(Z(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function ph(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let s=i.cache.get(e.id);if(s)return s;let o=zA(e,t,n,r,i).catch(a=>{if(a instanceof Xe&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},d=new Xe(a.message,c);throw d.cause=a,d}throw a});return i.cache.set(e.id,o),o}async function La(e,t,n=[e]){return ph(e,t,n,[],{cache:new Map,charged:new Set})}function WA(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity==="monotone_nondecreasing",e-t.value)}function BA(e,t,n={}){$a(e);let r=ur(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:WA(t.value,r),verdict:i?"retired":oh(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:ah(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function HA(e,t,n,r){let i=$A(e,t);if(i.size===0)return;let s=e.provider_policy,o=s?.triggers[r];if(!s||!o)throw new be(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let a=new Set(s.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!a.has(d))throw new be(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new be(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new be(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!o.allow_network)throw new be(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function rh(e,t,n,r,i){try{return await La(n,r,i)}catch(s){if(s instanceof Xe){let o=s.check?` check ${s.check}`:"",a=s.measurement_id??n.id,c=new be(`assurance gate ${e} assertion ${t} measurement ${a} source ${s.source_kind}${o} field ${s.field} could not resolve: ${s.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}});throw c.cause=s,c}throw s}}async function fh(e,t,n,r){Sn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new be(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new be(`assurance gate ${e} does not declare trigger ${r.trigger}`);HA(i,t,n,r.trigger);let s=await uh(i.assertion_ids,sh,async c=>{let d=t.assertions.find(h=>h.id===c),l=t.measurements.find(h=>h.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let h=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(g=>!h.has(g.status))}}else if(d.scope.kind==="filter"){let h=d.scope.measurement_id,g=t.measurements.find(v=>v.id===h),y=await rh(i.id,d.id,g,n,t.measurements),w=new Set(y.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(h=>h.id===d.owner_item_id),_=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return BA(d,await rh(i.id,d.id,l,u,t.measurements),{owner_terminal:_})}),o=s.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=s.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":a?"warn":"pass",exit_code:o?1:0,assertions:s,assertions_total:s.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:lh(s.map(c=>c.cost),Math.max(0,...s.map(c=>c.cost.duration_ms)))}}function Ji(e){return kA.join(e,"assurance.json")}async function _h(e){let t=await ee(Ji(e));return t===null?mr():Qi(t)}function Qi(e){try{return Sn(JSON.parse(e))}catch(t){throw new f("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",p.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function Zi(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function VA(e,t){e==="measurement"?Oa(t):e==="assertion"?$a(t):ch(t)}async function pr(e,t){let n=structuredClone(Zi(await _h(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function hh(e,t,n){let r=Zi(await _h(e),t).find(i=>i.id===n);if(!r)throw new be(`assurance ${t} ${n} not found`);return structuredClone(r)}async function es(e,t,n,r={}){VA(t,n);let i=await R(e),s=H(r.author,i.author_default),o=await dn({pmRoot:e,filePath:Ji(e),op:`assurance:${t}:put`,author:s,message:r.message,lockTtlSeconds:Yi,lockWaitMs:Xi,mutate:a=>{let c=a===null?mr():Qi(a),d=Zi(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&EA(d[l],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new N(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),Sn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
|
-
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function Ma(e,t,n={}){let r=mr();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),
|
|
4
|
-
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function
|
|
5
|
-
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function yh(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await R(e);await cn({pmRoot:e,op:"assurance:gate:verdict",author:H(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Yi,lockWaitMs:Xi})}async function wh(e,t={}){let n=t.limit??AA;if(!Number.isInteger(n)||n<1||n>1e3)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${1e3}`);return(await Lt(Ru(e),Mt)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}var YA=na("list").properties.outputSession,XA={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:{...YA},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},vh={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."}},kh={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},oe={type:"string",description:"pm item id, for example pm-abc1."},JA=`Operation name (one of): ${_o.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,QA={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."}},ZA={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 G(e,t=[]){return{...kh,properties:{...kh.properties,...e},required:t}}var ex=[{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:G({action:{type:"string",enum:[..._o],description:JA},id:oe,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...XA},["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:G({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:G({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:G({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:G({query:{type:"string"},options:{type:"object"},...ZA},["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:G({options:{type:"object"},...QA})},{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:G({id:oe,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:G({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:G({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:G({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:oe,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},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:G({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:G({id:oe,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:G({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:oe,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:G({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:G({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:oe,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:'List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls 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:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:G({subcommand:{type:"string",enum:[...Hd]},id:oe,target:oe,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:G({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:G({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:G({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:G({...vh,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",...jd],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:[...yo]},description:`Lifecycle roles for add-status: ${yo.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:vh}},["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:G({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:G({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:G({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."}})}],tx={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"},nx=ex.map(e=>{let t=tx[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:na(t,{properties:n,required:r})}});function bh(){return nx.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,i)=>r.localeCompare(i)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}var Sh=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"]]]),rx=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Nh=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ns=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"]),Gt=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"]),Lh=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"]]),Mh=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"]]),Fh=new Map([...Mh.entries()].flatMap(([e,t])=>at(t).map(n=>[n,e]))),Dh=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Pa=new Map(Dh.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),ix=10,sx=20,Ah=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."]]),Ph=[["init",qm],["install",Km],["uninstall",zm],["explore",Wm],["inventory",Yn],["manage",Jm],["describe",Bm],["reload",Qm],["doctor",Zm],["catalog",ep],["adopt",tp],["adopt-all",Hm],["activate",Vm],["deactivate",Ym],["migrate",Xm]],ox=[...Ph.map(([e,t])=>e==="init"?[e,Gm]:[e,t]),["upgrade",Ho]],ax=[...Ph.map(([e,t])=>[`extension ${e}`,t]),...ox.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["package list",Yn],["packages list",Yn],["extension list",Yn],["init",Pm],["config",Um],["extension",jm],["package",Bo],["packages",Bo],["install",np],["create",Ap],["item mutate",xp],["item complete",Cp],["item reopen",Ep],["copy",Rp],["focus",Tp],["update",Ip],["update-many",Op],["upgrade",Ho],["calendar",Vo],["cal",Vo],["context",Yo],["ctx",Yo],["get",Lp],["search",jp],["eval",Pp],["events",Np],["workspace",vt],["workspace position",[]],["workspace snapshot",vt],["workspace snapshot create",vt],["workspace snapshot list",vt],["workspace snapshot inspect",vt],["workspace snapshot restore",vt],["workspace snapshot delete",vt],["next",Up],["aggregate",bm],["deps",Fp],["graph",Dp],["guide",Mp],["reindex",rp],["history",Rm],["history-compact",Nm],["history-attest",Lm],["history-redact",Im],["history-repair",Om],["history-author-acknowledge",$m],["merge",Tm],["schema",Mm],["profile",Fm],["plan",Dm],["restore",cp],["delete",dp],["close",ip],["close-many",sp],["append",op],["claim",ap],["release",lp],["start-task",up],["pause-task",mp],["close-task",pp],["comments",Sm],["notes",Am],["learnings",xm],["files",Cm],["docs",Em],["test",fp],["test-runs-worker",[]],["test-all",_p],["telemetry",hp],["test-runs",gp],["gc",yp],["stats",wp],["ops",[]],["duplicates",vp],["validate",bp],["health",kp],["assurance",Sp],...Kp,["contracts",qp],["completion",Gp],["activity",$p],...[...Nh].map(e=>[e,km])],fr=new Map(ax);for(let{alias:e,canonical:t}of ze){let n=fr.get(e);n!==void 0&&fr.set(t,n)}function cx(e){let t=Fh.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function xh(e){let t=ze.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:We.includes(e)?pe(e):e.startsWith("extension-")?pe(`extension ${e.slice(10)}`):e.startsWith("package-")?pe(`package ${e.slice(8)}`):e.startsWith("item-")?pe(`item ${e.slice(5)}`):e.startsWith("test-runs-")?pe(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?pe(`templates ${e.slice(10)}`):ns.has(e)?Mh.get(e)??pe(e):null}function dx(e,t){let n=j(t);return n!==t||ze.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:at(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function at(e){return e.split("|").map(t=>pe(t)).filter(t=>t.length>0)}function lx(e,t){let n=new Set(t),r=new Set;for(let i of e)if(i.command_path)for(let s of at(i.command_path)){let o=s.split(" ").filter(a=>a.length>0);if(o.length!==0)for(let a=o.length;a>0;a-=1){let c=o.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((i,s)=>i.localeCompare(s))}function ts(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function _r(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function ux(e,t){if(!t)return{...e};let r=_r(e).filter(i=>{let s=i.properties;if(typeof s!="object"||s===null)return!1;let o=s.action;return typeof o!="object"||o===null?!1:o.const===t});return{...e,oneOf:r}}function Fa(e,t){let r=_r(e).filter(i=>{let s=i.properties;if(typeof s!="object"||s===null)return!1;let o=s.action;if(typeof o!="object"||o===null)return!1;let a=o.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function pe(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Uh(e){return e.replace(/\s+/g,"-")}function bt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ch(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let i=bt(r);!i||n.has(i)||(n.add(i),t.push(i))}return t}function Da(e,t,n){n&&(e[t]=!0)}function Eh(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?Ot(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function mx(e){let t=Eh(e.long,"long"),n=Eh(e.short,"short"),r=t??n;if(!r)return null;let i={flag:r};n&&t&&(i.short=n),Da(i,"required",e.required===!0),Da(i,"repeatable",e.repeatable===!0),Da(i,"list",e.list===!0),e.default!==void 0&&(i.default=e.default);let s=bt(e.description);s&&(i.description=s);let o=on(e);i.value_arity=o.value_arity;let a=bt(e.value_name)??o.value_name;a&&(i.value_name=a);let c=o.value_type??(o.value_name?"string":null);return c&&(i.value_type=c),i}function jh(e){let t=new Map;for(let r of e){let i=pe(r.target_command);if(i.length===0)continue;let s=t.get(i)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},o=`${r.layer}:${r.name}`;s.sourceDedupe.has(o)||(s.sourceDedupe.add(o),s.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=mx(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;s.dedupe.has(d)||(s.dedupe.add(d),s.flags.push(c))}t.set(i,s)}let n=new Map;for(let[r,i]of t.entries())n.set(r,{flags:i.flags,sources:i.sources.sort((s,o)=>{let a=s.layer.localeCompare(o.layer);return a!==0?a:(s.name??"").localeCompare(o.name??"")})});return n}function px(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...Wo.filter(({flag:n})=>n.startsWith("--output-"))]}}function fx(e){let t=jh(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let o=pe(s.command);if(o.length===0)continue;let a=bt(s.action)??Uh(o),c=Array.isArray(s.arguments)?s.arguments.map(d=>{let l=bt(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:bt(d.description)}:null}).filter(d=>d!==null):[];n.set(o,{...s.tier===void 0?{}:{tier:s.tier},...px(s,t.get(o)?.flags??[]),command:o,action:a,source:{layer:s.layer,name:s.name},description:bt(s.description),intent:bt(s.intent),arguments:c,examples:Ch(s.examples),failure_hints:Ch(s.failure_hints)})}let r=new Set;for(let s of e.handlers)r.add(pe(s));for(let s of n.keys())r.add(s);for(let s of t.keys())r.add(s);let i=[];for(let s of[...r].sort((o,a)=>o.localeCompare(a))){let o=n.get(s);i.push(_x(s,o,t.get(s)?.flags??[]))}return i}function _x(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Uh(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function hx(e){let t=e.flag.startsWith("--")?e.flag:void 0,n=Sa({long:t,short:t===void 0?e.flag:void 0});return n!==null&&/[a-z0-9]/iu.test(n)?n:null}function gx(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function yx(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",i=e.repeatable===!0||e.list===!0;return{type:i?"array":r,...i?{items:{type:r}}:{},...e.default!==void 0?{default:e.default}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function wx(e){let t=e.command.split("|").map(i=>i.trim()).filter(i=>i.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let i of e.arguments)n[i.name]=gx(i,e.action),i.required&&r.push(i.name);for(let i of e.flags){let s=hx(i);!s||n[s]!==void 0||(n[s]=Wo.some(o=>o.flag===i.flag&&o.flag.startsWith("--output-"))?lf[s]:yx(i,e.action),i.required===!0&&r.push(s))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function vx(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 kx(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((s,o)=>s.localeCompare(o)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let i=new Set(r.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let o=`${s.flag}|${s.short??""}`;if(!i.has(o))i.add(o),r.flags.push(s);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===o);a&&vx(a,s)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function bx(e,t=R){let n={mode:Et.extensions.policy.mode,trust_mode:Et.extensions.policy.trust_mode,default_sandbox_profile:Et.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=I(process.cwd(),e.path);if(!await me(sn(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let i=await t(r),s=await _i({pmRoot:r,settings:i,cwd:process.cwd(),noExtensions:!1}),o=await hi({...s,loaded:s.loaded});return{handlers:new Set(o.commands.handlers.map(c=>pe(c.command))),disabledReason:null,commandDefinitions:o.registrations.commands,flagRegistrations:o.registrations.flags,registrations:o.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function Sx(e,t={}){let n=new Map;for(let r of Vd){let i=ns.has(r);if(i&&!t.includePackageOwnedActions)continue;let s=xh(r);n.set(r,{action:r,provider:i?"extension":"core",requires_extension:i,command_path:s})}if(t.includePackageOwnedActions)for(let r of ns)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:xh(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ze.find(i=>i.alias===r.command)?.canonical??pe(r.command)});return[...n.values()].sort((r,i)=>(r.action??"").localeCompare(i.action??""))}function Ax(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&&(!Gt.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?at(e.command_path):[],r=n.some(o=>t.handlers.has(o)||t.handlers.has(j(o))),i=n.map(o=>Lh.get(j(o))).find(o=>typeof o=="string"),s=t.disabledReason===null&&r;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(i?`optional_package_not_installed:${i}`:"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 qh(e){let t=fr.get(e)??Ri,n=Xn(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function xx(e){return Gt.has(j(e))?!1:fr.has(e)}function Cx(e){return Nh.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Rh(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function Ex(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function Rx(e){let t=new Map;for(let r of e.definitions){let i=Rh(r.cli_flag);if(!i)continue;let s=r.cli_aliases.map(a=>Ex(a)).find(a=>a!==null),o=r.cli_aliases.map(a=>Rh(a)).filter(a=>a!==null&&a!==i);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},d=s?{flag:i,short:s}:{flag:i},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of o){let m=`${u}|`;c.seen.has(m)||(c.seen.add(m),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[r,i]of t.entries())n.set(r,zo(i.flags));return n}function Th(e,t){let n=[],r=new Set;for(let i of[...e,...t]){let s=`${i.flag}|${i.short??""}`;r.has(s)||(r.add(s),n.push(i))}return zo(n)}function Tx(e){let t=Sa(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function Ix(e,t,n,r){let i=(n??[]).map(Tx),s=t==="extension"&&(n!==void 0||Ox(e,r));return{flags:i,inherited:s?{inherited_flags:vm({readOutput:$x(e,r)})}:{}}}function Gh(e,t){let n=j(e);return t.find(r=>j(r.command)===n)}function Ox(e,t){return Gh(e,t)!==void 0}function $x(e,t){return Gh(e,t)?.read_output!==void 0}function Nx(e,t,n,r,i){let s=new Map(t);for(let{alias:o,canonical:a}of ze){let c=t.get(a)??t.get(o);c&&(s.set(o,c),s.set(a,c))}return e.map(o=>{let a=xx(o),c=a?qh(o):[],d=n.get(Cx(o))??[],l=s.get(o),u=Th(c,d),m=c.length>0&&(l?.flags.length??0)>0?"mixed":a?"core":"extension",_=Ix(o,m,l?.flags,i),h=Th(u,_.flags);return{command:o,flags:h,..._.inherited,...r?{canonical_command:zh(o),visibility:Kh(o,i),positionals:gm(o)?.slots??[],flag_invocations:c_(o,h)}:{},provider:m,extension_sources:l?.sources}}).sort((o,a)=>o.command.localeCompare(a.command))}function Lx(e,t=Rt){let n=new Set(e),r=new Map;for(let i of Dh){let s=i.aliases.filter(o=>n.has(o));r.set(i.canonical,{canonical:i.canonical,aliases:s,contracts:[]})}for(let i of t){if(!n.has(i.canonical)||i.registration==="commander"&&!n.has(i.alias))continue;let s=r.get(i.canonical)??{canonical:i.canonical,aliases:[],contracts:[]};s.aliases.includes(i.alias)||s.aliases.push(i.alias),s.contracts.push(i),r.set(i.canonical,s)}return[...r.values()].map(({contracts:i,...s})=>i.length===0?s:{...s,contracts:i}).sort((i,s)=>i.canonical.localeCompare(s.canonical))}function Mx(){return{create_string_options:Zp,create_repeatable_options:ef,update_string_options:tf,update_repeatable_options:nf,list_string_options:Vp,search_string_options:Yp,calendar_string_options:Xp,context_string_options:Jp,activity_string_options:Qp}}function Ih(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=rn(e,"create",n),i=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(i.map(a=>ve("create",a)))].sort((a,c)=>a.localeCompare(c)),o=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:i,required_flags:s,required_type_options:o,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function Fx(e){let t={},n={};for(let r of[...e.types].sort((i,s)=>i.localeCompare(s))){let i=e.by_type[r];t[r]=Ih(i,"strict"),n[r]=Ih(i,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Dx(e,t){let n=_r(e);if(n.length===0)return e;let r=!1,i=n.map(s=>{let o=s.properties;if(typeof o!="object"||o===null)return s;let a=o.action;return typeof a!="object"||a===null||a.const!=="create"?s:(r=!0,{...s,"x-create-required-options":t})});return r?{...e,oneOf:i}:e}function Px(e){let t=ts(e.action)!==void 0||ts(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,i=e.schemaOnly===!0,s=e.flagsOnly===!0,o=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=ts(e.action),l=ts(e.command),u=!r&&!c&&!i&&!s&&!o&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:r,schemaOnly:i,flagsOnly:s,availabilityOnly:o,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function Ux(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new f("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",p.USAGE)}async function jx(e,t=R){try{return await t(e)}catch{return structuredClone(Et)}}async function qx(e,t,n){let r=await jx(t),i=await bx(e),s=F(r,i.registrations??M()),o=$t(r.schema),a=fx(i);return{settings:r,runtimeProbe:i,typeRegistry:s,statusRegistry:q(r.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:Rx(o),createRequiredOptionContracts:Fx(s),extensionContracts:a,mergedExtensionContracts:kx(a.filter(c=>rs(n,c.command,a))),extensionFlagMap:jh(i.flagRegistrations)}}function Oh(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ns.has(e.selectedAction)||e.selectedCommand!==void 0&&Gt.has(j(e.selectedCommand)))}function Gx(e,t){let n=Sx(t,{includePackageOwnedActions:Oh(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Yd);return n.filter(i=>!r.has(i.action)&&(e.fullOutput||(t.find(s=>s.action===i.action)?.tier??xa(i.action))!=="internal"))}return Oh(e)&&e.selectedCommand!==void 0&&Gt.has(j(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:cx(j(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function Kx(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new f(`Unknown action: "${e.selectedAction}".`,p.USAGE)}function zx(e,t){return[...new Set([...We.filter(n=>!Gt.has(j(n))),...[...fr.keys()].filter(n=>!Gt.has(j(n))),...e.flatMap(n=>n.command_path?at(n.command_path).filter(r=>n.provider==="extension"||!Gt.has(j(r))||t.some(i=>i.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let i=ze.find(s=>s.alias===r||s.canonical===r);return i===void 0?[r]:[i.alias,i.canonical]}))])].map(n=>pe(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function Wx(e,t){let n=t.slice(0,ix),r=t.length-n.length,i=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),s=t.slice(0,sx),o=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new f(`Command "${e}" is a command namespace. Choose a concrete child command: ${i}.`,p.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:o,nextSteps:[`Retry with a child command, for example: ${o[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function Bx(e,t){return new f(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm package install ${t} --project" and retry.`,p.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 Hx(e){return new f(`Unknown command: "${e}".`,p.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 Vx(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(s=>s.startsWith(`${e.selectedCommand} `));if(r.length>0)throw Wx(e.selectedCommand,r);let i=Lh.get(j(e.selectedCommand));throw i?Bx(e.selectedCommand,i):Hx(e.selectedCommand)}function Yx(e,t){let n=Gx(e,t.mergedExtensionContracts);Kx(e,n);let r=zx(n,t.mergedExtensionContracts);Vx(e,r);let i=e.selectedCommand?Fh.get(j(e.selectedCommand)):void 0,s=e.selectedCommand?n.filter(d=>i?d.action===i:dx(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.some(d=>d.action===e.selectedAction))throw new f(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,p.USAGE);let o=e.selectedAction?s.filter(d=>d.action===e.selectedAction):s,a=[...new Map(o.map(d=>Ax(d,t.runtimeProbe)).map(d=>[i?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:s,scopedActionDescriptors:o,selectedPackageOwnedAction:i,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function Xx(e){return new Set(_r(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 i=r.const;return typeof i=="string"?i:null}).filter(t=>t!==null))}function Jx(e){let t=uf,n=_r(t),r=Xx(t),i=e.filter(s=>!r.has(s.action)).map(s=>wx(s));return i.length>0?{...t,oneOf:[...n,...i]}:t}function $h(e,t,n){let r=new Set(t.actionDescriptors.map(s=>s.action)),i=e.selectedAction?ux(n,e.selectedAction):e.selectedCommand?Fa(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):Fa(n,r);return e.runtimeOnly&&!e.selectedAction?Fa(i,new Set(t.actions)):i}function Qx(e,t,n){let r=Jx(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?Dx($h(e,n,r),t.createRequiredOptionContracts):$h(e,n,r);return{mergedSchema:r,filteredSchema:s}}function Zx(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?lx(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Kh(e,t){return t.find(n=>j(n.command)===j(e))?.tier??xa(e)}function rs(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||Kh(t,n)!=="internal"}function eC(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(Rt.filter(i=>i.hidden&&(i.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(i=>i.alias));if(e.summary&&!e.fullOutput)for(let i of Pa.keys())r.add(i);return t.filter(i=>!r.has(i)&&rs(e,i,n))}function zh(e){let t=ze.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Pa.get(n)??n}var tC=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"]]),nC=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function rC(e,t){let n=Ah.get(j(e))??(e.includes(" ")?void 0:Ah.get(zh(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>at(d.command).some(l=>j(l)===j(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 i=e.split(" "),s=i.at(-1),o=i.slice(0,-1).join(" "),a=tC.get(s),c=nC.get(e)??o;return{intent:a===void 0||o.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function iC(e,t=[],n={}){let r=n.includeFormatBudgets??!0,i=n.includeIntentProvenance??!0;return[...new Set(e.map(pe))].filter(s=>s.length>0).sort((s,o)=>s.localeCompare(o)).map(s=>{let o=Mo(s,{generateFallback:!0}),a=s.split(" ")[0],c=Pa.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...qh(s).map(m=>m.flag),...t.filter(m=>at(m.command).some(_=>j(_)===j(s))).flatMap(m=>m.flags.map(_=>_.flag))]),l=(Sh.get(j(s))??Sh.get(c)??rx).filter(m=>d.has(m)),u=rC(s,t);return{command:s,intent:u.intent,...i||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:o.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...o.default_max_estimated_tokens_by_format}}:{}}})}function sC(e){return e.map(t=>({budget:Mo(t,{generateFallback:!0}),envelope:Q_(t)}))}function oC(e){let t=new Map;for(let n of e){let r=nh(n),i=r===void 0?[p.SUCCESS,p.GENERIC_FAILURE,p.USAGE,p.NOT_FOUND,p.CONFLICT,p.DEPENDENCY_FAILED]:r.exit_codes,s=i.join(","),o=t.get(s)??{commands:[],exit_codes:i};o.commands.push(n),t.set(s,o)}return[...t.values()]}function aC(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>at(r.command).some(i=>j(i)===j(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(i=>at(i.command).some(s=>r.has(s)))}return t.extensionContracts.filter(r=>rs(e,r.command,t.extensionContracts))}function cC(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 dC(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=Tl);let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(i=>i.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(([i])=>r===void 0||i===r).map(([i,s])=>[i,[...new Set(s.map(o=>`--${o.cli_flag}`))].sort((o,a)=>o.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...qd],services:[...Gd],policy_modes:[...Kd],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Bd],trust_modes:[...zd],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Wd],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...rl],create_modes:[...il],close_validation_modes:[...sl],workflow_enforcement_modes:[...ol]},e.relationship_kind_contracts=[..._u,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(i=>i.definitions)].sort((i,s)=>i.kind.localeCompare(s.kind)).map(i=>({canonical:i.kind,aliases:[...i.aliases??[]],...i.inverse===void 0?{}:{inverse:i.inverse},ordering:i.ordering,hierarchy:i.hierarchy})))}function lC(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 uC(e,t,n,r,i){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=Nx(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let s=new Set(r);e.list_projections=Object.entries(hm).filter(([o])=>s.has(o)).map(([o,a])=>({command:o,default:a,brief_fields:[..._m,"priority"],compact_fields:[...fm]}))}e.command_aliases=t.fullOutput?i:i.map(({canonical:s,aliases:o})=>({canonical:s,aliases:o})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function mC(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=Mx();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function pC(e,t,n,r){e.command_summaries=iC(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...iu],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(pe))].filter(i=>au(i)!==void 0).sort((i,s)=>i.localeCompare(s)).map(i=>({command:i,modes:[...cu(i).keys()]}))}:{}},e.grammar_contracts={nouns:Pt.nouns,shared_verbs:Pt.shared_verbs,scope_before_verb:Pt.scope_before_verb,visible_top_level_ceiling:Pt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Pt.ceiling_raise_requires_pm_item,positional_shape_budget:Pt.positional_shape_budget,positional_shape_count:new Set(Ko.map(({slots:i})=>wm(i))).size,positional_action_count:Go.length,positional_action_parents:[...new Set(Go.map(({parent:i})=>i))].sort((i,s)=>i.localeCompare(s)),...r.includePositionalSignatures?{positional_signatures:Ko}:{}}}async function IP(e,t){let n=Px(e);Ux(n);let r=I(process.cwd(),t.path),i=await qx(t,r,n),s=Yx(n,i),o=Qx(n,i,s),a=Zx(n,s),c=eC(n,a,i.extensionContracts),d=cC(n,o,s,c),l=aC(n,i,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&pC(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return d;let m=Lx(s.commandCatalog.filter(_=>rs(n,_,i.extensionContracts)));return n.flagsOnly&&!n.fullOutput||dC(d,i,n),lC(d,n,o,l),uC(d,n,i,c,m),mC(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...dr],gate_triggers:[...st]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=ym.map(_=>({..._,reason:_.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=bh(),d.context_intents=du(),d.read_output_dimensions=ou,d.error_codes=X_,d.command_output_contracts=sC(c),d.diagnostic_output_contracts=su,d.command_exit_contracts={vocabulary:Ea,command_sets:oC(c)}),d}import{createHash as Bh}from"node:crypto";import hr from"node:fs/promises";import gr from"node:path";function Oe(e,t){throw new f(e,p.USAGE,t)}var fC="2026-07-15T06:22:12.276Z",_C=Date.parse(fC),hC=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Wh=e=>typeof e=="string"?e:"",Hh=e=>{let t=e??{},n=Wh(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Wh(t.ts))>=_C);return hC[r][i]};function Vh(e,t,n=20,r=new Set,i=!1){let s=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,_]of t.split(/\r?\n/).entries()){let h;try{h=JSON.parse(_)}catch{continue}d+=1;let g=Hh(h);if(g!=="attributed"){if(l+=1,g==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}a[g]+=1,i&&g==="actionable_unknown"&&o.push({item_id:e,line:m+1}),s.length<c&&s.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:s,samples_truncated:a.legacy_unknown+a.actionable_unknown>s.length,actionable_events:o}}var jP=(e,t,n=20,r=new Set)=>Vh(e,t,n,r);function Yh(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let s=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof s!="object"||s===null||!Array.isArray(s.events)))for(let o of s.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var yr=async(e,t=20,n=!1)=>{let r=gr.join(e,"history"),i;try{i=(await hr.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let s=new Set,o=[],a=[],c=0,d=0,l=0,u=0,m=0,_=0,h="_workspace.jsonl",g=new Set;if(i.includes(h))try{g=Yh(await hr.readFile(gr.join(r,h),"utf8"))}catch{g=new Set}for(let w of i){let v;try{v=await hr.readFile(gr.join(r,w),"utf8")}catch{continue}let k=w.slice(0,-6),b=Vh(k,v,t-o.length,g,n);c+=1,d+=b.checked_events,l+=b.unknown_event_count,u+=b.legacy_unknown_event_count,m+=b.actionable_unknown_event_count,_+=b.acknowledged_actionable_event_count,b.unknown_event_count>0&&s.add(k),o.push(...b.samples),n&&a.push(...b.actionable_events)}let y=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:_,affected_item_ids:[...s].sort((w,v)=>w.localeCompare(v)),samples:o,samples_truncated:y>o.length,...n?{actionable_events:a}:{}}};function gC(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function yC(e){try{return Yh(await hr.readFile(gr.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function wC(e){return(e.item_id===Mt||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function vC(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Oe(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Hh(i)!=="actionable_unknown"&&Oe(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:Bh("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Xh(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Oe("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Oe("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Oe("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let s=gC(t.all_actionable===!0?(await yr(e,0,!0)).actionable_events:r),o=await yC(e),a=new Map;for(let m of s)if(wC(m)||Oe(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(m.item_id))try{a.set(m.item_id,(await hr.readFile(gr.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Oe(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=s.map(m=>vC(m,o,a.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Bh("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function qP(e,t,n=50){return(await Xh(e,t,n)).plan}function kC(e,t){let n=e.length>0;return n&&t&&Oe("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&Oe("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:bC(e),all_actionable:t}}function bC(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),s=r===Mt||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!s||!Number.isSafeInteger(i)||i<1)&&Oe(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function GP(e,t){let n=kC(hf(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return SC(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:X(t,"planFingerprint")??X(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:X(t,"attributedAuthor")??X(t,"attributed_author")??void 0,reviewer:X(t,"reviewer"),reason:X(t,"reason")})}async function SC(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",s=await Xh(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:p.SUCCESS,plan:s.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Oe("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Oe("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==s.plan.plan_fingerprint)throw new f("Author acknowledgment selection changed after preview; no history was mutated.",p.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let a=s.completeCoordinates.filter(({disposition:u})=>s.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:m})=>({item_id:u,line:m}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:p.NO_EFFECT,plan:s.plan};let c=await R(e),d=await cn({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:r}},message:i,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),l=s.plan.actionable_count>0&&s.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:p.PARTIAL_EFFECT}:{outcome:"effect",exit_code:p.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...l,plan:s.plan,history_path:d.historyPath}}async function Jh(e,t,n){let r=await Pi(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Ui(r,"docs")}var is=1e6;function Ua(e,t=is,n=.8,r=!1){let i=new Set,s=(l,u)=>{if(i.add(`${l}:${u}`),i.size>t)throw new f(`Duplicate sweep exceeded ${t} candidate pairs; narrow it with statuses or since.`,p.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the duplicate query or increase its similarity threshold. No partial result was returned."})};if(r||n===0){for(let l=0;l<e.length;l+=1)for(let u=0;u<l;u+=1)s(u,l);return i}let o=new Map;for(let{prepared:l}of e)for(let u of l.tokens)o.set(u,(o.get(u)??0)+1);let a=new Map,c=new Map,d=new Map;for(let[l,{prepared:u}]of e.entries()){let m=[...u.tokens].sort((g,y)=>o.get(g)-o.get(y)||g.localeCompare(y)),_=m.length-Math.ceil(n*m.length-1e-12)+1,h=[{index:a,keys:[u.normalized],lengthFilter:!1},{index:c,keys:n<=.99?u.issueCodes:[],lengthFilter:!1},{index:d,keys:m.length===0?[""]:m.slice(0,_),lengthFilter:!0}];for(let g of h)AC(e,l,g,n,s)}return i}function AC(e,t,n,r,i){let s=e[t].prepared.tokens.length;for(let o of n.keys){let a=n.index.get(o)??[];for(let c of a){let d=e[c].prepared.tokens.length;n.lengthFilter&&Math.min(d,s)/Math.max(d,s)+1e-12<r||i(c,t)}a.push(t),n.index.set(o,a)}}var xC=3,Qh=20,CC=.8,EC=100,Zh=1e3;function eg(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`,`likely_duplicate_recovery:${e.recovery.action}:${e.recovery.item_id}`]}async function RC(e,t){let n=e.items[0],r=I(t.cwd??process.cwd(),t.pmRoot),i=q((await R(r)).schema);return ae(n.status,i)?{action:"reopen",item_id:n.id,command:`pm item reopen ${n.id} "<recurrence reason>"`,args:["item","reopen",n.id,"<recurrence reason>"]}:{action:"reuse",item_id:n.id,command:`pm get ${n.id} --full`,args:["get",n.id,"--full"]}}function ja(e){let t=e.limit??xC,n=e.threshold??CC;if(!Number.isSafeInteger(t)||t<0||t>Qh)throw new f(`Similarity limit must be an integer from 0 to ${Qh}.`,p.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new f("Similarity threshold must be a number from 0 to 1.",p.USAGE);return{limit:t,threshold:n}}function tg(e){let t=e.limit??EC;if(!Number.isSafeInteger(t)||t<0||t>Zh)throw new f(`Duplicate cluster limit must be an integer from 0 to ${Zh}.`,p.USAGE);let n=e.since===void 0?void 0:new Date(e.since);if(n&&Number.isNaN(n.getTime()))throw new f("Duplicate cluster --since must be a valid ISO timestamp.",p.USAGE);return{limit:t,since:n}}async function TC(e,t){let n=I(e.cwd??process.cwd(),e.pmRoot),r=await R(n),i=F(r),s=e.statuses?.map(u=>u.trim().toLowerCase()).filter(Boolean);if(e.statuses!==void 0&&s?.length===0)throw new f("Duplicate cluster statuses must include at least one lifecycle status or all.",p.USAGE);let o=q(r.schema),a=s?.map(u=>{if(u==="all")return u;let m=re(u,o);if(!m)throw new f(`Unknown duplicate-cluster status "${u}". Allowed: all, ${o.definitions.map(_=>_.id).join(", ")}.`,p.USAGE);return m}),c=a?.includes("all")===!0;if(c&&a?.some(u=>u!=="all"))throw new f('The "all" status cannot be combined with other statuses.',p.USAGE);let d=c?void 0:a,l=d?new Set(d):void 0;return{items:(await he(n,r.item_format,i.type_to_folder,void 0,r.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())),statuses:d}}var dU={buildDuplicateClusters:rg,collectDuplicateCandidatePairs:Ua,createDuplicateUnionFind:ng};function ng(e){let t=Array.from({length:e},(r,i)=>i);return{parent:t,findRoot:r=>{let i=r;for(;t[i]!==i;)i=t[i];for(;t[r]!==r;){let s=t[r];t[r]=i,r=s}return i}}}function IC(e,t,n,r){let i=[];for(let s of t){let[o,a]=s.split(":").map(u=>Number.parseInt(u,10)),c=qo(e[o].prepared,e[a].prepared);if(c.score<n)continue;let d=r.findRoot(o),l=r.findRoot(a);d!==l&&(r.parent[l]=d),i.push({left_id:e[o].item.id,right_id:e[a].item.id,...c})}return i}function rg(e,t,n,r){let i=new Map;for(let a of e.keys()){let c=n.findRoot(a),d=i.get(c)??[];d.push(a),i.set(c,d)}let s=new Map(e.map(({item:a},c)=>[a.id,n.findRoot(c)])),o=new Map;for(let a of t){let c=s.get(a.left_id),d=o.get(c)??[];d.push(a),o.set(c,d)}return[...i.values()].filter(a=>a.length>1).map(a=>{let c=(o.get(n.findRoot(a[0]))??[]).sort((d,l)=>l.score-d.score||d.left_id.localeCompare(l.left_id)||d.right_id.localeCompare(l.right_id));return{id:e[a[0]].item.id,items:a.map(d=>{let l=e[d].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((a,c)=>c.max_score-a.max_score||a.id.localeCompare(c.id)).slice(0,r)}function OC(e,t,n,r,i){return t.filter(s=>!n.has(s.id)).map(s=>({id:s.id,title:s.title,status:s.status,type:s.type,...jo(e,s.title)})).filter(s=>s.score>=r).sort((s,o)=>o.score-s.score||s.id.localeCompare(o.id)).slice(0,i)}async function $C(e,t={}){let n=e.title.trim();if(n.length===0)throw new f("Similarity candidate title must not be empty.",p.USAGE);let{limit:r,threshold:i}=ja(t),s=I(t.cwd??process.cwd(),t.pmRoot),o=await R(s),a=F(o),c=await Ai(s,Object.values(a.type_to_folder)),d=Po(n),l=c&&d.length>0?await Gu({pmRoot:s,expectedSourceCursor:c.source_cursor,query:d.map(_=>`"${_.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(r*10,50)}):null,u=l===null?await he(s,o.item_format,a.type_to_folder,void 0,o.schema):l.items,m=OC(n,u,new Set(e.excludeIds??[]),i,r);return{items:m,count:m.length,threshold:i,source:l?"persistent_index":"metadata_fallback"}}function NC(e,t={}){let{threshold:n}=ja({...t,limit:void 0}),{limit:r}=tg(t),i=new Set;for(let l of e){if(!l.id.trim()||i.has(l.id))throw new f("Duplicate analysis requires unique non-empty item ids.",p.USAGE);i.add(l.id)}let s=[...e].sort((l,u)=>l.id.localeCompare(u.id)).map(l=>({item:l,prepared:Uo(l.title)})),o=Ua(s,is,n,t.exhaustive===!0),a=ng(s.length),c=IC(s,o,n,a),d=rg(s,c,a,r);return{clusters:d,count:d.length,threshold:n,cost:{item_count:s.length,algorithm:t.exhaustive===!0||n===0?"exhaustive":"prefix_exact",possible_pairs:s.length*(s.length-1)/2,pair_limit:is,recall_guarantee:"exact",candidate_pairs:o.size,scored_pairs:o.size}}}async function ig(e={}){ja({...e,limit:void 0});let{since:t}=tg(e),{items:n,statuses:r}=await TC(e,t);return{...NC(n,e),source:"metadata_scan",filters:{statuses:r??null,since:e.since??null}}}async function qa(e,t){if(t.mode==="off")return;let n=await $C(e,t);if(n.count===0)return;let r=await RC(n,t),i=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!i){let s=n.items.map(a=>`${a.id} (${a.status}): ${a.title}`).join("; "),o=r.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new f(`Likely duplicate item(s) found: ${s}. ${o} or pass --allow-duplicate with explicit intent.`,p.CONFLICT,{code:"likely_duplicate",required:`${o}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:r.command,suggested_retry_args:r.args}})}return{mode:t.mode,bypassed:i,result:n,recovery:r}}async function fU(e,t={}){let n=await ig({pmRoot:I(process.cwd(),e.path),exhaustive:t.exhaustive,...t.status===void 0?{}:{statuses:t.status.flatMap(r=>r.split(",").map(i=>i.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(r=>{let i=r.id;return{...r,canonical_id:i,close_command:`pm close <duplicate-id> --duplicate-of ${i}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import{execFile as LC}from"node:child_process";import sg from"node:path";function og(e,t){return new Promise((n,r)=>{LC("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,s)=>{i?r(i):n(s)})})}function ag(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function wU(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(ag(n),!n)throw new RangeError("Source line range must use start:end.");return n}function MC(e){let t=new Map;for(let n of e.split(`
|
|
6
|
-
`)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function FC(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let s=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,a)=>o.localeCompare(a));n.set(i,s)}return n}async function DC(e){let t=sg.relative(e.workspaceRoot,sg.resolve(e.workspaceRoot,e.sourcePath)),n=await og(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await og(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:MC(n),commitItems:FC(r),available:!0}}function PC(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let s=i.source===t,o=s?i.target:i.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let a=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,s?i.kind:a.inverse??i.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function UC(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let s=t.shift(),o=s.kinds.length;i!==void 0&&o>=i||o>=e.maxDepth||(i=PC({current:s,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((s,o)=>s.nodes.join("\0").localeCompare(o.nodes.join("\0"))),r}function jC(e,t,n){let r=bf(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=UC({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(a=>[a.id,a]))}),s=i[0];if(!s)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(i.map(a=>a.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:s.nodes,kinds:s.kinds,alternative_decision_ids:o.slice(1)}}async function qC(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await DC({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function GC(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function KC(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function cg(e){ag(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await qC(e),r=KC(n),i=new Map;for(let s of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(s.item.id)),a=o.reduce((l,[,u])=>l+u,0),c=jC(s.item.id,e.corpus,t),d=GC({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});i.set(s.item.id,{score:a*100+s.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(s.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...s.files.map(l=>({kind:"linked_file",reference:l.path})),...o.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:s.item.value?.trim()||null,why_now:s.item.why_now?.trim()||null,outcome:s.item.outcome?.trim()||null,objective:s.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}import dg from"node:fs/promises";import $e from"node:path";var zC=32768;function Ga(e){return hn($e.normalize(e))}async function ss(e){try{return await dg.realpath(e)}catch{return $e.resolve(e)}}function An(e,t){let n=$e.isAbsolute(e.path)?$e.resolve(e.path):$e.resolve(t,e.path);return`${Ga(n)}::${e.scope}`}function os(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>os(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))os(i,t?`${t}.${r}`:r,n)}function WC(e){let t=[];return os(e.metadata,"metadata",t),os(e.body,"body",t),t}function BC(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function HC(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let s=new Set,o=i.value.slice(0,zC);for(let[a,c]of[[n,i.value],[r,o]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=BC(d[0]);!l||s.has(l)||(s.add(l),t.push({field:i.field,value:l}))}}}return t}async function VC(e,t,n=t){let r=$e.isAbsolute(e)?$e.resolve(e):$e.resolve(n,e),i;try{i=await dg.stat(r)}catch{return}if(!i.isFile())return;let[s,o]=await Promise.all([ss(t),ss(r)]);if(Ao(s,o)){let a=$e.relative(s,o);return!a||a.startsWith("..")||$e.isAbsolute(a)?void 0:{path:Ga(a),scope:"project"}}return{path:Ga(r),scope:"global"}}async function YC(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>An(c,t))),i=new Map,s=HC(WC(e)),o=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{o.set(c,await VC(c,t,n))}));let a=s.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=An(d,t),u=i.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function lg(e,t,n){let r=await Pi(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Ui(r,"files")}async function XC(e,t){let n=await ss(t),r=await Promise.all(e.map(async s=>{let o=s.trim();if(!o)throw new f("Files lookup paths must not be empty.",p.USAGE);if(!$e.isAbsolute(o))return hn(o);let a=await ss(o);return Ao(n,a)?hn($e.relative(n,a)):hn(a)})),i=[...new Set(r)].sort((s,o)=>s.localeCompare(o));if(i.length===0)throw new f("Files lookup requires at least one path.",p.USAGE);return i}function JC(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new f(`Files lookup ${r} must be a non-negative integer.`,p.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function ug(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function mg(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function QC(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(hn(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(mg)}async function ZC(e){if(e.explain)return cg({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function eE(e){if([e.strictRead,e.noTruncate,e.explain,Au()].includes(!0))return null;let t=await Ai(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?qu({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function tE(e){let t=[],n=await xi(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=QC({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&i.length>0)throw new f(`Files lookup could not read every item: ${i.join("; ")}`,p.GENERIC_FAILURE);let s=await ZC({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(s?[...r].sort((c,d)=>{let l=s.explanations.get(d.item.id).score-s.explanations.get(c.item.id).score;return l!==0?l:mg(c,d)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<r.length,truncated:e.offset+a.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:ug(c.item),files:c.files,...s?{traceability:s.explanations.get(c.item.id)}:{}})),...s?{traceability_receipt:s.receipt}:{}}}async function DU(e,t){let n=I(process.cwd(),t.path),r=_t(n);await z(n);let i=await XC(e.paths,r);if(e.lineRange&&i.length!==1)throw new f("Files lookup line attribution requires exactly one source path.",p.USAGE);let s=await R(n),o=F(s,M()),{offset:a,limit:c}=JC(e),d=await eE({pmRoot:n,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:a,limit:c,has_more:a+d.matches.length<d.total,truncated:a+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:ug(l.item),files:l.files}))}:tE({pmRoot:n,settings:s,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function PU(e,t,n){let r=I(process.cwd(),n.path),i=_t(r);await z(r);let s=await R(r),o=F(s,M()),a=await V(r,e,s.id_prefix,s.item_format,o.type_to_folder);if(!a)throw new f(`Item ${e} not found`,p.NOT_FOUND);let c=await le(a,{schema:s.schema}),d=await YC(c.document,i,process.cwd()),l=d.filter(x=>x.status==="addable"),u=d.filter(x=>x.status==="already_linked"),m=t.apply===!0,_=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let x=c.document.metadata.files??[];return{id:a.id,files:x,changed:!1,apply:m,count:x.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let h=H(t.author,s.author_default),g=l.map(x=>({path:x.path,scope:x.scope,note:_})),y=[],w=new Set,v=await Ie({pmRoot:r,settings:s,id:e,op:"files_discover",author:h,message:t.message??"Discover referenced file links",force:t.force,mutate(x){let D=[...x.metadata.files??[]],U=new Set(D.map(K=>An(K,i)));y=[],w.clear();for(let[K,Ge]of g.entries()){let ge=An(Ge,i);U.has(ge)||(D.push(Ge),U.add(ge),y.push(Ge),w.add(K))}let T=Of(D),E=t.appendStable?T:If(T);return E.length>0?x.metadata.files=E:delete x.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==g.length?[`files_discover_skipped_existing:${g.length-y.length}`]:[]}}}),k=v.item.files??[],b=new Set(y.map(x=>An(x,i))),A=k.filter(x=>b.has(An(x,i))),C=l.filter((x,D)=>!w.has(D)),S=[...u,...C];return{id:v.item.id,files:k,changed:A.length>0,apply:!0,count:k.length,candidate_count:d.length,addable_count:l.length,added_count:A.length,skipped_existing_count:S.length,candidates:d,added:A,skipped_existing:S}}var wr=["software-delivery","research","agent-evaluation","operations"];function pg(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function as(e,t,n,r,i){let s=`preset-${e}`,o=i.map(c=>({id:`${s}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),a=o.map(c=>pg(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:a,gates:[{id:`${s}-readiness`,description:n,assertion_ids:a.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function cs(e,t){return e==="software-delivery"?as(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?as(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?as(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):as(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function fg(e,t,n,r={}){return Ma(e,cs(t,n).declarations,r)}async function _g(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(s=>!n.has(s.status))};return await Promise.all(["files","tests","docs"].map(async s=>{let o={id:`derived-active-missing-${s}`,description:`Observed active items missing ${s} evidence.`,source:{kind:"links",link:s,state:"missing"}},c=(await La(o,r)).value,d=pg(`${o.id}-ceiling`,o.id,t,c,"observe"),l=`active-missing-${s}`;return{id:l,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[o],assertions:[d],gates:[{id:`derived-${l}`,description:`Observe the accepted ${s} evidence baseline.`,assertion_ids:[d.id],triggers:["ci","scheduled"]}]}}}))}function hg(e,t,n={}){return Ma(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function gg(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return es(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import vg from"node:fs/promises";import{createRequire as nE}from"node:module";import Ce from"node:path";function yg(e,t){let n=Ce.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Ce.sep}`)&&!Ce.isAbsolute(n))return n.split(Ce.sep).join("/");let r=Ce.resolve(e),i=0xcbf29ce484222325n;for(let o=0;o<r.length;o+=1)i^=BigInt(r.charCodeAt(o)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Ce.basename(Ce.dirname(e))}/package.json`}function rE(e){return e.includes(`${Ce.sep}.pnpm${Ce.sep}`)?"pnpm":e.includes(`${Ce.sep}node_modules${Ce.sep}`)?"npm":"other"}async function wg(e){try{let t=JSON.parse(await vg.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function Ka(e){try{return await vg.realpath(e)}catch{return Ce.resolve(e)}}async function kg(e,t,n=yu(import.meta.url,["../../.."])){let r=await Ka(t),i=await Ka(Ce.join(n,"package.json")),s=await wg(i),o=new Map;s!==void 0&&o.set(i,{version:s,path:yg(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=nE(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await Ka(l),m=await wg(u);if(m===void 0)continue;let _=u,h=o.get(_);if(h){h.consumers.includes(d.name)||(h.consumers.push(d.name),h.consumers.sort((g,y)=>g.localeCompare(y)));continue}o.set(_,{version:m,path:yg(u,r),layout:rE(u),consumers:[d.name]})}catch{}let a=[...o.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=s===void 0?[]:a.filter(d=>d.version!==s);return{host_version:s??null,copies:a,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${s}:${d.version}:${d.consumers.join("+")}`)}}var bg=25;function iE(e,t,n=[]){let r=["list","--status",e,...n],i=["--assignee-filter","unassigned"],s=["--updated-before",`-${t}h`];return{unowned:L([...r,...i]),idle:L([...r,...s]),stale:L([...r,...i,...s])}}function Sg(e,t){let n=e.items.length>bg;return{count:e.count,items:e.items.slice(0,bg),...n?{truncated:!0}:{},sweep:t}}function Ag(e,t,n=[]){let r=iE(t.in_progress,e.threshold_hours,n),i=(o,...a)=>`pm ${o} <id>${[...a,...n].map(c=>` ${Jr(c)}`).join("")}`,s=[...e.unowned.count>0?[`in_progress_unowned:${e.unowned.count}`]:[],...e.idle.count>0?[`in_progress_idle:${e.idle.count}`]:[]];return{warnings:s,details:s.length===0?void 0:{threshold_hours:e.threshold_hours,threshold_setting:"mutation_guard.stale_in_progress_hours",unowned:Sg(e.unowned,r.unowned),idle:Sg(e.idle,r.idle),item_remedies:{claim:i("claim"),take_over_idle:i("claim","--takeover-stale"),return_to_open:i("update","--status",t.open)}},remediation:{stale_in_progress_items:r.stale,in_progress_unowned:r.unowned,in_progress_idle:r.idle}}}import{createHash as sE}from"node:crypto";import ds from"node:path";var oE="2026-08-09T16:15:18.000Z",Cg=Symbol("pre-durable-disposition-eligible");function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function za(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function xg(e){return ct(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function Eg(e,t){if(typeof e!="string")return!1;let n=ds.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!ds.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(ds.posix.basename(n)===`${t}.toon`||ds.posix.basename(n)===`${t}.md`)}function aE(e,t){return typeof e.receipt_id=="string"&&sr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&Eg(e.item_path,t)}function Rg(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,s=Array.isArray(i)?new Set(i.flatMap(o=>xg(o)?[o.field]:[])):new Set;return za(t)&&za(n)&&za(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(xg)&&s.size===i.length&&t.length===s.size&&t.every(o=>s.has(o))}function cE(e,t){return aE(e,t)&&Rg(e)}function dE(e,t){return typeof e.receipt_id=="string"&&sr(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&Eg(e.item_path,t)&&Rg(e)}function lE(e){return e[Cg]===!0}function Tg(e,t){if(!ct(e)||!ct(e.context))return[];let n=e.context.merge;return!ct(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!ct(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:cE(r,t),[Cg]:dE(r,t),...typeof e.ts=="string"&&Eo(e.ts)?{eventTimestamp:e.ts}:{}}])}function Ig(e,t,n){if(!ct(e)||e.op!=="merge_reconcile")return[];if(!ct(e.context)||!ct(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!ct(i)||typeof i.receipt_id!="string"||!sr(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!Eo(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function Og(e,t,n=[]){let r=new Map;for(let o of n){let a=`${o.itemId}\0${o.originalHistoryLine}\0${o.receiptId}\0${o.originalEventTimestamp}`;r.set(a,Math.max(r.get(a)??0,o.auditHistoryLine))}let i=o=>lE(o)&&o.eventTimestamp!==void 0&&El(o.eventTimestamp,oE)<0&&(r.get(`${o.itemId}\0${o.line}\0${o.receiptId}\0${o.eventTimestamp}`)??0)>o.line;return{missing:e.filter(o=>!o.legacySummaryAccepted&&!t.has(o.receiptId)&&!i(o)).map(o=>({item_id:o.itemId,history_line:o.line,...sr(o.receiptId)?{receipt_id:o.receiptId}:{receipt_reference_hash:sE("sha256").update(o.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(o=>o.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}function ls(e,t,n=25){let r=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,a)=>o.localeCompare(a)),i=new Set(r),s=t.filter(o=>{let a=Fe(o.status,e);return a!==void 0&&i.has(a)}).map(o=>o.id).sort((o,a)=>o.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:s.length,affected_item_ids:s.slice(0,n),affected_item_ids_truncated:s.length>n}}function us(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}function Ng(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Pe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function uE(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function vr(e,t){let n=Pe(e,t);return{...n,sample:n.sample.map(r=>uE(r))}}function W(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function mE(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var pE={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:W(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:W(e.missing_required,t),missing_optional:W(e.missing_optional,t),missing:W(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:W(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:vr(e.discovered,t),effective:vr(e.effective,t),loaded:vr(e.loaded,t),failed:Pe(e.failed,t),warnings:W(e.warnings,t),activation:{failed:Pe(n.failed,t),warnings:W(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:mE(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Pe(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:W(n.affected_item_ids,t),samples:Pe(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:W(e.item_unreadable,t),item_conflict_markers:Pe(e.item_conflict_markers,t),item_parse_failures:W(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:W(n.tracked_paths,t)},history_unreadable:W(e.history_unreadable,t),history_conflict_markers:Pe(e.history_conflict_markers,t),history_invalid_json:Pe(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:W(n.candidate_items,t),confirmed_items:W(n.confirmed_items,t),resolved_false_positive_items:W(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:W(e.drifted_items,t),merge_receipt_attributed_items:W(e.merge_receipt_attributed_items,t),missing_streams:W(e.missing_streams,t),unreadable_streams:W(e.unreadable_streams,t),hash_mismatches:W(e.hash_mismatches,t),chain_mismatches:W(e.chain_mismatches,t),version_skews:W(e.version_skews,t),workspace_state_mismatches:W(e.workspace_state_mismatches,t),workspace_state_missing:W(e.workspace_state_missing,t),workspace_state_unreadable:W(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:W(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:W(e.stale_items_after,t),skipped:e.skipped})};function Wa(e,t){let n=pE[e.name];return n?n(e.details,t):e.details}function Lg(e){return{disabled_by_flag:e.details.disabled_by_flag,loaded_count:Array.isArray(e.details.loaded)?e.details.loaded.length:0,failed_count:0,warning_count:0,restore_with:"pm health --full"}}function fE(e){if(e.name==="extensions"&&e.status==="ok")return Lg(e);let t=Wa(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function Ba(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(r=>n.has(r.warning))}function _E(e){let t=W(e.warnings,8);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:fE(n)})),warnings:t.sample,findings:Ba(e,t.sample),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8},generated_at:e.generated_at}}function $g(e){return e.details.skipped===!0}function hE(e){let t=W(e.warnings,8),n=e.checks.filter($g).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!$g(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:Ba(e,t.sample),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8,omitted_checks:n},generated_at:e.generated_at}}function gE(e,t,n){return n?hE(e):t.brief===!0?_E(e):t.full===!0?e:{...e,checks:e.checks.map(r=>r.name==="extensions"&&r.status==="ok"?{...r,details:Lg(r)}:r),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function Ha(e,t,n){let r=e.warning_count??e.warnings.length,i=e.warnings.slice(0,100),s={...e,warning_count:r,warning_limit:100,warnings_truncated:r>100,warnings:i,findings:Ba(e,i)},o=gE(s,t,n);return{...o,warning_count:r,warning_limit:100,warnings_truncated:r>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:r,warnings_truncated:r>o.warnings.length}}:{}}}import dt from"node:fs/promises";import ce from"node:path";import xn from"node:fs/promises";import kr from"node:path";function Mg(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:s,ttl_seconds:o}=n;return typeof r!="string"||typeof i!="string"||typeof s!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:r,owner:i,created_at:s,ttl_seconds:o,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function yE(e,t,n){let r=Mg(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let s=n-i,o=Math.floor(s/1e3),a=s>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:o,stale:a,reason:a?"expired":"active"}}}async function Fg(e,t,n){let r=yE(e,t,n);if(r.detail!=="active")return r;let i=Mg(t),s=await Vl(i);return s==="unknown"?r:{detail:s==="dead"?"owner_dead":"active",entry:{...r.entry,owner_state:s,pid:i.pid,...s==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}async function wE(e,t,n){let r=await Xl(e,"gc");if(r===null)return!1;try{let i;try{i=await xn.readFile(e,"utf8")}catch(s){if(B(s))return!0;throw s}if(i!==t)return!1;n&&await Jl(e,t);try{await xn.unlink(e)}catch(s){if(!B(s))throw s}return!0}finally{await r()}}function vE(e,t,n){t==="owner_dead"&&(e.owner_dead_lock_samples??=[],e.owner_dead_lock_samples.length<20&&e.owner_dead_lock_samples.push(n)),t==="active"?e.active_lock_count+=1:t==="expired"||t==="owner_dead"?e.stale_lock_count+=1:e.unparseable_lock_count+=1}async function Dg(e,t){let n=t??Date.now(),r=kr.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},s;try{s=(await xn.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(o){if(B(o))return i;throw o}for(let o of s){let a;try{a=await xn.readFile(kr.join(r,o),"utf8")}catch(l){if(B(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c,entry:d}=await Fg(o,a,n);vE(i,c,d)}return i}async function kE(e,t,n,r,i,s,o){if(!t.dryRun){try{if(!await wE(n,s,o.reason==="owner_dead")){e.warnings.push(`lock_changed_or_busy:${i}`),e.retained.push(r),e.entries.push(o);return}}catch{e.warnings.push(`lock_remove_failed:${i}`),e.retained.push(r),e.entries.push(o);return}if(t.hooks?.onWrite){let a=await t.hooks.onWrite(n);e.warnings.push(...a)}}e.removed.push(r),e.entries.push(o)}async function Pg(e,t){let{hooks:n}=t,r=t.now??Date.now(),i=kr.join(e,"locks"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]};await Hl(e,kr.join(i,"gc.lock"),"gc");let o;try{o=(await xn.readdir(i)).filter(c=>c.endsWith(".lock")).sort()}catch(a){if(B(a))return s;throw a}for(let a of o){s.scanned+=1;let c=kr.join(i,a),d=`locks/${a}`;if(n?.onRead){let m=await n.onRead(c);s.warnings.push(...m)}let l;try{l=await xn.readFile(c,"utf8")}catch(m){if(B(m)){s.scanned-=1;continue}s.warnings.push(`lock_unreadable:${a}`),s.retained.push(d),s.entries.push({file:a,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let u=await Fg(a,l,r);if(u.detail==="unparseable_json"){s.warnings.push(`lock_unparseable:${a}`),s.retained.push(d),s.entries.push(u.entry);continue}if(u.detail==="invalid_timestamp"){s.warnings.push(`lock_invalid_timestamp:${a}`),s.retained.push(d),s.entries.push(u.entry);continue}if(u.detail==="active"){s.retained.push(d),s.entries.push(u.entry);continue}await kE(s,t,c,d,a,l,u.entry)}return s}var bE=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history record; the repair rebuilds the stream as one audited baseline from the on-disk item, and earlier versions stay unrecorded. When the stream was deleted by mistake, restore it from version control first (pm history-repair --all, with or without --append-only, rebuilds every missing stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"The item's history stream cannot be read; preview salvage, which removes lines that cannot hold a record and an invalid tail after a verified prefix, then apply it without --dry-run. Salvage refuses interior corruption, which needs recovery from version control, and a permission error needs the file's access fixed."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id> --append-only",summary:"The item's history chain is broken; append one record that bridges every break in the stream and keeps every recorded line byte-identical (pm history-repair <id> re-anchors the recorded entries instead). pm health previews the bridge for every chain mismatch, so a break a bridge cannot repair is reported as history_drift_chain_unbridgeable, and a stream no repair can keep as history_drift_unrepairable_stream, instead."},{code:"history_drift_chain_unbridgeable",command:"pm history-repair <id>",summary:"The item's history chain is broken in a way an append-only bridge cannot repair, for example a recorded patch that applies only on top of the unrecorded change (details.repair_refusals names the refusal reason); re-anchor the recorded entries instead (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unrepairable_stream",command:"pm history <id> --verify --full",summary:"Neither history repair can keep this stream (details.repair_refusals names both refusal reasons). Inspect it: a record that no longer matches its seal, or a malformed chain, needs the item's own stream restored from version control or a backup; a stream entry that is a link (reason stream_not_regular_file) needs the item's own stream restored as a regular file. Then run pm history <id> --verify --strict-exit."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_schema_field_option_collision",command:"pm schema rename-field <key> --to <new-key>",summary:"A custom field shadows a built-in option of a command it is registered for; rename it (item values move with it), or re-register the same key with another flag or a narrower --commands list."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Rebuild the history streams of the items without a history record as one audited baseline from each on-disk item."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"Preview salvage of the unreadable history streams, then apply it without --dry-run; interior corruption needs recovery from version control."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Va(e){if(typeof e!="string")return;let t=e.trim();for(let n of bE)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Ya(e){let t={};for(let n of e){let r=Va(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Ug(e){return Object.values(Ya(e))}import{execFile as SE}from"node:child_process";import{realpath as AE}from"node:fs/promises";import jg from"node:path";import{promisify as xE}from"node:util";var CE=xE(SE),EE=32*1024*1024,RE=1e4,TE=["search/eval-queries.json"];function Xa(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}async function IE(e,t=AE){return t(e).catch(()=>jg.resolve(e))}async function ms(e){let t=await kt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await IE(e),r=Xa(jg.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=Af.map(s=>`${r}/${Xa(s)}`);try{let{stdout:s}=await CE("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:EE,windowsHide:!0,timeout:RE}),o=new Set(TE.map(d=>`${r}/${d}`)),a=[...new Set(s.split("\0").filter(d=>d.length>0&&!o.has(Xa(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>Jr(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import qg from"node:path";import{realpath as OE}from"node:fs/promises";async function Gg(e,t){let n=t===null?[]:await Df(t,[qg.relative(t,qg.join(await OE(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function Kg(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await fn(e,pn(n),{gitWorkspaceRoot:t});if(i.status==="ok")return{audit:i,count:0,warnings:[]};let s=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:s,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${s}`]:[]}}function zg(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}import{lstat as $E}from"node:fs/promises";var Ja="history_drift_chain_mismatch",NE="history_drift_chain_unbridgeable",Hg="history_drift_unrepairable_stream",Wg="history_drift_hash_mismatch",Vg="history_drift_missing_stream",LE=["history_drift_unreadable_stream",Hg,"history_drift_version_skew","history_drift_merge_receipt"],ME=new Set([Ja,Vg]);function ps(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function FE(e,t){return e instanceof f?typeof e.context.reason=="string"?e.context.reason:e.code??t:t}async function Bg(e,t,n){try{await ji(e,{appendOnly:t,dryRun:!0},n);return}catch(r){return FE(r,t?"append_only_preview_failed":"rewrite_preview_failed")}}async function DE(e,t){let n=[];for(let r of ps(e.check.details.missing_streams)){let[i]=await Promise.allSettled([$E(Me(t,r))]);i.status==="fulfilled"&&i.value.isSymbolicLink()&&n.push({id:r,reason:"stream_not_regular_file",rewrite_refusal:"stream_not_regular_file"})}return n}async function Yg(e,t,n){let r=[],i=new Set(ps(e.check.details.version_skews));for(let s of ps(e.check.details.chain_mismatches)){if(i.has(s))continue;let o=await Bg(s,!0,t);if(o===void 0)continue;let a=await Bg(s,!1,t);r.push({id:s,reason:o,...a===void 0?{}:{rewrite_refusal:a}})}return[...r,...await DE(e,n)]}function PE(e,t,n){for(let r of[Ja,Vg]){if(!e.startsWith(`${r}:`))continue;let i=e.slice(r.length+1),s=t.get(i);return s===null?[]:[s===void 0?e:`${s}:${i}`]}return e.startsWith(`${Wg}:`)?n.has(e.slice(Wg.length+1))?[]:[e]:[e]}function Xg(e,t){let n=ps(e.check.details.version_skews),r=new Map([...n.map(s=>[s,null]),...t.map(s=>[s.id,s.rewrite_refusal===void 0?NE:Hg])]),i=new Set([...n,...t.filter(s=>s.rewrite_refusal!==void 0).map(s=>s.id)]);e.warnings=e.warnings.flatMap(s=>PE(s,r,i)).sort((s,o)=>s.localeCompare(o)),t.length!==0&&(e.check.details={...e.check.details,repair_refusals:t})}function Jg(e){if(LE.some(r=>Object.hasOwn(e,r)))return;let t=Object.keys(e),n=t.every(r=>ME.has(r));for(let r of t)n?e[r]="pm history-repair --all --append-only":r!==Ja&&(e[r]="pm history-repair --all")}var UE=5;function fs(e,t){let n=[],r={};for(let s of e){let o=ai(s);if(o.length!==0){for(let a of o)r[a.field]=(r[a.field]??0)+1;n.push({id:s.id,fields:o.map(a=>a.field),reasons:[...new Set(o.map(a=>a.reason))]})}}if(n.length===0)return;n.sort((s,o)=>s.id.localeCompare(o.id));let i=t?n.length:UE;return{details:{items:n.length,by_field:Object.fromEntries(Object.entries(r).sort(([s],[o])=>s.localeCompare(o))),rows:n.slice(0,i),truncated:n.length>i},warning:`validate_metadata_deferred_fields:${n.length}`}}var ty=25,qE=ce.join("runtime","telemetry","events.jsonl"),GE=ce.join("runtime","telemetry","state.json"),KE=2500,zE=500,ny=sm-3,WE=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function rc(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("extension_disabled_pm_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("in_progress_unowned:")||e.startsWith("in_progress_idle:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function ic(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Cn(e){return e.trim().toLowerCase()}function ec(e,t){let n=Cn(e),r=Cn(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function sc(e){try{return(await dt.stat(e)).isDirectory()}catch{return!1}}async function BE(e){let t=(await dt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>dt.readdir(ce.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>qn.some(s=>i.name.endsWith(s))).map(i=>ce.parse(i.name).name)))}async function HE(e,t,n,r){let i=await Te({path:e,scope:"project"}),s=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!s)return{warnings:i,overThreshold:!1,classification:"live"};let o;try{o=await dt.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(s){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function VE(e,t,n){let r=ce.join(e,"history");if(!await sc(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await dt.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),o=t.enabled?t.max_entries:null,a=[],c=[],d=[],l=[];for(let u of i){let m=ce.join(r,u),_=u.slice(0,-6),h=await HE(m,_,t,n);a.push(...h.warnings),h.classification==="tombstone"&&d.push(_),h.classification==="orphaned"&&l.push(_),h.overThreshold&&c.push(_)}return{count:i.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:o,tombstones:d,orphaned:l}}function tc(e,t){return ce.relative(e,t).replaceAll("\\","/")}async function ry(e,t){let n=[...new Set(Object.values(t))].sort((i,s)=>i.localeCompare(s)),r=[];for(let i of n){let s=ce.join(e,i),o=[];try{o=await dt.readdir(s)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&B(a))continue;continue}for(let a of o)qn.some(c=>a.toLowerCase().endsWith(c))&&r.push(ce.join(s,a))}return r.sort((i,s)=>tc(e,i).localeCompare(tc(e,s))),r}function YE(e){return!(typeof e=="object"&&e!==null&&"code"in e&&B(e))}function XE(e){let t=fs(e,!1);return t===void 0?{}:{curation:{deferred_fields:t.details}}}async function JE(e,t,n){let r=await ry(e,t),i=[],s=[],o=[],a=[],c=gt(M());for(let d of r){let l=tc(e,d),u;try{u=await dt.readFile(d,"utf8")}catch{i.push(l);continue}let m=an(u);if(m){s.push({path:l,...m});continue}try{let _=ci(u,{format:ul(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:si(_.metadata)})}catch{o.push(l)}}return{paths:r,unreadable:i,conflictMarkers:s,parseFailures:o,formatVersions:a}}async function QE(e){let t=ce.join(e,"history"),n=[],r=[],i=[],s=[],o=[],a=[];try{a=(await dt.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){YE(c)&&n.push("history")}for(let c of a){let d=c.slice(0,-6),l;try{l=await dt.readFile(ce.join(t,c),"utf8")}catch{n.push(d);continue}let u=an(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,_)=>{if(m.trim())try{let h=JSON.parse(m);s.push(...Tg(h,d).map(g=>({itemId:d,line:_+1,...g}))),o.push(...Ig(h,d,_+1))}catch{i.push({id:d,line:_+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:s,mergeReceiptDispositions:o}}function iy(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function ZE(e,t,n,r,i,s){let o=await JE(e,t,n),a=await QE(e),c=oi(o.formatVersions,4,1),d=q(n),l=Fi(s,T=>ae(T,d),ie()),u=await ms(e),m=await kt(e),_=await Gg(e,m),h=await Kg(e,m,r,i),g=m===null?null:await _n(m),y=await gn(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(y.durable_receipt_ids),v=Og(a.mergeReceiptReferences,w,a.mergeReceiptDispositions),k=v.missing,b=y.receipts.filter(T=>T.state==="pending"),{pendingDecisions:A,lossless:C}=yn(b),S=g?.status==="missing"&&g.missing_keys.length===5&&g.drifted_keys.length===0,x=[...o.unreadable.map(T=>`integrity_item_unreadable:${T}`),...o.conflictMarkers.map(T=>`integrity_item_conflict_marker:${T.path}:L${T.line}`),...o.parseFailures.map(T=>`integrity_item_parse_failed:${T}`),...a.unreadable.map(T=>`integrity_history_unreadable:${T}`),...a.conflictMarkers.map(T=>`integrity_history_conflict_marker:${T.id}:L${T.line}`),...a.invalidJson.map(T=>`integrity_history_invalid_json:${T.id}:L${T.line}`),...c.outdated.map(T=>`integrity_item_outdated_format_version:${T}`),...c.ahead.map(T=>`integrity_item_ahead_format_version:${T}`),...iy(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...g!==null&&g.status!=="ok"?[`merge_driver_configuration_${S?"missing":"drift"}:${g.missing_keys.length+g.drifted_keys.length}`]:[],...h.warnings,..._.warnings,...A.length>0?[`merge_decisions_unreviewed:${A.length}`]:[],...C.length>0?[`merge_receipts_pending:${C.length}`]:[],...zg({invalidEvidenceCount:y.invalid_evidence_count,missingHistoryReferenceCount:k.length})],D=[...new Set(x)].sort((T,E)=>T.localeCompare(E)),U=D.filter(T=>!T.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:U.length===0?"ok":"warn",ok:U.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:g===null||g.status==="ok"?0:g.missing_keys.length+g.drifted_keys.length,merge_fence:h.count,ignored_merge_artifacts:_.rules.length,pending_merge_decisions:A.length,lossless_merge_receipts:C.length,invalid_merge_receipt_evidence:y.invalid_evidence_count,missing_merge_receipt_history_references:k.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.acceptedDispositionCount},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,...XE(s),hierarchy_integrity:{...l,relations:Pe(l.relations,8)},history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:g===null?null:{...g,required:i},merge_fence:h.audit,ignored_merge_artifacts:_.rules,pending_merge_decision_items:[...new Set(A.map(T=>T.item_id))].sort((T,E)=>T.localeCompare(E)),lossless_merge_receipt_items:[...new Set(C.map(T=>T.item_id))].sort((T,E)=>T.localeCompare(E)),invalid_merge_receipt_evidence_details:y.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:y.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:k.slice(0,100),missing_merge_receipt_history_reference_details_truncated:k.length>100}},warnings:D,gitWorkspaceRoot:m,pendingMergeReceipts:b}}function eR(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function tR(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:eR(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function nR(e,t){let n=te(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function rR(e){let n=te(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function iR(e){return te(e.reason)??te(e.error)??te(e.message)}function Qa(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function sR(e){let t=[],n=[],r=[];e.forEach((s,o)=>{let a=nR(s.definition,o),c=rR(s.definition);if(c==="applied"){t.push({layer:s.layer,name:s.name,id:a,status:c});return}if(c==="failed"){r.push({layer:s.layer,name:s.name,id:a,status:c,reason:iR(s.definition)});return}n.push({layer:s.layer,name:s.name,id:a,status:c})}),t.sort(Qa),n.sort(Qa),r.sort(Qa);let i=[...r.map(s=>`extension_migration_failed:${s.layer}:${s.name}:${s.id}`),...n.map(s=>`extension_migration_pending:${s.layer}:${s.name}:${s.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function sy(e,t,n,r,i,s,o,a,c){let d=[...new Set(e)].sort((y,w)=>y.localeCompare(w)),l=[...new Set(d.map(y=>ic(y)))].sort((y,w)=>y.localeCompare(w)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,m=c.length>0,_=m?"partial":"full",h=d.map(ca).filter(y=>y!==void 0),g=Cf(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return g&&h.push(g),t>0&&h.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&h.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&h.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&h.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&h.push(`Unknown extension capabilities detected. Allowed capabilities: ${Ld.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&h.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&h.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?h.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&h.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),h.length===0&&h.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:s,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:_,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:h}}async function oR(e,t,n){let r=await Ef(_t(e)),i=await _i({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),s=i.loaded.map(S=>tR(S)),o=await kg(i.loaded,_t(e)),a=await hi({...i,loaded:i.loaded}),[c,d]=await Promise.all([aa(i.roots.project),aa(i.roots.global)]);await Hp(e,a.registrations.migrations);let l=sR(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},m=new Set(c.state.entries.map(S=>Cn(S.name))),_=new Set(d.state.entries.map(S=>Cn(S.name))),h=[...new Map(i.loaded.filter(S=>!(S.layer==="project"?m:_).has(Cn(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,x)=>{let D=`${S.layer}:${S.name}`,U=`${x.layer}:${x.name}`;return D.localeCompare(U)}),g=h.map(S=>`${S.layer}:${S.name}`).sort((S,x)=>S.localeCompare(x)),y=h.filter(S=>ec(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,x)=>S.localeCompare(x)),w=h.filter(S=>!ec(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,x)=>S.localeCompare(x)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],k=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...o.warnings],b=da(k),A=la(),C=sy(k,i.failed.length,a.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,g,y,w);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...i,loaded:s,warnings:k,activation:u,author_manifest:r,triage:C,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:A,capability_guidance:b,host_version_census:o}},warnings:k}}function nc(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Ng(e,ty);return{values:n.values,truncated:n.truncated,total:e.length}}function _s(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function aR(){let e=Ju();return e.source_context_source==="env_override"?e.source_context:null}function oy(e){let t=0,n=0,r=0,i=0,s=0;for(let o of e.split(`
|
|
7
|
-
`)){let a=o.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,s=Math.max(s,d),d>=ny&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:s}}function cR(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Zg(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function dR(e,t){let n=Hn(e.telemetry.endpoint).trim();return!t||!e.telemetry.enabled||n.length===0||Dt().telemetry_disabled?void 0:{attempted:!0,...await ay(n)}}function lR(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,s=n.last_failed_flush_at,o=s&&(!i||s>i),a=!i,c=t.validEntries>=zE;return(o||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function uR(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function mR(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>im?[`telemetry_schema_version_behind:${t}`]:[]}function pR(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function fR(){return{...Dt(),pm_no_telemetry:_s("PM_NO_TELEMETRY"),telemetry_otel_disabled:_s("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:_s("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:aR()}}function _R(e,t){return e.telemetry.enabled&&t.validEntries>0}function hR(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}function ey(e){try{return decodeURIComponent(e)}catch{return e}}async function ay(e){let t=e,n={};try{let r=new URL(e);r.pathname="/healthz",r.search="",r.hash="",(r.username.length>0||r.password.length>0)&&(n.authorization=`Basic ${Buffer.from(`${ey(r.username)}:${ey(r.password)}`).toString("base64")}`,r.username="",r.password=""),t=r.toString()}catch{}try{let r=await fetch(t,{method:"GET",headers:n,signal:AbortSignal.timeout(KE)});return{probe_url:wt(t),ok:r.ok,status:r.status,max_schema_version:(()=>{for(let i of WE){let s=r.headers.get(i)?.trim();if(s&&s.length>0)return s}})()}}catch(r){return{probe_url:wt(t),ok:!1,error:r instanceof Error?Qu(r.message.replaceAll(t,wt(t))):"probe_failed"}}}async function gR(e,t){let n=Zg(await ee(e)),r=e===t?n:Zg(await ee(t));return{runtimeState:n.runtimeState,spanState:r.runtimeState,stateParseFailed:n.stateParseFailed||r.stateParseFailed}}async function yR(e){let t=tt(process.cwd()),n=await R(t),r=ce.join(ce.dirname(ce.join(t,qE)),yt("events.jsonl")),i=ce.join(t,GE),s=ce.join(ce.dirname(i),yt("state.json")),o=await ee(r),a=o!==null,c=o?Buffer.byteLength(o,"utf8"):0,d=o?oy(o):cR(),{runtimeState:l,spanState:u,stateParseFailed:m}=await gR(s,i),_=Hn(n.telemetry.endpoint).trim(),h=wt(_),g=await dR(n,e.checkTelemetry),y=[];m&&y.push("telemetry_state_invalid_json"),y.push(...lR(n,d,l),...uR(g),...mR(g),...pR(n,u));let w=_R(n,d),v=typeof u.pending_otel_spans=="number"?u.pending_otel_spans:0;return{check:{name:"telemetry",status:y.length===0?"ok":"warn",ok:y.length===0,details:{enabled:n.telemetry.enabled,capture_level:n.telemetry.capture_level,endpoint:h,global_pm_root:t,queue_path:r,queue_exists:a,queue_entries:d.validEntries,queue_draining:hR(w,y),queue_invalid_rows:d.invalidRows,queue_rows_total:d.totalRows,queue_size_bytes:c,queue_high_retry_entries:d.highRetryEntries,queue_high_retry_threshold:ny,queue_max_attempts:d.maxAttempts,runtime_state_path:s,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:v,last_otel_attempt_at:u.last_otel_attempt_at??null,last_otel_success_at:u.last_otel_success_at??null,last_otel_failure_at:u.last_otel_failure_at??null,last_otel_failure_error:u.last_otel_failure_error??null,endpoint_probe:g??{attempted:!1},env_overrides:fR()}},warnings:y}}async function wR(e){let t;try{t=await Dg(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,...t.owner_dead_lock_samples?{owner_dead_lock_samples:t.owner_dead_lock_samples,recovery_command:"pm gc --scope locks"}:{},unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function vR(e){let t="metadata",n=e.items,r=await ir(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),s=[],o=[];if(i.length>0){n=await rt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await ir(e.pmRoot,n),s=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,k)=>v.localeCompare(k));let w=new Set(s);o=i.filter(v=>!w.has(v))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:_,workspaceStateMissing:h,workspaceStateUnreadable:g}=r,y=[...a.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),..._.map(w=>`history_drift_workspace_state_mismatch:${w}`),...h.map(w=>`history_drift_workspace_state_missing:${w}`),...g.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:s,resolved_false_positive_items:o,authoritative_item_source:i.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:_.length,workspace_state_missing:h.length,workspace_state_unreadable:g.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:_,workspace_state_missing:h,workspace_state_unreadable:g}},warnings:y}}function kR(e,t){let n=Du(e),r=Bu(n.settings),i=Hu(n.settings,t),s=r.active?Vu(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:s,semanticRuntimeAvailable:!!(r.active&&i.active)}}function bR(){return{refreshed:[],skipped:[],warnings:[]}}async function SR(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?bR():Xu(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function AR(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Yu(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function xR(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function CR(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function cy(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:Fo(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:Fo(r,e.vector_store?.adapter??null)}}function ER(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function RR(e,t,n){return e.enabled&&n.length>0&&t}async function TR(e,t,n,r,i){let s=kR(t,e),o=await Do(e),a=s.semanticRuntimeAvailable?ua(n,o.entries):[],c=await SR({pmRoot:e,snapshot:s,refreshPolicy:r,staleBefore:a}),d=await Do(e),l=s.semanticRuntimeAvailable?ua(n,d.entries):[],u=!s.runtimeDefaults.auto_ollama_defaults_applied,m=AR({strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:s.runtimeEmbeddingIdentity}),_=xR({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),h=nc(a,i),g=nc(l,i),y=RR(r,s.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:_.length===0?"ok":"warn",ok:_.length===0,details:{semantic_runtime_available:s.semanticRuntimeAvailable,compatibility_mode_auto_defaults:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:s.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:s.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:ER(r),...cy(t,s),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:s.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:ty,stale_items_before_total:h.total,stale_items_before:h.values,stale_items_before_truncated:h.truncated,refresh_attempted:y,refresh_skipped_reason:CR(r,s.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:g.total,stale_items_after:g.values,stale_items_after_truncated:g.truncated}},warnings:_}}function IR(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function dy(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new f("--check-only cannot be combined with --refresh-vectors",p.USAGE);if(n&&e.noRefresh===!0)throw new f("--no-refresh cannot be combined with --refresh-vectors",p.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var OR=new Set(["extensions","locks","search"]);function $R(e){let t=new Set(Dd.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(Pd));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of OR)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,s)=>i.localeCompare(s)),optionalDirs:[...n].sort((i,s)=>i.localeCompare(s)),optionalDirSet:n}}async function NR(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:s}=$R(t),o=[],a=[],c=[];for(let d of[...r,...i]){let l=ce.join(e,d);c.push(...await Te({path:l,scope:"project"})),!await sc(l)&&(s.has(d)?a.push(d):o.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:o,missingOptionalDirs:a,missingDirs:n?[...o,...a]:[...o],hookWarnings:c}}function ly(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=e.summary===!0||t,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function LR(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?he(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):rt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Za(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function MR(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function FR(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function DR(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var oc=e=>e.unknown_event_count??0,ac=e=>e.actionable_unknown_event_count??oc(e);function PR(e,t,n,r,i,s,o){let a=oc(r),c=ac(r),d=a>0,l=c>0,u=i.count>0||o!==void 0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...d?{author_attribution:r}:{},...i.count>0?{stale_in_progress:i}:{},...o===void 0?{}:{in_progress_work:o},...s.outcomes.length>0?{provenance_resolver_outcomes:s.outcomes}:{},...s.invalid_values.length>0?{provenance_invalid_values:s.invalid_values}:{},provenance_sample:s.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function uy(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function UR(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function jR(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function qR(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function my(e){let t=new Map;for(let[i,s]of Object.entries(e.remediationSources))for(let o of s)t.has(o)||t.set(o,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let s=t.get(i)??"integrity",o=Va(i)?.code??ic(i),a=n.get(s)?.details,c=typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{},d=ca(i)??(o==="agent_guidance_outdated"?"pm init --agent-guidance add":o==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":c[o]),l=rc(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:o,check:s,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function GR(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1&&Jg(e.remediationMap),e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function KR(e){for(let t of e.checks){let n=Ya(e.remediationSources[t.name]);GR({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount});for(let[r,i]of Object.entries(t.name==="storage"?e.storageRemediation:{}))Object.hasOwn(n,r)&&(n[r]=i);Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function zR(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),i=new Map;for(let o of e.pendingMergeReceipts){let a=i.get(o.item_id)??[];a.push(o),i.set(o.item_id,a)}let s=[];for(let o of n){if(r.has(o))continue;let a=i.get(o);if(!(!a||a.length===0))try{await ji(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),s.push(o)}catch{}}return[...new Set(s)].sort((o,a)=>o.localeCompare(a))}function WR(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function py(e,t={}){let n=I(process.cwd(),e.path);await z(n);let r=sn(n),{settings:i,warnings:s}=await Mu(n),o=[...new Set(s)],a=F(i,M()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=dy(t),m=await NR(n,a,c),_=IR(i),h=await yR({checkTelemetry:t.checkTelemetry===!0}),g=await oR(n,i,!!e.noExtensions),y=ly(t),w=[],v=await LR({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:y,itemReadWarnings:w}),k=v,b=ls(q(i.schema),v),C=[...(await Rf({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(ne=>ne.startsWith("agent_guidance_")),..._,...us(b)],S=y.skipDrift?{warnings:[]}:await gi({pmRoot:n,settings:i,itemIds:v.map(ne=>ne.id),commandLabel:"health"}),x=await VE(n,i.history.compact_policy,await BE(n)),D=await yr(n,20,t.verboseAuthorEvents===!0),U=ac(D),T=U>0?[`history_unknown_author_events:${U}`]:[],E=q(i.schema),K=await nm(n,v,{in_progress_status:E.in_progress_status,status_registry:E,threshold_hours:i.mutation_guard.stale_in_progress_hours}),Ge=uy(K.stale),ge=Ag(K,{in_progress:E.in_progress_status,open:E.open_status},Ye(e)),Ze=[...Ge.warnings,...ge.warnings],mt=await Ff(n),pt=mt.warnings,ye=await wR(n),Ke=y.skipIntegrity&&!l?{...Za("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await ZE(n,a.type_to_folder,i.schema,i,l,v),ue=y.skipDrift?Za("history_drift"):await vR({pmRoot:n,items:k,settings:i,typeRegistry:a,itemReadWarnings:w}),Qt=[...new Set(w)],Zt=await zR({gitWorkspaceRoot:Ke.gitWorkspaceRoot,pendingMergeReceipts:Ke.pendingMergeReceipts,historyDriftCheck:ue,global:e});WR(ue,Zt),Xg(ue,await Yg(ue,e,n));let xt=y.skipVectors?Za("vectorization"):await TR(n,i,k,u,t.verboseStaleItems===!0),de=[MR(r,i,o),FR(m,c),DR(C,b),h.check,g.check,PR(v,i,x,D,Ge.scan,mt,ge.details),ye.check,Ke.check,ue.check,xt.check],Ae=UR({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:C,normalizedItemReadWarnings:Qt,telemetryCheck:h,extensionCheck:g,historyPolicyWarnings:S.warnings,historySummary:x,authorAttributionWarnings:T,staleInProgressWarnings:Ze,provenanceWarnings:pt,locksCheck:ye,integrityCheck:Ke,historyDriftCheck:ue,vectorizationCheck:xt}),fe=qR({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:C,normalizedItemReadWarnings:Qt,telemetryCheck:h,extensionCheck:g,historyPolicyWarnings:S.warnings,historySummary:x,authorAttributionWarnings:T,staleInProgressWarnings:Ze,provenanceWarnings:pt,locksCheck:ye,integrityCheck:Ke,historyDriftCheck:ue,vectorizationCheck:xt});KR({checks:de,remediationSources:fe,historyDriftedCount:jR(ue),overThresholdCount:x.over_threshold.length,storageRemediation:ge.remediation});let $=Ae.filter(ne=>!rc(ne,l)),ft=my({warnings:Ae,checks:de,remediationSources:fe,requireMergeDrivers:l}),xe=new Set(ft.filter(ne=>ne.severity==="gate_failing").map(ne=>ne.check)),Dn=new Set(ft.map(ne=>ne.check));for(let ne of de)ne.ok=!xe.has(ne.name),Dn.has(ne.name)&&(ne.status="warn");let we={ok:$.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&$.length>0?p.GENERIC_FAILURE:0},checks:de,warnings:Ae,findings:ft,failed_because:$,generated_at:O()};return Ha(we,t,y.summaryMode)}var Nq={buildHierarchyIntegrityWarnings:iy,buildExtensionHealthTriageSummary:sy,buildHealthFindings:my,buildCapabilityContractMetadata:la,buildStaleInProgressHealthSummary:uy,buildVectorizationProviderDetails:cy,collectUnknownCapabilityGuidance:da,isAdvisoryHealthWarning:rc,isDirectory:sc,isExpectedUnmanagedExtension:ec,listItemDocumentPaths:ry,normalizeEndpointForDisplay:wt,normalizeExtensionNameForMatch:Cn,parseTelemetryQueue:oy,probeTelemetryEndpointHealth:ay,projectHealthResult:Ha,resolveActionableUnknownAuthorEventCount:ac,resolveHealthSkipPolicy:ly,resolveUnknownAuthorEventCount:oc,resolveVectorRefreshPolicy:dy,selectStaleItemDetail:nc,summarizeHealthCheckDetails:Wa,summarizeExtensionList:vr,summarizeRecordList:Pe,summarizeStringList:W,telemetryEnvFlagEnabled:_s,warningCode:ic};function fy(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!pm(e,t).ok)return{reason:"unverified_history"};let r=eu(),i={reason:"no_proven_transition"};for(let[s,o]of e.entries()){let a=n.has(String(r.metadata.status));r=Pu(r,o.patch,s+1,o.op),n.has(String(r.metadata.status))?a||(i=["create","close","cancel","update","update_audit"].includes(o.op)&&Cl(o.ts)?{timestamp:o.ts,source_index:s+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function _y(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function hy(e,t,n,r,i){let s=_y(n),o=t.filter(d=>s.has(d.status)&&!d.closed_at),a=[],c=[];for(let d of r?o:[]){let l;try{let u=await Lt(Me(e,d.id),d.id),{body:m,..._}=d;l=fy(u,{metadata:_,body:m},s)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}a.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:o.length,missing_closed_at_item_ids:o.slice(0,i).map(d=>d.id),missing_closed_at_item_ids_truncated:o.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:a.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:a,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function gy(e,t){let n=I(process.cwd(),t.path),r=await R(n),i=q(r.schema);await Ie({pmRoot:n,settings:r,id:e.item_id,op:"update",author:H(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(s){if(s.metadata.closed_at)return{changedFields:[]};let o=await Lt(Me(n,s.metadata.id),s.metadata.id),a=_y(i),c=fy(o,s,a);if(!("timestamp"in c)||c.timestamp!==e.value)throw new f("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",p.GENERIC_FAILURE);return s.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}function BR(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function yy(e){return`${e.item_id} ${e.link_kind}`}function wy(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=BR(i.classification,r.classification),i.owners.set(yy(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[yy(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(s=>{let o=t(s.item_id);return{id:s.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:s.link_kind}}).sort((s,o)=>{let a=s.id.localeCompare(o.id);return a!==0?a:s.field.localeCompare(o.field)})}))}function vy(e,t,n,r,i=40){let s=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,o=new Map(t.map(d=>[d.path,d])),a={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=wy(e,n).map(d=>{let l=[],u=[];for(let _ of d.items){let h=re(_.status,r)??_.status;r.terminal_statuses.has(h)?(u.push(_),h===r.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):l.push(_)}a.missing_linked_links_count+=d.items.length,a.active_missing_linked_links_count+=l.length,a.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(a.active_missing_linked_paths_count+=1);let m=o.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,s),items_truncated:d.items.length>s}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),a.missing_linked_path_rows_count=c.length,a.missing_linked_path_rows=c.slice(0,s),a.missing_linked_path_rows_truncated=c.length>s,a}import En from"node:fs/promises";import Rn from"node:path";async function HR(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let s;try{s=await En.readdir(Rn.join(e,i))}catch{return}for(let o of s)for(let a of qn)if(o.toLowerCase().endsWith(a)){r.push({relativePath:`${i}/${o}`,id:o.slice(0,-a.length)});break}})),r.sort((i,s)=>i.relativePath.localeCompare(s.relativePath))}function VR(e,t){let{id:n,relativePath:r,liveItemIds:i,out:s}=e,o=an(t);if(o){s.conflictMarkers.push({id:n,path:r,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=YR(e,t);a!==null&&(a.op==="delete"&&i.has(n)&&s.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(s.repairReconciliations+=1))}function YR(e,t){let{id:n,relativePath:r,out:i}=e,s=null,o=!1,a=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of a){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");s=d}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(s.op==="create"){if(o)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return s}function cc(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function XR(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await En.readdir(Rn.join(e,"history"))}catch{return n}for(let i of r.sort((s,o)=>s.localeCompare(o))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await En.readFile(Rn.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:cc("history stream",o)});continue}VR({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},s)}return n}function ky(e){let t=an(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function JR(e){let t=[],n=0,r=null;try{r=await ee(sn(e))}catch(s){n+=1,t.push({path:"settings.json",detail:cc("configuration file",s)})}if(r!==null){n+=1;let s=ky(r);s!==null&&t.push({path:"settings.json",detail:s})}let i;try{i=await En.readdir(Rn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of i.sort((o,a)=>o.localeCompare(a))){if(!s.endsWith(".json"))continue;n+=1;let o;try{o=await En.readFile(Rn.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:cc("configuration file",c)});continue}let a=ky(o);a!==null&&t.push({path:`schema/${s}`,detail:a})}return{scanned:n,unparseable:t}}async function by(e,t,n,r={}){let i=await HR(e,n),s=new Set(i.map(u=>u.id)),o=new Map;for(let u of i){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((_,h)=>_.localeCompare(h))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Rn.join(e,u.relativePath);return ci(await En.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await XR(e,s),l=await JR(e);return{item_files_on_disk:i.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}function Sy(e,t,n){if(t.length===0)return{details:{},warnings:[]};let r=t.filter(i=>i.dropped!==void 0).length;return{details:{[`schema_${e}_definition_loss_count`]:t.length,[`schema_${e}_definition_losses`]:t.slice(0,n),[`schema_${e}_definition_losses_truncated`]:t.length>n},warnings:[...r>0?[`validate_schema_${e}_definition_dropped:${r}`]:[],...t.length>r?[`validate_schema_${e}_definition_partial:${t.length-r}`]:[]]}}async function Ay(e,t,n){let{configured:r}=await Wp(e,t),i=Io(e,r.files?.statuses,To.statuses),s=Io(e,r.files?.types,To.types),o=Sy("status",Jo(Qo(e,i),Nl(await Xo(i))??[],"id",(d,l)=>Ol(d,l).loss),n),a=Sy("type",Jo(Qo(e,s),$l(await Xo(s))??[],"name",d=>dl(d,"schema_file").loss),n),c=[...o.warnings,...a.warnings];return{details:{...o.details,...a.details,...c.length===0?{}:{schema_definition_loss_fix_hint:"A dropped status or type is not registered, and a definition read in part ignores the listed members. Edit or remove the listed entries in the named schema file: give every status an id and every type a name, use strings for names, descriptions, aliases and folders, and agent, human or gate for execution_role."}},warnings:c}}import Sc from"node:fs/promises";import{realpathSync as aT}from"node:fs";import{execFile as cT}from"node:child_process";import Se from"node:path";import{promisify as dT}from"node:util";var QR=["metadata","resolution"],dc=["metadata","resolution","estimates","timestamps","lifecycle"],ZR="completed";function lc(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function xy(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Cy(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=xy(n.close_reason)??ZR;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${lc(r)}`,gate:"resolution"})}return t}function Ey(e){let t=[];for(let n of e){let r=xy(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${lc(r)}`,gate:"metadata"})}return t}function Ry(e,t){return e.map(n=>{let r=Lu(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function Ty(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function Iy(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${lc(n.path)}`})}return t}function Oy(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new f(`--fix-scope values must not be empty. Supported values: ${dc.join(", ")}.`,p.USAGE);return new Set(QR)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(dc.includes(i)){n.add(i);continue}throw new f(`Unknown --fix-scope value "${r}". Supported values: ${dc.join(", ")}.`,p.USAGE)}return n}function $y(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function br(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}var eT=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function tT(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=eT.exec(n);if(!r)return null;let i=r[1],s=i.toUpperCase(),o=i.slice(0,i.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(m=>m.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${s}`)||d.includes(`ISSUE CODE \`${s}\``)||d.includes(`\`${s}\``)||d.includes(`[${s}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(o.toUpperCase())||l?s:null}function Ny(e){return typeof e=="string"&&e.trim().length>0}function nT(e){let t=new Set(e.map(a=>a.id.toLowerCase())),n=new Map,r=new Map;for(let a of e){let c=a.id.toLowerCase(),d=new Set([...a.parent===null?[]:[a.parent.toLowerCase()],...a.derivations].filter(l=>l!==c&&t.has(l)));n.set(c,d);for(let l of d){let u=r.get(l)??[];u.push(c),r.set(l,u)}}let s=[...[...n].filter(([,a])=>a.size===0).map(([a])=>a)],o=new Set;for(let a=0;a<s.length;a+=1)for(let c of r.get(s[a])??[]){let d=n.get(c);d.delete(s[a]),d.size===0&&(o.add(c),s.push(c))}return e.filter(a=>!o.has(a.id.toLowerCase()))}function Ly(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||Ny(i.duplicate_of))continue;let s=tT(i.title,{...t,evidenceText:i.body});if(s===null)continue;let o=n.get(s);o||(o=[],n.set(s,o)),o.some(a=>a.id===i.id)||o.push({id:i.id,title:i.title,parent:Ny(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(a=>["discovered_from","supersedes","incident_from"].includes(a.kind)).map(a=>a.id.trim().toLowerCase()).filter(a=>a!==i.id.toLowerCase())})}let r=[];for(let[i,s]of n){if(s.length<2)continue;let o=nT(s);if(o.length<2)continue;let a=[...o].sort((c,d)=>c.id.localeCompare(d.id));r.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return r.sort((i,s)=>i.code.localeCompare(s.code))}function My(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,s)=>i.localeCompare(s))){let i=t.get(r),s={};for(let o of[...i.keys()].sort((a,c)=>a.localeCompare(c)))s[o]=i.get(o);n[r]=s}return n}function Fy(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Dy(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let s of t){let o=Fy(s);if(o.length===0)continue;let a=i.get(o);a?a.push(s):i.set(o,[s])}return e.map(s=>{if(s.includes(",")||s.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:s,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(i.get(Fy(s))??[]).filter(a=>a!==s).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:o.slice(0,r),candidates_truncated:o.length>r}})}function Py(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}async function hs(e){return e.includeBody?rt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):xi(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}var rT=5;async function iT(e,t){let n=t.hashMismatches.filter(s=>s!==Mt);if(n.length===0)return;let r=await R(e),i=F(r,M());for(let s of n){let o=await di(e,s,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let a=await V(e,s,r.id_prefix,r.item_format,i.type_to_folder);if(a===null)throw new f(`Item ${s} not found`,p.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await le(a,{schema:r.schema});if(c.metadata.id!==s)throw new f(`Item identity changed while validating ${s}`,p.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await Mf(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(m=>m!==s),...d[u].filter(m=>m===s)].sort((m,_)=>m.localeCompare(_));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==s),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===s)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await o()}}}async function gs(e,t,n){let r=await ir(e,t);await iT(e,r);let s=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,d])=>d>0).map(([d,l])=>`${d}:${l}`),o=n?Number.POSITIVE_INFINITY:rT,a=r.driftedItems.slice(0,o),c=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:c.length>0?"error":s.length===0?"ok":"warn",ok:c.length===0&&s.length===0,details:{identity_discontinuities:c.slice(0,o),identity_discontinuities_count:c.length,identity_discontinuities_truncated:c.length>o,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,o)}},warnings:s}}function uc(e){let t=0,n=new Map,r=new Map,i=[],s=new Set,o=[],a=l=>{n.set(l,t),r.set(l,t),t+=1,i.push(l),s.add(l);for(let m of e.get(l)??[])n.has(m)?s.has(m)&&r.set(l,Math.min(r.get(l),n.get(m))):(a(m),r.set(l,Math.min(r.get(l),r.get(m))));if(r.get(l)!==n.get(l))return;let u=[];for(;i.length>0;){let m=i.pop();if(s.delete(m),u.push(m),m===l)break}u.sort((m,_)=>m.localeCompare(_)),o.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return o.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function ys(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],s=new Set([n]),o=a=>{for(let c of(t.get(a)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!s.has(c)){if(s.add(c),i.push(c),o(c))return!0;i.pop(),s.delete(c)}}return!1};return o(n)?[...i]:[...e,n]}function sT(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function oT(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let s=r.resolve(i.kind);if(!s?.hierarchy)continue;let o=n.get(i.id.toLowerCase());o&&(s.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function mc(e,t=ie()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((s,o)=>s.id.localeCompare(o.id))){let s=r.get(i.id),o=sT(i.parent,n);o&&s.push(o),oT(i,r,n,t)}for(let[i,s]of r)r.set(i,[...new Set(s)].sort());return r}function pc(e,t,n=ie()){let r=Fi(e,o=>t?ht(o,t):o==="closed"||o==="canceled",n),i=mc(e,n),s=r.cycles.map(o=>o.item_ids);return{cycle_count:s.length,active_cycle_count:r.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(s.flat())].sort(),cycle_sample_paths:s.map(o=>ys(o,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:r.divergences.map(o=>`${o.child_id}:scalar=${o.scalar_parent_id}:dependencies=${o.dependency_parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`)}}function St(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function fc(e){return St(e).replace(/\/+$/,"")}function Ue(e){let t=te(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function _c(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}var lT=["src","tests","docs"],uT=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],mT=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),pT=["resolution","expected_result","actual_result"],fT=["default","tracked-all","tracked-all-strict"],Uy=["core","strict","custom"],ks=["off","warn","error"],yc=["author","acceptance_criteria","estimated_minutes","close_reason"],Gy=[...yc,"reviewer","risk","confidence","sprint","release"],wc=Array.from(new Set(Gy)),_T={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"},hT={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},gT={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},yT={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},wT={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},vT=32*1024*1024,kT=1e4,vc=40,je=5,bT=4096,ST=255,AT=dT(cT);function Ky(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?Ky(r):r);return t}function xT(e){return{...e,checks:e.checks.map(t=>({...t,details:Ky(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function Ss(e,t){return re(e,t)??e}function Sr(e,t){return t.terminal_statuses.has(Ss(e,t))}function At(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ws(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function CT(e){let t=At(Ud),n={blocked_reason:At(Pr.blocked_reason),resolution:At(Pr.resolution),actual_result:At(Pr.actual_result)},r=At(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:At(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:At(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:At(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:ws(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:ws(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:ws(i.resolution,n.resolution)?"default":"settings",actual_result:ws(i.actual_result,n.actual_result)?"default":"settings"}}}function zy(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Uy.includes(t))return t;throw new f(`Unknown --metadata-profile value "${e}". Supported values: ${Uy.join(", ")}.`,p.USAGE)}function Wy(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ks.includes(t))return t;throw new f(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ks.join(", ")}.`,p.USAGE)}function By(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ks.includes(t))return t;throw new f(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ks.join(", ")}.`,p.USAGE)}function ET(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>_T[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function RT(e,t,n){let r=ET(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...yc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Gy],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...yc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var TT=new Set(["acceptance_criteria","estimated_minutes"]);function Hy(e,t,n,r){return!r&&TT.has(t)&&Sr(e.status,n)?!1:t==="author"?!te(e.author):t==="acceptance_criteria"?!te(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ss(e.status,n)===n.close_status&&!te(e.close_reason):t==="reviewer"?!te(e.reviewer):t==="risk"?!te(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!te(e.confidence):t==="sprint"?!te(e.sprint):!te(e.release)}function Vy(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new f(`Unknown --scan-mode value "${e}". Supported values: ${fT.join(", ")}.`,p.USAGE)}function Yy(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Se.resolve(t);let n=Se.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Se.dirname(Se.dirname(n));let i=Se.resolve(process.cwd()),s=jy(n),o=jy(i),a=Se.relative(s,o);return a.length===0||!a.startsWith("..")&&!Se.isAbsolute(a)?n:i}function jy(e){try{return aT.native(e)}catch{return Se.resolve(e)}}function IT(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Ac(e,t,n){let r=t.length>0?Se.join(e,t):e,i;try{i=await Sc.readdir(r,{withFileTypes:!0})}catch(s){if(B(s))return;throw s}for(let s of i){if(s.name.startsWith("."))continue;let o=t.length>0?Se.join(t,s.name):s.name;if(s.isDirectory()){if(mT.has(s.name))continue;await Ac(e,o,n);continue}s.isFile()&&n.push(St(o))}}async function kc(e){let t=[];for(let n of lT)await Ac(e,n,t);for(let n of uT){let r=Se.join(e,n);try{(await Sc.stat(r)).isFile()&&t.push(St(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function Xy(e){try{let{stdout:t}=await AT("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:vT,windowsHide:!0,timeout:kT}),n=t.split("\0").map(r=>St(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function OT(e,t){let n=new Set,r=fc(Fd);r.length>0&&n.add(r);let i=fc(Se.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((s,o)=>s.localeCompare(o))}function qy(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function $T(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await Xy(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await kc(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await kc(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function J(e,t=je){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Kt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=J(e,vc);return{values:n.values,truncated:n.truncated,total:e.length}}var NT={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},LT={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function MT(e){let t=e.missing_fields.map(n=>`${NT[n]} "${LT[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Jy(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(o=>typeof o=="string"):Ug(t);if(i.length===0)return;let s=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...s?{fix_hints_truncated:!0}:{}}}function Qy(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var FT="validate_metadata_duplicate_issue_codes";function Zy(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:je,r=e.slice(0,n);return{rows:r.map(s=>({code:s.code,count:s.count,ids:s.ids,titles:s.titles,remediation_hint:`Items ${s.ids.join(", ")} share issue code "${s.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${FT}:${e.length}`]}}function DT(e,t,n){let r=Object.fromEntries(wc.map(i=>[i,[]]));for(let i of e)for(let s of wc)Hy(i,s,t,n)&&r[s].push(i.id);return r}function PT(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let s=t[i];s.length>0&&r.push(`${hT[i]}:${s.length}`)}return r.push(...n),r}function ew(e,t){let n={};for(let r of e.required_fields){let i=t[r],s=i?i.length:0,o=gT[r];n[o]=s}return n}function tw(e,t,n){let r=[];for(let i of e.required_fields){let s=t[i];if(s)for(let o of s){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:i})}}return r}function UT(e,t,n,r){for(let i of t.required_fields){let s=n[i];if(!s||s.length===0)continue;let o=yT[i],a=wT[i];if(!o||!a)continue;let c=J(s,r?s.length:je);e[o]=c.values,e[a]=c.truncated}}function nw(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:te(n.get(i)?.resolution)})):[]}function rw(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:te(n.get(i)?.type)})):[]}function jT(e,t,n,r,i){let s=new Map(e.map(v=>[v.id,v])),o=t.profile==="strict",a=DT(e,n,o),c=Ly(e,{configuredPrefixes:i}),d=Zy(c,r),l=PT(t,a,d.warnings),u=ew(t,a),m=tw(t,a,s),_=My(m),h={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...wc],counts:u,missing_by_type:_,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(h.configured_custom_required_fields=[...t.configured_custom_fields]);let g=fs(e,r);g!==void 0&&(h.deferred_fields=g.details,l.push(g.warning)),UT(h,t,a,r);let y=nw(t,a,s),w=rw(t,a,s);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:h},warnings:l,closeReasonBackfillRows:y,estimateBackfillRows:w}}function qT(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Ss(m.status,t))),s=[],o=[];for(let m of i){let _=pT.filter(h=>!te(m[h]));_.length!==0&&(s.push({id:m.id,missing_fields:_}),o.push({id:m.id,missing_fields:_,close_reason:te(m.close_reason)}))}let a=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:je,d=J(s.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=s.map(m=>MT(m)),u=J(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:i.length,missing_resolution_items:s.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function iw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sw(e,t="pm",n=hu()){let r=new Set(e.map(s=>s.id)),i=[...e].sort((s,o)=>s.id.localeCompare(o.id));return new Map(i.map(s=>{let o=new Set,a=Ue(s.blocked_by);a&&r.has(a)&&o.add(a),(s.dependencies??[]).filter(d=>{let l=Ue(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ue(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>o.add(d));let c=Ue(s.definition_of_ready);return aw(c??"",t).filter(d=>r.has(d)).forEach(d=>o.add(d)),[s.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function ow(e,t,n){let r=kf(e,n?l=>Sr(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),s=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:je,a=J(i,o),c=J(s,o),d=J(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+s.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function aw(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${iw(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,s)=>i.localeCompare(s))}function cw(e,t="pm"){let n=sw(e,t),r=uc(n),i=[...new Set(r.flat())].sort((o,a)=>o.localeCompare(a)),s=r.map(o=>ys(o,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:s}}function dw(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function bs(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function lw(e,t){let n=bs(e).split("/").filter(Boolean),r=bs(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function GT(e,t){let n=bs(t),r=bs(e),i=t.endsWith("/")?t:`${t}/`,s=e.startsWith(i),o=n.length>0&&n===r,a=lw(e,t);return!s&&!o&&a===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function KT(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function zT(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(s=>(r==="docs"?s.docs??[]:s.files??[]).map(o=>({item:s,link:o}))).forEach(({item:s,link:o})=>{if(o.scope!=="project")return;let a=St(o.path);if(a.length===0||a===e)return;let c=GT(e,a);c!==null&&KT(i,s,c.score)&&(i={item:s,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function uw(e,t){return e.map(n=>{let r=dw(n),i=r==="docs_unowned"?"docs":"files",s=zT(n,r,t),o=s?.id??"<id>";return{path:n,classification:r,owner_candidate:s,remediation_hint:`pm ${i} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function mw(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function WT(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Ue(e[n]);return i?r.some(s=>i.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function BT(e,t,n,r,i){let s=Ue(t.parent),o=s?n.get(r.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!Sr(o.status,i)}}function HT(e,t,n,r){let i=Ue(e.blocked_by),s=Ue(e.blocked_reason),o=s?.toLowerCase(),a=Ss(e.status,n),c=[];return t.has(a)?(!i&&!s&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&r.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function VT(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!Sr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=WT(c,r);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=Ue(c.parent),u=l?i.get(s.get(l.toLowerCase())??l):void 0;if(u&&Sr(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(BT(c,u,i,s,n))),t){let m=HT(c,o,n,r);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((_,h)=>_.localeCompare(h))})}}return a}function YT(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function vs(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function hc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function XT(e,t,n,r,i){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=vs("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),a=vs("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=vs("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=vs("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=hc("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=hc("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=hc("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...s,...o?[o]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function pw(e){let t=St(e);return t.length>bT||t.split(/[\\/]/).some(n=>n.length>ST)}async function JT(e,t){let n=Se.isAbsolute(t)?t:Se.resolve(e,t);if(pw(n))return!1;try{let r=await Sc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return IT(r,["ENOENT","ENOTDIR"])}}async function QT(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(s=>({item:i,artifact:s,link_kind:"files"})),...(i.docs??[]).map(s=>({item:i,artifact:s,link_kind:"docs"}))]);for(let{item:i,artifact:s,link_kind:o}of r){if(s.scope!=="project")continue;if(Tf(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let a=St(s.path);a.length!==0&&(n.linkedProjectPaths.add(a),await JT(t,s.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:o})))}return n}function ZT(e,t,n,r,i,s){let o=r==="tracked-all-strict",a=o&&!i,c=i||o,d=c?[]:OT(t,n),l=d.length===0?[]:e.candidateFiles.filter(_=>qy(_,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(_=>!qy(_,d)),m={};if(l.length>0){let _=Kt(l,s);m.pm_internals={count:l.length,paths:_.values,paths_truncated:_.truncated,paths_total:_.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function fw(e,t,n,r,i,s,o,a="pm"){let c=VT(e,t,i,s);YT(c);let d=cw(c.activeItems,a),l=pc(e,i),u=ls(i,e,o?Number.POSITIVE_INFINITY:je),m=[...XT(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...us(u)],_=o?Number.POSITIVE_INFINITY:je,h=J(c.closureLikeRows.map(x=>`${x.id}:${x.fields.join(",")}`),_),g=J(c.terminalParentRows.map(x=>`${x.id}:${x.parent_id}:${x.parent_status}`),_),y=J(c.staleBlockerRows.map(x=>`${x.id}:${x.status}:${x.reasons.join(",")}`),_),w=J(d.cycle_item_ids,_),v=J(d.cycle_sample_paths,_),k=J(l.cycle_item_ids,_),b=J(l.cycle_sample_paths,_),A=J(l.cardinality_violation_rows,_),C=J(l.parent_divergence_rows,_),S=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:S?"error":m.length===0?"ok":"warn",ok:!S&&m.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:h.values,active_closure_like_metadata_rows_truncated:h.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:g.values,active_terminal_parent_rows_truncated:g.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:w.values,dependency_cycle_item_ids_truncated:w.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:b.values,parent_cycle_sample_paths_truncated:b.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:A.values,hierarchy_cardinality_violation_rows_truncated:A.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:C.values,hierarchy_parent_divergence_rows_truncated:C.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function _w(e,t,n,r,i,s,o=q(Et.schema)){let a=await QT(e,t),c=new Map(e.map(E=>[E.id,E])),d=[...new Set(a.missingLinkedPaths)].sort((E,K)=>E.localeCompare(K)),l=await $T(t,r),u=ZT(l,n,t,r,i,s),m=u.candidateFiles.filter(E=>!a.linkedProjectPaths.has(E)),_=uw(m,e),h=Dy(d,u.candidateFiles),g=new Map(h.map(E=>[E.path,E.classification])),y=h.filter(E=>E.classification==="moved").length,w=a.staleLinkRows.map(E=>({...E,classification:g.get(E.path)??"deleted"})).sort((E,K)=>E.item_id.localeCompare(K.item_id)||E.path.localeCompare(K.path)||E.link_kind.localeCompare(K.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),m.length>0&&v.push(`validate_files_orphaned_paths:${m.length}`);let k=[...a.remoteLinkedPaths].sort((E,K)=>E.localeCompare(K)),b=Kt(k,s),A=Kt(d,s),C=Kt(m,s),S=Kt(_.map(E=>`${E.path}:${E.classification}:owner_candidate=${E.owner_candidate?.id??"unowned"}`),s),x=s?_:Kt(mw(_),!1).values,D=Kt(Py(h),s),T=vy(w,h,E=>c.get(E),o,s?1/0:vc);return T.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${T.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:s?"full":"summary",file_list_summary_limit:vc,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:k.length,remote_linked_paths_total:b.total,remote_linked_paths:b.values,remote_linked_paths_truncated:b.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:A.total,missing_linked_paths:A.values,missing_linked_paths_truncated:A.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:h.filter(E=>E.classification==="deleted").length,missing_linked_paths_malformed_count:h.filter(E=>E.classification==="malformed").length,missing_linked_path_classifications:D.values,missing_linked_path_classifications_truncated:D.truncated,...T,orphaned_paths_count:m.length,orphaned_paths_total:C.total,orphaned_paths:C.values,orphaned_paths_truncated:C.truncated,orphaned_path_classifications:S.values,orphaned_path_classifications_truncated:S.truncated,orphaned_path_rows_count:_.length,orphaned_path_rows:x}},warnings:v,staleLinkPruneRows:w}}function eI(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},s)=>{let o=t[s];if(o.trusted)return;let a=_c(i.command??"");n.push(`${r.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${a}`)}),n}async function hw(e,t,n,r){let i=new Set(e.map(A=>A.id.toLowerCase())),s=0,o=0,a=new Set,c=[],d=e.flatMap(A=>(A.tests??[]).map(C=>({item:A,linkedTest:C}))),l=await Uf(jf()),u=await qf(r,d.map(({linkedTest:A})=>A),l),m=eI(d,u);for(let{item:A,linkedTest:C}of d){if(typeof C.command!="string"||C.command.trim().length===0)continue;s+=1;let S=Pf(C.command,t);if(S.length!==0){o+=S.length;for(let x of S)a.add(x),i.has(x.toLowerCase())||c.push(`${A.id}:${x}:${_c(C.command)}`)}}let _=[...new Set(c)].sort((A,C)=>A.localeCompare(C)),h=[...new Set(_.map(A=>A.split(":")[1]??""))].filter(A=>A.length>0).sort((A,C)=>A.localeCompare(C)),g=[];_.length>0&&g.push(`validate_command_references_stale_pm_ids:${_.length}`),m.length>0&&g.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let y=n?Number.POSITIVE_INFINITY:je,w=J(_,y),v=J(h,y),k=J([...a].sort((A,C)=>A.localeCompare(C)),y),b=J(m,y);return{check:{name:"command_references",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_items:e.length,linked_commands_scanned:s,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:b.values,untrusted_linked_tests_truncated:b.truncated,stale_pm_id_references_count:_.length,stale_pm_ids_count:h.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:g}}function tI(e,t){let n=oi(e.map(c=>({ref:c.id,version:si(c)})),4,1),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:je,s=J(n.outdated,i),o=J(n.ahead,i),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:4,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:r}}var bc="pm validate auto-fix";async function gw(e,t,n){switch(e.kind){case"set_closed_at":await gy(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:bc};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new f("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",p.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function gc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function yw(e,t,n){let r=[],i=[],s=new Map;for(let o of e.filter(a=>gc(a)===null))try{await gw(o,t,n),r.push(o)}catch(a){i.push({fix:o,error:a})}for(let o of e.filter(a=>gc(a)!==null)){let a=gc(o),c=s.get(a);c?c.push(o):s.set(a,[o])}for(let o of s.values()){let a=o[0];if(!a)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await lg(a.item_id,{remove:c,message:bc},t):await Jh(a.item_id,{remove:c,message:bc},t),r.push(...o)}catch(d){i.push(...o.map(l=>({fix:l,error:d})))}}return um(i.map(o=>o.error)),{applied:r,failed:i}}var IG={applyValidateFix:gw,applyValidateFixes:yw,attachValidateFixHints:Jy,buildCommandReferencesCheck:hw,buildDependencyReferencesCheck:ow,buildCloseReasonBackfillRows:nw,buildFilesCheck:_w,buildLifecycleCheck:fw,buildLifecycleDependencyGraph:sw,buildLifecycleParentGraph:mc,buildEstimateBackfillRows:rw,buildMetadataCounts:ew,buildMissingFieldOccurrences:tw,buildOrphanedPathRows:uw,classifyOrphanedPath:dw,collectDefaultProjectFileCandidates:kc,collectTrackedGitFileCandidates:Xy,detectLifecycleDependencyCycles:cw,detectLifecycleParentCycles:pc,escapeRegExp:iw,extractItemIds:aw,findLifecycleDependencyCycleComponents:uc,isMetadataFieldMissing:Hy,linkedArtifactPathExceedsFilesystemLimits:pw,listFilesRecursive:Ac,resolveDependencyCycleSeverity:Wy,resolveParentCycleSeverity:By,resolveFileScanMode:Vy,resolveLifecycleDependencyCycleSamplePath:ys,resolveRequestedChecks:Qy,resolveValidateMetadataProfile:zy,resolveWorkspaceRoot:Yy,sharedDirectoryPrefixLength:lw,summarizeOrphanedPathRows:mw,summarizeDuplicateIssueCodes:Zy,toMeaningfulString:Ue};function nI(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function rI(e,t,n,r){let i=await by(e,new Set(t.map(y=>y.id)),n,{schema:r.schema,extensionFieldNames:gt(M())}),s=[];i.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let o=s.length,a=await ms(e);a.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await kt(e),d=await fn(e,pn(r),{gitWorkspaceRoot:c});d.status==="drift"&&s.push(`validate_merge_fence_drift:${d.missing_patterns.length+d.stale_patterns.length}`);let l=c===null?null:await _n(c);l!==null&&l.status!=="ok"&&s.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await gn(c??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:_,lossless:h}=yn(m);_.length>0&&s.push(`validate_merge_decisions_unreviewed:${_.length}`),nI(s,u.invalid_evidence_count);let g=o>0?"error":s.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:g,ok:g==="ok",details:{...i,merge_fence:d,merge_driver_configuration:l,pending_merge_decision_count:_.length,pending_merge_decision_items:[...new Set(_.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),lossless_merge_receipt_count:h.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(h.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:s}}async function iI(e,t,n,r){let i=[zp(n,r),await Bp(t,n,r),await Ay(t,n,r)];for(let s of i)Object.assign(e.check.details,s.details),e.warnings.push(...s.warnings)}function Je(e,t,n){n&&Jy(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function sI(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let i=await xf(e.pmRoot,e.items,r?1/0:je,e.sourceIncomplete);Je(t,i,n)}if(e.requestedChecks.has("metadata")){let i=jT(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let s=r?1/0:je,o=await hy(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,s);t.closureTimestampFixes=o.fixes,Object.assign(i.check.details,o.details),i.warnings.push(...o.warnings),await iI(i,e.pmRoot,e.settings.schema,s),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",Je(t,i,n)}if(e.requestedChecks.has("resolution")){let i=qT(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,Je(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=fw(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,Je(t,i,n),Je(t,ow(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await _w(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,Je(t,i,n)}return e.requestedChecks.has("command_references")&&Je(t,await hw(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&Je(t,await gs(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&Je(t,tI(e.items,r),n),e.requestedChecks.has("storage_integrity")&&Je(t,await rI(e.pmRoot,e.items,F(e.settings,M()).type_to_folder,e.settings),n),t}function oI(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...Ey(t.closeReasonBackfillRows)),r.push(...Cy(t.resolutionBackfillRows)),r.push(...Ry(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Ty(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Iy(t.staleLinkPruneRows)),r}async function aI(e,t,n,r,i,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=oI(e,t,n),{applicable:a,gated:c}=$y(o,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await yw(a,i,s);l.push(...m.applied.map(br)),u.push(...m.failed.map(({fix:_,error:h})=>({...br(_),error:h instanceof Error?h.message:String(h)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,_)=>m.localeCompare(_)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(br),applied_fixes:l,gated_fixes:c.map(m=>({...br(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function ww(e,t,n={}){ru(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new f("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",p.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new f("--fix-scope requires --auto-fix.",p.USAGE);let i=Oy(e.fixScope),s=I(process.cwd(),t.path);await z(s);let o=await R(s),a=q(o.schema),c=F(o,M()),d=Qy(e),l=[],u=await hs({includeBody:["history_drift","metadata","completeness"].some(U=>d.has(U)),pmRoot:s,settings:o,typeToFolder:c.type_to_folder,warnings:l}),m=l.length>0;if(d.has("history_drift")){let U=await yr(s);U.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${U.actionable_unknown_event_count}`)}let _=typeof e.metadataProfile=="string"?"option":"settings",h=zy(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),g=RT(h,_,o.validation.metadata_required_fields),y=CT(o),w=Wy(e.dependencyCycleSeverity),v=By(e.parentCycleSeverity),k=Vy(e.scanMode),b=Yy(s),A=await sI({requestedChecks:d,options:e,global:t,pmRoot:s,workspaceRoot:b,settings:o,items:u,statusRegistry:a,metadataPolicy:g,lifecyclePatternPolicy:y,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:k,initialWarnings:[...new Set(l)],sourceIncomplete:m}),C=r?await aI(e,A,o,i,t,n):void 0,S=[...new Set(A.warnings)].sort((U,T)=>U.localeCompare(T)),D={ok:!A.checks.some(U=>U.status==="error"),has_warnings:S.length>0,checks:A.checks,warnings:S,...C!==void 0?{fixes:C}:{},generated_at:O(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?D:{...xT(D),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as cI}from"node:child_process";import{promisify as dI}from"node:util";var lI=dI(cI),uI=16,mI=3e4;function pI(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(s=>typeof s=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function fI(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let s of Object.entries(i).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(r,s))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${s}`);for(let[s,o]of Object.entries(r)){let a=i[s];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${s}`);if(o===null||typeof o!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${s} must be ${a.type}`)}return{...r}}async function _I(e,t,n,r){let i=fI(e,t),s=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...vu(n)}));s.catch(()=>{});let o;try{let a=await Promise.race([s,new Promise((c,d)=>{o=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??mI),o.unref?.()})]);return pI(e,t.key,a)}finally{clearTimeout(o)}}function kw(e,t,n,r){let i=e;for(let s of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new Xe(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[s]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(s=>typeof s=="string"))return i;throw new Xe(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function vw(e,t,n,r){let i=e.checks.find(o=>o.name===t);if(!i)throw new Xe(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:kw(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function hI(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await lI("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function gI(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(uI,t.length)},async()=>{for(;r<t.length;){let s=r;r+=1;let o=t[s],a=await Lt(Me(e,o.id),o.id);n[s]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function Ar(e,t={}){let n=await R(e),r=F(n),i=q(n.schema),o=(t.strict_read===!0?(await Sf(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await rt(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(_=>({..._,id:_.id,status:_.status,type:_.type})),a={path:e},c=M(),d=Object.fromEntries((c?.assurance_providers??[]).map(_=>[_.definition.id,{cost_class:_.runtime_definition.cost_class,network:_.runtime_definition.network}])),l=new Map,u,m;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await hI(e,t.tree_id),items:o,history:t.include_history===!1?[]:await gI(e,o),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async _=>{if(_.kind==="graph"){let y=Z({operation:_.operation,parameters:_.parameters??{}}),w=l.get(y);w===void 0&&(w=Lf(_.operation,void 0,void 0,{..._.parameters,full:!0},a),l.set(y,w));let v=await w;return{value:kw(v,_.field,_.kind),population_size:o.length,cost:o.length}}if(_.kind==="validate"){u??=ww({counts:!0},a);let y=await u;return vw(y,_.check,_.field,_.kind)}if(_.kind==="health"){m??=py(a,{checkOnly:!0,full:!0});let y=await m;return vw(y,_.check,_.field,_.kind)}let h=t.providers?.[_.provider];if(h)return h(_);let g=Eu(c,_.provider);if(!g)throw new TypeError(`assurance provider ${_.provider} is not registered`);return _I(g.runtime_definition,_,e,t.trigger??"sdk")}}}import{createHash as yI}from"node:crypto";function bw(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:i}=Ii({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function wI(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let r=n;if(r.fingerprint!==t||typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return r.offset}function vI(e,t,n,r,i,s){let o=Object.fromEntries(ta.map(_=>[_,0])),a=0,c=0,d=0,l=0,u=[],m=yI("sha256").update(i);for(let _ of r){let h=e.membership.get(_),g=n.has(_),y=h.family_ids.length>0;y&&g&&(a+=1),y||(c+=1),g||(d+=1);let w=t.get(_)?.escape_class;w!==void 0&&ta.includes(w)&&(o[w]+=1,l+=1),m.update(Z([_,g,t.get(_)??null,h.id,h.family_ids])),(!s||!y||!g)&&u.push(_)}return{classCounts:o,coveredCount:a,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:m.digest("hex")}}function Sw(e,t,n={}){df(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let i=new Set,s=new Map;for(let b of t){if(i.has(b.id))throw new TypeError(`Duplicate recurrence item ${b.id}`);i.add(b.id);let A=Ti(b);A!==void 0&&s.set(b.id,A)}let o=sf(e.families,s),a=[...o.membership.keys()].sort(),c=Z({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:m,classifiedCount:_,selected:h,fingerprint:g}=vI(o,s,i,a,c,n.uncoveredOnly===!0),y=wI(n.cursor,g);if(y>h.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=h.slice(y,y+r).map(b=>{let A=o.membership.get(b),C=i.has(b);return{item_id:b,lineage_id:A.id,lineage_item_count:A.item_ids.length,family_ids:A.family_ids,present:C,...C?A.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=y+w.length,k=a.length===0?null:d.production_defect/a.length;return{ok:u===0&&m===0,fingerprint:g,items:w,total:h.length,has_more:v<h.length,...v<h.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:g,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:a.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:m,classified_item_count:_,unclassified_item_count:a.length-_,class_counts:d,escape_rate:_===a.length?k:null,escape_rate_lower_bound:k},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as kI}from"node:crypto";var xc,Aw=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],Cc=["measurement","assertion","gate"];function bI(e){if(Aw.includes(e))return e;throw ti({command_path:"assurance",token:e,allowed:Aw,display_name:"assurance action"})}function Tn(e,t,n){throw new f(t,p.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function SI(e){if(!e)return Tn("kind",`Assurance declaration kind is required. Expected: ${Cc.join(", ")}`,"pm assurance list measurement");if(Cc.includes(e))return e;throw new f(`Assurance declaration kind is required. Expected: ${Cc.join(", ")}`,p.USAGE)}function xw(e){if(!e)return Tn("preset",`Assurance preset is required. Expected: ${wr.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(wr.includes(e))return e;throw new f(`Assurance preset is required. Expected: ${wr.join(", ")}`,p.USAGE)}function Ec(e){return e.owner?.trim()?e.owner.trim():Tn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function AI(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new f("assurance definition must be valid JSON",p.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new f("assurance put requires a JSON object definition",p.USAGE);return n}async function xI(e){let[t,n,r]=await Promise.all([pr(e,"measurement"),pr(e,"assertion"),pr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Cw(e,t){return t===!0?{id:e.id}:e}async function CI(e,t){let n=t.authorization_decision;if(!n)return[];let r=await Ar(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(o=>o.id===n),s=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!s.has(i.status))throw new f(`Assurance authorization ${n} must name a terminal Decision item`,p.USAGE);return[i.id]}async function EI(e,t){let n=sa(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>1e3))throw new f(`assurance verdict limit must be an integer from 1 through ${1e3}`,p.USAGE);let r=await wh(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Ew(e,t,n){try{return await Ra(()=>hh(e,t,n))}catch(r){if(!(r instanceof f)||r.context.reason!=="assurance_evaluation_refused")throw r;let i=["--pm-path",e,"assurance","list",t,"--output-budget","2000","--json"],s=L(i);throw Object.assign(r.context,{changed:!1,value:n,required:`Choose a configured ${t} declaration ID using the bounded discovery command.`,why:`The requested ${t} declaration does not exist. The registry and history were not changed.`,examples:[s],recovery:{next_best_command:s,suggested_retry:s,suggested_retry_args:i}}),r}}async function RI(e,t,n){if(e==="presets"){if(t.preset??t.id)return cs(xw(t.preset??t.id),Ec(t));let i=wr.map(s=>{let o=cs(s,"pm-owner");return{id:s,title:o.title,description:o.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return bn(()=>fg(n,xw(t.preset??t.id),Ec(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await _g(await Ar(n,{resolve_tree:!1,trigger:"derive"}),Ec(t)),s=t.apply?await bn(()=>hg(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...s?{applied:s}:{}}}if(!t.id)return Tn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new f("assurance promote requires --enforcement warn|block",p.USAGE);let r=await Ew(n,"assertion",t.id);return bn(()=>gg(n,r,t.enforcement,{author:t.author,message:t.message}))}async function TI(e,t,n){if(!e.id)return Tn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new f("assurance run requires a trigger",p.USAGE);if(!st.includes(e.trigger))throw new f(`Unknown assurance trigger ${e.trigger}. Expected: ${st.join(", ")}`,p.USAGE);let i=e.trigger,[s,o]=await Promise.all([xI(t),Ar(t,{...n.workspace,tree_id:e.tree,trigger:i})]),a=await Ra(()=>fh(r,s,o,{trigger:i,dry_run:e.dry_run===!0}));return a.dry_run||await yh(t,a,{author:e.author,message:e.message}),a}function Rw(e){throw e instanceof f?e:new f(e instanceof Error?e.message:"assurance risk request is invalid",p.USAGE)}function II(e){if(e.limit!==void 0)throw new f(`assurance ${e.action} does not accept --limit; set limit inside the definition`,p.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new f(`assurance ${e.action} definition must be valid JSON`,p.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?bw(t):Ii(t)}catch(n){if(e.action==="risk"&&n instanceof cf)throw new f(n.message,p.USAGE,{required:"Supply definition.policy with the project's declared recurrence policy and definition.change with the proposed change; no policy is inferred.",recovery:{suggested_retry:`pm assurance ${e.action} --help`,suggested_retry_args:["assurance",e.action,"--help"]}});return Rw(n)}}function OI(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function $I(e,t,n){let r=Z(t.policy),i=xc?.pm_root===e?xc:void 0,s=new Map(n.map(d=>[d.id,kI("sha256").update(Z([rf(d),Ti(d)])).digest("hex")])),o=i?.policy_serialized===r?i:void 0,a=o?OI(o,s):new Set,c=of(t.policy,o?n.filter(d=>a.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...a]}:{});return xc={pm_root:e,policy_serialized:r,item_fingerprints:s,index:c},c}async function NI(e,t){let n=II(e),r=await Ar(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?af($I(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):Sw(n.policy,r.items,n)}catch(i){return Rw(i)}}async function LI(e,t={},n={}){let r=bI(e.action),i=I(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return RI(r,e,i);if(r==="verdicts")return EI(e,i);if(r==="run")return TI(e,i,n);if(["risk","lineages"].includes(r))return NI(e,i);let s=SI(e.kind);if(r==="list")return pr(i,s);if(!e.id)return Tn("id",`assurance ${r} requires an id`,`pm assurance ${r} ${s} <id>`);let o=e.id;if(r==="show")return Ew(i,s,o);if(r==="remove"){let l=await bn(()=>gh(i,s,o,{author:e.author,message:e.message}));return Cw(l,e.idOnly)}let a=AI(s,e.definition);if(a.id!==o)throw new f(`Assurance definition id ${a.id} does not match requested id ${o}`,p.USAGE);let c={author:e.author,message:e.message,...s==="assertion"?{authorized_decision_ids:await CI(i,a)}:{}},d=await bn(()=>es(i,s,a,c));return Cw(d,e.idOnly)}function pK(e,t,n){let r={...e,...t};return LI({action:X(r,"subcommand")??X(r,"assuranceAction")??X(r,"operation")??"",kind:X(r,"kind"),id:X(r,"id"),definition:r.definition,trigger:X(r,"trigger"),tree:X(r,"treeId")??X(r,"tree"),gate:X(r,"gate"),limit:sa(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:X(r,"author"),message:X(r,"message"),preset:X(r,"preset"),owner:X(r,"owner"),apply:r.apply===!0,enforcement:X(r,"enforcement")},n)}import Rc from"node:fs/promises";import Tw from"node:path";var MI=1440*60*1e3,FI=new Set(["committed","compensated"]);function DI(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:n.abandonment!==void 0?"abandoned":typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function PI(e,t,n,r,i){let s=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(s))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=r-s;return FI.has(t)?o>i?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function UI(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],s=DI(await Rc.readFile(e,"utf8")),o=PI(t,s.status,s.updatedAt,r.nowMs,r.retentionMs);return o.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),o.remove&&!r.dryRun&&(await Rc.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:o,warnings:i}}async function Iw(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=Math.max(0,t.retentionDays)*MI,o=Tw.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Rc.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(B(d))return a;throw d}for(let d of c){let l=Tw.join(o,d),u=`transactions/sdk/${d}`,m=await UI(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:s});a.warnings.push(...m.warnings),a.scanned+=1;let{decision:_}=m;if(!_.remove){a.retained.push(u),a.entries.push(_.entry);continue}a.removed.push(u),a.entries.push(_.entry)}return a}import zt from"node:fs/promises";import Cr from"node:path";import As from"node:fs/promises";import Tc from"node:path";var jI=864e5;function qI(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function GI(e,t){let n;try{n=await As.readdir(e,{withFileTypes:!0})}catch(i){if(B(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let s=Tc.join(e,i.name),o;try{o=await As.readdir(s)}catch(a){B(a)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of o)a.endsWith(".json")&&r.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function Ow(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=Math.max(0,t.retentionDays)*jI,o=Tc.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await GI(o,a.warnings);for(let d of c){let l=Tc.join(o,d),u=`checkpoints/${d}`;a.scanned+=1,r?.onRead&&a.warnings.push(...await r.onRead(l));let m;try{m=await As.readFile(l,"utf8")}catch(w){if(B(w)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let _=qI(m),h=_===null?Number.NaN:Date.parse(_);if(!Number.isFinite(h)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:_,age_seconds:null,stale:!1,reason:"unparseable"});continue}let g=i-h,y={file:u,created_at:_,age_seconds:Math.floor(g/1e3),stale:g>s,reason:g>s?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await As.unlink(l)}catch(w){if(!B(w)){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}r?.onWrite&&a.warnings.push(...await r.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}var xr=["index","embeddings","runtime","locks","checkpoints","transactions"],KI=1440*60*1e3,$w=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"},{scope:"runtime",relativePath:"runtime/history-stream-summary.json",kind:"file"}];async function zI(e,t,n){let r=t.relativePath,i=Cr.join(e,r),s=await Te({path:i,scope:"project"});if(t.scope==="runtime"&&await Nw(e))return{removed:!1,redirected:!0,warnings:s};try{let o=await zt.lstat(i);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...s,`not_a_file:${r}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...s,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:s};t.kind==="file"?await zt.unlink(i):await zt.rm(i,{recursive:!0,force:!0});let a=await nt({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...s,...a]}}catch(o){if(B(o))return{removed:!1,warnings:s};throw o}}async function WI(e,t,n){let r=[],i=[],s=[],o=!1;for(let a of $w.filter(c=>t.includes(c.scope))){if(a.scope==="runtime"&&o){i.push(a.relativePath);continue}let c=await zI(e,a,n);o||=c.redirected===!0,(c.removed?r:i).push(a.relativePath),s.push(...c.warnings)}if(t.includes("runtime")&&!o&&(o=await Nw(e)),o)s.push("redirected_runtime_directory:runtime");else if(t.includes("runtime")){let a=await BI(e,n);r.push(...a.removed),i.push(...a.retained),s.push(...a.warnings)}return{removed:r,retained:i,warnings:s}}async function Nw(e){try{return!(await zt.lstat(Cr.join(e,"runtime"))).isDirectory()}catch(t){if(B(t))return!1;throw t}}async function BI(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],s=[],o=Date.now()-KI;for(let a of n){let c=Cr.join(e,a.relativePath);if(!await me(c))continue;let d=(await zt.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=Cr.posix.join(a.relativePath,l),m=Cr.join(c,l);s.push(...await Te({path:m,scope:"project"}));let _=await zt.stat(m).catch(h=>{if(!B(h))throw h});if(_){if(_.mtimeMs>o){i.push(u);continue}r.push(u),!t&&(await zt.rm(m,{recursive:!0,force:!0}),s.push(...await nt({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:s}}function HI(e){if(!e||e.length===0)return[...xr];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new f(`--scope requires at least one value (${xr.join(",")})`,p.USAGE);let n=new Set;for(let r of t){if(!xr.includes(r))throw new f(`Invalid --scope value "${r}". Expected one or more of: ${xr.join(", ")}`,p.USAGE);n.add(r)}return xr.filter(r=>n.has(r))}function VI(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),e.removed.includes("runtime/history-stream-summary.json")&&t.push('History stream summary was removed; the next "pm activity" or "pm context" read parses every history stream once to rebuild it.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function FK(e,t={}){let n=I(process.cwd(),e.path);await z(n);let r=await R(n),i=t.dryRun===!0,s=HI(t.scope),{removed:o,retained:a,warnings:c}=await WI(n,s,i),d;if(s.includes("locks")){let _=await Pg(n,{dryRun:i,hooks:{onRead:h=>Te({path:h,scope:"project"}),onWrite:h=>nt({path:h,scope:"project",op:"gc:lock_remove"})}});o.push(..._.removed),a.push(..._.retained),c.push(..._.warnings),d={scanned:_.scanned,removed:_.removed.length,retained:_.retained.length}}let l;if(s.includes("transactions")){let _=r.checkpoints.retention_days,h=await Iw(n,{dryRun:i,retentionDays:_,hooks:{onRead:g=>Te({path:g,scope:"project"}),onWrite:g=>nt({path:g,scope:"project",op:"gc:transaction_journal_remove"})}});o.push(...h.removed),a.push(...h.retained),c.push(...h.warnings),l={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:_}}let u;if(s.includes("checkpoints")){let _=r.checkpoints.retention_days,h=await Ow(n,{dryRun:i,retentionDays:_,hooks:{onRead:g=>Te({path:g,scope:"project"}),onWrite:g=>nt({path:g,scope:"project",op:"gc:checkpoint_remove"})}});o.push(...h.removed),a.push(...h.retained),c.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:_}}c.push(...await xu({mode:i?"gc:dry-run":"gc",total_items:$w.filter(_=>s.includes(_.scope)).length}));let m=VI({dryRun:i,scopes:s,removed:o});return{ok:c.length===0,dry_run:i,scope:s,removed:o,retained:a,warnings:c,...d?{locks:d}:{},...u?{checkpoints:u}:{},...l?{transactions:l}:{},guidance:m,generated_at:O()}}var jK=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function YI(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 xs(e,t){return Ic(e,t,{operation:"close"})}function Ic(e,t,n){let r=YI(e);if(!t||r.closeReason!==void 0)return r;let i=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 f("Close reason text is required because governance.require_close_reason is enabled",p.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:i,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 Lw(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,i=e.dependencies??[],s=i.filter(d=>d.kind==="blocked_by"),o=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),o&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let d=new Set(s),l=i.filter(u=>!d.has(u));l.length>0?e.dependencies=l:delete e.dependencies,a.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:a,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...s.length>0?[`closed_removed_predecessors:${e.id}:${s.map(d=>d.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${s.length}`]:[]]};let c=[...new Set([...n?[n]:[],...s.map(d=>d.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}var XI=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function JI(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 f(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,p.USAGE)}function Fw(e){let t=[];for(let n of XI){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function Dw(e,t,n={}){let r=Fw(e);if(r.length===0)return;let i={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},s=r.map(a=>`--${a.key.replaceAll("_","-")}`),o=[...t,"update",e.id,...r.flatMap((a,c)=>[s[c],i[a.key]?.trim()||"<value>"])];return{missing:s,suggested_retry:L(o),suggested_retry_args:o}}async function QI(e,t,n){let r=new Set,i=t;for(;typeof i=="string"&&i.trim().length>0;){let s=i.trim();if(s===n)return!0;if(r.has(s))return!1;r.add(s),i=(await e(s))?.duplicate_of}return!1}function ZI(e){return typeof e!="string"||e.trim().length===0}async function eO(e,t,n,r){let i=n?.trim();if(!i)return;if(i===r)throw new f("An item cannot be closed as a duplicate of itself.",p.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=F(t,M()),o=new Map,a=async d=>{if(o.has(d))return o.get(d)??null;let l=await V(e,d,t.id_prefix,t.item_format,s.type_to_folder);if(!l)return o.set(d,null),null;let{document:u}=await le(l,{schema:t.schema});return o.set(d,u.metadata),u.metadata},c=await a(i);if(!c)throw new f(`Duplicate target "${i}" was not found. Create or locate the canonical item first.`,p.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 ${i}" --duplicate-of ${i}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await QI(a,c.duplicate_of,r))throw new f(`Circular duplicate reference detected. Target "${i}" points back to "${r}".`,p.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 f(`Duplicate target "${i}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,p.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 tO(e,t,n){return e.filter(r=>r.parent===t&&!ae(r.status,n)).map(r=>r.id).sort((r,i)=>r.localeCompare(i))}function nO(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),i=cm(e),s=t.trim().toLowerCase(),o=n.blocked_statuses;return e.filter(a=>o.has(a.status)).map(a=>({item:a,blockerIds:i.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let d=r.get(c);return d!==void 0&&ae(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function rO(e,t,n,r,i,s,o){let a=nO(n,r,s),c=[],d=[],l=[],u=[],m;for(let _ of a)try{let h=await Ie({pmRoot:e,settings:t,id:_.id,op:"update",author:i,message:`Auto-unblocked after blocker ${r} closed`,mutate(g){let y=g.metadata.dependencies??[],w=y.filter(k=>{let b=k.id.trim().toLowerCase();return k.kind!=="blocked_by"||!_.blocker_ids.includes(b)});g.metadata.status=s.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 (${_.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:${h.item.id}:resolved_blockers=${_.blocker_ids.join(",")}`),d.push(h.item.id)}catch(h){let g=h instanceof Error?h.message.replace(/\s+/g," ").trim():"unknown";Vn(h)?(m??=h,l.push(_.id)):u.push({id:_.id,reason:g}),c.push(`auto_unblock_failed:${_.id}:${g}`)}if(m!==void 0){let _=await mm(m,e),h=[...s.blocked_statuses].sort().join(",");throw aO(_,{closedId:r,unblockedIds:d,conflictIds:l,failed:u,openStatus:s.open_status,blockedStatuses:h,commandScope:o})}return c}var lt=10,Oc=20,iO=[{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 sO(e){for(let t of iO){let n=e[t.list];if(Array.isArray(n))for(;n.length>t.floor&&!Zu(e);)n.pop(),Reflect.set(e,t.omitted,Number(e[t.omitted])+1)}return e}function Mw(e){let t=e.length-lt;return`${e.slice(0,lt).join(", ")}${t>0?`, and ${t} more`:""}`}var oO="post_close_auto_unblock_refused";function aO(e,t){let{closedId:n,conflictIds:r,failed:i,commandScope:s}=t,o=String(e.context.item_id),a=h=>L([...s,"update",h,"--status",t.openStatus,"--unset","blocked_by","--unset","blocked_reason","--expect-hash",`${h}=<item_hash>`]),c=i.slice(0,lt).map(h=>({id:h.id,reason:tu(h.reason,160)})),d=i.length===0?"":` Auto-unblocking also failed for ${Mw(i.map(h=>h.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.`,l=L([...s,"list","--status",t.blockedStatuses,"--fields","id,title,blocked_by,dependencies","--limit","200"]),u=[...r.slice(0,lt).flatMap(h=>[L([...s,"get",h,"--json"]),a(h)]),...c.map(h=>L([...s,"get",h.id,"--json"]))],m=r.length>lt||i.length>lt||u.length>Oc,_=u.slice(0,m?Oc-1:Oc);return new f(`${n} was closed, but auto-unblocking ${o} was refused. ${e.message}`,e.exitCode,{...e.context,reason:oO,examples:fu(o,!1,{scopeArgs:s}).examples,required:`The close of ${n} is complete; do not retry it. Only unblocking ${r.length===1?o:`the guarded dependents it refused (${Mw(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(o)}${r.length===1?"":" for each id"}.${d}${m?` This refusal does not list a step for every dependent left blocked; list them with ${l}, and while it reports has_more, continue with --after <next_cursor>.`:""}`,nextSteps:m?[..._,l]:_,details:sO({...structuredClone(e.context.details),pending_unblock:r.slice(0,lt),pending_unblock_omitted:Math.max(0,r.length-lt),auto_unblock_failed:c,auto_unblock_failed_omitted:Math.max(0,i.length-lt)}),side_effects:[{path:`history/${n}.jsonl`,op:"close"},...t.unblockedIds.map(h=>({path:`history/${h}.jsonl`,op:"update"}))]})}async function nz(e,t,n){if(!Vn(e)||!e.context.side_effects?.some(s=>`${s.op}:${s.path}`==`close:history/${t}.jsonl`))return;let r=String(e.context.item_id);return{warnings:[...e.context.side_effects.filter(s=>s.op==="update").map(s=>s.path.slice(8,-6)).map(s=>`auto_unblocked:${s}`),`auto_unblock_refused:${r}:item_revision_conflict`],dependent_revision_conflict:{item_id:r,error:Zr(e),...await lm(e,n)}}}function cO(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:i,key:s}of r){if(typeof i!="string")continue;let o=i.trim();o.length!==0&&(e[s]=o,n.push(s))}return n}function dO(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:i,value:s}of r)ZI(e[i])&&(e[i]=s,n.push(i));return n}function lO(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(([i,s])=>t.has(i)||s===void 0||s.trim().length===0?[]:[`${i}=${s}`]);return e.force===!0?[...r,"--force"]:r}function uO(e,t,n){let r=t.map(y=>y.label),i=t.map(y=>`--${y.key.replaceAll("_","-")}`),s=i.flatMap(y=>[y,"<value>"]),o=[...n.commandScope,"update",e.id,...s],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),l=pu(n.pmRoot),u=typeof n.options.author=="string"&&n.options.author.trim().length===0,m=d.length>0?`its lifecyclePolicy override (${d.join(", ")}) has no CLI spelling`:u?"its explicitly blank author has no CLI spelling (pm close refuses an empty --author)":l===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(m!==void 0)return new f(a,p.USAGE,{code:"close_validation_missing_fields",required:`Pass ${t.map(y=>y.key).join(", ")} on the same SDK close; ${m}, so no CLI retry reproduces it.`,recovery:{missing:i,next_best_command:L(o)},nextSteps:["Retry the same SDK close with the missing evidence supplied, inside the same lifecycle policy and revision guards.",c]});let _=n.closeReason===void 0?[]:[`--reason=${n.closeReason}`],h=l.map(y=>`--expect-hash=${y}`),g=[...n.commandScope,"close",e.id,..._,...lO(n.options,new Set(i)),...h,...s];return new f(a,p.USAGE,{code:"close_validation_missing_fields",required:`Supply ${i.join(", ")}: pm close accepts them and records them in the same write as the closure.`,recovery:{missing:i,suggested_retry:L(g),suggested_retry_args:g,next_best_command:L(o)},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 mO(e,t,n,r){let i=t.map(a=>jl(a.field).flag),s=[...r.author?.trim()?[`--author=${r.author}`]:[],...r.force===!0?["--force"]:[]],o=[...n,"update",e.id,...s,...i.flatMap(a=>[a,"<value>"])];return new f(`Cannot close item ${e.id}: deferred fields still have no value (${t.map(a=>a.field).join(", ")}). Supply them or use --validate-close warn.`,p.USAGE,{code:"close_validation_deferred_fields",required:`Supply ${i.join(", ")}: each was deferred at create (${t.map(a=>`${a.field}: ${a.reason}`).join("; ")}).`,recovery:{missing:i,next_best_command:L(o)},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 pO(e,t,n){let r=ai(e);if(r.length===0)return[];if(t==="strict")throw mO(e,r,n.commandScope,n.options);return[`close_validation_deferred_fields:${e.id}:${r.map(i=>i.field).join(",")}`]}function fO(e,t,n,r){let i=[];if(t!=="off"){i.push(...pO(e,t,r));let s=Fw(e);if(s.length>0){let o=s.map(a=>a.label);if(t==="strict")throw uO(e,s,r);i.push(`close_validation_missing_fields:${e.id}:${o.join(",")}`)}if(n.length>0){if(t==="strict")throw new f(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,p.USAGE);i.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return i}return n.length>0&&i.push(`closed_with_active_children:${e.id}:${n.join(",")}`),i}function _O(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function hO(e){let t=["assignee","claim_principal"].filter(n=>e[n]!==void 0);for(let n of t)delete e[n];return[...t]}function gO(e,t){if(ae(e.status,t.statusRegistry)&&!t.force)throw new f(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,p.CONFLICT,{recovery:Dw(e,t.commandScope,t.options)});let n=cO(e,t.options),r=dO(e,t.duplicateOf),i=fO(e,t.validateCloseMode,t.activeChildIds,t);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let o=["status","closed_at",...s?["completed_at"]:[],..._O(e,t.closeReason),...n];if(rm(e)&&(e.plan_mode="completed",o.push("plan_mode")),t.duplicateOf!==void 0){o.push("duplicate_of");for(let c of r)o.includes(c)||o.push(c)}o.push(...hO(e));let a=Lw(e,t.lifecyclePolicy);return o.push(...a.changedFields),i.push(...a.warnings),{changedFields:o,...i.length>0?{warnings:i}:{}}}async function yO(e,t,n,r){let i=I(process.cwd(),r.path),s=Ye(r);await z(i);let o=await R(i),a=q(o.schema),c=H(n.author,o.author_default),d=F(o,M()).type_to_folder,l=await V(i,e,o.id_prefix,o.item_format,d);if(!l)throw await Ft(i,e,o.id_prefix,d);let u=await eO(i,o,n.duplicateOf,l.id),m={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},_=xs({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},m.requireCloseReason).closeReason,h=JI(n.validateClose)??o.governance.close_validation_default,g=await he(i,o.item_format,d,void 0,o.schema),y=tO(g,l.id,a),w=O(),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([...s,"update",l.id,"--completed-at","<ISO>"])}.`}:{}},b=await un({pmRoot:i,settings:o,id:l.id,op:"close",author:c,message:n.message,force:n.force,resolveHistoryContext:()=>({completion:{timestamp:k.timestamp,source:k.source}}),mutate(C){return n.completedAt===void 0&&C.metadata.completed_at!==void 0&&(k={timestamp:C.metadata.completed_at,source:"existing"}),gO(C.metadata,{pmRoot:i,commandScope:s,statusRegistry:a,force:n.force,options:n,duplicateOf:u,validateCloseMode:h,activeChildIds:y,closeReason:_,closedAt:w,completedAt:v,lifecyclePolicy:m})}}),A=h==="warn"?Dw(b.item,s):void 0;return{item:b.item,changed_fields:b.changedFields,...A?{follow_up:{kind:"complete_close_evidence",missing:A.missing,suggested_command:A.suggested_retry,suggested_command_args:A.suggested_retry_args}}:{},warnings:[...b.warnings,...await rO(i,o,g,l.id,c,a,s)],completion:k}}function Cs(e,t,n,r){return yO(e,t,n,r)}function Pw(e){return[...e].sort().join("\0")}function wO(e,t,n){let r=e.successors.get(t);r?r.push(n):e.successors.set(t,[n]);let i=e.predecessors.get(n);i?i.push(t):e.predecessors.set(n,[t])}function Uw(e,t,n,r,i){let s=t.resolve(i);if(s?.ordering!==!0)return;let o=vf(r),a=o===void 0?void 0:e.canonicalIds.get(o.toLowerCase());if(a===void 0)return;let c=(s.precedence??"source_before_target")==="source_before_target";wO(e,c?n:a,c?a:n)}function vO(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},r=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0);for(let i of r){let s=i.id.trim();n.canonicalIds.set(s.toLowerCase(),s)}for(let i of r){let s=i.id.trim();Uw(n,t,s,i.blocked_by,"blocked_by");for(let o of i.dependencies??[])typeof o!="object"||o===null||Uw(n,t,s,o.id,typeof o.kind=="string"?o.kind:"related")}for(let i of[n.successors,n.predecessors])for(let s of i.values())s.sort();return n}function kO(e,t){let n=new Set([t]),r=[t];for(;r.length>0;){let i=r.pop();for(let s of[e.successors,e.predecessors])for(let o of s.get(i)??[])n.has(o)||(n.add(o),r.push(o))}return n}function bO(e,t){let n=new Map;for(let r of t){let i=(e.successors.get(r)??[]).filter(s=>t.has(s));i.length>0&&n.set(r,i)}return n}function jw(e,t,n){let r=vO(e,t),i=r.canonicalIds.get(n.trim().toLowerCase());if(i===void 0)return{cycles:[],successors:new Map,canonical:n};let s=bO(r,kO(r,i));return{cycles:$f(s).filter(o=>o.includes(i)),successors:s,canonical:i}}function SO(e,t,n){let r=new Set(t),i=r.has(n)?n:t[0];if(e.get(i)?.includes(i))return[i,i];for(let s of e.get(i)??[]){if(!r.has(s))continue;let o=AO(e,r,i,s);if(o)return o}return[...t,t[0]]}function AO(e,t,n,r){let i=[[r]],s=new Set([n,r]);for(;i.length>0;){let o=i.shift(),a=o.at(-1);for(let c of e.get(a)??[]){if(c===n)return[n,...o,n];!t.has(c)||s.has(c)||(s.add(c),i.push([...o,c]))}}}function Es(e,t,n){let r=ie(),i=jw(e,r,n),s=jw(t,r,n),o=new Set(i.cycles.map(Pw)),a=new Set(oa(e,void 0,r).map(d=>`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`));return[...oa(t,void 0,r).filter(d=>d.holder_id.toLowerCase()===n.trim().toLowerCase()&&!a.has(`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`)).map(d=>`ordering_storage_contradiction_created:${Nf(d)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...s.cycles.filter(d=>!o.has(Pw(d))).map(d=>`ordering_cycle_created:${SO(s.successors,d,s.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}function Rs(e,t){let n=t.resolve(e);return n?.hierarchy===!0||n?.outgoing==="one"||n?.incoming==="one"}function qw(e,t,n,r,i){let s=JSON.stringify([t,n,r]),o=e.get(s);o===void 0&&(o={kind:t,direction:n,node_id:r,endpoints:new Set},e.set(s,o)),o.endpoints.add(i)}function Gw(e,t){let n=new Map;for(let r of e)for(let i of r.dependencies??[]){let s=t.resolve(i.kind);s===void 0||s.hierarchy||(s.outgoing==="one"&&qw(n,s.kind,"outgoing",r.id,i.id),s.incoming==="one"&&qw(n,s.kind,"incoming",i.id,r.id))}return n}function Ts(e,t,n=ie()){let r=Gw(e,n),i=Gw(t,n);for(let s of[...i.keys()].sort()){let o=i.get(s);if(o.endpoints.size<=1)continue;let a=r.get(s);if(![...o.endpoints].every(c=>a?.endpoints.has(c)))throw new f(`Relationship ${o.kind} permits only one ${o.direction} endpoint for ${o.node_id}.`,p.USAGE,{code:"dependency_cardinality_created",field:"dependencies",value:o.kind,relationship_cardinality:{kind:o.kind,direction:o.direction,node_id:o.node_id,endpoint_ids:[...o.endpoints].sort()},required:"The final dependency set must satisfy the active relationship kind's one-edge cardinality.",nextSteps:["Drop extra --dep seeds, or remove conflicting rows with update --dep-remove before adding another edge.","Choose another kind only when its declared semantics match the intended relationship."]})}}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 CO(e){return xO[e]}function Nc(e){return CO(e)!==void 0}function Lc(){return No.map(e=>e.field).join(", ")}var EO=Object.freeze({fields:[],reason:void 0,optionKeys:new Set});function RO(e){return(e??[]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function Kw(e,t){let n=tn(t,"defer"),r=tn(t,"defer-reason"),i=RO(e.defer),s=e.deferReason?.trim();if(i.length===0){if(s!==void 0&&s.length>0)throw new f(`${r} needs ${n}: name the fields whose values are not known yet.`,p.USAGE,{code:"create_deferral_fields_required",required:`Pass ${n} with ${r}, or drop ${r}.`,nextSteps:[`Deferrable fields: ${Lc()}.`]});return EO}let o=new Map;for(let c of i){let d=Lo(c);if(d===void 0)throw new f(`${n} cannot defer "${c}". Deferrable fields: ${Lc()}.`,p.USAGE,{code:"create_deferral_field_unsupported",required:`Defer only ${Lc()}; supply every other field, or clear a repeatable option with its --clear-* flag.`});o.set(d.field,d)}if(s===void 0||s.length===0)throw new f(`${n} requires ${r}: record why the deferred values are not known yet.`,p.USAGE,{code:"create_deferral_reason_required",required:`Pass ${r} "<why>", for example the system the record was imported from.`});let a=No.filter(c=>o.has(c.field));return{fields:a,reason:s,optionKeys:new Set(a.map(c=>c.option))}}function Mc(e,t,n,r,i={}){let s=e.fields.filter(c=>{let d=t[c.option];return typeof d=="string"&&d.trim().length>0||i[c.field]!==void 0||n.has(c.field)});if(s.length===0)return;let o=tn(r,"defer"),a=s.map(c=>c.field).join(", ");throw new f(`Cannot both defer and set ${a}: ${o} records a value as not known yet.`,p.USAGE,{code:"create_deferral_conflict",required:`Drop ${o} for ${a}, or drop the value (or unset) you supplied for it.`})}function zw(e){if(e.fields.length!==0)return ql(e.fields.map(t=>({field:t.field,reason:e.reason})))}function Ww(e,t=[]){let r=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(o=>typeof o=="string").flatMap(o=>o.split(",")).map(o=>Lo(o)).filter(o=>o!==void 0),i=new Set(r.map(o=>o.field)),s=t.filter(o=>o.commands.includes("create")&&i.has(o.metadata_key)).flatMap(o=>Fl(o));return[...r.map(o=>o.option),...s]}function Bw(e,t,n,r,i={}){let s=new Set(t.fields.map(l=>l.field)),o=n.filter(l=>l.commands.includes("create")),a=l=>l.required!==!0&&s.has(l.metadata_key),c=new Set(o.filter(a).map(l=>`--${l.cli_flag}`)),d=new Set(o.filter(l=>!a(l)&&Dl(l,r)&&ri(i,l)===void 0).map(l=>`--${l.cli_flag}`));return e.filter(l=>!c.has(l)||d.has(l))}var TO="hierarchy-integrity";async function Is(e){let t=e.required?await di(e.pmRoot,TO,e.ttlSeconds,e.author,!1,!1,e.waitMs,{waitPolicy:"progress"}):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}function Os(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function $s(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ns(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(nl.includes(t))return t;let n=Re(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new f("Confidence must be an integer 0..100 or one of low|med|medium|high",p.USAGE);return n}function Ls(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new f("Regression must be one of true|false|1|0",p.USAGE)}var Hw=[["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 IO=["documentAnnotationSnapshot","runtimeFieldCommands","ownershipMetadataBypass","ownershipDependencyBypass"];function Ms(e){let t=Hw.find(([r])=>r===e)?.[1]??e.replaceAll(/_([a-z])/gu,(r,i)=>i.toUpperCase()),n=[["update",ea],["create",Zo]].flatMap(([r,i])=>i.flatMap(s=>{if(s.target!==t)return[];let o=s.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:r,flag:o}]}));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:i})=>`Use the declared core mutation: pm ${r}${r==="update"?" <id>":""} ${i} <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 Yw={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 Vw(e){return e.flatMap(t=>[t.flag,...t.short===void 0?[]:[t.short],...t.aliases??[]])}function Xw(e){if(e==="update_many"){let i=Xw("update"),s=Vw(Xn("update-many"));return{options:new Set([...i.options,...s.map(o=>$o(o))]),flags:new Set([...i.flags,...s])}}let t=e==="update"?ea:Zo,n=Vw([...Xn(e),...Ri]),r=[...t.flatMap(i=>[i.target,...i.keys]),...n.map(i=>$o(i)),...e==="update"?IO:[]];return{options:new Set(r),flags:new Set(n)}}function OO(e,t){let n=Yw[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 $O(e,t,n,r){return e.definitions.some(i=>i.metadata_key===t.metadata_key&&i.commands.includes(n)&&ri(r,i)!==void 0)}function Fs(e,t,n){let r=Yw[t],i=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([s])=>s!=="field"));return s=>{let o=Il(s),a=e.definitions.filter(_=>_.metadata_key===o||_.key===o),c=a.find(_=>_.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:[s]},nextSteps:[`The project schema declares "${c.key}" for ${c.commands.join(", ")} only; ${r.name} cannot set it.`,d]};if(i!==void 0&&$O(e,c,t,i))return{recovery:{provided_fields:[s]},nextSteps:[`This invocation already sets "${c.key}" through a declared flag or option; drop the --field ${s} assignment so the field receives one value.`,d]};let l=Xw(t),u=Ml(c,e,l,t),m=u===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} ${Oo(u)} <value>`;return{recovery:{provided_fields:[s],...u===void 0?{}:{suggested_flags:[Oo(u)]}},nextSteps:[m,OO(Ll(c,e,l.options,t),t),d]}}}var NO=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Jw(e,t,n,r){if(NO.has(t.trim().toLowerCase())||n!==r.open_status)return;let i=Fe("in_progress",r);if(!(i===void 0||i===r.open_status))return{command:`pm claim ${e} --start`,to_status:i}}function Zw(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 f(`${t} must be one of true|false|1|0|yes|no`,p.USAGE)}function Fc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function qe(e,t,n,r=n){if(!t.includes(e))throw new f(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,p.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 ev=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function LO(e,t){return t==="defined"?e!==void 0:!!e}function Qw(e,t,n){if(!LO(e,n))return;let r=Re(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new f(`--event ${t} must be an integer >= 1`,p.USAGE);return r}function MO(e,t,n){let r=e?se(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new f("--event recur_until must be at or after start",p.USAGE);return r}function FO(e){return Array.from(new Set(Fc(e).map(t=>qe(t.toLowerCase(),cl,"event weekday")))).sort((t,n)=>vo(t)-vo(n))}function DO(e){return Array.from(new Set(Fc(e).map(t=>{let n=Re(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new f("--event recur_by_month_day values must be integers 1..31",p.USAGE);return n}))).sort((t,n)=>t-n)}function PO(e,t){return Array.from(new Set(Fc(e).map(n=>se(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function tv(e,t,n,r){let i=e.recur_freq?.trim(),s=e.recur_interval?.trim(),o=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![i,s,o,a,c,d,l].some(k=>k!==void 0))return;if(!i)throw new f("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",p.USAGE);let m=qe(i.toLowerCase(),al,"event recurrence frequency"),_=Qw(s,"recur_interval",r),h=Qw(o,"recur_count",r),g=MO(a,t,n),y=FO(c),w=DO(d),v=PO(l,n);return{freq:m,interval:_,count:h,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 In(e,t=ie()){let n=t.resolve(e);if(n)return n.kind;let r=new Set(wo),i=[...wo,...t.list().filter(({kind:s})=>!r.has(s)).flatMap(({kind:s,aliases:o})=>[s,...o])];throw new f(`Invalid dependency kind value "${e}". Allowed: ${i.join(", ")}`,p.USAGE,{field:"kind",value:e,recovery:{allowed_values:i},required:`dependency kind must be one of: ${i.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function Er(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new f(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,p.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 Rr(e,t,n=ie()){for(let r of t??[])try{gu(e,r.id,r.kind,n)}catch(i){throw new f(Zr(i),p.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function nv(e,t){return(await le(e,{schema:t})).document.metadata.created_at}async function UO(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await V(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:nv(n,t.schema)}function jO(e){let t=e.registry.require(e.dependency.kind);return new f(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,p.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 qO(e){let t=e.dependencies.filter(i=>e.registry.resolve(i.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(i.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:i,located:s})=>s===null?[]:[[i,s]])),r=new Map(await Promise.all([...new Set(t.map(({id:i})=>i))].map(async i=>[i,await nv(n.get(i),e.context.schema)])));for(let i of e.holders){let s=await UO(i,e.context);if(s!==void 0)for(let o of t){let a=r.get(o.id),c=Date.parse(s),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw jO({holder:i,dependency:o,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function Ds(e){let t=e.registry??ie(),n=(e.dependencies??[]).filter(o=>!am(o.source_kind)),r=[...new Set(n.map(o=>o.id))],i=await Promise.all(r.map(async o=>({target:o,located:await V(e.pmRoot,o,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=i.filter(({located:o})=>o===null).map(({target:o})=>o).sort((o,a)=>o<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new f(`Dependency target${s.length===1?"":"s"} not found: ${s.join(", ")}`,p.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:s,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${s.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await qO({dependencies:n,missingTargets:s,resolutions:i,holders:e.holders??[],registry:t,context:e}),s.map(o=>`dependency_target_unresolved:${o}`)}var rv="--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.",GO="--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).",KO=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,zO=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,sv=1e3,Dc=60*sv,WO=60*Dc;function iv(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new f(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,p.USAGE);return n.toISOString()}function BO(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new f(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,p.USAGE);let i=r.replace(/^([+-]?\d+)mo$/i,"$1m"),s=KO.exec(r);if(s){let c=s[1]==="-"?-1:1,d=Number.parseInt(s[2],10)*c;return iv(n.getTime()+d*Dc,r)}let o=zO.exec(r);if(o){let[,c,d,l,u]=o;if(d||l||u){let _=c==="-"?-1:1,h=Number.parseInt(d??"0",10),g=Number.parseInt(l??"0",10),y=Number.parseInt(u??"0",10),w=h*WO+g*Dc+y*sv;return iv(n.getTime()+_*w,r)}}let a=i.startsWith("+")||i.startsWith("-")?i:`+${i}`;return se(a,n,"event.duration")}function ov(e,t,n,r){if(t&&n)throw new f(GO,p.USAGE);if(n){let s=BO(e,n);if(s<e)throw new f(rv,p.USAGE);return s===e?void 0:s}if(!t)return;let i=se(t,r,"event.end");if(i<e)throw new f(rv,p.USAGE);if(i!==e)return i}var HO=["at","date","text","title"],VO=["start","date","end","duration","title","description","location","timezone","all_day",...ev],YO=["key","value"];function av(e,t){return t==="trimmed"?e?.trim():e}function XO(e,t){return t==="defined"?e!==void 0:!!e}function Ps(e,t,n){return e.map(r=>{let i=_e(r,"--reminder");Ne(i,"--reminder",HO);let s=av(i.at??i.date,n.valueMode),o=av(i.text??i.title,n.valueMode);if(!s||!o)throw new f("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",p.USAGE);let a=o.trim();if(!a)throw new f("--reminder text must not be empty",p.USAGE);return{at:se(s,t,"reminder.at"),text:a}})}function Us(e,t,n){return e.map(r=>{let i=_e(r,"--event");Ne(i,"--event",VO);let s=(i.start??i.date)?.trim();if(!s)throw new f("--event requires start=<iso|relative> or date=<iso|relative>",p.USAGE);let o=se(s,t,"event.start"),a=i.end?.trim(),c=i.duration?.trim(),d=ov(o,a,c,t),l=i.title,u=i.description,m=i.location,_=i.timezone,h=l?.trim(),g=u?.trim(),y=m?.trim(),w=_?.trim(),v=[["title",l,h],["description",u,g],["location",m,y],["timezone",_,w]];for(let[C,S,x]of v)if(S!==void 0&&!x)throw new f(`--event ${C} must not be empty`,p.USAGE);let k=i.all_day?.trim(),b=tv(i,o,t,n.recurrenceEmptyNumericGuard),A=XO(k,n.allDayEmptyGuard)?Zw(k,"--event all_day"):void 0;return{start_at:o,end_at:d,title:h,description:g,location:y,all_day:A,timezone:w,recurrence:b}})}function js(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new f("--type-option values must not be empty",p.USAGE);let i,s;if(r.includes(",")||r.includes(`
|
|
8
|
-
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=_e(r,"--type-option");Ne(a,"--type-option",YO),i=a.key?.trim(),s=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 f("--type-option requires key=value or key=<name>,value=<value> entries",p.USAGE);i=r.slice(0,d).trim(),s=r.slice(d+1).trim()}if(!i||!s)throw new f("--type-option requires key and value",p.USAGE);t[i]=s}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}var JO=["strict","progressive"],QO=["lightweight"],uv=new Set(["Reminder","Meeting","Event"]),ZO=new Set(["author","created_at","text"]),qs=new Map(pf.map(e=>[e.optionKey,e.canonical]));function e0(e,t){let n=re(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new f(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,p.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function t0(e,t){let n=e.default_status;if(n!==void 0){let r=re(n,t);if(r)return r}return t.open_status}function Pc(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new f(`Invalid created_at timestamp "${e}"`,p.USAGE);return new Date(n).toISOString()}var n0=Oi();function mv(e){if(Be(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let s=t.unset?[...t.unset]:[];s.includes(i)||s.push(i),t.unset=s};Jn(t.template)&&(t.template=void 0);let r=new Set([...qs.keys(),"rank"]);for(let i of r){if(Be(e,i))continue;let s=t[i];if(typeof s!="string"||!Jn(s))continue;let o=i==="rank"?"order":qs.get(i)??i;n(o),t[i]=void 0}return Ve(e,Ni(t,n0))}function Ee(e){if(e!==void 0)return e}var cv=["id","kind","type","author","created_at","source_kind"],Gs=["path","scope","note"];function r0(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let o=s.trim(),a=Ks(o,cv);Er(o,a);let c=a?_e(s,"--dep"):{id:o,kind:"related"};a&&Ne(c,"--dep",cv);let d=Ee(c.id),l=i0(Ee(c.kind??c.type));if(!d||!l)throw new f("--dep requires id and kind, or a bare item id to create a related dependency",p.USAGE);if(d.trim().toLowerCase()==="undefined")throw new f(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,p.USAGE);let u=nr(Ee(c.source_kind)),m=Qr(c.author,"--dep author");return{id:rr(d,n,u),kind:In(l),created_at:Pc(c.created_at,t),author:m??r,source_kind:u??"cli:create:dep",author_source:m?"asserted":"detected"}}),explicitEmpty:!1})}function i0(e){return typeof e=="string"?ie().resolve(e)?.kind??e.trim():e}function Ks(e,t){return Xd(e,t)?!0:Kr(e)}function Bt(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(ke(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(o=>{let a=o.trim(),c=()=>{if(a.length===0)throw new f(`${e} requires text=<value>`,p.USAGE);return{created_at:n,author:r,text:a}},d;try{d=_e(o,e)}catch(m){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw m}if(Object.keys(d).filter(m=>!ZO.has(m)).length>0)return{created_at:Pc(d.created_at,n),author:Qr(d.author,`${e} author`)??r,text:a};let u=d.text??"";if(u==="")throw new f(`${e} requires text=<value>`,p.USAGE);return{created_at:Pc(d.created_at,n),author:Qr(d.author,`${e} author`)??r,text:u}}),explicitEmpty:!1})}function Uc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),i=Ks(r,Gs);go(r,"--file","file path",i);let s=i?_e(n,"--file"):{path:r};if(i&&Ne(s,"--file",Gs),!s.path)throw new f("--file requires path=<value> or a bare file path",p.USAGE);return{path:s.path,scope:qe(s.scope??"project",Br,"file scope"),note:Ee(s.note)}}),explicitEmpty:!1})}function jc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),i=Ks(r,Sl);go(r,"--test","test command",i);let s=i?Al(_e(n,"--test"),"--test"):{command:r},o=Ee(s.command),a=Ee(s.path);if(!o)throw new f("--test requires command=<value> or a bare command (path=<value> is optional metadata)",p.USAGE);let c=Ee(s.timeout_seconds),d=Ee(s.timeout);if(c&&d&&c!==d)throw new f("--test timeout and timeout_seconds must match when both are provided",p.USAGE);let l=c??d;return{command:o,path:a,scope:qe(s.scope??"project",Br,"test scope"),timeout_seconds:l?Re(l,"timeout_seconds"):void 0,pm_context_mode:Hf(s.pm_context_mode,"--test"),workspace_context_mode:Vf(s.workspace_context_mode,"--test"),env_set:zf(s.env_set,"--test"),env_clear:Wf(s.env_clear,"--test"),shared_host_safe:Bf(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:fa(s.assert_stdout_contains),assert_stdout_regex:_a(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:fa(s.assert_stderr_contains),assert_stderr_regex:_a(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Yf(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:Xf(s.assert_json_field_equals,"--test"),assert_json_field_gte:Jf(s.assert_json_field_gte,"--test"),note:Ee(s.note),phase:Gf(s.phase,"--test")}}),explicitEmpty:!1})}function qc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),i=Ks(r,Gs),s=i?_e(n,"--doc"):{path:r};if(i&&Ne(s,"--doc",Gs),!s.path)throw new f("--doc requires path=<value> or a bare doc path",p.USAGE);return{path:s.path,scope:qe(s.scope??"project",Br,"doc scope"),note:Ee(s.note)}}),explicitEmpty:!1})}function s0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Ps(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function o0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--event","Use --clear-events to clear linked events."),{values:Us(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function a0(e,t,n,r=[]){let i=[...Md.filter(s=>e[s]!==void 0),...r.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(i))}function c0(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function dv(e,t,n){let r=Un("create",e);if(!r)throw new f(`Unsupported ${n} entry "${e}" for type "${t}"`,p.CONFLICT);return r}function d0(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 pv(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 l0(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(dv(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(dv(r,e.name,"required_create_repeatables"));return n}function u0(e,t,n,r){for(let i of e)if(!(!pv(t,i)&&!n.has(i)))throw new f(`Option ${ve("create",i)} is disabled for type "${r}" by command_option_policies`,p.USAGE)}function m0(e,t,n){if(t!=="strict")return;let r=e.filter(s=>n.has(s)&&!Nc(s));if(r.length===0)return;let i=[...new Set(r.map(s=>ve("create",s)))].sort((s,o)=>s.localeCompare(o));throw new f(`Strict create mode requires concrete values for ${i.join(", ")}; --unset cannot satisfy a required scalar option (only repeatable options accept an explicit --clear-* empty set)`,p.USAGE)}function p0(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:js(e),explicitEmpty:!1})}async function f0(e){return await zr(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 _0(e){return Tt(e)?await f0(e):e}function h0(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 f(`Invalid --create-mode value "${e}". Allowed: ${JO.join(", ")}`,p.USAGE)}function g0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new f("--schedule-preset must not be empty",p.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new f(`Invalid --schedule-preset value "${e}". Allowed: ${QO.join(", ")}`,p.USAGE)}function y0(e,t,n){let r=h0(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new f("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",p.USAGE);return"progressive"}function w0(e,t,n,r,i,s){let o=e.name,a=d0(t),c=l0(e,n),d=rn(e,"create",c);if(d.errors.length>0)throw new f(d.errors.join("; "),p.CONFLICT);u0(d.disabled,a,r,o),m0(d.required,n,r);let l=m=>m==="author"&&i!=="unknown"||m==="status"&&e.default_status!==void 0||s.has(m)||r.has(m)&&Nc(m)?!0:pv(a,m),u=d.required.filter(m=>!l(m));return[...new Set(u.map(m=>ve("create",m)))].sort((m,_)=>m.localeCompare(_))}var fv=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function v0(e,t){let n=[];for(let r of e){let i=r.match(fv);i&&i[2]===t&&n.push(i[1])}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function k0(e,t){return e.filter(n=>{let r=n.match(fv);return!r||r[2]!==t})}function b0(e,t,n,r){let i=k0(e,t);if(i.length===0)return;let s=_v(n,[],[],r.open_status);throw new f(i.join("; "),p.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function S0(e,t){let r=e.options.find(i=>i.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function A0(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 _v(e,t,n,r){let i=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],o=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of o){if(a.has(c))continue;let d=gv[c];i.push(...d?[d]:A0(c,e.name,r)),a.add(c)}for(let c of n){let d=S0(e,c);i.push("--type-option",`${c}=${d}`)}return i.join(" ")}function Gc(e,t,n="cli"){let r=e?.trim();if(!r){let i=n==="sdk";throw t==="--title"?e!==void 0?new f(i?"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.",p.USAGE):new f(i?'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.',p.USAGE):new f(`Missing required option ${i?tn("sdk",t.replace(/^--/u,"")):t}`,p.USAGE)}return r}function x0(e,t,n){let r={};for(let[i,s]of Object.entries(e))r[i]=Array.isArray(s)?[...s]:s;for(let[i,s]of Object.entries(t))s!==void 0&&(r[i]=Array.isArray(s)?[...s]:s);return C0(r,t,n),Ve(t,r)}function C0(e,t,n){let r=[...ia(t.unset,n).optionKeys,...Ww(t.defer,n?.definitions)].flatMap(i=>i==="order"?[i,"rank"]:i==="tags"?[i,"addTags"]:[i]);for(let i of r)Reflect.get(t,i)===void 0&&Reflect.deleteProperty(e,i)}function E0(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function R0(){let e=M();return e?e.commands.some(t=>t.action==="templates-show"||E0(t.command)==="templates show"):!1}function T0(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new f(`Templates package returned invalid payload for template "${t}". Expected an options object.`,p.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new f(`Templates package returned invalid options for template "${t}".`,p.GENERIC_FAILURE);let r={};for(let[i,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[i]=s;continue}if(Array.isArray(s)&&s.every(o=>typeof o=="string")){r[i]=[...s];continue}throw new f(`Templates package returned unsupported option value for "${i}" in template "${t}".`,p.GENERIC_FAILURE)}return r}async function I0(e,t,n){if(!R0())throw new f("--template requires the templates package. Install it first (for example: pm install templates --project).",p.USAGE);let r=await Cu({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled)throw Object.hasOwn(r,"cause")?tm("templates show",r):new f(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.`,p.USAGE);return T0(r.result,e)}function Y(e,t,n){return e.has(t)||n===void 0?void 0:Ee(n)}function Wt(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var O0=new Set(["milestone","meeting","reminder","event"]);function hv(e,t,n,r){let i=t!==void 0,s=n!==void 0&&n.length>0,o=r!==void 0&&r.length>0;return O0.has(e.toLowerCase())&&!i&&!s&&!o}function $0(e,t,n,r,i){let s=[];return e.toLowerCase()==="event"&&(i===void 0||i.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),hv(e,n,r,i)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function N0(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 i=await Ql(r);return i===void 0?{parent:e,parentSource:void 0}:{parent:i,parentSource:"focus"}}async function L0(e,t,n,r,i,s,o){let a=mn(yi(i,o),t.id_prefix);if(Ei(a))return{parent:a,warnings:[]};if(vi(r,a,t.id_prefix,o),await V(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let d=De(a,t.id_prefix);return{parent:a,warnings:wi(d,s,o).warnings}}async function M0(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await L0(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy,e.audience)}async function F0(e){if(e.explicitId===void 0)return Tu(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});Zn(e.explicitId,"create","id");let t=e.explicitId.trim();if(t.length===0||Iu(t))throw new f("--id must not be empty or use a placeholder token",p.USAGE);let n=De(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new f("--id must contain only letters, numbers, and dashes after normalization",p.USAGE);return n}function lv(e,t,n,r,i,s){let o=Y(e,t,n);if(o===void 0)return{value:void 0,warnings:[]};let a=bi(r,o,i,s);return{value:a.value,warnings:a.warnings}}async function D0(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:i,blockedBy:s,status:o,statusExplicit:a,nowValue:c,author:d}=e,l=e.dependencyValues;if(s===void 0)return{dependencyValues:l,status:o};let u=De(s,n.id_prefix),m=await V(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!m)return{dependencyValues:l,status:o};if((l??[]).some(g=>g.id===m.id&&g.kind==="blocked_by")||(l=[...l??[],{id:m.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:l,status:o};let h=i.blocked_statuses.has("blocked")?"blocked":[...i.blocked_statuses].sort((g,y)=>g.localeCompare(y))[0]??i.open_status;return{dependencyValues:l,status:h}}function P0(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let i=t.governance.create_default_type?.trim();if(i&&i.length>0&&et(i,n)){e.type=i;return}et("Task",n)&&(e.type="Task")}function U0(e,t){return e.options.filter(n=>Un("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 f(`Template custom type option "${n.key}" must be a string, number, or boolean value`,p.USAGE)})}async function j0(e,t,n,r,i){let s=e,o=[];if(s.template!==void 0){let h=s.template.trim();if(h.length===0)throw new f("--template must not be empty. Omit --template to disable template usage.",p.USAGE);let g=await I0(h,t,n);s=mv(er("create",x0(g,s,$t(r.schema))))}if(s.type===void 0&&P0(s,r,i),s.type===void 0)throw new f("Missing required option --type <value>",p.USAGE);let a=et(s.type,i);if(!a){let h=Ou(s.type),g=h?et(h,i):void 0;if(g)o.push(`type_coercion:${s.type.trim()}:${g}`),s.type=g,a=g;else throw new f(Si(s.type,i.types,ni(n,r.schema)),p.USAGE)}let c=Yr(a,i);if(!c)throw new f(`Invalid type value "${s.type}"`,p.USAGE);let d=c.name,l=U0(c,s),u=l.map(h=>`${h.key}=${String(s[h.key])}`);if(u.length>0){s.typeOption=[...u,...s.typeOption??[]];for(let h of l)delete s[h.key]}let m=g0(s.schedulePreset);if(m!==void 0&&!uv.has(d))throw new f(`--schedule-preset ${m} is only supported for Reminder, Meeting, or Event types`,p.USAGE);let _=y0(s.createMode,m,r.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:d,schedulePreset:m,createMode:_,warnings:o}}function q0(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),i=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of i)if(s.enabled){if(s.values&&s.values.length>0)throw new f(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,p.USAGE);n.add(s.metadataKey),r.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function G0(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,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let s=qs.get(r)??r;throw new f(`Cannot combine --unset ${s} with ${ve("create",r)}`,p.USAGE)}}function K0(e){if(Be(e))return;let t=(n,r)=>{if(Be(e,r))return;let i=qs.get(r),s=i?`Use --unset ${i} to clear this field.`:void 0;$i(n,ve("create",r),s)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function z0(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new f(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,p.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new f(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,p.USAGE)}var gv={"--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 W0(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:i,openStatus:s,type:o,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(h=>{let g=h.type==="boolean"?"<true|false>":h.type==="array"?"<json-array>":h.type==="object"?"<json-object>":h.type==="number"?"<number>":h.type==="string_array"||h.repeatable?"<value>":"<string>";return{example:`--${h.cli_flag} ${g}`,description:`--${h.cli_flag} maps to ${h.metadata_key} (${h.type}${h.repeatable?", repeatable":""})`}}),l=[_v(n,r,i,s),...d.map(h=>h.example)].join(" "),u=[`Run "pm create --help --type ${o}" for type-aware required option guidance.`,...t.filter(h=>h==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+o+").")];a==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),uv.has(o)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(h=>h.description).join("; ")}.`);let m=[...new Set(t.flatMap(h=>{let g=h.split(" ",1)[0],y=gv[g];return y?[y]:[]}))];m.length>0&&u.push(`If the truthful value is an empty collection, use ${m.join(", ")} instead of inventing metadata.`);let _=t.length===1?`Missing required option ${t[0]} for type "${o}"`:`Missing required options ${t.join(", ")} for type "${o}"`;throw new f(_,p.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${o}" in one invocation.`,examples:[...m.map(h=>`pm create --type ${o} ${h} ...`),l],nextSteps:u,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...m,...t,"--create-mode progressive"]}:void 0})}function B0(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new f("Cannot combine --unset tags with --add-tags",p.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?jr(t.tags):[];return Gr(n,t.addTags)}function H0(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new f("--order and --rank must match when both are provided",p.USAGE);let n=t.order??t.rank,r=Wt(e,"order",n,i=>Re(i,"order"));if(r!==void 0&&!Number.isInteger(r))throw new f("Order must be an integer",p.USAGE);return r}function V0(e,t,n,r,i,s){if(r.completedAt!==void 0&&e!==t.close_status)throw new f("--completed-at requires a terminal create status.",p.USAGE);let o=e!==t.close_status?void 0:r.completedAt===void 0?s:se(r.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:o,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:i}:{explicit:r.closeReason};return{closeReason:Ic(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:o,warnings:[]}}async function Y0(e){let{pmRoot:t,type:n,id:r,settings:i,typeRegistry:s,author:o,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:m,similarityCandidate:_,allowDuplicate:h}=e,g=ll(t,n,r,i.item_format,s.type_to_folder),y=Me(t,r),w=ie(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(C=>Rs(C.kind,w)),k=await Is({pmRoot:t,author:o,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:v}),b=v,A=[];try{let C=await li(t,r,i.locks.ttl_seconds,o,!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let S=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await he(t,i.item_format,s.type_to_folder,void 0,i.schema):void 0,x=await V(t,r,i.id_prefix,i.item_format,s.type_to_folder);if(x)throw new f(`Item "${r}" already exists`,p.CONFLICT,{code:"item_already_exists",id:x.id,path:x.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 ${x.id}.`]});if(S){Ts(S,[...S,c.metadata],w);let E=q(i.schema);Di(S,[...S,c.metadata],r,K=>ae(K,E),w)}let D=await Uu({pmRoot:t,settings:i,operation:"create",author:o,before:null,after:c});await Su({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,author:o,sdk:Wu({pmRoot:t,settings:i,typeToFolder:s.type_to_folder})});let U=await Ku(t,o,{required:i.governance.duplicate_detection_mode==="strict"&&h!==!0}),T=[];try{i.governance.duplicate_detection_mode==="strict"&&h!==!0&&await qa(_,{pmRoot:t,mode:"strict",threshold:i.governance.duplicate_detection_threshold,limit:i.governance.duplicate_detection_limit,allowDuplicate:!1}),await C.fence(async()=>{await Le(g,Wl(c,{format:i.item_format,schema:i.schema,extensionFieldNames:a}));try{let E=uu({nowIso:m,author:o,op:"create",before:d,after:c,message:l,context:D.decisions.length===0?void 0:{workflow_policies:D.decisions}});await mu(y,E)}catch(E){throw await tl(g),E}}),b&&(await k(),b=!1),T=await zu({pmRoot:t,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:g,document:c})}finally{await U()}A=[...D.warnings,...S?Es(S,[...S,c.metadata],r):[],...T,...await nt({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await nt({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],ku({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:bu(c.metadata,u),changed_fields:u})}finally{await C.release()}}finally{b&&await k()}return A}async function IW(e,t){let n=er("create",e),r=He(n),i=mv(await _0(n)),s=I(process.cwd(),t.path);await z(s);let o=await R(s),a=q(o.schema),c=$t(o.schema),d=F(o,M()),l=await j0(i,t,s,o,d);i=l.resolvedOptions;let{typeDefinition:u,type:m,createMode:_}=l,h=ia(i.unset,c),{explicitUnsets:g,clearOptionKeys:y}=q0(i,h);G0(i,h),K0(i);let w=Kw(i,r);Mc(w,i,h.metadataKeys,r);let v=H(Ee(i.author),o.author_default),k=w0(u,i,_,y,v,w.optionKeys),b=O(),A=r0(i.dep,b,o.id_prefix,v),C=Bt("--comment",i.comment,b,v),S=Bt("--note",i.note,b,v),x=Bt("--learning",i.learning,b,v),D=Uc(i.file),U=jc(i.test);U.values=await qi(U.values,v,b);let T=qc(i.doc),E=s0(i.reminder,b),K=o0(i.event,b),Ge=p0(i.typeOption),ge=jn(m,Ge.values,d),Ze=M(),mt=gt(Ze),pt=pi(i.field,Ze,Ms,Fs(c,"create",i)),ye=Pl(i,c,m);Mc(w,i,h.metadataKeys,r,ye.values),ye.missing_required_flags=Bw(ye.missing_required_flags,w,c.definitions,m,i);let Ke=new Set(ye.missing_required_flags),ue=c.definitions.filter(Q=>Ke.has(`--${Q.cli_flag}`));z0(pt,ye,h);let Qt=v0(ge.errors,m),Zt=Qt.map(Q=>`--type-option ${Q}=<value>`),xt=[...new Set([...k,...Zt,...ye.missing_required_flags])].sort((Q,fo)=>Q.localeCompare(fo));W0({combinedMissingFlags:xt,typeDefinition:u,missingRequiredCreateFlags:k,missingRequiredTypeOptionKeys:Qt,openStatus:a.open_status,type:m,createMode:_,missingRequiredRuntimeFields:ue}),b0(ge.errors,m,u,a);let de=await F0({pmRoot:s,settings:o,typeRegistry:d,explicitId:i.id}),Ae=i.status!==void 0?e0(i.status,a):t0(u,a),fe=i.priority!==void 0?ki(i.priority):2,$=h.metadataKeys,ft=B0($,i),xe=Wt($,"deadline",i.deadline,Q=>se(Q,new Date(b),"deadline")),Dn=Wt($,"estimated_minutes",i.estimatedMinutes,Q=>Wr(Q,"estimated-minutes")),we=Y($,"acceptance_criteria",i.acceptanceCriteria),ne=Y($,"definition_of_ready",i.definitionOfReady),Mr=H0($,i),oo=Y($,"goal",i.goal),Fr=Y($,"objective",i.objective),ob=Y($,"value",i.value),ab=Y($,"impact",i.impact),cb=Y($,"outcome",i.outcome),db=Y($,"why_now",i.whyNow),lb=Y($,"assignee",i.assignee),ub=$.has("author")?void 0:Ee(i.author)??v,mb=Y($,"parent",i.parent),Sd=await N0(mb,i,$,s),ao=Sd.parent,pb=Sd.parentSource,fb=Y($,"reviewer",i.reviewer),_b=Wt($,"risk",i.risk,Q=>qe(Os(Q),Hr,"risk")),hb=Wt($,"confidence",i.confidence,Q=>Ns(Q)),gb=i.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Ad=o.validation.sprint_release_format,Ct=[...l.warnings,...$0(m,de,xe,E.values,K.values)],xd=await M0({itemId:de,parent:ao,pmRoot:s,settings:o,typeRegistry:d,policy:gb,audience:r});ao=xd.parent,Ct.push(...xd.warnings);let Cd=lv($,"sprint",i.sprint,"sprint",Ad,r),yb=Cd.value;Ct.push(...Cd.warnings);let Ed=lv($,"release",i.release,"release",Ad,r),wb=Ed.value;Ct.push(...Ed.warnings);let Rd=Y($,"blocked_by",i.blockedBy),Td=await D0({pmRoot:s,settings:o,typeRegistry:d,statusRegistry:a,blockedBy:Rd,dependencyValues:A.values,status:Ae,statusExplicit:i.status!==void 0,nowValue:b,author:v}),co=Td.dependencyValues;Rr(de,co),Ct.push(...await Ds({pmRoot:s,dependencies:co,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:d.type_to_folder,allowUnresolved:i.allowUnresolvedDeps,holders:[{id:de,createdAt:b}],schema:o.schema})),Ae=Td.status;let vb=Y($,"blocked_reason",i.blockedReason),kb=Y($,"unblock_note",i.unblockNote),bb=Y($,"reporter",i.reporter),Sb=Wt($,"severity",i.severity,Q=>qe($s(Q),Vr,"severity")),Ab=Y($,"environment",i.environment),xb=Y($,"repro_steps",i.reproSteps),Id=Y($,"resolution",i.resolution),Cb=Y($,"expected_result",i.expectedResult),Eb=Y($,"actual_result",i.actualResult),Rb=Y($,"affected_version",i.affectedVersion),Tb=Y($,"fixed_version",i.fixedVersion),Ib=Y($,"component",i.component),Ob=Wt($,"regression",i.regression,Q=>Ls(Q)),$b=Y($,"customer_impact",i.customerImpact),lo=Gc(i.title,"--title",r),uo=i.description??"",Dr=i.body??"",Od=await qa({title:lo,description:uo,body:Dr},{pmRoot:s,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:i.allowDuplicate});Ct.push(...eg(Od));let mo=V0(Ae,a,o,i,Id,b),Nb=mo.closeReason,Lb=Ae===a.close_status?b:void 0,Mb=mo.completedAt;Ct.push(...mo.warnings);let en=zl({id:de,title:lo,description:uo,type:m,type_options:ge.normalized,status:Ae,closed_at:Lb,completed_at:Mb,close_reason:Nb,priority:fe,tags:ft,created_at:b,updated_at:b,deadline:xe,assignee:lb,author:ub,estimated_minutes:Dn,acceptance_criteria:we,deferred_fields:zw(w),definition_of_ready:ne,order:Mr,goal:oo,objective:Fr,value:ob,impact:ab,outcome:cb,why_now:db,parent:ao,reviewer:fb,risk:_b,confidence:hb,sprint:yb,release:wb,blocked_by:Rd,blocked_reason:vb,unblock_note:kb,reporter:bb,severity:Sb,environment:Ab,repro_steps:xb,resolution:Id,expected_result:Cb,actual_result:Eb,affected_version:Rb,fixed_version:Tb,component:Ib,regression:Ob,customer_impact:$b,dependencies:co,comments:C.values,notes:S.values,learnings:x.values,files:D.values,tests:U.values,docs:T.values,reminders:E.values,events:K.values,...pt,...ye.values});vl(en),fi(en,Ze),ju(en,s);let Fb=Bl({metadata:en,body:Dr},{schema:o.schema,extensionFieldNames:mt}),Db={metadata:{},body:""},$d=[...g].sort((Q,fo)=>Q.localeCompare(fo)),Pb=c0(i.message,$d),Nd=a0(en,Dr,$d,[...Object.keys(pt),...Object.keys(ye.values??{})]),Ub=await Y0({pmRoot:s,type:m,id:de,settings:o,typeRegistry:d,author:v,extensionFieldNames:mt,afterDocument:Fb,beforeDocument:Db,historyMessage:Pb,changedFields:Nd,nowValue:b,similarityCandidate:{title:lo,description:uo,body:Dr},allowDuplicate:i.allowDuplicate}),po=structuredClone(en);_==="strict"&&g.has("dependencies")&&(po.dependencies=[]);let jb=Jw(de,m,Ae,a);return hv(m,xe,E.values,K.values)&&lu(`[pm] warning: ${m} '${de}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${de} --deadline <ISO>' or 'pm update ${de} --event "start=<ISO>,end=<ISO>"'.`),{item:po,changed_fields:Nd,warnings:[...Qn("create",i,r==="sdk",po),...Ct,...Ub],...Object.fromEntries([["parent_source",pb],["next_transition",jb],["similarity_advisory",Od]].filter(Q=>Q[1]!==void 0))}}function Ht(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:Fe("in_progress",e)??e.open_status}import{AsyncLocalStorage as X0}from"node:async_hooks";var J0="strict",Ws="start_blocked_by_open_dependency";function yv(e,t,n){if(t===void 0)return!1;let r=Nt(Ht(n),n);return Nt(t,n)===r&&Nt(e??"",n)!==r}function zs(e,t,n){let r=i=>De(i.trim(),n).toLowerCase();return r(e)===r(t)}var Q0=new Set(["cli:create:blocked_by","cli:update:blocked_by"]);function Kc(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===De(t.trim(),n).toLowerCase()&&Q0.has(e.source_kind?.trim().toLowerCase()??"")}function Z0(e,t,n){let r=e.dependencies??[],i=r.filter(o=>o.kind==="blocked_by");if(r.some(o=>o.kind!=="blocked_by"&&Wn(o.kind)==="blocked_by"&&zs(o.id,t,n)))return L(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&zs(e.blocked_by,t,n))){let o=i.filter(a=>zs(a.id,t,n));return o.length===1&&o.every(a=>a.id===mn(a.id,n,void 0))?L(["update",e.id,"--dep-remove",`id=${o[0].id},kind=blocked_by`]):L(["get",e.id,"--fields","blocked_by,dependencies"])}return i.filter(o=>zs(o.id,t,n)).every(o=>Kc(o,e.blocked_by,n))?L(["update",e.id,"--unset","blocked_by"]):L(["get",e.id,"--fields","blocked_by,dependencies"])}var e$=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function t$(e,t){try{return(await dm(e)).filter(n=>!n.resolved)}catch(n){let r=em(n)?n.context.code:void 0;if(!t||typeof r!="string"||!e$.has(r))throw n;return r}}async function wv(e){let t=e.settings.governance.start_blocker_enforcement??J0;if(t==="off")return[];let n=F(e.settings,M()).type_to_folder,r=e.metadata.id,i=await t$({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n,metadata:e.metadata},t==="warn"||e.force===!0);if(typeof i=="string")return[`start_blocker_unverifiable:${r}:${i}`];if(i.length===0)return[];let s=i.map(o=>o.id).join(",");if(t==="warn")return[`start_with_open_blockers:${r}:${s}`];if(e.force===!0)return[`start_blocker_override:${r}:${s}`];throw new f(`Cannot start ${r}: ${i.length===1?"its blocker":`${i.length} of its blockers`} ${s} ${i.length===1?"is":"are"} still open.`,p.CONFLICT,{code:"start_blocked_by_open_dependency",item_id:r,required:`Finish or close the open blocker${i.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:[...i.filter(o=>o.external!==!0).slice(0,3).map(o=>L(["get",o.id])),Z0(e.metadata,i[0].id,e.settings.id_prefix),"pm next"],details:{enforcement:t,open_blockers:i.map(o=>({id:o.id,title:o.title,status:o.status,external:o.external===!0}))}})}async function Bs(e){if(e.requested===!1||!yv(e.fromStatus,e.metadata.status,e.registry))return[];let t=await wv(e),n=zc.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var zc=new X0;function vv(e){return zc.run({warnings:new Set},e)}async function kv(e){let t=zc.getStore();if(t===void 0)return[];let n=yv(e.metadata.status,Ht(e.registry),e.registry)?await wv(e):[];for(let r of n)t.warnings.add(r);return n}var bv="terminal_state_unchanged";function Sv(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function n$(e,t){return re(e,t)===t.close_status}function r$(e){let t=n=>mf.includes(n.trim().toLowerCase());return ff(e.unset??[],t).some(t)}function Av(e){!e.settings.governance.require_close_reason||!r$(e.options)||xs({explicit:e.options.closeReason},!0)}function Wc(e,t,n,r=!1){if(!n$(e.status,n))return!1;let i=Sv(t.closeReason);return r&&t.closeReason!==void 0&&i===void 0||i!==void 0&&i!==Sv(e.close_reason)?!1:t.completedAt===void 0||se(t.completedAt,new Date,"completed-at")===e.completed_at}async function xv(e){let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Ft(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await le(t,{schema:e.settings.schema});return n.metadata}async function Cv(e,t,n,r,i){if(n.length===0)return{item:t,changed_fields:[],warnings:[...e.workflowTransitionWarnings,bv]};let s=Ve(e.options,{...e.options,status:void 0,closeReason:void 0,completedAt:void 0}),o=await r(e.id,s,e.global);return Wc(o.item,e.options,e.statusRegistry,e.settings.governance.require_close_reason)?{item:o.item,changed_fields:o.changed_fields,warnings:[...e.workflowTransitionWarnings,...o.warnings,bv]}:i(o)}function On(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=$u({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Fe(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Fe(e.toStatus,e.statusRegistry)??e.toStatus,i=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Nu(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new f(i,p.USAGE);return`workflow_transition_not_allowed: ${i}`}function Hs(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",i=Date.parse(r),s=Number.isFinite(i)?new Date(i).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function Bc(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 Ev(e,t,n){let r=t.filter(i=>!e.some(s=>Bc(s,i)));if(r.length!==0)throw new f(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,p.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r.map(i=>({...i,id:i.id??"*"})),available_dependencies:e.map(i=>({id:i.id,kind:i.kind,source_kind:i.source_kind,author:i.author,created_at:i.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 Rv(e,t){if(!Array.isArray(e)||e.length===0)return;let n=s=>(Array.isArray(s)?s:[]).filter(o=>typeof o=="object"&&o!==null&&typeof o.id=="string"),r=new Map;for(let s of n(t)){let o=Hs(s);r.set(o,(r.get(o)??0)+1)}let i=[];for(let s of n(e)){let o=Hs(s),a=r.get(o)??0;a>0?r.set(o,a-1):i.push(`${s.id}/${s.kind}`)}return i.length>0?i.join(","):void 0}var i$=(()=>{let e=new Map;for(let t of Li)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Vs=new Map(Li.map(e=>[e.optionKey,e.canonical])),s$=Li.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),o$=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),a$=Oi({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Dv(e){if(Be(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let s=t.unset?[...t.unset]:[];s.includes(i)||s.push(i),t.unset=s},r=new Set([...Vs.keys(),"rank"]);for(let i of r){if(Be(e,i))continue;let s=t[i];if(typeof s!="string"||!Jn(s))continue;let o=i==="rank"?"order":Vs.get(i)??i;n(o),t[i]=void 0}return Ve(e,Ni(t,a$))}function MB(e,t,n,r=["update"]){return[...Xc([...e],t,n,r).metadataKeys]}function Xc(e,t,n=[],r=["update"]){return _f({raw:e,supportedFields:s$,resolveDefinition:i=>{let s=n.find(a=>{let c=a.toLowerCase();return c===i||c.replaceAll("_","-")===i||c.replaceAll("-","_")===i});return i$.get(i)??r.map(a=>ra(i,a,t)).find(a=>a!==void 0)??(s?{optionKey:"field",metadataKey:s}:void 0)}})}var Tv=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 Iv(e){let t=e.disallowedFlags.flatMap(r=>{let i=Tv.get(r);return i?[i(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let i=Tv.get(r);return i?[`Replace ${r} with: ${i(e.id)}`]:[]});return new f(e.message,p.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function c$(e,t,n){let r=t.ownershipMetadataBypass===!0,i=t.ownershipDependencyBypass===!0;if(!r&&!i)return;if(r&&i)throw new f("Choose only one package-provided ownership bypass mode.",p.USAGE);let s=(c,d,l)=>{c&&l.push(d)};if(i){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new f("The dependency ownership bypass requires at least one --dep value",p.USAGE);if(c.length>0)throw Iv({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 o=[];s(t.status!==void 0,"--status",o),s(t.closeReason!==void 0,"--close-reason",o),s(t.assignee!==void 0,"--assignee",o),s(t.parent!==void 0,"--parent",o),s(t.blockedBy!==void 0,"--blocked-by",o),s(t.blockedReason!==void 0,"--blocked-reason",o),s(t.unblockNote!==void 0,"--unblock-note",o),s(t.dep!==void 0,"--dep",o),s(t.depRemove!==void 0,"--dep-remove",o),s(t.replaceDeps===!0,"--replace-deps",o),s(t.replaceTests===!0,"--replace-tests",o),s(t.replaceFiles===!0,"--replace-files",o),s(t.replaceDocs===!0,"--replace-docs",o),s(t.note!==void 0,"--note",o),s(t.learning!==void 0,"--learning",o),s(t.test!==void 0,"--test",o),s(t.reminder!==void 0,"--reminder",o),s(t.event!==void 0,"--event",o),s(t.clearDeps===!0,"--clear-deps",o),s(t.clearComments===!0,"--clear-comments",o),s(t.clearNotes===!0,"--clear-notes",o),s(t.clearLearnings===!0,"--clear-learnings",o),s(t.clearFiles===!0,"--clear-files",o),s(t.clearTests===!0,"--clear-tests",o),s(t.clearDocs===!0,"--clear-docs",o),s(t.clearReminders===!0,"--clear-reminders",o),s(t.clearEvents===!0,"--clear-events",o);let a=[...n].filter(c=>o$.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(o.push(...a),o.length>0)throw Iv({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: ${o.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:o})}function d$(e,t){let n=re(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new f(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,p.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function l$(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:Pv(e)}function Pv(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new f(`Invalid dependency created_at timestamp "${e}"`,p.USAGE);return new Date(t).toISOString()}function Vt(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var u$=["id","kind","type","author","created_at","source_kind"],m$=["id","kind","type","author","created_at","source_kind"];function Uv(e){return e.startsWith("```")||e.includes(`
|
|
9
|
-
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Kr(e)}function Jc(e){return typeof e=="string"?ie().resolve(e)?.kind??e.trim():e}function p$(e,t,n,r){return e?(ke(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let o=s.trim(),a=Uv(o);Er(o,a);let c=a?_e(s,"--dep"):{id:o,kind:"related"};a&&Ne(c,"--dep",u$);let d=c.id?.trim(),l=Jc((c.kind??c.type)?.trim());if(!d||!l)throw new f("--dep requires id and kind, or a bare item id to add a related dependency",p.USAGE);if(d.toLowerCase()==="undefined")throw new f(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,p.USAGE);let u=nr(Vt(c.source_kind)),m=Vt(c.author);return{id:rr(d,t,u),kind:In(l),created_at:l$(c.created_at,n),author:m??r,source_kind:u??"cli:update:dep",author_source:m?"asserted":"detected"}})}):{additions:[]}}function f$(e,t){return e?(ke(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new f("--dep-remove requires id or key/value selectors",p.USAGE);let i=Uv(r);if(Er(r,i,"--dep-remove"),i){let s=_e(r,"--dep-remove");Ne(s,"--dep-remove",m$);let o=s.id?.trim();if(s.id===void 0)return _$(s);if(!o)throw new f("--dep-remove key/value form requires a non-empty id=<value>",p.USAGE);if(o.toLowerCase()==="undefined")throw new f(`--dep-remove id must not use placeholder token "${o}"`,p.USAGE);let a=Jc(Vt(s.kind??s.type)),c=nr(Vt(s.source_kind)),d=Vt(s.author),l=Vt(s.created_at);return{id:rr(o,t,c),kind:a?In(a):void 0,source_kind:c,author:d,created_at:l?Pv(l):void 0}}if(r.toLowerCase()==="undefined")throw new f(`--dep-remove id must not use placeholder token "${r}"`,p.USAGE);return{id:De(r,t)}})):[]}function _$(e){let t=Jc(Vt(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 f("--dep-remove key/value form requires id=<value>, or kind=<kind> alone to remove every row of that kind",p.USAGE);return{kind:In(t)}}function Ys(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function h$(e,t,n,r,i){let s=[...e??[]],o=!1;if(t===void 0){let a=s.filter(c=>i===void 0||!Kc(c,i.value,i.idPrefix));return a.length!==s.length&&(s=a,o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}return s.some(a=>a.kind==="blocked_by"&&a.id===t)||(s.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}async function g$(e,t,n,r,i,s){if(e===void 0||t)return{};let o=e.trim();if(o.length===0)return{};let a=await V(n,De(o,r),r,i,s);return a?{id:a.id}:{unresolved:o}}function y$(e,t,n,r,i,s){let o=h$(e.dependencies,t,n,r,s);o.changed&&(o.dependencies===void 0?delete e.dependencies:e.dependencies=o.dependencies,i.includes("dependencies")||i.push("dependencies"))}function w$(e){return`${e.path}::${e.scope}`}function v$(e){return`${e.path}::${e.scope}`}function k$(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function Ov(e,t){let n=Un("update",e);if(!n)throw new f(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,p.CONFLICT);return n}function b$(e,t,n){let r=new Set,i=(s,o)=>{o&&r.add(s)};if(i("title",e.title!==void 0),i("description",e.description!==void 0),i("body",e.body!==void 0),i("status",e.status!==void 0),i("closeReason",e.closeReason!==void 0),i("priority",e.priority!==void 0),i("type",e.type!==void 0),i("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),i("deadline",e.deadline!==void 0),i("estimatedMinutes",e.estimatedMinutes!==void 0),i("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),i("definitionOfReady",e.definitionOfReady!==void 0),i("order",e.order!==void 0||e.rank!==void 0),i("goal",e.goal!==void 0),i("objective",e.objective!==void 0),i("value",e.value!==void 0),i("impact",e.impact!==void 0),i("outcome",e.outcome!==void 0),i("whyNow",e.whyNow!==void 0),i("author",e.author!==void 0),i("message",e.message!==void 0),i("assignee",e.assignee!==void 0),i("parent",e.parent!==void 0),i("reviewer",e.reviewer!==void 0),i("risk",e.risk!==void 0),i("confidence",e.confidence!==void 0),i("sprint",e.sprint!==void 0),i("release",e.release!==void 0),i("blockedBy",e.blockedBy!==void 0),i("blockedReason",e.blockedReason!==void 0),i("unblockNote",e.unblockNote!==void 0),i("reporter",e.reporter!==void 0),i("severity",e.severity!==void 0),i("environment",e.environment!==void 0),i("reproSteps",e.reproSteps!==void 0),i("resolution",e.resolution!==void 0),i("expectedResult",e.expectedResult!==void 0),i("actualResult",e.actualResult!==void 0),i("affectedVersion",e.affectedVersion!==void 0),i("fixedVersion",e.fixedVersion!==void 0),i("component",e.component!==void 0),i("regression",e.regression!==void 0),i("customerImpact",e.customerImpact!==void 0),i("dep",e.dep!==void 0),i("depRemove",e.depRemove!==void 0),i("dep",e.replaceDeps===!0),i("comment",e.comment!==void 0),i("note",e.note!==void 0),i("learning",e.learning!==void 0),i("file",e.file!==void 0),i("test",e.test!==void 0),i("test",e.replaceTests===!0),i("file",e.replaceFiles===!0),i("doc",e.replaceDocs===!0),i("doc",e.doc!==void 0),i("reminder",e.reminder!==void 0),i("event",e.event!==void 0),i("typeOption",e.typeOption!==void 0),i("field",e.field!==void 0),i("force",e.force===!0),i("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),i("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),i("dep",e.clearDeps===!0),i("comment",e.clearComments===!0),i("note",e.clearNotes===!0),i("learning",e.clearLearnings===!0),i("file",e.clearFiles===!0),i("test",e.clearTests===!0),i("doc",e.clearDocs===!0),i("reminder",e.clearReminders===!0),i("event",e.clearEvents===!0),i("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=Xc(e.unset,t,n,e.runtimeFieldCommands);for(let o of s.optionKeys)i(o,!0)}return r}function S$(e,t,n,r,i){let s=Yr(e,n);if(!s)throw new f(`Invalid type value "${e}"`,p.USAGE);let o=rn(s,"update",[]);if(o.errors.length>0)throw new f(o.errors.join("; "),p.CONFLICT);let a=b$(t,r,i);for(let c of o.disabled)if(a.has(Ov(c,e)))throw new f(`Option ${ve("update",c)} is disabled for type "${e}" by command_option_policies`,p.USAGE);for(let c of o.required)if(!a.has(Ov(c,e)))throw new f(`Missing required option ${ve("update",c)} for type "${e}"`,p.USAGE)}var A$=new Set(["order","rank"]),x$=ko.filter(e=>!A$.has(e)),jv=["tags","closeReason",...x$],C$=["title","description","body","status","closeReason","completedAt","priority","type",...ko,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],E$=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>se(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Wr(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"}],R$=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>qe(Os(e),Hr,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Ns(e)}],T$=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>qe($s(e),Vr,"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=>Ls(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Yc(e,t,n){for(let r of e){let i=t[r.optionKey],s=n.clearItemMetadataKeys.has(r.metadataKey);if(!(i===void 0&&!s)){if(s){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof i!="string")throw new f(`${ve("update",String(r.optionKey))} must be a string value`,p.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(i,n):i.trim(),n.changedFields.push(r.metadataKey)}}}async function I$(e){return Dv(await zr(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 O$(e){let t=er("update",e);return Tt(t)?await I$(t):Dv(t)}function $$(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 Hc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new f(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,p.USAGE);if(e.enabled&&e.clearEnabled)throw new f(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,p.USAGE)}function N$(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new f("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",p.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 f("--replace-deps requires at least one --dep entry",p.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new f("--replace-deps cannot be combined with --dep-remove",p.USAGE);Hc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Hc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Hc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function L$(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 f(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,p.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function M$(e){let t={};for(let n of jv)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function F$(e,t){let n=M$(e);for(let[r,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let s=Vs.get(r)??r;throw new f(`Cannot combine --unset ${s} with ${ve("update",r)}`,p.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new f("Cannot combine --unset acceptance-criteria with --add-ac",p.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new f("Cannot combine --unset acceptance-criteria with --remove-ac",p.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new f("Cannot combine --unset tags with --add-tags",p.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new f("Cannot combine --unset tags with --remove-tags",p.USAGE)}}function D$(e){if(Be(e))return;let t=(n,r)=>{if(Be(e,r))return;let i=Vs.get(r),s=i?`Use --unset ${i} to clear this field.`:void 0;$i(n,ve("update",r),s)};for(let n of jv)t(e[n],String(n));t(e.order??e.rank,"order"),ke(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),ke(e.event,"--event","Use --clear-events to clear linked events.")}function P$(e,t){let n={};for(let r of C$)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 U$(e){let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Ft(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await le(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function j$(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return he(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function q$(e){e.before&&(Ts(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Di(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>ae(t,e.statusRegistry),ie()))}function G$(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new f("--order and --rank must match when both are provided",p.USAGE)}async function K$(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=He(e.options),n=mn(yi(e.options.parent,t),e.settings.id_prefix);if(Ei(n))return{resolvedParentValue:n,warnings:[]};if(vi(e.id,n,e.settings.id_prefix,t),await V(e.pmRoot,n,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:n,warnings:[]};let i=De(n,e.settings.id_prefix);return{resolvedParentValue:n,warnings:wi(i,e.parentReferencePolicy,t).warnings}}function z$(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function W$(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Ft(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await le(t,{schema:e.settings.schema}),r=e.options.type!==void 0?et(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",i=On({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return i?[i]:[]}async function B$(e){if(!e.fieldFlags.status||re(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;Av(e);let n=Object.entries(e.fieldFlags).filter(([s,o])=>o&&s!=="status"&&s!=="closeReason"&&s!=="completedAt").map(([s])=>s),r=await xv(e);if(Wc(r,e.options,e.statusRegistry,e.settings.governance.require_close_reason))return Cv(e,r,n,Tr,s=>$v(e,s));let i;if(n.length>0){let s=Ve(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0});i=await Tr(e.id,s,e.global)}return $v(e,i)}async function $v(e,t){let n=await Cs(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...Qn("update",e.options,He(e.options)==="sdk",n.item),...e.workflowTransitionWarnings,...(t?.warnings??[]).filter(s=>!s.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:i}}function H$(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Gc(t.title,"--title",He(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")),re(e.metadata.status,n)??e.metadata.status}var V$=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function Y$(e,t){for(let n of V$)e[n]!==void 0&&(delete e[n],t.push(n))}function X$(e,t,n,r,i){let s=d$(n,t.statusRegistry);if(e.metadata.status=s,i.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,i.push("closed_at","completed_at");return}!ae(s,t.statusRegistry)&&ae(r,t.statusRegistry)&&Y$(e.metadata,i)}function J$(e,t,n,r){if(t.options.status!==void 0&&X$(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!ae(e.metadata.status,t.statusRegistry))throw new f("--completed-at can only be set on a terminal item",p.USAGE);e.metadata.completed_at=se(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function Q$(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 i=t.options.closeReason?.trim()??"";if(i.length===0)throw new f(ho(He(t.options),"close-reason"),p.USAGE);e.metadata.close_reason=i}r.push("close_reason");return}t.options.status!==void 0&&ae(n,t.statusRegistry)&&!ae(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function Z$(e,t,n,r){J$(e,t,n,r),Q$(e,t,n,r)}function eN(e,t,n){let r=et(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=ki(t.options.priority),n.push("priority")),t.options.type!==void 0){let i=et(t.options.type,t.typeRegistry);if(!i)throw new f(Si(t.options.type,t.typeRegistry.types,ni(t.pmRoot,t.settings.schema)),p.USAGE);e.metadata.type=i,r=i,n.push("type")}return S$(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),tN(e,t,r,n),r}function tN(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let s=js(t.options.typeOption??[]),o=jn(n,s,t.typeRegistry);if(o.errors.length>0)throw new f(o.errors.join("; "),p.USAGE);e.metadata.type_options=o.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let i=jn(n,e.metadata.type_options,t.typeRegistry);if(i.errors.length>0)throw new f(`Current type options are incompatible with type "${n}". ${i.errors.join("; ")}. Use --clear-type-options to clear them.`,p.USAGE);e.metadata.type_options=i.normalized}function nN(e,t){let n=new Set(t.map(i=>Ys(i))),r=new Set;return e.filter(i=>{if(!n.has(Ys(i)))return!0;let s=Hs(i);return r.has(s)?!1:(r.add(s),!0)})}function rN(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=nN(r,t.dependencyUpdates.additions);let i=new Set(r.map(s=>Ys(s)));for(let s of t.dependencyUpdates.additions){let o=Ys(s);i.has(o)||(r.push(s),i.add(o))}}t.dependencyRemovals.length>0&&(Ev(r,t.dependencyRemovals,e.metadata.id),r=r.filter(i=>!t.dependencyRemovals.some(s=>Bc(i,s)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function iN(e,t,n){Vc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Vc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Vc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Vc(e,t,n,r,i,s){n===void 0&&!i.has(t)||(i.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],s.push(t))}function sN(e,t,n){Nv(e,"files",t.options.file,t.fileUpdates.values,w$,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),oN(e,t,n),Nv(e,"docs",t.options.doc,t.docUpdates.values,v$,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Nv(e,t,n,r,i,s,o,a){if(!(n===void 0&&!o.has(t))){if(s)e.metadata[t]=r;else if(o.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>i(l)));for(let l of r){let u=i(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}a.push(t)}}function oN(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Lv(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Lv([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Lv(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let i=k$(r);n.has(i)||(t.push(r),n.add(i))}return t}function aN(e,t,n){let r=t.options.addTags,i=t.options.removeTags,s=Array.isArray(r)&&r.length>0||Array.isArray(i)&&i.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let o=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?jr(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Qd(Gr(o,r),i),n.changedFields.push("tags")}Yc(E$,t.options,n),dN(e,t,n.changedFields)}function cN(e,t,n){let r=t.options.addAc,i=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(i)&&i.length>0))return;let s=Jd(qr(e.metadata.acceptance_criteria),r,i);if(s.unmatchedRemovals.length>0)throw new f(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,p.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let o=s.criteria.join("; ");e.metadata.acceptance_criteria!==o&&(o===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=o,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function dN(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 i=Re(r??"","order");if(!Number.isInteger(i))throw new f("Order must be an integer",p.USAGE);e.metadata.order=i}n.push("order")}}function lN(e,t,n,r){uN(e,t,n.changedFields),mN(e,t,n.changedFields),Yc(R$,t.options,n),Mv(e,t,"sprint",r,n.changedFields),Mv(e,t,"release",r,n.changedFields),pN(e,t,n.changedFields),Yc(T$,t.options,n)}function uN(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 f(ho(He(t.options),"assignee",". Use --unset assignee to clear it."),p.USAGE);wl(r,"--assignee"),e.metadata.assignee=r}n.push("assignee")}}function mN(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 Mv(e,t,n,r,i){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=bi(n,t.options[n]??"",t.settings.validation.sprint_release_format,He(t.options));e.metadata[n]=s.value,r.push(...s.warnings)}i.push(n)}}function pN(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)&&y$(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n,{value:r,idPrefix:t.settings.id_prefix})}function fN(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Ps(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=Us(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function _N(e,t,n){Fv(e,t.runtimeFieldRegistry.definitions.map(i=>i.metadata_key),t.clearItemMetadataKeys,n),Fv(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[i,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(i)){let o=i.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(d=>d.metadata_key===i)?.cli_flag??o;throw new f(`Cannot combine --unset ${o} with --${c}`,p.USAGE)}Pn(e[i],s)||(e[i]=s,n.push(i))}let r=pi(t.options.field,t.extensionRegistrations,Ms,Fs(t.runtimeFieldRegistry,(t.options.runtimeFieldCommands??[]).includes("update_many")?"update_many":"update",t.options));for(let i of Object.keys(r))if(t.clearItemMetadataKeys.has(i))throw new f(`Cannot combine --unset ${i.replaceAll("_","-")} with --field ${i}=...`,p.USAGE);for(let[i,s]of Object.entries(r))Pn(e[i],s)||(e[i]=s,n.push(i))}function Fv(e,t,n,r){for(let i of t)!n.has(i)||e[i]===void 0||(delete e[i],r.push(i))}function hN(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(i=>{let s=t[i];return s!==void 0&&(!Array.isArray(s)||!Pn(s,n[i]??[]))});if(r!==void 0)throw new f(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,p.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 gN(e,t){hN(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,i=[],s=[],o=H$(e,t.options,t.statusRegistry,i),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:i,nowValue:t.nowValue};Z$(e,t,o,i),eN(e,t,i),rN(e,t,i),iN(e,t,i),sN(e,t,i),aN(e,t,c),cN(e,t,c),lN(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&Rr(e.metadata.id,e.metadata.dependencies),re(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,i.includes("assignee")||i.push("assignee")),fN(e,t,i),_N(a,t,i),fi(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys});let d=e.metadata,l=[...new Set(i)].filter(m=>m==="body"?e.body!==r:!Pn(n[m],d[m])),u=Rv(n.dependencies,d.dependencies);return u!==void 0&&s.push(`dependencies_removed:${e.metadata.id}:${u}`),t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${qr(n.acceptance_criteria).length}:${qr(d.acceptance_criteria).length}`),{changedFields:l,warnings:s}}async function qv(e,t,n,r={}){Zn(e,"update","id");let i=await O$(t),s=I(process.cwd(),n.path);await z(s);let o=await R(s),a=q(o.schema),c=$t(o.schema),d=M(),l=gt(d),u=F(o,d),m=o.governance.workflow_enforcement??"off",_=m==="off"?[]:ln(o.schema),h=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(i.allowMissingParent===!0)][o.validation.parent_reference],g=Xc(i.unset,c,l,i.runtimeFieldCommands),y=new Set(g.optionKeys),w=new Set(g.metadataKeys);N$(i),L$({definitions:$$(i),options:i,clearOptionKeys:y,clearItemMetadataKeys:w}),c$(e,i,w),F$(i,g),D$(i);let v=H(i.author,o.author_default),k=new Date,b=k.toISOString(),A=p$(i.dep,o.id_prefix,b,v);Rr(e,A.additions);let C=await Ds({pmRoot:s,dependencies:A.additions,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:u.type_to_folder,allowUnresolved:i.allowUnresolvedDeps,holders:[{id:e}],schema:o.schema}),S=f$(i.depRemove,o.id_prefix),x=Bt("--comment",i.comment,b,v),D=i.ownershipMetadataBypass===!0&&x.values?{...x,values:x.values.map(fe=>({...fe,author:v}))}:x,U=Bt("--note",i.note,b,v),T=Bt("--learning",i.learning,b,v),E=Uc(i.file),K=jc(i.test);K.values=await qi(K.values,v,b);let Ge=qc(i.doc),ge=[],Ze=await K$({id:e,options:i,unsetTargets:g,pmRoot:s,settings:o,typeRegistry:u,parentReferencePolicy:h}),mt=await g$(i.blockedBy,w.has("blocked_by"),s,o.id_prefix,o.item_format,u.type_to_folder),pt=mt.id,ye=[...Ze.warnings,...z$(mt)],Ke=Ul(i,c,i.runtimeFieldCommands),ue=P$(i,Ke);if(!Object.values(ue).some(Boolean))return U$({pmRoot:s,id:e,settings:o,typeRegistry:u});ge.push(...await W$({options:i,fieldFlags:ue,workflowEnforcement:m,typeWorkflows:_,statusRegistry:a,typeRegistry:u,pmRoot:s,id:e,settings:o}));let Zt=await B$({options:i,fieldFlags:ue,statusRegistry:a,workflowTransitionWarnings:ge,global:n,id:e,pmRoot:s,settings:o,typeRegistry:u});if(Zt)return Zt;G$(i);let xt=ie(),de=ue.parent&&!w.has("parent")||A.additions.some(fe=>Rs(fe.kind,xt)),Ae=await Is({pmRoot:s,author:v,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:de});try{let fe=await j$({fieldFlags:ue,clearedMetadataKeys:w,pmRoot:s,settings:o,typeToFolder:u.type_to_folder}),$,ft,xe=await un({pmRoot:s,settings:o,typeToFolder:u.type_to_folder,id:e,op:yN(i,r),author:v,message:i.message,resolveHistoryContext:()=>ft,force:i.force,bypassAssigneeConflict:i.ownershipMetadataBypass===!0||i.ownershipDependencyBypass===!0,extensionFieldNames:l,skipNoop:!0,async mutate(we){let ne=we.metadata.status;$=wN({document:we,recurrenceReason:r.recurrenceReason,requestedStatus:i.status,statusRegistry:a}),ft=$?{recurrence:$}:void 0,fe=fe?.map(Fr=>Fr.id===we.metadata.id?structuredClone(we.metadata):Fr);let Mr=gN(we,{options:i,settings:o,typeRegistry:u,statusRegistry:a,runtimeFieldRegistry:c,extensionRegistrations:d,extensionFieldNames:l,clearItemMetadataKeys:w,dependencyUpdates:A,dependencyRemovals:S,commentUpdates:D,noteUpdates:U,learningUpdates:T,fileUpdates:E,testUpdates:K,docUpdates:Ge,resolvedParentValue:Ze.resolvedParentValue,resolvedBlockedByDependencyId:pt,runtimeFieldUpdates:Ke,nowValue:k,nowIso:b,author:v,pmRoot:s});q$({before:fe,document:we,statusRegistry:a});let oo=await Bs({pmRoot:s,settings:o,metadata:we.metadata,fromStatus:ne,registry:a,force:i.force===!0});return{...Mr,warnings:[...Mr.warnings,...oo]}}});await Ae();let Dn=fe?Es(fe,fe.map(we=>we.id===xe.item.id?xe.item:we),xe.item.id):[];return{item:xe.item,changed_fields:xe.changedFields,warnings:[...Qn("update",i,He(i)==="sdk",xe.item),...ge,...ye,...C,...Dn,...xe.warnings],...$===void 0?{}:{lifecycle_transition:$}}}finally{await Ae()}}function yN(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function wN(e){if(e.recurrenceReason===void 0)return;let t=re(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!ae(t,e.statusRegistry))throw new f(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,p.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=re(n,e.statusRegistry)??n,i=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(o=>{let a=i[o];return typeof a=="string"?[[o,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:s}}async function Tr(e,t,n){return qv(e,t,n)}async function FB(e,t,n,r){Zn(r,"reopen","reason");let i=await qv(e,t,n,{recurrenceReason:r});if(i.lifecycle_transition===void 0)throw new f(`Item ${e} did not produce the required recurrence receipt.`,p.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{...i,lifecycle_transition:i.lifecycle_transition}}import{createHash as vN}from"node:crypto";import{readFileSync as kN}from"node:fs";function Xs(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new f("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",p.USAGE);let n=typeof e.handoff=="string"?Fe(e.handoff,t):void 0;if(n===void 0||ht(n,t)||n===t.in_progress_status)throw new f("--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.",p.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new f("--handoff requires --message with implementation evidence and the next verification step.",p.USAGE);return n}function Gv(e,t,n,r,i){if(ht(e.status,r)||!e.assignee?.trim())throw new f("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",p.CONFLICT);let s=n.governance.workflow_enforcement??"off",o=On({enforcement:s,typeWorkflows:s==="off"?[]:ln(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),a={from_status:e.status,to_status:t,message:i},c=e.status===t?[]:["status"];return e.status=t,{receipt:a,warnings:o?[o]:[],changedFields:c}}var Wv="no_available_next_item",cH="stale_claim_takeover_refused";function Bv(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 Hv(e,t){return Bv(e)===t}function bN(e){return Hv(e,"already_claimed_by")}async function Zc(e,t,n,r={}){let i=I(process.cwd(),n.path);await z(i);let s=await R(i),o=q(s.schema),a=H(r.author,s.author_default),c=ui(a),d=r.takeoverStale===!0;AN(d,t);let l=null,u=!1,m={},_,h=[],g=await un({pmRoot:i,settings:s,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,resolveHistoryContext:()=>_===void 0?void 0:{stale_claim_takeover:_},async mutate(w,v){let b=w.metadata.assignee??"",A=w.metadata.claim_principal?.trim()||b;if(l=b.trim().length>0?b:null,ht(w.metadata.status,o)&&!t)throw new f(`Cannot claim terminal item ${w.metadata.id} without --force`,p.CONFLICT);if(l!==null&&A!==c){let K=await SN({pmRoot:i,storageId:v.storageId,metadata:w.metadata,holder:b,author:a,thresholdHours:s.mutation_guard.stale_in_progress_hours,force:t,ifAvailable:r.ifAvailable===!0,takeoverStale:d});if(K.kind==="skip")return u=!0,h.push(`claim_skipped_held_by:${Co(b)}`),{changedFields:[]};_=K.takeover,h.push(K.warning)}let S={assignee:a,claim_principal:c},x=["assignee","claim_principal"].filter(K=>w.metadata[K]!==S[K]);Object.assign(w.metadata,S);let D=w.metadata.status,{changedFields:U,warnings:T,...E}=$N(w.metadata,r.start===!0,s,o);return T.push(...await ON({pmRoot:i,settings:s,metadata:w.metadata,fromStatus:D,registry:o,force:t,start:r.start===!0})),m=E,h.push(...T),{changedFields:[...x,...U],warnings:h}}}),y=Vv(await Yv("claim",g.item.id,n,u,()=>Qf({pmRoot:i,settings:s,principal:c,itemId:g.item.id})));return h.push(...y.warnings),{item:xo(g.item),changed_fields:g.changedFields,claimed_by:u&&l!==null?It(l):a,previous_assignee:l===null?null:It(l),forced:t,...u?{skipped:!0}:{},...h.length>0?{warnings:h}:{},...Qc("suggestions",y.suggestions),...m,..._===void 0?{}:{takeover:_}}}async function SN(e){if(e.ifAvailable&&!e.takeoverStale)return{kind:"skip"};if(e.force)return{kind:"take",warning:`claim_takeover:${Co(e.holder)}->${e.author}`};let t=await e_(e.pmRoot,e.storageId,e.holder,{updated_at:e.metadata.updated_at,threshold_hours:e.thresholdHours}),n=e.takeoverStale?xN(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 RN(e.metadata.id,t,e.takeoverStale)}function AN(e,t){if(!(!e||!t))throw new f("--takeover-stale cannot be combined with --force",p.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 xN(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 CN={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 EN(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:`${CN[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 RN(e,t,n){let r=t.activity,i=r.stale_policy,s={item_id:e,claimed_by:t.holder,claimed_at:t.since,claim_source:t.source,claim_activity:r},o="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=EN(e,r);return new f(`Item ${e} is ${t.phrase}, and its claim is not stale under ${i.setting} (${c.reason}).`,p.CONFLICT,{code:"stale_claim_takeover_refused",...s,required:`The claim must be idle for at least ${i.threshold_hours}h (${i.setting}) before --takeover-stale may take it.`,why:`${o} 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 f(`Item ${e} is already ${t.phrase}. Use --force to take over, or --if-available to skip without failing.`,p.CONFLICT,{code:"already_claimed_by",...s,why:o,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.",...i.stale?[`Re-run with --takeover-stale: the claim has been idle ${r.idle_hours}h, past ${i.setting}=${i.threshold_hours}.`]:[],a]})}var TN="claim_semantic_attribution_unrecorded";function Vv(e){return e?{warnings:[e.warning],suggestions:[e.suggestion]}:{warnings:[],suggestions:[]}}function Qc(e,t){return t.length>0?{[e]:t}:{}}var IN="release_semantic_attribution_unrecorded";async function Yv(e,t,n,r,i){if(!r)try{await i();return}catch(s){let o=Bv(s)??"unexpected_error",a=Ye(n);return{warning:e==="claim"?TN:IN,suggestion:`The ${e} of ${t} is saved, but the session attribution that names this agent's active work was not updated (${o}); nothing needs a retry. If ${L([...a,"health"])} reports a stale lock, remove it with ${L([...a,"gc","--scope","locks"])}.`}}}function dH(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new f(n?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",p.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 f("Specify either an item id or --next, not both",p.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 ON(e){return e.start?Bs(e):kv(e)}function $N(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(ht(e.status,r))throw new f(`Cannot start terminal item ${e.id}; reopen it with pm item reopen before starting it`,p.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 i=Ht(r),s=n.governance.workflow_enforcement??"off",o=On({enforcement:s,typeWorkflows:s==="off"?[]:ln(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:i}),a={from_status:e.status,to_status:i},c=e.status===i?[]:["status"];return e.status=i,{start:a,changedFields:c,warnings:o?[o]:[]}}async function lH(e,t,n={},r={}){if(n.takeoverStale===!0)throw new f("--takeover-stale cannot be combined with --next",p.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 i=NN(n.maxAttempts),s=await R(I(process.cwd(),t.path)),o={...n,author:H(n.author,s.author_default)},a=await t_({...r,callerAuthor:o.author,limit:String(i)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return LN(c.slice(0,i),e,t,o)}function NN(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new f("--max-attempts must be an integer from 1 to 100",p.USAGE);return t}async function LN(e,t,n,r={},i=Zc){let s=0,o=[],a=()=>o.length>0?{start_refused:[...o]}:{};for(let c of e){s+=1;try{let d=await i(c.id,t,n,r),l={...d,recommendation:c,attempts:s,available:!0,...a()};if(!d.skipped)return l}catch(d){if(Hv(d,Ws)){o.push(c.id);continue}if(!bN(d))throw d}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:H(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,...a(),warnings:[Wv]};throw MN(s,o,r.start===!0)}function MN(e,t,n){let r=e===0,i="Every ranked candidate was claimed by another agent before this atomic selection completed.";return r?i="No ready items matched the specified filters or selection criteria.":t.length>0&&(i=`${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 f(r?"No actionable items matched the selection filters":"No actionable item remained available to claim",r?p.NOT_FOUND:p.CONFLICT,{code:Wv,why:i,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 FN(e){if(e===void 0)return[];let t=e.trim();if(It(t)===t)return t.startsWith("-")?[`--author=${t}`]:["--author",t]}var Xv="release_claim_ended_by_close";function Jv(e,t,n,r,i){let s=FN(i),o=s===void 0?void 0:L([...Ye(r),"claim",e,"--force",...s]),a=o===void 0||kl(o)!==o?"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 ${o} only when that takeover is approved.`;return new f(`A close of ${e} already ended your claim, and ${t} has claimed it since; ${n} cannot move or release another holder's claim.`,p.CONFLICT,{code:Xv,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 Qv(e){let t=e.assignee?.trim();return t?e.claim_principal?.trim()||t:void 0}async function Zv(e,t,n){let r=I(process.cwd(),t.path),i=await R(r),s=ui(H(n,i.author_default)),o=F(i,M()).type_to_folder,a=await V(r,e,i.id_prefix,i.item_format,o);if(!a)return _=>_();let c=Me(r,a.id),d=zv(c),{document:l}=await le(a,{schema:i.schema}),u=Qv(l.metadata);if(u!==void 0&&u!==s&&await ha(r,a.id,s))throw Jv(a.id,It(l.metadata.assignee.trim()),"--pause",t,n);let m=Kv(l.metadata,d);return _=>mi({pmRoot:r,id:a.id,validate:h=>{if(Kv(h.metadata,zv(c))!==m)throw new f(`${a.id} changed while the pause was judged, so nothing was written.`,p.CONFLICT,{code:DN,item_id:a.id,nextSteps:[`Check the current holder with ${L([...Ye(t),"get",a.id])}, reconfirm any override, then re-run the original pause command unchanged.`]})}},_)}var DN="pause_item_changed";function Kv(e,t){return JSON.stringify([Qv(e)??null,e.status,e.updated_at,t])}function zv(e){try{return vN("sha256").update(kN(e)).digest("hex")}catch{return"absent"}}async function Js(e,t,n,r={}){let i=I(process.cwd(),n.path);await z(i);let s=await R(i),o=H(r.author,s.author_default),a=ui(o),c=r.ownershipReleaseBypass===!0,d=null,l=q(s.schema),u=Xs(r,l);if(u!==void 0&&c)throw new f("Ownership-release bypass only clears ownership; it cannot change a handoff status.",p.USAGE);let m,_,h;try{h=await Ie({pmRoot:i,settings:s,id:e,op:"release",author:o,message:r.message,force:t,bypassAssigneeConflict:c,...c?{}:{callerClaimScope:({storageId:w,callerPrincipal:v})=>ha(i,w,v)},mutate(w,v){if(v.callerClaimScoped===!0){let b=It(w.metadata.assignee.trim());if(u!==void 0)throw Jv(w.metadata.id,b,"--handoff",n,r.author);return _=b,{changedFields:[],warnings:[`${Xv}:${w.metadata.id}:${b}`]}}d=w.metadata.assignee??null;let k=u===void 0?void 0:Gv(w.metadata,u,s,l,r.message);return m=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){or(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=Vv(await Yv("release",h.item.id,n,!1,()=>Zf({pmRoot:i,principal:a,itemId:h.item.id}))),y=_===void 0?PN(h.item,l):{warnings:[],suggestions:[`A close of ${h.item.id} already ended your claim; ${_} claimed it afterwards and keeps it. The item was not changed.`]};return{item:xo(h.item),released_by:o,changed_fields:h.changedFields,previous_assignee:d===null?null:It(d),forced:t,...m===void 0?{}:{handoff:m},...Qc("warnings",[...h.warnings,...y.warnings,...g.warnings]),...Qc("suggestions",[...y.suggestions,...g.suggestions])}}function PN(e,t){return Nt(e.status,t)===Nt(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:[]}}async function ed(e,t,n){try{return await n()}catch(r){let i=r instanceof f?r.context:{},s=new f(r instanceof Error?r.message:String(r),r instanceof f?r.exitCode:p.GENERIC_FAILURE,{...i,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${i.why?` ${i.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...i.nextSteps??[]]});throw s.cause=r,s}}async function xH(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new f("--start cannot be combined with --next or --if-available for an explicit item",p.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 R(I(process.cwd(),n.path)),i=Ht(q(r.schema));return vv(async()=>{let s=await Zc(e,t.force===!0,n,Mi(t,{},["start"])),o=s.item.id,a=await ed(o,"claim",()=>Tr(o,Mi(t,{status:i},["assignee","start","next","ifAvailable","maxAttempts","takeoverStale"]),n)).catch(async c=>{throw await UN(c,s,n,t.author)});return{id:o,action:"start_task",claim:s,update:a}})}async function UN(e,t,n,r){if(!(e instanceof f)||e.code!==Ws||t.previous_assignee!==null)return e;let i=String(t.item.id);try{await mi({pmRoot:I(process.cwd(),n.path),id:i,validate:o=>{if(o.metadata.assignee!==t.claimed_by||o.metadata.claim_principal!==t.item.claim_principal)throw new f("The claim this start took is no longer its own.",p.CONFLICT)}},()=>Js(i,!1,n,{author:r,message:"Release the claim: a blocker opened before its start could be recorded"}))}catch{return e}let s=e.cause instanceof f?e.cause:e;return new f(s.message,s.exitCode,{...s.context,why:`${s.context.why??""} A blocker opened after this start's claim, so the claim was released and no ownership remains.`.trim()})}async function CH(e,t,n){let r=await R(I(process.cwd(),n.path)),i=q(r.schema);Xs({...t,pause:!0},i);let s=await Zv(e,n,t.author),o=i.open_status,a=await s(()=>Tr(e,Mi(t,{status:o},["assignee","pause"]),n)),c=a.item.id,d=await ed(c,"update",()=>Js(c,t.force===!0,n,t));return{id:c,action:"pause_task",update:a,release:d}}async function EH(e,t,n,r){let i=await Cs(e,t,n,r),s=i.item.id,o=await ed(s,"close",()=>Js(s,n.force===!0,r,n));return{id:s,action:"close_task",close:i,release:o}}import Ir from"node:crypto";import{cp as ek,lstat as jN,mkdir as Yt,readFile as Nn,readdir as nd,rename as rk,rm as id,writeFile as Qs}from"node:fs/promises";import P from"node:path";var ik="https://schema.unbrained.dev/pm/workspace-snapshot/v1",UH=["create","list","inspect","restore","delete"],sk=P.join("runtime","workspace-snapshots"),qN=new Set(["checkpoints","locks","runtime","search","transactions"]),GN=/^[a-z0-9][a-z0-9._-]*$/,$n="sdk-workspace-transaction",td={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},ok={renameEntry:rk,removeEntry:async e=>{await id(e,{recursive:!0,force:!0})}},rd=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 Yl(this.lockPath,$n);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await Nn(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!==$n||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await Le(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
|
|
10
|
-
`)}finally{await t()}}};async function
|
|
11
|
-
`).filter(t=>t.trim().length>0).length}async function
|
|
12
|
-
`,"utf8"),await Yt(
|
|
13
|
-
`,"utf8"),await
|
|
14
|
-
`)}var
|
|
15
|
-
`,result:i})}});return{changed:o.changed,observation:o.result,ledger_path:"improvement-ledger.json"}}async function kk(e={}){let t=I(e.cwd??process.cwd(),e.pmRoot);await z(t);let n=e.metric===void 0?void 0:yk(e.metric),r=e.since===void 0?void 0:wk(e.since,"since"),i=sL(e.limit),o=ad(await ee(gk.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 o){let d=a.get(c.metric)??[];d.push(c),a.set(c.metric,d)}return{observations:[...o].reverse().slice(0,i),total:o.length,truncated:o.length>i,trends:[...a].map(([,c])=>dL(c)).sort((c,d)=>c.metric.localeCompare(d.metric)),source:"audited_workspace_singleton"}}function lL(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 uL(e,t,n){let r=t,i=new Set([e.id]);for(;r!==void 0&&!i.has(r.id);)i.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function mL(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,i)=>r.entries[0].ts.localeCompare(i.entries[0].ts)||r.id.localeCompare(i.id)),t.push(...n.map(r=>r.children))}}function bk(e=zn,t=Kn){return t.map(n=>{let r=e.filter(i=>((n==="model"?i.model_environment_keys:i.provenance_environment_keys?.[n])?.length??0)>0||i.provenance_resolvers?.[n]!==void 0).map(i=>i.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function AV(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let i=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};i.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?i.observed+=1:r.agent_provenance?.model===null?i.unavailable+=1:i.legacy_missing+=1,n.set(r.agent_harness,i)}return[...n.values()].map(r=>{let i=r.observed+r.unavailable;return{...r,coverage:i===0?null:r.observed/i,inert:i>=t&&r.observed===0}}).sort((r,i)=>r.harness.localeCompare(i.harness))}function Sk(e,t=Kn,n=1){let r=new Map;for(let i of e)if(i.agent_harness)for(let s of t){let o=`${i.agent_harness}\0${s}`,a=r.get(o)??{harness:i.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=i.agent_provenance?.[s];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(o,a)}return[...r.values()].map(i=>{let s=i.observed+i.unavailable;return{...i,coverage:s===0?null:i.observed/s,inert:s>=n&&i.observed===0}}).sort((i,s)=>i.harness.localeCompare(s.harness)||i.dimension.localeCompare(s.dimension))}function xV(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 i=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let l=`${c.agent_harness}\0${d}`,u=i.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let m=c.agent_provenance?.[d];m?.value&&(u.observed+=1,u.by_source[m.source]=(u.by_source[m.source]??0)+1),i.set(l,u)}let s=[...i.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[l])=>d.localeCompare(l)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),o=s.filter(c=>c.entries>=r),a=o.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:o.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:s,failures:a}}function CV(e){let t=[...e].sort((s,o)=>s.ts.localeCompare(o.ts)||s.author.localeCompare(o.author)||s.op.localeCompare(o.op)||s.before_hash.localeCompare(o.before_hash)||s.after_hash.localeCompare(o.after_hash)),n=new Map,r=new Map;for(let s of t){let o=s.agent_episode,a=lL(s),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(s);continue}let l={id:a.id,...o?.label===void 0?{}:{label:o.label},...o?.parent_id===void 0?{}:{parent_id:o.parent_id},source:a.source,entries:[s],children:[]};n.set(c,l),o!==void 0&&r.set(a.id,l)}let i=[];for(let s of n.values()){let o=s.parent_id?r.get(s.parent_id):void 0;o&&uL(s,o,r)?o.children.push(s):i.push(s)}return mL(i),i}var pL=1e4,Ak=1e5,fL=1e3,_L=30,hL=["append","comment","docs","file","learning","note","test_run"];function gL(e){let t=e??pL;if(!Number.isSafeInteger(t)||t<1||t>Ak)throw new f(`History analytics event limit must be an integer from 1 to ${Ak}.`,p.USAGE,{code:"invalid_history_analytics_limit"});return t}function xk(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new f("History analytics minimum sample must be an integer from 1 to 10000.",p.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function yL(e){let t=e?.trim();if(!t)return new Date(Date.now()-_L*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let i=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(i)||i<1)throw new f("History analytics --since duration must be positive.",p.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-i*s).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new f("History analytics --since must be an ISO timestamp or negative duration such as -30d.",p.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function Zs(e,t){let n=gL(t.eventLimit),r=yL(t.since),i=[],s=r,o=!1;for(;i.length<n;){let a=await n_({pmRoot:e,since:s,limit:Math.min(fL,n-i.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(i.push(...c),o=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:i,receipt:{since:r,events:i.length,truncated:o,...o?{next_cursor:s}:{},source:"history_event_index"}}}function wL(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function vL(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 kL(e){return hL.some(t=>e.startsWith(t))}function Ck(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 bL(e,t,n){let r=new Map,i=new Map,s=new Map;for(let o of t){let a=wL(o.entry,e),c=vL(o.entry),d=i.get(o.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&i.set(o.item_id,l),!a)continue;let u=Ck(r,a);u.events+=1,kL(o.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,s.set(o.item_id,a)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:r,lastCloseValue:s}}function SL(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let i=new Set((r.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of i){let o=t.get(s);o&&(Ck(e,o).defectEscapes+=1)}}}function AL(e,t,n,r){let i=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:i==="available"?t.closes/r:null,rework_rate:i==="available"?t.reopens/t.closes:null,defect_escape_rate:i==="available"?t.defectEscapes/t.closes:null,sample_status:i}}function xL(e,t,n,r,i,s){let{buckets:o,lastCloseValue:a}=bL(e,t,r);return SL(o,a,n),{dimension:e,status:o.size===0?"unavailable":"available",rows:[...o].map(([c,d])=>AL(c,d,i,s)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function CL(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,i=Date.parse(n),s=Date.parse(r);return!Number.isFinite(i)||!Number.isFinite(s)?1:Math.max(1,(s-i)/864e5)}function EL(e,t,n){let r=bk(t),i=Sk(e,Kn,n),s=i.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),o=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:i,inert:s,undeclared:o,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...o.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function NV(e,t=zn,n={}){return cd(await Zs(e,n),t,n)}function cd(e,t=zn,n={}){let r=xk(n.minimumSample);return{...EL(e.events.map(i=>i.entry),t,r),window:e.receipt}}async function LV(e,t,n,r={}){return dd(await Zs(e,r),t,n,r)}function dd(e,t,n,r={}){let i=xk(r.minimumSample),s=CL(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(o=>xL(o,e.events,t,n,i,s)),minimum_sample:i,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}import TL from"node:fs/promises";import Rk from"node:path";function eo(e,t,n,r,i,s="min"){let o=i==="min"?e-t:t-e,a=s==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return o<0||o===0&&r!==null&&a<0}function RL(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,i=null,s=null,o=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 l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,m=Date.parse(u);Number.isNaN(m)||(eo(m,o,u,i,"min")&&(o=m,i=u),eo(m,a,u,s,"max","max")&&(a=m,s=u))}return{id:e,bytes:n,lines:r,oldest_ts:i,newest_ts:s}}function Ek(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),i=e.map(({id:_,raw:h})=>RL(_,h)),s=0,o=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let _ of i){if(s+=_.lines,o+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);eo(h,d,_.id,a?.id??null,"min")&&(d=h,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);eo(h,l,_.id,c?.id??null,"max")&&(l=h,c={id:_.id,ts:_.newest_ts})}}let u=r===0?[]:[...i].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),m=r===0?[]:[...i].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:s,total_bytes:o,largest_by_bytes:u,deepest_by_lines:m,oldest_entry:a,newest_entry:c}}function IL(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function OL(e,t,n,r,i){let s=tr(e,"type",r),o=new Set(s.rows.map(m=>m.key)),a=t.filter(m=>!o.has(m)),d=(i?[...s.rows,...a.map(m=>({label:m,key:m,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(m=>({type:m.key??m.label,total:m.total,open:m.buckets.open,in_progress:m.buckets.in_progress,blocked:m.buckets.blocked,draft:m.buckets.draft,closed:m.buckets.closed,canceled:m.buckets.canceled,other:m.buckets.other})),l=IL([...n]);for(let m of e)l[m.status]+=1;let u=Object.fromEntries(Object.entries(l).filter(([,m])=>i||m>0));return{byType:d,byStatus:u,omitted:i?0:a.length+Object.values(l).filter(m=>m===0).length}}function $L(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function NL(e){let t=Rk.join(e,"history");if(!await me(t))return[];await Te({path:t,scope:"project"});let n=(await TL.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,s)=>i.localeCompare(s)),r=[];for(let i of n){let s=Rk.join(t,i),o=await ee(s);o!==null&&(await Te({path:s,scope:"project"}),r.push({id:i.slice(0,-6),raw:o}))}return r}async function LL(e,t){let n=[],r=O();for(let i of r_(t.observe,r))n.push(await vk({metric:i.name,value:i.value,direction:t.direction,unit:i.unit,threshold:i.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function ML(e,t,n){let r={};return t.byAssignee&&(r.assignee=tr(e,"assignee",n)),t.byTag&&(r.tag=tr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=tr(e,"priority",n)),r}async function FL(e,t,n,r,i){let s={since:i.since,eventLimit:i.eventLimit,minimumSample:i.minimumSample},o=i.provenanceCoverage||i.fleetAttribution?await Zs(e,s):void 0;return{provenanceCoverage:i.provenanceCoverage&&o?cd(o,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:i.fleetAttribution&&o?dd(o,t,r,s):void 0}}function DL(e,t,n,r,i){let s=Object.keys(i.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...i.metadataCoverage?{metadata_coverage:i.metadataCoverage}:{},...s?{breakdowns:i.breakdowns}:{},...i.storage?{storage:i.storage}:{},...i.fieldUtilization?{field_utilization:i.fieldUtilization}:{},...i.improvementLedger?{improvement_ledger:i.improvementLedger}:{},...i.recordedObservations.length>0?{recorded_observations:i.recordedObservations}:{},...i.provenanceCoverage?{provenance_coverage:i.provenanceCoverage}:{},...i.fleetAttribution?{fleet_attribution:i.fleetAttribution}:{},generated_at:O()}}async function t2(e,t={}){let n=I(process.cwd(),e.path);await z(n);let r=await R(n),i=await LL(e,t),s=F(r,M()),o=q(r.schema),a=t.fieldUtilization?await rt(n,r.item_format,s.type_to_folder,void 0,r.schema):await he(n,r.item_format,s.type_to_folder,void 0,r.schema);await gi({pmRoot:n,settings:r,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=gf(o),d=OL(a,s.types,o.definitions.map(k=>k.id),c,t.includeEmpty===!0),l=await NL(n),u=0;for(let k of l)u+=$L(k.raw);let m=t.storage?Ek(l):void 0,_=t.metadataCoverage?yf(a,c):void 0,h=ML(a,t,c),g=t.fieldUtilization?wf(a):void 0,y=t.measurements===!0||i.length>0?await kk({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:v}=await FL(n,a,r,o.terminal_statuses,t);return DL({items:a.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:_,breakdowns:h,storage:m,fieldUtilization:g,improvementLedger:y,recordedObservations:i,provenanceCoverage:w,fleetAttribution:v})}import PL from"node:fs/promises";import ut from"node:path";var Nk=ut.join("runtime","telemetry","state.json"),$r=ut.join("runtime","telemetry"),UL=20,md=Rt.filter(e=>e.lifecycle==="deprecated"),Tk=["status","flush","stats","clear"],Ik=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},ld=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Ok=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},jL=e=>({command:ld(e.event.command,"<unknown>"),eventType:ld(e.event.event_type,"unknown"),eventSchemaVersion:Ok(e.event.schema_version),clientSchemaVersion:Ok(e.client_schema_version)}),qL=()=>({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:{}}),GL=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},KL=e=>{let t=e?.command_resolution;return ld(t,"")||void 0},Lk=(e,t)=>{e[t]=(e[t]??0)+1},zL=(e,t)=>{let n=GL(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=KL(t);r!==void 0&&Lk(e.resolution_counts,r)},WL=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,$k=(e,t)=>{t!==void 0&&e.add(t)},BL=(e,t)=>{let n=jL(t),r=e.get(n.command)??qL();r.count+=1,r.max_attempts=Math.max(r.max_attempts,WL(t.attempts)),Lk(r.event_type_counts,n.eventType),$k(r.event_schema_versions,n.eventSchemaVersion),$k(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&zL(r,t.event.payload),e.set(n.command,r)},HL=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((s,o)=>s-o),i=Object.entries(t.resolution_counts).sort((s,o)=>s[0].localeCompare(o[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,o)=>s[0].localeCompare(o[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,o)=>s-o),client_schema_versions:[...t.client_schema_versions].sort((s,o)=>s-o),...r.length>0?{duration_p50_ms:Ik(r,.5),duration_p95_ms:Ik(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}:{},...i.length>0?{command_resolution_counts:Object.fromEntries(i)}:{}}},VL=e=>{let t=(e??"status").trim().toLowerCase();if(Tk.includes(t))return t;throw ti({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Tk,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},pd=()=>{throw new f("--limit must be a positive integer",p.USAGE)},Mk=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?pd():e,YL=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?pd():Mk(Number.parseInt(t,10))},XL=e=>e===void 0?UL:typeof e=="number"?Mk(e):typeof e=="string"?YL(e):pd(),JL=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},QL=e=>{try{let t=JSON.parse(e);return JL(t)?t:void 0}catch{return}},ZL=e=>e===null?[]:e.split(`
|
|
16
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),
|
|
17
|
-
`)},e,250)}catch{}return s}async function
|
|
18
|
-
`),!0},n,250)}catch{return!1}}var to=e=>e??null,ro=async e=>{let t=await R(e),n=ut.join(e
|
|
19
|
-
`)}catch{}},xM=async(e,t,n)=>{let r=[],i=0;for(let s of e){let o=await a_(s.id,{run:!1},{...t,path:n});i+=o.tests.length,r.push({item:s,tests:o.tests})}return{itemTests:r,linkedTests:i}},CM=async e=>{let t=q(e.settings.schema),n=F(e.settings,M()),r=lM(e.options.status,t),i=Pk(e.options.limit,"--limit"),s=Pk(e.options.offset,"--offset")??0,a=(await he(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>r?d.status===r:!0).sort((d,l)=>d.id.localeCompare(l.id));return{filteredItems:i===void 0?a.slice(s):a.slice(s,s+i),statusFilter:r,limitFilter:i,offsetFilter:s}},jk=e=>{let t=e.filter(Gi).map(({provenance:n,provenance_invalid:r,updated_by:i,updated_at:s,note:o,timeout_seconds:a,...c})=>c);return t.length===0?"":Z(t)},qk=(e,t)=>t.length===0?fd(e):`${fd(e)}:setup[${t}]`,EM=e=>{let t=new Map;for(let{tests:n}of e){let r=jk(n);for(let i of n){if(Gi(i))continue;let s=qk(i,r);if(!t.has(s)){t.set(s,i.timeout_seconds);continue}t.set(s,bM(t.get(s),i.timeout_seconds))}}return t};function RM(e,t){try{bl(e.command);return}catch(n){if(!(n instanceof f)||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 TM=(e,t)=>{let n=[],r=[],i=Kf(e.tests),s=jk(i),o=ma();return{plans:i.map(c=>{let d=Gi(c),l=d?fd(c):qk(c,s),u=o.blocked(c);if(u)return{test:c,key:l,duplicate:!1,refusal:u};let m=RM(c,e.item.id);if(m)return{test:c,key:l,duplicate:!1,refusal:o.record(c,m)};if(d)return n.push(c),{test:c,key:l,duplicate:!1,refusal:void 0};if(t.seenTestKeys.has(l))return{test:c,key:l,duplicate:!0,refusal:void 0};t.seenTestKeys.add(l),r.push(l);let _=t.effectiveTimeoutByKey.get(l);return n.push(_===void 0?c:{...c,timeout_seconds:_}),{test:c,key:l,duplicate:!1,refusal:void 0}}),testsToRun:n,reservedKeys:r}},IM=(e,t,n)=>{if(e.some(r=>r.phase==="setup"&&r.status!=="passed"))for(let r of t)n.seenTestKeys.delete(r)},OM=async(e,t)=>{let{plans:n,testsToRun:r,reservedKeys:i}=TM(e,t),s=r.length>0?await o_(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}):[];IM(s,i,t);let o=0,a=ma(),c=n.map(({test:m,key:_,duplicate:h,refusal:g})=>{if(g)return a.blocked(m)??g;if(!h){let y=s[o];return o+=1,a.blocked(m)??a.record(m,y)}return a.blocked(m)??{command:m.command,path:m.path,status:"skipped",error:`Duplicate linked test skipped (key=${_}).`}}),d=SM(c),l=pa(c),u=await LM(e,d,c,t);return{passed:d.passed,failed:d.failed,skipped:d.skipped,trackingWarnings:u,failureCategories:l,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:l}}},$M=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),NM=e=>e?!0:void 0,LM=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let i=$M(t,r.options);await i_({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:i?"failed":"passed",started_at:r.runStartedAt,finished_at:O(),recorded_at:O(),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:NM(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}})}catch(i){return Vn(i)?(r.revisionConflicts.push(i),[]):[`test_result_tracking_failed:${e.item.id}:${mM(i)}`]}return[]},MM=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},_d=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},FM=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:tt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:EM(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:H(e.options.author,e.settings.author_default),trackingRunId:pM(),trackingAttempt:MM(),trackingResumedFrom:_d(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),DM=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:pa([]),trackingWarnings:[]},i=e.failOnEmptyTestRun===!0&&t===0;return i&&(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:i}},PM=async(e,t,n)=>{for(let[i,s]of e.entries()){so(t.options,`item ${i+1}/${e.length} start id=${s.item.id} linked_tests=${s.tests.length}`);let o=await OM(s,t);AM(n.failureCategories,o.failureCategories),n.passed+=o.passed,n.failed+=o.failed,n.skipped+=o.skipped,n.trackingWarnings.push(...o.trackingWarnings),n.results.push(o.result),so(t.options,`item ${i+1}/${e.length} end id=${s.item.id} status=${o.failed===0?"passed":"failed"} passed=${o.passed} failed=${o.failed} skipped=${o.skipped}`)}let[r]=t.revisionConflicts;if(r!==void 0)throw r},UM=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(i=>i.run_results),r=s_(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}`)},jM=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}),qM=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(" "),GM=async(e,t)=>{let n=I(process.cwd(),t.path);await z(n);let r=await R(n),i=await CM({pmRoot:n,settings:r,options:e}),s=uM(e.timeout),o=O(),a=await xM(i.filteredItems,t,n);return so(e,qM({...i,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:i.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:s,runStartedAt:o}},KM=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}},D2=async(e,t)=>{let n=await GM(e,t),{accumulation:r,failOnEmptyTestRunTriggered:i}=DM(e,n.linkedTests,n.filteredItems),s=FM({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await PM(n.itemTests,s,r),UM(e,r);let o=KM({options:e,accumulation:r,failOnEmptyTestRunTriggered:i});return so(e,`end status=${o.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),jM({ok:o.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:o.failOnSkippedTriggered,failOnEmptyTestRunTriggered:i})};import wF from"node:os";import Ln from"node:fs/promises";import{spawn as Bk}from"node:child_process";import{createHash as zM,randomBytes as WM}from"node:crypto";import Nr from"node:path";var Hk=new Set(["queued","running"]),wd=new Set(["passed","failed","stopped","canceled"]),BM=3e3,HM=3e3,VM=3e4,Vk=100,Gk=100;function Yk(){return Date.now()}function Xk(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function YM(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function XM(){let e=Date.now().toString(36),t=WM(3).toString("hex");return`tr-${e}-${t}`}function JM(e,t,n){let r={kind:e,command:Xk(t),pm_root:Nr.resolve(n)};return zM("sha256").update(JSON.stringify(r)).digest("hex")}function Mn(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function QM(e){await nn(ml(e)),await nn(bo(e)),await nn(pl(e)),await nn(fl(e)),await nn(gl(e))}async function Jk(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new f(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,p.GENERIC_FAILURE)}}async function Qe(e,t){let n={...t,updated_at:O()};await Le(So(e,t.id),`${JSON.stringify(n,null,2)}
|
|
20
|
-
`)}async function
|
|
21
|
-
`);return}await Le(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:yd(n,
|
|
22
|
-
`)}async function
|
|
23
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{A as mn,B as ie,D as Fi,G as Di,H as Cf,Ha as jf,Ia as qf,J as oa,Ja as sr,K as Ef,Ka as ua,M as Rf,Na as Gf,Oc as a_,Rc as c_,U as Tf,_a as or,bb as gn,eb as yn,l as Sf,lb as ji,o as Af,oa as Pf,p as nr,pa as Uf,pb as i_,qb as s_,s as xf,wb as o_,y as rr,yb as ha,z as ir}from"./chunk-ZL6J6JYT.js";import{a as Xo,d as Jo,e as Jp,f as Qo,g as Qp}from"./chunk-X5D5YUHR.js";import{a as Kf}from"./chunk-4QA5O64H.js";import{J as bf,a as Oi,b as Qn,c as Ni,d as ke,e as $i,f as yf,g as wf,h as Li,i as Zn,j as vf,k as kf,l as ra,m as ia,n as er,r as tr,t as Mi,u as X,y as sa}from"./chunk-L2ZSSMYY.js";import{C as Hf,E as Gi,F as Vf,G as Yf,H as ma,I as pa,N as Xf,O as Jf,P as Qf,Q as Zf,R as e_,S as fa,T as _a,U as t_,V as n_,W as r_,Z as d_,a as Mf,aa as l_,da as u_,ia as m_,ja as p_,m as hn,q as Ff,r as Df,t as Pi,u as Ui,v as zf,w as Wf,x as Bf,z as qi}from"./chunk-YSVOXCYH.js";import{Aa as Lf,j as Zp,oa as ca,pa as Nf,qa as da,ra as la,u as Of,va as $f}from"./chunk-4YQMQOUO.js";import{a as Yp,l as aa}from"./chunk-3HKPVOAN.js";import{i as bt,k as pn,l as fn,m as _n}from"./chunk-Q6K7HWZ7.js";import{c as If}from"./chunk-OGVSGXQX.js";import{N as lf,O as Ti,P as uf,Q as ta,S as mf,T as pf,V as ff,W as _f,X as Ii,Y as hf,a as ef,b as tf,c as nf,ca as na,d as rf,f as sf,ga as gf,j as Zo,k as of,l as af,m as ea,n as cf,o as df}from"./chunk-C6WM6ZN4.js";import{a as Gp,e as zp,k as Wp,s as Bp,t as Jn,u as Hp,x as Vp}from"./chunk-QDV7S2QS.js";import{$b as Vn,A as Zd,Ad as Kp,B as Re,C as Wr,E as bl,H as Sl,Ha as Si,J as Al,Jb as Hu,Ka as ln,La as Nu,Ma as $u,Na as Du,Nc as Po,Ob as Vu,Oc as Uo,Pc as jo,Qb as Yu,Qc as qo,R as ti,Tb as Do,U as Eu,Ua as Pu,Vb as Xu,Xb as Ju,Yb as yt,Zb as Qu,_b as wt,ab as Uu,ac as Pt,c as Be,ca as gi,cc as Zu,e as He,eb as qu,f as tn,fb as Gu,fd as nm,g as ho,ga as De,h as Xd,ha as Tu,i as jr,ib as Ku,j as qr,ja as yi,jb as Ai,k as Jd,ka as Iu,kb as zu,l as Gr,la as wi,lc as em,m as Qd,ma as vi,mb as V,na as ki,nb as le,nd as rm,o as _e,p as Kr,pb as xi,pc as tm,q as go,qb as he,r as $e,ra as bi,rb as rt,sb as Wu,sd as im,tb as Dt,td as sm,ua as Ou,ud as Ci,v as Ve,vb as un,vd as om,wb as Ie,x as It,xa as Hn,yb as Fo,z as zr,zb as Bu,zd as Ri}from"./chunk-CBUC4X7Q.js";import{B as ju,H as z,a as Ft,b as Ru,e as cn,f as dn,j as Lu,t as Mu,u as R,v as Fu}from"./chunk-OXC5KBIQ.js";import{A as _o,Aa as si,Bb as Zl,Da as oi,Df as _u,Ea as re,Ec as ru,Ed as ou,Eg as _i,Fa as Lt,Fd as au,Ff as hu,Ga as ae,Gg as hi,Ha as $o,Hb as ui,Hf as Bn,Ia as Lo,Ib as H,Ja as jl,Jf as gu,La as ai,Ld as cu,Mf as yu,Na as ql,Nb as Mt,O as Ao,Oa as an,Pa as Gl,Pg as vu,Q as Ye,Qa as Kl,Qe as lu,Sa as zl,T as Nt,Ua as ci,Ub as eu,Va as Wl,Wa as Bl,X as te,Xg as M,Yc as iu,_ as Zr,a as jd,ab as Hl,ad as su,bb as Vl,cb as Yl,cg as gt,ch as ku,db as Xl,dg as pi,dh as bu,eb as Jl,fa as Rl,fb as di,fd as Mo,fg as fi,ga as on,gb as li,gh as nt,ha as Ro,hf as uu,ia as ei,if as mu,jf as mi,jh as Su,kh as Te,l as qd,lg as wu,m as Gd,mh as Au,n as Kd,nb as Ql,nh as xu,o as zd,oa as Tl,of as pu,oh as Cu,p as Wd,q as Bd,qb as zn,r as We,rb as Wn,s as Hd,se as du,tf as fu,vc as tu,wc as nu,xa as ii,y as Vd,ya as Kn,z as Yd}from"./chunk-NRQCBUYD.js";import{A as pl,B as fl,C as _l,D as hl,E as gl,F as yl,b as ko,c as jn,d as ve,g as F,h as et,i as Yr,j as rn,k as qn,l as Gn,o as I,p as _t,q as tt,r as sn,s as ll,t as ul,u as Me,v as Xr,x as ml,y as bo,z as So}from"./chunk-GSLOAEY2.js";import{g as Xp}from"./chunk-WSEIEDEK.js";import{$ as $m,$a as Cp,Aa as np,Ba as rp,C as zo,Ca as ip,D as Wo,Da as sp,Ea as op,F as vt,Fa as ap,G as pm,Ga as cp,H as fm,Ha as dp,I as _m,Ia as lp,J as hm,Ja as up,K as Ei,L as gm,M as ym,N as wm,Na as mp,O as vm,Oa as pp,P as km,Pa as fp,Q as bm,Qa as _p,R as Sm,Ra as hp,S as Am,Sa as gp,T as xm,Ta as yp,U as Cm,Ua as wp,V as Em,Va as vp,W as Rm,Wa as kp,X as Tm,Xa as bp,Y as Im,Ya as Sp,Z as Om,Za as Ap,_ as Nm,_a as xp,aa as Lm,ab as Ep,ba as Mm,bb as Rp,c as am,ca as Fm,cb as Tp,d as cm,da as Dm,db as Vo,e as dm,ea as Pm,eb as Ip,fb as Op,ga as Um,gb as Yo,ha as Bo,hb as Np,ia as jm,ib as $p,ja as qm,jb as Lp,ka as Gm,kb as Mp,la as Km,lb as Fp,ma as Yn,mb as kt,na as zm,nb as Dp,oa as Wm,ob as Pp,p as Go,pa as Bm,pb as Up,q as lm,qa as Hm,qb as jp,ra as Vm,sa as Ym,sb as qp,t as um,ta as Xm,u as Ko,ua as Jm,v as Ut,va as Qm,vb as Xn,wa as Zm,x as mm,xa as ep,ya as Ho,za as tp}from"./chunk-A5ZEMOVR.js";import{$ as Oo,A as Ot,B as xo,C as wl,D as Qr,E as vl,F as Co,I as kl,K as xl,Q as O,S as Eo,T as Cl,U as El,W as se,_ as Ll,a as Z,aa as Ml,b as Un,ba as No,ca as Fl,da as ri,fa as Dl,ga as Pl,ha as Ul,i as ze,k as P,l as Ur,m as Tt,v as Jr,x as L}from"./chunk-I4SPJQQI.js";import{E as dl,I as Il,P as To,T as Ol,W as Nl,X as $l,Z as Io,_ as ni,ba as q,ca as Fe,d as yo,da as $t,fa as ht,h as wo,i as Br,j as Hr,k as Vr,l as nl,n as rl,o as il,p as sl,q as ol,s as al,t as cl,u as vo}from"./chunk-TE6FBDHP.js";import{A as p,C as f,D as nn,E as me,F as el,G as B,H as ee,L as Le,N as tl,a as Ld,m as Md,p as Fd,s as Dd,u as Pd,w as Ud,x as Pr,y as Rt}from"./chunk-K672XXGQ.js";var Hb=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file, or from stdin when set to -.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),Vb=new Set(["--add","--body","--comment","--dep","--dep-remove","--description","--doc","--event","--field","--file","--learning","--note","--remove","--reminder","--test","--type-option"]),Yb=new Set(["append","comments","create","docs","files","learnings","notes","test","update","update-many"]),Xb=new Set(["close-many:--ids","comments:--file","create:--body-file","history-compact:--ids","learnings:--file","notes:--file","update:--body-file","update-many:--ids"]),Jb=new Set(["close-many:--ids","history-compact:--ids","update-many:--ids"]),Qb=["--allow-","--check-","--dry-run","--explain","--fail-","--fix-","--full","--has-","--include-","--json","--no-","--prune-","--quiet","--refresh-","--require-","--runtime-only","--schema-only","--skip-","--stream","--strict-","--summary","--today","--verbose"],Zb=new Set(["--activate","--active-only","--adopt","--adopt-all","--all","--all-actionable","--all-affected-ids","--all-day","--all-streams","--acknowledge-linked-tests","--append-stable","--auto-fix","--auto-pm-context","--availability-only","--background","--brief","--by-assignee","--by-priority","--by-tag","--catalog","--claim","--clear","--clear-comments","--clear-criteria","--clear-deps","--clear-docs","--clear-events","--clear-files","--clear-learnings","--clear-notes","--clear-reminders","--clear-tests","--clear-type-options","--cli-only","--closed","--compact","--completion","--count","--counts","--deactivate","--declarative","--defaults","--describe","--diff","--doctor","--empty-body","--explore","--field-utilization","--filter-empty-body","--flags-only","--follow","--force","--global","--highlight","--hybrid","--id-only","--if-available","--ignore-global","--include_unparented","--infer","--init","--install","--isolated","--lean","--list","--local","--manage","--markdown","--metadata-coverage","--next","--normalize-provenance","--only","--only-last","--output-row-contract","--override-linked-pm-context","--override-linked-workspace-context","--packages-only","--past","--phrase-exact","--profile","--progress","--project","--promote-to-item-dep","--provenance","--provenance-summary","--raw","--ready-only","--ready_only","--rebuild","--recent","--reload","--repair","--replace-deps","--replace-docs","--replace-files","--replace-tests","--required","--required-on-create","--run","--runtime-probe","--save-baseline","--scaffold","--semantic","--shared-host-safe","--storage","--takeover-stale","--title-exact","--token-accounting","--trace","--tree","--unbounded","--uninstall","--validate-paths","--verify","--watch","--with-packages"]),eS=new Set(["--only-index"]),tS=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),nS=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),rS=new Set(["--regression"]);function iS(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:Xb.has(`${e}:${t}`)?["argv","file","stdin"]:t.endsWith("-file")?["argv","file"]:Vb.has(t)&&Yb.has(e)?["argv","stdin"]:["argv"]}function sS(e,t){let n=tS.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,r=t.value_type==="boolean"||t.flag==="--stdin"||t.flag==="--stdin-json"||t.flag.startsWith("--filter-")&&(t.flag.endsWith("-missing")||t.flag.startsWith("--filter-has-")||t.flag.startsWith("--filter-no-"))||Qb.some(i=>t.flag.startsWith(i));return n||eS.has(t.flag)||!Zb.has(t.flag)&&!r}function oS(e,t){return t.value_arity!==void 0?t.value_arity:sS(e,t)?rS.has(t.flag)||nS.has(`${e}:${t.flag}`)?"optional":"required":"none"}function aS(e,t){let n=Ur(e),r=oS(n,t),i=r!=="none",s=iS(n,t.flag),o=t.description??Hb[t.flag]??`${i?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:o,takes_value:i,value_required:r==="required",...i?{value_name:t.value_name??"value"}:{},value_type:i?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:s,...s.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{},...Jb.has(`${n}:${t.flag}`)?{file_token_prefix:"@"}:{}}}function f_(e,t){return t.map(n=>aS(e,n))}function MF(e,t,n){let r=e.trim().toLowerCase(),i=[],s=new Map,o=0;for(let c of n)if(c.command.trim().toLowerCase()===r){if(o+=1,s.has(c.flag)){i.push({code:"duplicate_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} was observed more than once.`});continue}s.set(c.flag,c)}let a=new Set(t.map(({flag:c})=>c));for(let c of t){let d=s.get(c.flag);if(!d){i.push({code:"missing_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} has no executable option observation.`});continue}for(let[l,u]of[["takes_value","takes_value_mismatch"],["value_required","value_required_mismatch"],["repeatable","repeatable_mismatch"]])c[l]!==d[l]&&i.push({code:u,command:r,flag:c.flag,detail:`${r} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of s.values())a.has(c.flag)||i.push({code:"undeclared_observation",command:r,flag:c.flag,detail:`${r} ${c.flag} is executable but absent from invocation contracts.`});return i.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:i.length===0,declared_count:t.length,observed_count:o,findings:i}}import{readFile as cS}from"node:fs/promises";function tD(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Ve(e,t)}function v_(e){return Object.prototype.toString.call(e)==="[object Object]"}function dS(e,t,n,r){let i=O();if(!v_(e))return{...r({created_at:i,author:n,text:t}),text:t,edited_at:i};let s=o=>typeof o=="string"&&o!=="";return{...e,...s(e.created_at)?{}:{created_at:i},...s(e.author)?{}:{author:n},text:t,edited_at:i}}function __(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new f(`Structured context events are append-only and cannot be ${t}.`,p.USAGE,{code:"structured_event_immutable"})}function lS(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function jt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function nD(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let s=_e(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function uS(e){return typeof e=="object"&&e!==null&&"code"in e}function h_(e,t){if(!It(e))throw new f(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,p.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function mS(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new f(`Specify ${t} text using only one input source: --add, --stdin, or --file`,p.USAGE);let r=Zd(),i=It(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",i)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return h_(e,"--stdin"),{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new f("--file path cannot be empty",p.USAGE);if(s==="-")return h_(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await cS(s,"utf8"),emptyFlag:"--file"}}catch(o){if(uS(o)&&el(o))throw new f(`--file path not found: ${s}. Use --file - to read stdin.`,p.USAGE);let a=o instanceof Error?o.message:String(o);throw new f(`Failed to read --file path "${s}": ${a}. Use --file - to read stdin.`,p.USAGE)}}async function rD(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new f("Specify only one of --edit or --delete",p.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new f("--delete cannot be combined with replacement text",p.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new f("--delete must be a positive integer",p.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new f("--edit must be a positive integer",p.USAGE);let n=await mS(e,t);if(e.edit!==void 0){if(!n)throw new f("--edit requires replacement text from --add, --stdin, or --file",p.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function ar(e,t){throw e instanceof f&&e.exitCode===p.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new f(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function k_(e){return e==="comments"?"--stdin":"--add -"}var iD="annotation_flag_like_value";function pS(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function fS(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function _S(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=fS(t),i=k_(e.collectionKey),s=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 o=r.split(/[ =]/,1)[0],a=o==="--file"?"that file":"stdin",c=e.conflictingOperand===void 0?"":` "${e.conflictingOperand}" was read as positional text, which ${o} cannot be combined with: drop it, or pass it as the text without ${o}.`;return new f(`${e.textFlag} value "${t}" looks like an option, not annotation text: ${e.textFlag} took ${o} as its value. Drop ${e.textFlag} and pass ${r} on its own.${c}`,p.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}`],...s})}return new f(`${e.textFlag} value "${t}" looks like an option, not annotation text. Use ${i} to read stdin, or use text=${t} for literal dash-leading text.`,p.USAGE,{code:"annotation_flag_like_value",required:`Use ${i} for stdin input, pass plain text, or use text=${t} when the text really starts with "-".`,examples:[`${e.commandPrefix} ${i}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...s})}function hS(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!pS(e)))throw _S({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function gS(e,t,n,r,i){if(n.input.mode!=="edit")return;let s=nu(t);if(s===void 0)return;let o=n.collectionKey.replace(/s$/,""),a=n.input.index,c=Ye(r)[0]==="--pm-path"?["--pm-path",i]:[];throw new f(`Replacement text for ${o} ${a} on ${e} ends with the read-output compaction marker, so it was copied from a compacted read that left out ${s} characters. Nothing was written.`,p.USAGE,{code:"annotation_text_compacted",item_id:e,details:{collection:n.collectionKey,entry_index:a,omitted_characters:s},required:`Read the whole ${o} 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 yS(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new f(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,p.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(wS(e,t),e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new f(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,p.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> ${k_(e.collectionKey)}`]})}function wS(e,t){if(t.expectAt!==void 0){if(e.input.mode!=="edit"&&e.input.mode!=="delete")throw new f(`--expect-at guards an --edit or --delete of one ${e.collectionKey.replace(/s$/,"")}`,p.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 f("--expect-at must be the non-empty created_at timestamp of the entry you read",p.USAGE,{code:"annotation_expectation_invalid",required:"Pass the created_at value of the row you read at that index, as a string."})}}function g_(e,t,n,r,i){if(i===void 0)return;let s=t[n]?.created_at,o=typeof s=="string"?s:null;if(o===i)return;let a=t.flatMap((m,_)=>m?.created_at===i?[_+1]:[]),c=r.collectionKey.replace(/s$/,""),d=r.input.mode==="delete"?"--delete":"--edit",l=n+1,u=a.length===1?` The ${c} created at ${i} is at index ${a[0]}.`:a.length>1?` ${a.length} ${r.collectionKey} were created at ${i}: indexes ${a.join(", ")}.`:` No ${c} on ${e} was created at ${i}.`;throw new f(`${c.charAt(0).toUpperCase()}${c.slice(1)} ${l} on ${e} was created at ${o||"an unrecorded time (malformed entry)"}, not ${i}; refusing ${d} of an entry the caller did not read. Nothing was written.${u}`,p.CONFLICT,{code:"annotation_entry_mismatch",item_id:e,details:{collection:r.collectionKey,entry_index:l,expected_created_at:i,actual_created_at:o,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 ${i}${d==="--edit"?' --add "<text>"':""}`]})}function vS(e,t,n,r,i,s){let o=jt(e.metadata,t),a=i?o.findIndex(c=>v_(c)&&c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],written:o,position:a}:(o.push(s({created_at:O(),author:n,text:r})),e.metadata[t]=o,{changedFields:[t],written:o,position:o.length-1})}function y_(e,t,n){return Gl.has(e)?t.map((i,s)=>s).sort((i,s)=>Kl(t[i],t[s])||i-s).indexOf(n)+1:n+1}async function sD(e,t,n,r){yS(r,t);let i=I(process.cwd(),n.path);await z(i);let s=await R(i),o=F(s,M()),a=Hn(t.limit);if(r.input.mode==="list"){let h=await V(i,e,s.id_prefix,s.item_format,o.type_to_folder);if(!h)throw new f(`Item ${e} not found`,p.NOT_FOUND);let g=await le(h,{schema:s.schema}),y=jt(g.document.metadata,r.collectionKey);return Ki(h.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=H(t.author,s.author_default);if(r.input.mode==="delete"){let h=r.deleteOp??r.op,g;try{g=await Ie({pmRoot:i,settings:s,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let v=jt(w.metadata,r.collectionKey),k=w_(r.input.index,v.length,r.collectionKey);return g_(e,v,k,r,t.expectAt),__(v[k],"deleted"),v.splice(k,1),w.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(w){ar(w,r.conflictGuidance)}let y=jt(g.item,r.collectionKey);return Ki(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??"";hS(d,r);let l=r.parseText(r.input.value??"");if(!l.trim())throw new f(`${r.input.emptyFlag??"--add"} text cannot be empty`,p.USAGE);if(gS(e,l,r,n,i),r.input.mode==="edit"){let h=r.editOp??r.op,g,y=0;try{g=await Ie({pmRoot:i,settings:s,id:e,op:h,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(k){let b=jt(k.metadata,r.collectionKey),A=w_(r.input.index,b.length,r.collectionKey);g_(e,b,A,r,t.expectAt);let C=b[A];return __(C,"edited"),b[A]=dS(C,l,c,r.createEntry),y=y_(r.collectionKey,b,A),k.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(k){ar(k,r.conflictGuidance)}let w=jt(g.item,r.collectionKey),v=y;return Ki(g.item.id,r.collectionKey,w,a,t.includeMeta===!0,{action:"edit",entryIndex:v,entry:w[v-1]},t.fullHistory===!0)}let u,m=0;try{u=await Ie({pmRoot:i,settings:s,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(h){let g=vS(h,r.collectionKey,c,l,t.ifAbsent===!0,r.createEntry);return m=y_(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(h){ar(h,r.conflictGuidance)}let _=jt(u.item,r.collectionKey);return Ki(u.item.id,r.collectionKey,_,a,t.includeMeta===!0,{action:"add",entryIndex:m,entry:_[m-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function w_(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),i=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,s=t===1?`1 ${r}`:`${t} ${n}`;throw new f(`${i} index ${e??"(missing)"} out of range (item has ${s})`,p.USAGE)}return e-1}function kS(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 b_(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function bS(e,t){let n=e.length-t.length;return t.map((r,i)=>b_(r,n+i+1))}function Ki(e,t,n,r,i,s,o=!1){let a=s===void 0||o?bS(n,lS(n,s!==void 0&&o?void 0:r)):s.entry===void 0?[]:[b_(s.entry,s.entryIndex)],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...s?.changedCount===void 0?{}:{changed:s.changedCount===1},...[i,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...kS(t,s,c)}}import{isDeepStrictEqual as R_}from"node:util";var SS=new Set(["__proto__","prototype","constructor"]),cr=Symbol("looseOptionOccurrences");function it(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,r)=>r.toUpperCase())}function AS(e,t,n){let r=e[t];if(r===void 0){e[t]=n;return}if(Array.isArray(r)){r.push(n),e[t]=r;return}e[t]=[r,n]}function ga(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(1,o).trim(),value:n.slice(o+1),attached:!0};let a=n.slice(1).trim(),c=e[t+1];return typeof c=="string"&&!c.startsWith("-")?{consumed:2,key:a,value:c}:{consumed:1,key:a,value:!0}}let r=n.indexOf("=");if(r>=0)return{consumed:1,key:n.slice(2,r).trim(),value:n.slice(r+1),attached:!0};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let i=n.slice(2).trim(),s=e[t+1];return typeof s=="string"&&!s.startsWith("-")?{consumed:2,key:i,value:s}:{consumed:1,key:i,value:!0}}function Wi(e){return SS.has(e)}function Hi(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return Rl(t)}function wn(e){let t=[],n=Nt(e.long)??"",r=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let i=it(n.slice(2));i.length>0&&!Wi(i)&&t.push(i)}if(r.startsWith("-")&&!r.startsWith("--")){let i=it(r.slice(1));i.length>0&&!Wi(i)&&t.push(i)}return[...new Set(t)]}function uD(e){let t=new Set;for(let n of e)for(let r of wn(n))t.add(r);return t}function qt(e){let t=Nt(e.long)??"";if(t.startsWith("--")){let n=it(t.slice(2));if(n.length>0&&!Wi(n))return n}return wn(e)[0]??null}function vn(e){let t=Nt(e.long)??"";if(t.startsWith("--")&&t.length>2)return t;let n=typeof e.short=="string"?e.short.trim():"";return n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function T_(e,t){return[...(t.definitions??e).map(r=>vn(r)).filter(r=>r!==null),...t.inheritedFlags??[]]}function mD(e,t,n,r={}){if(t.length===0)return;let i=new Set,s=new Map,o=[],a=T_(t,r);for(let c of t){let d=wn(c),l=vn(c);for(let u of d)i.add(u),c.enabled===!1&&s.set(u,l);c.required===!0&&c.enabled!==!1&&d.length>0&&o.push({keys:d,label:l,definition:c})}for(let c of Object.keys(e)){i.has(c)||I_(`--${c}`,`--${c}`,n,a);let d=s.get(c);d&&O_(d,n)}for(let c of o){let d=l=>Object.hasOwn(e,l)&&(c.definition.list!==!0||wa(c.definition,e[l]));c.keys.some(d)||N_(c.definition,c.keys[0],c.label,n)}}function I_(e,t,n,r){let i=r.length>0?` Expected one of: ${[...new Set(r)].join(", ")}.`:"";throw new f(`Unknown option '${e}' for extension command '${n}'.${i}`,p.USAGE,{code:"unknown_option",flag:t,required:`Use a flag the command accepts; run pm contracts --command ${n} --flags-only --json to list them.`})}function O_(e,t){throw new f(`Option '${e}' is disabled for extension command '${t}'.`,p.USAGE,{code:"extension_option_disabled",flag:e,required:`Remove ${e}; the command declares it with enabled: false.`,why:"A disabled declaration keeps the flag in the contract while refusing every value for it.",examples:[`pm ${t} --help`],nextSteps:[`Run pm contracts --command ${t} --flags-only --json to list the flags this command accepts.`]})}function N_(e,t,n,r){let i=on(e),s=i.value_arity==="none"?n:i.value_arity==="optional"?`${n} [${i.value_name}]`:`${n} <${i.value_name}>`;throw new f(`Missing required option '${n}' for extension command '${r}'.`,p.USAGE,{code:"missing_required_option",flag:n,field:t,required:`Pass ${s}.`,why:"The command declares this flag as required, so pm refuses the invocation before the extension handler runs.",examples:[`pm ${r} ${s}`],nextSteps:[`Run pm contracts --command ${r} --flags-only --json to read each flag's sdk_option key.`],recovery:{missing:[n]}})}function xS(e){return typeof e=="string"||e==null?e:String(e)}function CS(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);return Number.isFinite(t)?t:e}return e}function $_(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return e}var ES={string:xS,number:CS,boolean:$_};function Gt(e,t){return Array.isArray(e)?e.map(n=>Gt(n,t)):ES[t](e)}function ya(e,t,n){let r=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(i=>i!=null&&i!==""):Ro(e);return t?r.map(i=>Gt(i,t)):r}function wa(e,t){return ya(t,null,e.repeatable===!0).length>0}function RS(e,t,n,r){return n?ya(e,t,r):t?Gt(e,t):e}function TS(e,t,n){let r=M_(e,t);return r.length===0?n:r.map(i=>i.value)}function L_(e){return on(e).value_arity==="none"}function va(e,t,n,r,i){let s=vn(e),o=i?` for extension command '${i}'`:"",a=n===!0?"no value":JSON.stringify(n);throw new f(`Option '${s}'${o} expects ${r}; received ${a}.`,p.USAGE,{code:"extension_flag_value_invalid",flag:s,required:`Pass ${s} ${t==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${t} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${t} value for ${s}.`,`Run pm ${i??"<command>"} --help to review the declared flag contract.`]})}function ka(e,t){return e.value_validation==="strict"&&t!=="string"}function M_(e,t){let n=e[cr];if(!n)return[];let r=new Set(t);return n.filter(i=>r.has(i.key))}function IS(e,t,n,r){if(L_(e))for(let i of M_(n,t)){if(i.attached!==!0)continue;let s=e.list===!0&&e.repeatable!==!0?Ro(i.value):[i.value];for(let o of s){let a=ei(Gt(o,"boolean"),"boolean");a!==null&&va(e,"boolean",o,a.expected,r)}}}function OS(e,t,n,r,i){let s=Array.isArray(n)?n.flat(1/0):[n],o=r?s:s.flatMap(a=>typeof a=="string"?a.split(","):[a]);for(let a of o)if(typeof a=="string"&&a.trim().length===0){let c=ei(a,t);va(e,t,a,c.expected,i)}}function ba(e,t,n,r){if(!ka(e,n))return t;let i=n==="boolean"&&L_(e),s=o=>{let a=ei(o,n);return a===null?o:i&&typeof o=="string"?!0:va(e,n,o,a.expected,r)};return Array.isArray(t)?t.map(s):s(t)}function NS(e,t,n,r){for(let i of n)if(!(i===t||!Object.hasOwn(e,i))){if(Object.hasOwn(e,t)){if(r){let s=e[t],o=e[i];e[t]=[...Array.isArray(s)?s:[s],...Array.isArray(o)?o:[o]].filter(a=>a!=null)}delete e[i];continue}e[t]=e[i],delete e[i]}}function F_(e,t,n=e,r){if(t.length===0)return e;let i=Object.create(null);for(let[o,a]of Object.entries(e))i[o]=a;let s=new Set(t.map(o=>qt(o)).filter(o=>o!==null));for(let o of t){let a=qt(o);if(a){let c=wn(o).filter(d=>d===a||!s.has(d));$S(i,o,a,c,n,r)}}return i}function $S(e,t,n,r,i,s){let o=t.list===!0,a=Hi(t);a&&!o&&LS(e,t,n,r,a,s),NS(e,n,r,o);let c=t.repeatable===!0;if(!Object.hasOwn(e,n)){t.default!==void 0&&(e[n]=RS(t.default,a,o,c));return}if(a==="boolean"&&ka(t,a)&&IS(t,r,i,s),o){e[n]=MS(t,r,i,e[n],a,c,s);return}a&&(e[n]=ba(t,Gt(e[n],a),a,s))}function LS(e,t,n,r,i,s){for(let o of r)o!==n&&Object.hasOwn(e,o)&&ba(t,Gt(e[o],i),i,s)}function MS(e,t,n,r,i,s,o){let a=TS(n,t,r);i&&ka(e,i)&&OS(e,i,a,s,o);let c=ya(a,i,s);return i?ba(e,c,i,o):c}function pD(e){let t=Object.create(null),n=[];Object.defineProperty(t,cr,{value:n});let r=0;for(;r<e.length;){let i=ga(e,r);if(!i){r+=1;continue}let s=it(i.key);if(s.length===0||Wi(s)){r+=i.consumed;continue}AS(t,s,i.value),n.push({...i,key:s}),r+=i.consumed}return t}function fD(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let r=ga(e,n);if(r){n+=Math.max(1,r.consumed);continue}t.push(e[n]),n+=1}return t}function _D(e,t){if(t.length===0)return[...e];let n=new Set,r=new Set;for(let o of t){let a=Hi(o);for(let c of wn(o))n.add(c),a==="boolean"&&r.add(c)}if(n.size===0)return[...e];let i=[],s=0;for(;s<e.length;){if(e[s]==="--"){i.push(...e.slice(s+1));break}let o=ga(e,s);if(o){let a=it(o.key);if(n.has(a)){let c=e[s],d=r.has(a)&&!c.includes("=")?1:o.consumed;s+=d;continue}}i.push(e[s]),s+=1}return i}function Sa(e){return qt(e)}function S_(e){return e.trim().toLowerCase().split(/\s+/u).filter(t=>t.length>0).join(" ")}function hD(e,t){let n=S_(t);if(n.length===0)return[];let r=P(n);return e.flags.filter(i=>P(S_(i.target_command))===r).flatMap(i=>[...i.flags])}function D_(e,t,n,r){let i=vn(e),[s,o]=n;throw new f(`Options '${s}' and '${o}' both set ${i} for extension command '${r}' with different values.`,p.USAGE,{code:"extension_option_spelling_conflict",required:`Pass ${i} once, under the handler key '${t}'.`,why:`'${s}' and '${o}' are spellings of the same declared flag, and pm refuses to choose between two different values.`,nextSteps:[`Remove '${s}' or '${o}' and pass one value as '${t}'.`,`Run pm contracts --command ${r} --flags-only --json to read each flag's sdk_option key.`]})}function gD(e,t,n,r={}){if(t.length===0)return e;let i=t.map(l=>l.repeatable===!0&&l.list!==!0?{...l,list:!0}:l),s=j_(i),o=jS(e,s,n),a=new Set([...s.long.values()].map(({handlerKey:l})=>l)),c=Object.create(null),d=Object.create(null);for(let[l,u]of Object.entries(o))a.has(l)?c[l]=u:u===void 0||r.undeclaredKeys==="pass"||DS(l)?d[l]=u:I_(l,PS(l),n,T_(i,{}));return U_(c,i,n),Object.assign(d,F_(c,i,P_(c,s),n))}function P_(e,t){let n=new Set([...t.long.values()].map(({handlerKey:s})=>s)),r=Object.entries(e).filter(([s])=>n.has(s)).flatMap(([s,o])=>(Array.isArray(o)?o.flat(1/0):[o]).map(a=>({consumed:1,key:s,value:a,attached:!0}))),i=Object.create(null);return Object.defineProperty(i,cr,{value:r}),i}function U_(e,t,n){for(let r of t){let i=qt(r);if(i===null)continue;let s=vn(r),o=e[i],a=Object.hasOwn(e,i);r.enabled===!1&&a&&O_(s,n);let c=a&&(r.list!==!0||wa(r,o));r.required===!0&&r.enabled!==!1&&!c&&N_(r,i,s,n),r.list!==!0&&Array.isArray(o)&&FS(s,n)}}function FS(e,t){throw new f(`Option '${e}' for extension command '${t}' takes one value; received an array.`,p.USAGE,{code:"extension_flag_value_invalid",flag:e,required:`Pass one value for ${e}, or ask the package to declare it with list: true or repeatable: true.`,why:"The flag is not declared list or repeatable, so pm refuses an array before the extension handler runs instead of handing it a value of the wrong shape.",nextSteps:[`Run pm contracts --command ${t} --flags-only --json to read each flag's value contract.`]})}var A_=new Set([...[...xl].filter(e=>e.startsWith("--")).flatMap(e=>{let t=e.replace(/^--/u,"");return[t,...t.startsWith("no-")?[t.slice(3)]:[]].flatMap(r=>[it(r),r.replaceAll("-","_")])}),"force","subcommand","inputResponses","requestState"]);function DS(e){return A_.has(e)||A_.has(it(e.replace(/^-{1,2}/u,"")))}function PS(e){return`--${e.replace(/^-+/u,"").replace(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`}function j_(e){let t={long:new Map,short:new Map},n=(r,i,s)=>{i.length>0&&!r.has(i)&&r.set(i,s)};for(let r of e){let i=qt(r);if(i===null)continue;let s={handlerKey:i,definition:r};n(t.long,i,s);let o=typeof r.short=="string"?r.short.trim():"";o.startsWith("-")&&!o.startsWith("--")&&n(t.short,o.slice(1),s)}return t}function Bi(e,t){return e.long.get(t)??e.short.get(t.replace(/^-(?!-)/u,""))??e.long.get(it(t.replace(/^-{1,2}/u,"")))}function q_(e,t,n,r){let i=/^(?:--)?no-(.+)$/u.exec(t)?.[1];if(i===void 0||Bi(e,t)!==void 0)return{spelling:t,value:n};let s=Bi(e,i);return s===void 0||Hi(s.definition)!=="boolean"?{spelling:t,value:n}:(s.definition.list===!0||s.definition.repeatable===!0)&&Array.isArray(n)?{spelling:i,value:n.flat(1/0).map(o=>x_(t,s.definition,o,r))}:s.definition.list===!0&&n!==void 0?{spelling:i,value:x_(t,s.definition,n,r)}:{spelling:i,value:n===void 0?n:zi(t,s.definition,n,r)}}function yD(e,t,n){let r=j_(e);try{let i=q_(r,t,n,"");if(i.spelling===t)return;let s=Bi(r,i.spelling);return(s.definition.list===!0||s.definition.repeatable===!0)&&!wa(s.definition,i.value)?void 0:{key:s.handlerKey,value:i.value}}catch{return}}function x_(e,t,n,r){let i=s=>s.trim().length===0?s:String(zi(e,t,s.trim(),r));return n==null?n:typeof n!="string"?zi(e,t,n,r):n.trim().length===0?n:t.repeatable===!0||!n.includes(",")?zi(e,t,n,r):n.split(",").map(i).join(",")}function zi(e,t,n,r){let i=$_(n);return typeof i=="boolean"?!i:US(e,t,n,r)}function US(e,t,n,r){let i=vn(t);throw new f(`Option '${e}' for extension command '${r}' negates ${i} and expects true, false, 1, or 0; received ${JSON.stringify(n)}.`,p.USAGE,{code:"extension_flag_value_invalid",flag:i,required:`Pass ${i} as true or false, or '${e}' as true.`,why:`'${e}' is the negated spelling of the boolean ${i}, so only a boolean value can be inverted before the extension handler runs.`,nextSteps:[`Run pm contracts --command ${r} --flags-only --json to read each flag's value contract.`]})}function jS(e,t,n){let r=Object.create(null),i=new Map;for(let[s,o]of Object.entries(e)){let{spelling:a,value:c}=q_(t,s,o,n),d=Bi(t,a);if(d===void 0)r[a]=c;else if(c!==void 0){let l=i.get(d.handlerKey);l===void 0?(i.set(d.handlerKey,a),r[d.handlerKey]=c):R_(C_(d.definition,d.handlerKey,r[d.handlerKey],t,n),C_(d.definition,d.handlerKey,c,t,n))||D_(d.definition,d.handlerKey,[l,a],n)}}return r}function C_(e,t,n,r,i){let s={[t]:n};return U_(s,[e],i),F_(s,[e],P_(s,r),i)[t]}function G_(e){let t=new Map;for(let n of e){let r=qt(n);if(r===null)continue;let i={definition:n,handlerKey:r,kind:Hi(n),arity:on(n).value_arity,scalar:n.list!==!0},s=[Nt(n.long),typeof n.short=="string"?n.short.trim():""];for(let o of s.filter(a=>a?.startsWith("-")===!0))t.has(o)||t.set(o,i)}return t}function K_(e,t,n,r=YS){let i=e.optionOf(n),s=t.get(n),o=s!==void 0&&r(s)?s:void 0;if(i!==void 0){let a={arity:i.arity,...i.variadic===!0?{variadic:!0}:{}};if(o?.handlerKey===i.key)return{...a,declared:o};if(s!==void 0)return a;let c=VS(t,n,i,r);return c===void 0?a:{...a,declared:c,negates:!0}}if(!(!e.includesLooseFlags||s===void 0))return o===void 0?{arity:s.arity,loose:!0}:{arity:s.arity,declared:o,loose:!0}}function Aa(e){return e.length>1&&e.startsWith("-")}var z_=/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/u;function W_(e,t,n){let{tokens:r}=e,i=0,s,o=!1,a=!1;for(;i<r.length||s!==void 0;){let c=s??r[i++];if(c==="--")return;if(a&&s===void 0&&qS(e,c))continue;let d=Aa(c)?KS(e,c,r[i],t,n):{consumedByCommander:!1,consumed:0};if(i+=d.consumed,s=d.group,a=d.variadic===!0,!d.consumedByCommander){if(GS(e.stop,c,o))return;o=!0}}}function qS(e,t){return!Aa(t)||e.negativeNumbersAreValues&&z_.test(t)}function GS(e,t,n){return e!==void 0&&(e.atFirstUnrecognized||!n&&e.atSubcommand(t))}function KS(e,t,n,r,i){let s=zS(t,n,r);if(s!==void 0)return i(s.spelling,s.entry,s.value,"loose"),{consumedByCommander:!1,consumed:s.consumed};let o=r(t);if(o!==void 0){let a=o.arity==="required"||o.arity==="optional"&&n!==void 0&&(!Aa(n)||e.negativeNumbersAreValues&&z_.test(n));return i(t,o,o.negates===!0?!1:a?n:!0,"commander"),{consumedByCommander:!0,consumed:a?1:0,variadic:o.variadic===!0}}return t[1]!=="-"?{consumed:0,...WS(t,r,i)}:{consumedByCommander:BS(t,r,i,e.includesLooseFlags?i:()=>{}),consumed:0}}function zS(e,t,n){let r=e.indexOf("="),i=r>1?e.slice(0,r):e,s=n(i);if(s?.loose===!0)return r>1?{spelling:i,entry:s,value:e.slice(r+1),consumed:0}:t!==void 0&&!t.startsWith("-")?{spelling:i,entry:s,value:t,consumed:1}:{spelling:i,entry:s,value:!0,consumed:0};let o=r<0&&e.startsWith("--no-")?n(`--${e.slice(5)}`):void 0;return o?.loose===!0&&o.declared?.kind==="boolean"?{spelling:e,entry:o,value:!1,consumed:0}:void 0}function WS(e,t,n){let r=e.slice(0,2),i=e.length>2?t(r):void 0;return i===void 0||i.loose===!0?{consumedByCommander:!1}:i.arity!=="none"?(n(r,i,e.slice(2),"commander"),{consumedByCommander:!0}):(n(r,i,!0,"commander"),{consumedByCommander:!0,group:`-${e.slice(2)}`})}function BS(e,t,n,r){let i=e.indexOf("=");if(i>2){let o=e.slice(0,i),a=t(o);return a!==void 0&&a.arity!=="none"?(n(o,a,e.slice(i+1),"commander"),!0):(a?.declared?.kind==="boolean"&&r(o,a,e.slice(i+1),"loose"),!1)}let s=e.startsWith("--no-")?t(`--${e.slice(5)}`):void 0;return s?.declared?.kind==="boolean"&&r(e,s,!1,"loose"),!1}function wD(e,t,n){let r=G_(t),i=new Map;for(let s of e)W_(s,o=>K_(s,r,o),(o,a,c)=>{a.declared!==void 0&&HS(i,a.declared,o,c,n)})}function HS(e,t,n,r,i){let{definition:s,handlerKey:o,kind:a}=t,c=a?Gt(r,a):r,d=e.get(o)??new Map,l=[...d].find(([u,m])=>u!==n&&!R_(m,c));l!==void 0&&D_(s,o,[l[0],n],i),d.set(n,c),e.set(o,d)}function VS(e,t,n,r){let i=t.startsWith("--no-")?e.get(`--${t.slice(5)}`):void 0;return i!==void 0&&r(i)&&i.kind==="boolean"&&i.handlerKey===n.key?i:void 0}function YS(e){return e.scalar}function E_(e){return!e.scalar&&e.kind==="boolean"&&e.arity==="none"}function vD(e,t,n){let r=G_(n),i=[...new Set(r.values())].filter(E_);if(i.length===0)return e;let s=new Set(n.map(m=>qt(m)).filter(m=>m!==null)),o=m=>wn(m.definition).filter(_=>_===m.handlerKey||!s.has(_)),a=new Map([...i].reverse().flatMap(m=>o(m).map(_=>[_,m]))),c=new Map;for(let m of t)W_(m,_=>K_(m,r,_,E_)??XS(m,a,_),(_,h,g,y)=>{if(h.declared===void 0)return;let w=c.get(h.declared)??[];w.push(y==="commander"?{value:g}:null),c.set(h.declared,w)});let d=[...c].filter(([,m])=>m.some(_=>_!==null));if(d.length===0)return e;let l=e[cr]??[];for(let[m,_]of d){let h=new Set(o(m)),g=l.filter(({key:k})=>h.has(k));if(g.length===0)continue;let y=k=>({consumed:0,key:m.handlerKey,value:k.value}),w=0,v=_.filter(k=>k===null).length===g.length?_.map(k=>k===null?g[w++]:y(k)):[...g,..._.filter(k=>k!==null).map(y)];l=[...l.filter(({key:k})=>!h.has(k)),...v]}let u=Object.assign(Object.create(null),e);return Object.defineProperty(u,cr,{value:l}),u}function XS(e,t,n){let r=!n.startsWith("--")&&e.optionOf(n.slice(0,2))!==void 0;if(!e.includesLooseFlags||r)return;let i=t.get(it(n.replace(/^-+/u,"")));return i===void 0?void 0:{arity:i.arity,declared:i,loose:!0}}var JS=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate","workspace"]),QS=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),ZS=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),eA=new Set(["extension","install","package","packages","upgrade"]);function tA(e){let t=P(e.trim().toLowerCase());if(t==="ops")return"quality";for(let[n,r]of Object.entries(ZS))if(r.has(t))return n;return eA.has(t)?"extensions":"internal"}var kn=Object.freeze([...We.flatMap(e=>e==="item"?["item","item-reopen"]:[e,...ze.filter(t=>t.alias===e).map(t=>t.canonical)]).map(e=>({command:e,tier:JS.has(P(e))?"core":QS.has(P(e))?"standard":"full",family:tA(e)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]),nA=kn,B_=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),AD=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function xD(e){let t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=B_.max_lines&&n<=B_.max_utf8_bytes}}var H_={core:0,standard:1,full:2,internal:3},V_=new Map(nA.map(({command:e,tier:t})=>[e,t]));function xa(e,t="standard"){return V_.get(e.trim().toLowerCase())??V_.get(P(e.trim().toLowerCase()))??t}function CD(e){return Y_(e,kn)}function Y_(e,t){let n=H_[e];return t.filter(r=>r.tier!=="internal"&&H_[r.tier]<=n).map(r=>r.command)}function ED(e){return X_(e,kn)}function X_(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}var rA=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],iA=new Set([...Tt.filter(e=>e.hidden).map(e=>e.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function RD(e=kn){return rA.map(t=>({family:t,commands:X_(t,e).filter(n=>e.find(r=>r.command===n)?.tier!=="internal"&&!iA.has(n))})).filter(({commands:t})=>t.length>0)}var sA=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function TD(e,t){return oA(e,t,kn)}function oA(e,t,n){if(t==="full")return[...e];let r=new Set(Y_(t,n));return e.filter(i=>{let s=sA[i];return s!==void 0&&r.has(s)})}var ID=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),OD=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function ND(){return aA(kn)}function aA(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:n,tier:r,family:i})=>`| \`${n}\` | ${r} | ${i} |`),""].join(`
|
|
2
|
+
`)}var Ca=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],cA=new Map(Ca.map(e=>[e.exit_code,e.class]));function Vi(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function dA(e){if(!e)return[];let t=new Set,n=new Set;return e.map(r=>{let i=r.state.trim(),s=r.probe_id.trim(),o=Vi(r.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(i)||!/^[a-z][a-z0-9-]*$/.test(s)||o.length===0||t.has(i)||n.has(s))throw new TypeError("Invalid pm refusal state contract");return t.add(i),n.add(s),{state:i,probe_id:s,entrypoints:o,expected_exit_class:r.expected_exit_class}}).sort((r,i)=>r.state.localeCompare(i.state))}function lA(e,t,n,r,i){return![[1,2,3,4,5].includes(e.exit_code),e.meaning.trim().length>0,e.recovery.trim().length>0,t.length>0,n.length>0,/^[a-z][a-z0-9_]*$/.test(r),i.every(s=>/^[a-z][a-z0-9_]*$/.test(s)),cA.get(e.exit_code)===e.class].includes(!1)}function uA(e,t){let n=e,r=new Set;for(;n.canonical_code!==n.code;){if(r.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);r.add(n.code);let i=t.get(n.canonical_code);if(!i)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=i}return n}function mA(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let r=uA(n,t);if(r.exit_code!==n.exit_code||r.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let i=e.filter(s=>s.code!==r.code&&s.canonical_code===r.code).map(s=>s.code).sort();if(n.code===r.code?JSON.stringify(n.aliases)!==JSON.stringify(i):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function Q_(e){let t=new Set,n=e.map(r=>{let i=r.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(i))throw new TypeError(`Invalid pm error code: ${JSON.stringify(r.code)}`);if(t.has(i))throw new TypeError(`Duplicate pm error code: ${i}`);t.add(i);let s=Vi(r.sources),o=Vi(r.emitting_commands),a=(r.canonical_code??i).trim(),c=Vi(r.aliases??[]),d=dA(r.owned_states);if(!lA(r,s,o,a,c))throw new TypeError(`Invalid pm error code contract: ${i}`);if(d.some(l=>l.expected_exit_class!==r.class))throw new TypeError(`Invalid pm refusal state exit class: ${i}`);return Object.freeze({...r,code:i,meaning:r.meaning.trim(),recovery:r.recovery.trim(),sources:s,emitting_commands:o,canonical_code:a,aliases:c,owned_states:d})});return mA(n),Object.freeze(n.sort((r,i)=>r.code.localeCompare(i.code)))}function LD(e,t){let n=J_(e,t);return J_(n.canonical_code??n.code,t)}function J_(e,t){let n=e.trim(),r=t.find(i=>i.code===n);if(!r)throw new TypeError(`Unknown pm error code "${n}"`);return r}var pA="Inspect the structured error guidance, then retry the suggested command when one is present.",fA=new Map(Ca.map(e=>[e.exit_code,e.class]));function Z_(e){return e.map(t=>{let n=`${t.code.replaceAll("_"," ")} condition.`,r={code:t.code,meaning:`${n.charAt(0).toUpperCase()}${n.slice(1)}`,stability:t.stable?"stable":"provisional",exit_code:t.exit_code,class:fA.get(t.exit_code),recovery:pA,sources:t.sources,emitting_commands:t.emitting_commands??["*"],canonical_code:t.canonical_code??t.code,aliases:t.aliases??[]};return t.owned_states&&(r.owned_states=t.owned_states),r})}var eh=[{code:"acceptance_criteria_mutation_conflict",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_remove_unmatched",exit_code:3,sources:["sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"]},{code:"acceptance_criteria_semicolon_forbidden",exit_code:2,stable:!0,sources:["core/item/parse.ts"]},{code:"accepted_rejected_value",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"alias_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"alias_target_missing",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"already_claimed_by",exit_code:4,stable:!0,sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"ambiguous_option_combination",exit_code:2,stable:!0,sources:["sdk/lifecycle/claim.ts","sdk/lifecycle/plan.ts"],emitting_commands:["claim","plan"]},{code:"annotation_alias_conflict",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"annotation_entry_mismatch",exit_code:4,sources:["sdk/annotations.ts"]},{code:"annotation_expectation_invalid",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_expectation_without_target",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_flag_like_value",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_if_absent_without_append",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_message_without_text",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"annotation_text_compacted",exit_code:2,sources:["sdk/annotations.ts"]},{code:"annotation_text_source_conflict",exit_code:2,sources:["sdk/runtime-input.ts"]},{code:"annotation_transposed_subcommand",exit_code:2,sources:["cli/register-annotations.ts"]},{code:"append_empty_body",exit_code:2,stable:!0,sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"]},{code:"assurance_registry_invalid",exit_code:1,sources:["sdk/governance/assurance.ts"]},{code:"bare_comma_entry_ambiguous",exit_code:2,sources:["core/item/parse.ts"]},{code:"blocker_identity_read_failed",exit_code:1,sources:["sdk/query/declared-blockers.ts"]},{code:"body_file_conflicts_with_body",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_missing_path",exit_code:2,stable:!0,sources:["core/io/body-file.ts"]},{code:"body_file_unreadable",exit_code:3,stable:!0,sources:["core/io/body-file.ts"]},{code:"budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"bulk_create_route",exit_code:2,sources:["cli/register-mutation.ts"]},{code:"bulk_ids_input_empty",exit_code:2,sources:["core/io/bulk-ids-input.ts","sdk/history-compact.ts","sdk/history-mcp.ts"],owned_states:[{state:"bulk_ids_stdin_contains_no_nonempty_ids",probe_id:"bulk-ids-stdin-empty",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_missing_path",exit_code:2,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_token_omits_its_path",probe_id:"bulk-ids-file-path-missing",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_unreadable",exit_code:3,sources:["core/io/bulk-ids-input.ts"],owned_states:[{state:"bulk_ids_file_path_cannot_be_read",probe_id:"bulk-ids-file-unreadable",entrypoints:["update-many"],expected_exit_class:"not_found"}]},{code:"bundle_integrity_torn_install",exit_code:1,stable:!0,sources:["cli/bundle-integrity.ts"]},{code:"capability_undeclared",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"capability_unused",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"child_projection_item_bound_exceeded",exit_code:1,stable:!0,sources:["sdk/item-children.ts"]},{code:"close_reason_required",exit_code:2,stable:!0,sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"]},{code:"close_through_update",exit_code:1,stable:!0,sources:["core/telemetry/observability.ts"]},{code:"close_validation_deferred_fields",exit_code:2,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"close_validation_missing_fields",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"collected_zero_items",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"collection_transposed_subcommand",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"command_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"command_namespace",exit_code:2,stable:!0,sources:["sdk/cli-contracts/runtime-contracts.ts"]},{code:"command_override_conflict",exit_code:4,stable:!0,sources:["sdk/compose.ts"]},{code:"config_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"config_key_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts","sdk/config.ts"]},{code:"config_value_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"conflicting_lifecycle_owner",exit_code:2,stable:!0,sources:["cli/register-operations.ts"]},{code:"context_evaluation_read_incomplete",exit_code:2,sources:["sdk/context-relevance.ts"]},{code:"context_signal_store_invalid",exit_code:2,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_stale",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_signal_store_write_failed",exit_code:1,sources:["sdk/context-signal-store.ts"]},{code:"context_takes_no_item_argument",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"core_item_field_requires_dedicated_flag",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"create_deferral_conflict",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_field_unsupported",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_fields_required",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_deferral_reason_required",exit_code:2,sources:["sdk/lifecycle/create-deferrals.ts"],emitting_commands:["create"]},{code:"create_positional_type_without_title",exit_code:2,stable:!0,sources:["cli/register-mutation.ts"]},{code:"dependency_cardinality_created",exit_code:2,sources:["sdk/graph/cardinality-integrity.ts"]},{code:"dependency_edge_not_allowed",exit_code:2,stable:!0,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_flag_value_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_remove_no_match",exit_code:3,sources:["sdk/lifecycle/dependency-removal.ts"],emitting_commands:["update"]},{code:"dependency_target_not_found",exit_code:3,sources:["sdk/dependency-flag-validation.ts"]},{code:"dependency_temporal_order_invalid",exit_code:2,sources:["sdk/dependency-flag-validation.ts"]},{code:"duplicate_canonical_flag",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"duplicate_command",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"duplicate_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"duplicate_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"duplicate_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"duplicate_probe",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"duplicate_sweep_cost_limit",exit_code:4,stable:!0,sources:["sdk/query/duplicate-candidates.ts"],emitting_commands:["duplicate-candidates"]},{code:"duplicate_target_circular",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_is_duplicate",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_missing",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_self",exit_code:2,stable:!0,sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"empty_corpus",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"empty_surface",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"event_cursor_query_mismatch",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"event_history_integrity_failed",exit_code:1,sources:["core/history/event-index.ts"]},{code:"event_index_unavailable",exit_code:1,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"exit_code_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"expect_hash_background_unsupported",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invalid",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_invocation_rewritten",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_requires_mutation",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expect_hash_target_required",exit_code:2,sources:["sdk/lifecycle/item-revision.ts"]},{code:"expected_revision_duplicate",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"expected_revision_scope_conflict",exit_code:2,sources:["core/store/item-mutation-precondition.ts"]},{code:"extension_command_activation_failed",exit_code:1,stable:!0,sources:["cli/commander-usage.ts"]},{code:"extension_dependency_name_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_spec_invalid",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_dependency_version_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"extension_flag_value_invalid",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_install_incomplete_source_scan",exit_code:2,sources:["sdk/extension/install-plan.ts"]},{code:"extension_install_rollback_failed",exit_code:1,sources:["sdk/extension/install-snapshot.ts"]},{code:"extension_install_soft_failed",exit_code:1,stable:!0,sources:["cli/register-setup.ts"]},{code:"extension_install_source_contains_destination",exit_code:2,stable:!0,sources:["sdk/extension/install-runtime.ts"]},{code:"extension_item_field_reserved",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_type_conflict",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_item_field_unknown",exit_code:2,stable:!0,sources:["core/extensions/item-fields.ts"]},{code:"extension_mutation_guard_failed",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_decision",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_invalid_denial",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_mutation_guard_timed_out",exit_code:4,stable:!0,sources:["core/extensions/extension-hook-runtime.ts"]},{code:"extension_option_disabled",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_option_spelling_conflict",exit_code:2,sources:["sdk/extension/command-options.ts"]},{code:"extension_read_output_invalid",exit_code:2,sources:["sdk/read-output/extension.ts"]},{code:"extension_update_health_partial_coverage",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"extensions_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"field_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_flag_invalid",exit_code:2,sources:["core/profile/profile-lint.ts"]},{code:"field_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_mcp_input_collision",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"field_option_collision",exit_code:1,sources:["core/profile/profile-lint.ts"]},{code:"finalization_invalid_document",exit_code:2,sources:["sdk/transactions/item-finalization.ts"]},{code:"github_source_entry_unbuilt",exit_code:2,stable:!0,sources:["sdk/extension/shared.ts"]},{code:"hierarchy_cardinality_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_cycle_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"hierarchy_parent_divergence_created",exit_code:4,sources:["sdk/graph/hierarchy-integrity.ts"]},{code:"history_append_only_repair_unavailable",exit_code:4,sources:["sdk/history/append-only-repair.ts"]},{code:"history_author_acknowledge_plan_conflict",exit_code:4,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_plan_fingerprint_required",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_preview_limit_invalid",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_required_values_missing",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_conflict",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_selector_required",exit_code:2,stable:!0,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_not_actionable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_author_acknowledge_target_unreadable",exit_code:2,sources:["sdk/author-attribution.ts"]},{code:"history_baseline_unavailable",exit_code:1,sources:["core/history/projection.ts"]},{code:"history_compact_boundary_bridged",exit_code:2,sources:["sdk/history-compact.ts"]},{code:"history_drift_chain_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_chain_mismatches"]},{code:"history_drift_chain_unbridgeable",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_hash_mismatch",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_hash_mismatches"]},{code:"history_drift_merge_receipt",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_missing_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_missing_streams"]},{code:"history_drift_unreadable_stream",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_unreadable_streams"]},{code:"history_drift_unrepairable_stream",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"history_drift_version_skew",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_drift_version_skews"]},{code:"history_json_invalid",exit_code:1,sources:["core/history/read.ts"]},{code:"history_merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/history/read.ts"],canonical_code:"merge_conflict_markers_detected"},{code:"history_record_integrity_invalid",exit_code:4,sources:["sdk/history/reanchor-refusal.ts"]},{code:"history_record_invalid",exit_code:1,sources:["core/history/read.ts"]},{code:"history_record_version_unsupported",exit_code:4,sources:["sdk/history/reanchor-refusal.ts"]},{code:"history_redact_bridge_unlocated",exit_code:1,sources:["sdk/history-redact.ts"]},{code:"history_replay_invalid",exit_code:1,sources:["core/history/projection.ts","core/history/tombstone.ts"]},{code:"history_salvage_refused",exit_code:4,sources:["sdk/history/salvage.ts"]},{code:"history_stream_over_compact_threshold",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"history_target_out_of_range",exit_code:1,stable:!0,sources:["core/history/projection.ts"]},{code:"history_timestamp_invalid",exit_code:1,sources:["core/history/event-index.ts","core/history/history.ts"]},{code:"history_union_rebase_conflict",exit_code:4,sources:["sdk/merge/history-scalar-rebase.ts"]},{code:"history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_history_unknown_author_events"]},{code:"history_version_mapping_unavailable",exit_code:2,sources:["core/history/version-address.ts"]},{code:"history_version_pruned",exit_code:2,sources:["core/history/projection.ts"]},{code:"history_version_unreconstructable",exit_code:2,sources:["core/history/projection.ts"]},{code:"host_environment_capacity_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_operation_invalid",exit_code:2,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_permission_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"host_environment_resource_fault",exit_code:1,sources:["core/fs/host-environment-errors.ts"]},{code:"improvement_metric_contract_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"improvement_observation_conflict",exit_code:4,sources:["sdk/improvement-ledger.ts"]},{code:"in_progress_idle",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"in_progress_unowned",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"incomplete_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"inconsistent_concept_kind",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"init_existing_settings_requires_force",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_gitignore_unwritable",exit_code:1,stable:!0,sources:["sdk/workspace.ts"]},{code:"init_id_prefix_conflict",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"init_id_prefix_path_like",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"integrity_history_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_history_conflict_markers"]},{code:"integrity_history_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_history_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_ahead_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_ahead_items"]},{code:"integrity_item_conflict_marker",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_outdated_format_version",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_format_version_outdated_items"]},{code:"integrity_item_parse_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"integrity_item_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"invalid_argument_value",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/item/priority.ts","core/shared/url-credentials.ts","core/telemetry/observability.ts","sdk/config.ts","sdk/context-intent-contracts.ts","sdk/dependencies.ts","sdk/extension/listing-fields.ts","sdk/extension/static-inventory.ts","sdk/governance/assurance-mutation-error.ts","sdk/history-redact.ts","sdk/lifecycle/create.ts","sdk/lifecycle/task-composition.ts","sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts","sdk/linked-artifacts.ts","sdk/query/next.ts","sdk/runtime-input.ts","sdk/runtime.ts","sdk/runtime/mutation-admission.ts","sdk/runtime/mutation-value-validation.ts","sdk/runtime/schema-preview.ts","sdk/test/run-phases.ts","sdk/workspace.ts"],emitting_commands:["*","create","next","task-composition","update","update-many"]},{code:"invalid_command_usage",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"invalid_event_cursor",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_cursor_mode",exit_code:2,sources:["cli/register-list-query.ts","sdk/mutation-events.ts","sdk/runtime-extended-actions.ts"]},{code:"invalid_event_follow_interval",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_limit",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_event_since",exit_code:2,stable:!0,sources:["sdk/mutation-events.ts"]},{code:"invalid_history_analytics_limit",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_minimum_sample",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_history_analytics_since",exit_code:2,sources:["sdk/history-analytics.ts"]},{code:"invalid_improvement_ledger",exit_code:1,sources:["sdk/improvement-ledger-validation.ts"]},{code:"invalid_improvement_metric",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_limit",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_improvement_observation_timestamp",exit_code:2,sources:["sdk/improvement-ledger.ts"]},{code:"invalid_provenance_predicate",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"invalid_query_cursor",exit_code:2,stable:!0,sources:["sdk/pagination.ts","sdk/query/window-pagination.ts"]},{code:"invalid_read_output_session",exit_code:2,sources:["sdk/read-output-session.ts"]},{code:"invalid_reproducible_process_environment",exit_code:2,sources:["sdk/reproducibility/process.ts"]},{code:"invalid_workspace_snapshot_target",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"item_already_active",exit_code:4,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"item_already_exists",exit_code:4,stable:!0,sources:["sdk/lifecycle/create.ts"],emitting_commands:["create"]},{code:"item_deleted",exit_code:3,sources:["core/history/tombstone.ts"]},{code:"item_document_encoding_invalid",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_document_invalid",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_document_roundtrip_failed",exit_code:1,stable:!0,sources:["core/item/item-format.ts"]},{code:"item_format_version_unsupported",exit_code:4,sources:["core/item/item-format.ts"]},{code:"item_id_collision",exit_code:4,stable:!0,sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"]},{code:"item_identity_ambiguous",exit_code:4,sources:["core/store/item-store.ts"]},{code:"item_identity_conflict",exit_code:4,sources:["sdk/governance/validate-history-drift.ts","sdk/lifecycle/item-revision.ts","sdk/merge/three-way.ts","sdk/query/declared-blockers.ts"]},{code:"item_identity_reserved",exit_code:4,sources:["core/history/history.ts"]},{code:"item_not_found",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/item-store.ts","core/telemetry/observability.ts","sdk/governance/validate-history-drift.ts"]},{code:"item_revision_conflict",exit_code:4,sources:["core/store/item-mutation-precondition.ts"]},{code:"likely_duplicate",exit_code:4,stable:!0,sources:["sdk/similarity.ts"]},{code:"linked_artifact_mutation_conflict",exit_code:2,sources:["sdk/linked-artifacts.ts"]},{code:"linked_artifact_note_conflict",exit_code:4,sources:["sdk/linked-artifacts.ts"]},{code:"linked_artifact_note_key_misread",exit_code:2,sources:["sdk/linked-artifacts.ts"]},{code:"linked_resource_positional_value",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"linked_resource_value_list",exit_code:2,sources:["cli/error-guidance.ts"]},{code:"linked_test_command_immutable",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_command_not_executable",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_context_invalid",exit_code:2,sources:["sdk/test/entry.ts"]},{code:"linked_test_patch_fields_unsupported",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_remove_no_match",exit_code:3,sources:["sdk/test/execution.ts"]},{code:"linked_test_update_ambiguous",exit_code:2,sources:["sdk/test/update.ts"]},{code:"linked_test_update_no_match",exit_code:3,sources:["sdk/test/update.ts"]},{code:"linked_test_value_not_quoted",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"list_source_incomplete",exit_code:1,stable:!0,sources:["sdk/query/list.ts"],emitting_commands:["list"]},{code:"local_package_archive_unsafe",exit_code:2,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"local_source_not_found_bare_name",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"lock_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"]},{code:"lock_lost",exit_code:4,sources:["core/lock/lock.ts"]},{code:"lock_path_unsafe",exit_code:4,sources:["core/lock/lock-confinement.ts"]},{code:"locks_stale_count",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"locks_unreadable",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"malformed_plan_step_evidence",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"managed_state_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"managed_state_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_capabilities_absent",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"manifest_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"manifest_unknown_key",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_declares_an_unknown_top_level_key",probe_id:"author-manifest-unknown-key",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"manifest_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"mcp_annotation_file_unavailable",exit_code:2,sources:["sdk/runtime-input.ts"]},{code:"mcp_stdin_unavailable",exit_code:2,sources:["sdk/annotations.ts"]},{code:"mcp_task_not_found_or_not_authorized",exit_code:3,sources:["sdk/mcp/tasks.ts"]},{code:"merge_artifacts_ignored",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_bun_launcher_unavailable",exit_code:5,sources:["sdk/merge/install.ts"]},{code:"merge_conflict_markers_detected",exit_code:1,stable:!0,sources:["core/item/item-format.ts"],aliases:["history_merge_conflict_markers_detected"]},{code:"merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_driver_configuration_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_driver_configuration_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]}];var th=[{code:"merge_fence_drift",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_fence_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_git_config_unwritable",exit_code:5,stable:!0,sources:["sdk/merge/install.ts"]},{code:"merge_receipt_evidence_invalid",exit_code:4,sources:["core/diagnostics/remediation.ts","sdk/merge/reconcile.ts"]},{code:"merge_receipt_history_reference_missing",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_receipt_not_portable",exit_code:4,sources:["sdk/merge/receipts.ts"]},{code:"merge_receipts_pending",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"merge_reconcile_receipt_evidence_untrusted",exit_code:4,sources:["sdk/history-repair.ts"]},{code:"merge_root_not_found",exit_code:3,stable:!0,sources:["sdk/merge/install.ts"]},{code:"merge_settlement_hook_conflict",exit_code:4,sources:["sdk/merge/settlement-hook.ts"]},{code:"merge_settlement_review_required",exit_code:4,sources:["sdk/merge/ignored-artifacts.ts","sdk/merge/reconcile.ts","sdk/merge/stage.ts"]},{code:"missing_allowed_values",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"missing_cli_flag",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_directory",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"missing_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_lifecycle_target",exit_code:2,stable:!0,sources:["sdk/extension.ts"]},{code:"missing_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"missing_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"missing_parameter_alias",exit_code:1,sources:["sdk/cli-contracts/tool-option-contracts.ts"]},{code:"missing_positive_execution_receipt",exit_code:1,sources:["sdk/test/execution.ts"]},{code:"missing_probe",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"missing_required_argument",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","cli/schema/registration.ts","core/telemetry/observability.ts","sdk/governance/assurance-action.ts","sdk/history-redact.ts","sdk/invocation-author.ts","sdk/lifecycle/claim.ts","sdk/linked-artifacts.ts"],emitting_commands:["*","claim"]},{code:"missing_required_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/extension/command-options.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"]},{code:"missing_suggested_retry",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"missing_suggested_retry_args",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"module_import_failed",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"multi_target_github_install_ambiguous",exit_code:2,stable:!0,sources:["cli/register-setup.ts"]},{code:"mutation_author_required",exit_code:2,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"mutation_document_unreadable",exit_code:2,sources:["cli/register-structured-mutation.ts"]},{code:"mutation_option_value_invalid",exit_code:2,sources:["sdk/lifecycle/mutation-option-validation.ts"],emitting_commands:["item mutate"]},{code:"mutation_secret_guard_blocked",exit_code:4,stable:!0,sources:["sdk/mutation-guard.ts"]},{code:"no_matching_tests",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_projects_matched_filters",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_test_files_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_tests_found",exit_code:1,stable:!0,sources:["sdk/test/execution-receipts.ts"]},{code:"no_update_fields",exit_code:1,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts"]},{code:"no_version_bounds_declared",exit_code:1,sources:["core/extensions/manifest-schema.ts"],owned_states:[{state:"author_workspace_manifest_omits_canonical_pm_version_bounds",probe_id:"author-manifest-version-bounds-missing",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"non_refusal_exit",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"npm_pack_json_shape_unsupported",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_missing",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_archive_unsafe",exit_code:1,sources:["sdk/extension/install-sources.ts"]},{code:"npm_package_not_found",exit_code:3,stable:!0,sources:["sdk/extension/install-sources.ts"]},{code:"npm_source_shorthand_ambiguous",exit_code:2,sources:["sdk/extension/install-sources.ts"]},{code:"output_budget_exceeded",exit_code:2,sources:["sdk/testing.ts"]},{code:"ownership_conflict",exit_code:4,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"]},{code:"ownership_dependency_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"ownership_metadata_bypass_restricted_options",exit_code:1,stable:!0,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"package_spec_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"package_upgrade_modes_mutually_exclusive",exit_code:2,sources:["sdk/governance/upgrade.ts"]},{code:"positional_shape_budget_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"positional_signature_mismatch",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"profile_name_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_name_not_normalized",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_summary_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"profile_title_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"project_runtime_history_epoch_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_item_format_incompatible",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_mutation",exit_code:4,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_runtime_stale_read",exit_code:1,sources:["sdk/environment/project-runtime-compatibility.ts"]},{code:"project_schema_field_requires_declared_flag",exit_code:2,sources:["core/extensions/item-fields.ts"]},{code:"projection_options_mutually_exclusive",exit_code:2,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"provenance_value_domain_invalid",exit_code:2,sources:["core/diagnostics/remediation.ts"]},{code:"read_output_cursor_command_mismatch",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_invalid",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_cursor_stale",exit_code:2,sources:["sdk/read-output/continuation.ts"]},{code:"read_output_mutation_conflict",exit_code:2,sources:["sdk/read-output-contracts.ts"]},{code:"read_output_surface_unsupported",exit_code:2,sources:["sdk/extension/static-inventory.ts","sdk/read-output-contracts.ts"]},{code:"recovery_kind_mismatch",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"redundant_edge",exit_code:1,stable:!0,sources:["sdk/graph/remediation.ts"]},{code:"refusal_allowed_values_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_error_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_exit_code_mismatch",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_mutated_state",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_probe_missing",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"refusal_recovery_failed",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"reindex_already_running",exit_code:4,stable:!0,sources:["sdk/governance/reindex.ts"]},{code:"removed_canonical_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"removed_compatibility_spelling",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"reopen_reason_required",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reopen_receipt_missing",exit_code:1,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"reopen_target_status_invalid",exit_code:2,sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"]},{code:"reported_zero_passes",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reported_zero_tests",exit_code:1,sources:["sdk/test/execution-receipts.ts"]},{code:"reserved_item_field",exit_code:1,stable:!0,sources:["sdk/compose.ts"]},{code:"retry_failed",exit_code:1,sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"]},{code:"schema_field_flag_invalid",exit_code:2,sources:["sdk/schema/field-option-collisions.ts"]},{code:"schema_field_option_collision",exit_code:2,sources:["sdk/schema/field-option-collisions.ts"]},{code:"schema_migration_input_required",exit_code:2,stable:!0,sources:["cli/migration-gates.ts"]},{code:"semantic_spelling_collision",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"settings_invalid",exit_code:2,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_read_fs_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_invalid_schema",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_read_merge_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"settings_section_document_malformed",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_document_missing",exit_code:3,sources:["core/store/settings-sections.ts"]},{code:"settings_section_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_name_invalid",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_reserved",exit_code:2,sources:["core/store/settings-sections.ts"]},{code:"settings_section_revision_conflict",exit_code:4,sources:["core/store/settings-sections.ts"]},{code:"settings_unreadable",exit_code:1,sources:["sdk/extension/static-inventory.ts"]},{code:"settings_write_assigned_path_invalid",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_json",exit_code:2,sources:["core/store/settings.ts"]},{code:"settings_write_invalid_existing_schema",exit_code:2,sources:["core/store/settings.ts"]},{code:"stale_budget",exit_code:1,sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"]},{code:"stale_claim_takeover_refused",exit_code:4,sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"stale_destination",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_in_progress_items",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"stale_lock_requires_override",exit_code:4,sources:["core/lock/lock.ts"]},{code:"stale_observed_signature",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"stale_revision",exit_code:4,sources:["core/store/item-store.ts"]},{code:"start_blocked_by_open_dependency",exit_code:4,sources:["sdk/lifecycle/start-blockers.ts"],emitting_commands:["claim","start-task","update"]},{code:"status_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"status_lifecycle_role_required",exit_code:2,sources:["sdk/schema.ts"]},{code:"stdin_json_invalid",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"stdin_json_persisted_annotation_changed",exit_code:2,sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"stdin_json_unknown_key",exit_code:2,stable:!0,sources:["sdk/structured-mutations.ts"]},{code:"structured_entry_key_repeated",exit_code:2,sources:["core/item/parse.ts"]},{code:"structured_event_immutable",exit_code:2,stable:!0,sources:["sdk/annotations.ts"]},{code:"structured_event_input_conflict",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_empty",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_json_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"structured_event_since_invalid",exit_code:2,stable:!0,sources:["sdk/notes.ts"]},{code:"suggested_retry_args_mismatch",exit_code:1,sources:["sdk/agent/refusal-closure.ts"]},{code:"telemetry_endpoint_probe_failed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_endpoint_probe_http_status",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_otel_export_failing",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_high_retries",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_invalid_rows",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_queue_pending",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_schema_version_behind",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"telemetry_state_invalid_json",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"template_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"terminal_plan_mutation",exit_code:4,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"terminal_state_conflict",exit_code:4,stable:!0,sources:["core/telemetry/observability.ts","sdk/lifecycle/claim.ts"],emitting_commands:["*","claim"]},{code:"test_measure_requires_execution",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"test_measure_requires_run",exit_code:2,sources:["sdk/test/prerequisites.ts"]},{code:"text_unpaired_surrogate",exit_code:2,sources:["core/item/item-format.ts","core/shared/output-unicode.ts"]},{code:"tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],aliases:["validate_storage_tracked_runtime_cache_files"]},{code:"tracker_not_initialized",exit_code:3,stable:!0,sources:["cli/error-guidance.ts","core/store/tracker-preflight.ts","core/telemetry/observability.ts"],owned_states:[{state:"selected_tracker_root_exists_without_settings",probe_id:"tracker-root-settings-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_missing",exit_code:3,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_does_not_exist",probe_id:"tracker-root-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_not_directory",exit_code:2,stable:!0,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_a_regular_file",probe_id:"tracker-root-not-directory",entrypoints:["list"],expected_exit_class:"usage"}]},{code:"tracker_root_unreadable",exit_code:1,sources:["core/store/tracker-preflight.ts"],owned_states:[{state:"selected_tracker_root_is_not_readable",probe_id:"tracker-root-unreadable",entrypoints:["list"],expected_exit_class:"generic_failure"}]},{code:"transaction_abandoned",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_committed",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_create_compensated",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_journal_invalid",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_partial_mutation",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_plan_mismatch",exit_code:4,sources:["sdk/workspace-transaction.ts"]},{code:"transaction_preview_external_schema",exit_code:2,sources:["sdk/item-transaction.ts"]},{code:"transaction_preview_non_regular_file",exit_code:2,sources:["core/fs/fs-utils.ts"]},{code:"transaction_preview_snapshot_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"transaction_recovery_plan_missing",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"type_duplicate",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"type_invalid",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"undeclared_observation",exit_code:1,sources:["sdk/flag-invocation-contracts.ts"]},{code:"unexpected_refusal_probe",exit_code:1,sources:["sdk/agent/refusal-corpus-contracts.ts"]},{code:"unknown_command",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"]},{code:"unknown_context_intent",exit_code:2,stable:!0,sources:["sdk/context-intent-contracts.ts"]},{code:"unknown_error",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"unknown_field",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_field_projection",exit_code:2,stable:!0,sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"]},{code:"unknown_item_type",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_lifecycle_action",exit_code:2,stable:!0,sources:["sdk/agent/subcommand-recovery.ts"],canonical_code:"unknown_subcommand"},{code:"unknown_noun",exit_code:2,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"unknown_option",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","cli/runtime/invocation-options.ts","core/telemetry/observability.ts","sdk/extension/command-options.ts"],owned_states:[{state:"declared_option_is_rejected_on_the_selected_command_path",probe_id:"cross-command-unknown-option",entrypoints:["deps"],expected_exit_class:"usage"}]},{code:"unknown_plan_template",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"unknown_provenance_dimension",exit_code:2,stable:!0,sources:["sdk/history-provenance.ts"]},{code:"unknown_status",exit_code:3,stable:!0,sources:["sdk/schema.ts"]},{code:"unknown_subcommand",exit_code:2,stable:!0,sources:["cli/error-guidance.ts","sdk/agent/subcommand-recovery.ts"],aliases:["unknown_lifecycle_action"],owned_states:[{state:"config_action_token_is_not_declared",probe_id:"config-unknown-action",entrypoints:["config"],expected_exit_class:"usage"},{state:"graph_command_token_is_not_declared",probe_id:"graph-unknown-subcommand",entrypoints:["graph"],expected_exit_class:"usage"},{state:"nested_command_token_is_not_declared_by_its_family",probe_id:"schema-unknown-subcommand",entrypoints:["schema"],expected_exit_class:"usage"},{state:"package_lifecycle_token_is_not_declared",probe_id:"package-unknown-action",entrypoints:["package"],expected_exit_class:"usage"}]},{code:"unsafe_init_recovery",exit_code:1,sources:["sdk/agent/tracker-preflight-contracts.ts"]},{code:"unsupported_update_option",exit_code:1,stable:!0,sources:["cli/error-guidance.ts"]},{code:"upsert_key_ambiguous",exit_code:4,sources:["sdk/structured-mutations.ts"]},{code:"upsert_key_conflict",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"upsert_key_duplicate",exit_code:2,sources:["sdk/item-transaction.ts","sdk/structured-mutations.ts"]},{code:"upsert_key_missing",exit_code:2,sources:["sdk/structured-mutations.ts"]},{code:"upsert_match_changed",exit_code:4,sources:["sdk/item-transaction.ts"]},{code:"validate_command_references_stale_pm_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_missing_linked_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_orphaned_paths",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_files_tracked_all_strict_forces_pm_internals",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_format_version_ahead_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_ahead_format_version"},{code:"validate_format_version_outdated_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_item_outdated_format_version"},{code:"validate_hierarchy_parent_cycle",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_hierarchy_parent_cycle_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_history_drift_chain_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_chain_mismatch"},{code:"validate_history_drift_hash_mismatches",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_hash_mismatch"},{code:"validate_history_drift_missing_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_missing_stream"},{code:"validate_history_drift_unreadable_streams",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_unreadable_stream"},{code:"validate_history_drift_version_skews",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_drift_version_skew"},{code:"validate_history_unknown_author_events",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"history_unknown_author_events"},{code:"validate_lifecycle_active_closure_like_metadata",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_active_terminal_parent",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_dependency_cycles_error",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_lifecycle_stale_blockers",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_decisions_unreviewed",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_driver_configuration",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_merge_fence_drift",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_custom_profile_missing_required_fields",exit_code:2,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_duplicate_issue_codes",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_acceptance_criteria",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_close_reason",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_closed_at",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_confidence",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_estimate",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_release",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_reviewer",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_risk",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_metadata_missing_sprint",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_resolution_missing_fields",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_schema_field_option_collision",exit_code:1,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_duplicate_item_ids",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_history_conflict_markers",exit_code:4,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"integrity_history_conflict_marker"},{code:"validate_storage_resurrected_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_tracked_runtime_cache_files",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"],canonical_code:"tracked_runtime_cache_files"},{code:"validate_storage_unparseable_config",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unparseable_history",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"validate_storage_unreadable_items",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_embedding_identity_changed",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"vectorization_stale_items_remaining",exit_code:1,stable:!0,sources:["core/diagnostics/remediation.ts"]},{code:"visible_surface_ceiling_exceeded",exit_code:1,sources:["sdk/cli-contracts/grammar-contracts.ts"]},{code:"workflow_duplicate_type",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_policy_approval_history_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_audit_failed",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_input_unreadable",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_invalid",exit_code:2,sources:["core/policy/workflow-policy.ts"]},{code:"workflow_policy_refused",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_policy_registry_invalid",exit_code:4,sources:["core/policy/workflow-policy-store.ts"]},{code:"workflow_status_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_transition_malformed",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_empty",exit_code:1,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workflow_type_unknown",exit_code:2,stable:!0,sources:["core/profile/profile-lint.ts"]},{code:"workspace_history_chain_invalid",exit_code:4,sources:["core/history/workspace-history.ts"]},{code:"workspace_history_state_conflict",exit_code:4,stable:!0,sources:["core/history/workspace-history.ts"]},{code:"workspace_root_pm_path",exit_code:2,stable:!0,sources:["sdk/init.ts"]},{code:"workspace_snapshot_force_required",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_manifest_mismatch",exit_code:4,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_name_reserved_fingerprint",exit_code:2,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_not_found",exit_code:3,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_permission_denied",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_resource_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"workspace_snapshot_storage_exhausted",exit_code:1,sources:["sdk/workspace-snapshot.ts"]},{code:"wrong_item_type",exit_code:2,stable:!0,sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]}];var nh=Q_(Z_([...eh,...th]));var _A=["mutation_receipt","entity","collection","diagnostic","stream"],hA=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),gA=new Set(["close-many","update-many"]),yA=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),wA=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function bn(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!_A.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function rh(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return gA.has(n)?bn({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):hA.has(n)?bn({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):yA.has(n)?bn({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):wA.has(n)?bn({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):bn({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var vA=We.map(e=>rh(e)),kA=new Map(vA.map(e=>[e.command,e])),bA=new Map([["files lookup",bn({command:"files lookup",kind:"collection",wrapper_key:"matches",cardinality:"many",format_flag:"--json"})]]);function ih(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let n=Ur(t),r=bA.get(n);if(r!==void 0)return{...r,command:t};let[i=t]=n.split(" "),s=kA.get(i);return s?{...s,command:t}:rh(t)}function SA(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function AA(e){return SA(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function HD(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!AA(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}var Ea=[{exit_code:p.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:p.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:p.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:p.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:p.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:p.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:p.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:p.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],sh=[p.SUCCESS,p.GENERIC_FAILURE,p.USAGE,p.NOT_FOUND,p.CONFLICT,p.DEPENDENCY_FAILED],xA=new Set(["close-many","update-many"]),ah=We.map(e=>({command:e,exit_codes:xA.has(e)?[...sh,p.NO_EFFECT,p.PARTIAL_EFFECT]:[...sh]})),oh=new Map(ah.map(e=>[e.command,e])),CA=[p.SUCCESS,p.NO_EFFECT,p.PARTIAL_EFFECT];function JD(e){return CA.includes(e)}function QD(e){return Ea.some(t=>t.exit_code===e)}function ch(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return oh.get(t)??oh.get(t.split(" ")[0])}function ZD(e,t=We,n=ah){let r=new Map(n.map(d=>[d.command,d])),i=t.filter(d=>!r.has(d)),s=e.filter(d=>{let l=r.get(d.command)??r.get(d.command.split(" ")[0]);return l===void 0||!l.exit_codes.includes(d.exit_code)}),o=new Set(e.map(d=>d.exit_code)),c=[...new Set(n.flatMap(d=>d.exit_codes))].filter(d=>!o.has(d)).sort((d,l)=>d-l);return{ok:i.length===0&&s.length===0&&c.length===0,missing_commands:i,undeclared_observations:s,unreachable_exit_codes:c}}function eP(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:p.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:p.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:p.PARTIAL_EFFECT}:{outcome:"effect",exit_code:p.SUCCESS}}var $=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},be=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Xe=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function Sn(e){try{return await e()}catch(t){throw t instanceof $?new f(t.message,p.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Ra(e){try{return await e()}catch(t){throw t instanceof be?new f(t.message,p.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as EA}from"node:crypto";import RA from"node:path";var lh=1,st=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],dr=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],TA=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],IA=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Yi=30,Xi=5e3,uh=4,OA=50;function ot(e,t){if(!IA.test(e))throw new $(`${t} must be a stable lowercase id`)}function NA(e,t){if(!Number.isFinite(e)||e<0)throw new $(`${t} must be a finite non-negative number`)}function ur(e){let t=TA.filter(i=>e[i]!==void 0);if(t.length!==1)throw new $(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function Ia(e,t){return Z(e)===Z(t)}function mh(e,t){if(t.polarity==="equals")return Ia(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function ph(e){let t=ur(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>mh(r.observed,t)===(r.expected==="pass"))}function $A(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!Ia(e.value,t.value)}function LA(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||Z(e.scope)!==Z(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return $A(ur(e),ur(t))||n[t.enforcement]<n[e.enforcement]||r}function MA(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new $("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new $("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new $("items source equals/state requires field")}function FA(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new $("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(n=>n!==void 0).length>1)throw new $("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new $("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new $("dependency_kind source source_kind_state must be present or missing")}function DA(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new $("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new $("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new $("prose_edge_gap exemption selectors must not be empty")}}function Oa(e){ot(e.id,"measurement.id"),e.max_cost!==void 0&&NA(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new $(`measurement.source.kind must be one of ${dr.join(", ")}`);let n=Reflect.get(t,"kind");if(!dr.includes(n))throw new $(`measurement.source.kind must be one of ${dr.join(", ")}`);let r=t;if(r.kind==="items"&&MA(r),r.kind==="dependency_kind"&&FA(r),r.kind==="prose_edge_gap"&&DA(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new $(`${r.kind} source requires field`);return r.kind==="provider"&&(ot(r.provider,"provider source provider"),ot(r.key,"provider source key")),e}function Na(e){if(ot(e.id,"assertion.id"),ot(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new $("assertion.owner_item_id is required");let t=ur(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new $(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new $("retired assertion requires retire_reason");e.scope.kind==="filter"&&ot(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new $("assertion negative control requires pass and fail cases");if(!ph(e))throw new $(`assertion ${e.id} negative control does not prove its bound`);return e}function PA(e){if(!Array.isArray(e.allowed_providers))throw new $("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)ot(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new $("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!st.includes(t))throw new $(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new $(`gate provider policy trigger ${t} is invalid`)}}function fh(e){if(ot(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new $("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new $("gate requires at least one assertion");for(let t of e.assertion_ids)ot(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new $(`gate.triggers is required and must be an array of ${st.join(", ")}`);if(e.triggers.length===0)throw new $("gate requires at least one trigger");for(let t of e.triggers)if(!st.includes(t))throw new $(`gate trigger must be one of ${st.join(", ")}`);return e.provider_policy&&PA(e.provider_policy),e}function An(e){if(e.version!==lh)throw new $(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(Oa(r),t.has(`measurement:${r.id}`))throw new $(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(Na(r),t.has(`assertion:${r.id}`))throw new $(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){fh(r);let i=r.assertion_ids.filter(s=>!e.assertions.some(o=>o.id===s));if(i.length>0)throw new $(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new $(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of _h(e))if(!n.has(r))throw new $(`${i.join(", ")} references missing measurement ${r}`);return e}function $a(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)$a(n,t)}function _h(e){let t=new Map,n=(r,i)=>{let s=t.get(r)??[];s.push(i),t.set(r,s)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];$a(r.source.expression,i);for(let s of i)n(s,`derived measurement ${r.id}`)}return t}function UA(e,t){let n=e.assertion_ids.flatMap(s=>{let o=t.assertions.find(a=>a.id===s);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let s=n.pop();if(r.has(s))continue;r.add(s);let o=t.measurements.find(a=>a.id===s);o.source.kind==="provider"?i.add(o.source.provider):o.source.kind==="derived"&&$a(o.source.expression,n)}return i}function mr(){return{version:lh,measurements:[],assertions:[],gates:[]}}function jA(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let s=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?s:!s}return Ia(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function qA(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function GA(e,t){let n=[],r=Bn(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let s of i.dependencies??[]){let o=Bn(s.kind)??s.kind.trim().toLowerCase(),a=s.source_kind?.trim();o===r&&qA(e,a)&&n.push(`${i.id}->${s.id}${a?`@${a}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function KA(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let s=Reflect.get(i,"text");typeof s=="string"&&t.push(s)}}}return t}function zA(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function Ta(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function WA(e){let t=new Map,n=new Set,r=[],i=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,s=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let a of o.dependencies??[])n.add(Ta(o.id,a.id));for(let a of[o.parent,o.blocked_by])typeof a=="string"&&n.add(Ta(o.id,a));for(let a of KA(o)){let c=[...a.matchAll(i)].map(d=>d[0]);s+=c.length,r.push({holder_id:o.id,segment:a,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:s}}function BA(e,t){let n=WA(t.items),r=new Map;for(let o of n.prose_mentions){let a=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(a)];for(let d of c){let l=Ta(o.holder_id,d);if(n.linked_pairs.has(l)||zA(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);r.get(l)?.explicit===!0&&!u||r.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],s=i.map(o=>o.contributor).sort();return{value:s.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:s.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(o=>o.explicit).length,implicit_subject:i.filter(o=>!o.explicit).length}}}function HA(e,t){return{value:t.history.filter(r=>(e.op===void 0||r.op===e.op)&&(e.author===void 0||r.author===e.author)&&(e.harness===void 0||r.agent_harness===e.harness)&&(e.model===void 0||r.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function VA(e,t){let n=t.items.filter(r=>{let i=r[e.link],s=Array.isArray(i)&&i.length>0;return e.state==="present"?s:!s});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function YA(e,t){let n=e.source;return n.kind==="items"?jA(n,t):n.kind==="dependency_kind"?GA(n,t):n.kind==="prose_edge_gap"?BA(n,t):n.kind==="history"?HA(n,t):n.kind==="links"?VA(n,t):null}function hh(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function XA(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function gh(e,t,n){let r=new Array(e.length),i=0,s=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o],o)}});return await Promise.all(s),r}async function yh(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let a=await wh(o,t,n,r,i);if(typeof a.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=i.charged.has(o.id)?[]:[a.cost];return i.charged.add(o.id),{value:a.value,costs:c,population_size:a.population_size,contributors:a.contributors}}let s=await gh(e.operands,uh,o=>yh(o,t,n,r,i));return{value:XA(e.operator,s.map(o=>o.value)),costs:s.flatMap(o=>o.costs),population_size:Math.max(0,...s.map(o=>o.population_size)),contributors:[...new Set(s.flatMap(o=>o.contributors))]}}async function JA(e,t,n,r,i){Oa(e);let s=Date.now(),o,a=[],c=0;if(e.source.kind==="derived"){let u=await yh(e.source.expression,t,n,[...r,e.id],i);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},a=u.costs}else{let u=YA(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let d={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-s},l=hh([...a,d],Date.now()-s);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new be(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${EA("sha256").update(Z(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function wh(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let s=i.cache.get(e.id);if(s)return s;let o=JA(e,t,n,r,i).catch(a=>{if(a instanceof Xe&&a.measurement_id===void 0){let c={measurement_id:e.id,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}},d=new Xe(a.message,c);throw d.cause=a,d}throw a});return i.cache.set(e.id,o),o}async function La(e,t,n=[e]){return wh(e,t,n,[],{cache:new Map,charged:new Set})}function QA(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity==="monotone_nondecreasing",e-t.value)}function ZA(e,t,n={}){Na(e);let r=ur(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:QA(t.value,r),verdict:i?"retired":mh(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:ph(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function ex(e,t,n,r){let i=UA(e,t);if(i.size===0)return;let s=e.provider_policy,o=s?.triggers[r];if(!s||!o)throw new be(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let a=new Set(s.allowed_providers),c={low:0,medium:1,high:2};for(let d of i){if(!a.has(d))throw new be(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new be(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new be(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${r}`);if(l.network&&!o.allow_network)throw new be(`assurance gate ${e.id} refuses network provider ${d} at trigger ${r}`)}}async function dh(e,t,n,r,i){try{return await La(n,r,i)}catch(s){if(s instanceof Xe){let o=s.check?` check ${s.check}`:"",a=s.measurement_id??n.id,c=new be(`assurance gate ${e} assertion ${t} measurement ${a} source ${s.source_kind}${o} field ${s.field} could not resolve: ${s.message}`,{gate_id:e,assertion_id:t,measurement_id:a,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}});throw c.cause=s,c}throw s}}async function vh(e,t,n,r){An(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new be(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new be(`assurance gate ${e} does not declare trigger ${r.trigger}`);ex(i,t,n,r.trigger);let s=await gh(i.assertion_ids,uh,async c=>{let d=t.assertions.find(h=>h.id===c),l=t.measurements.find(h=>h.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let h=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(g=>!h.has(g.status))}}else if(d.scope.kind==="filter"){let h=d.scope.measurement_id,g=t.measurements.find(v=>v.id===h),y=await dh(i.id,d.id,g,n,t.measurements),w=new Set(y.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(h=>h.id===d.owner_item_id),_=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return ZA(d,await dh(i.id,d.id,l,u,t.measurements),{owner_terminal:_})}),o=s.some(c=>c.verdict==="fail"&&c.enforcement==="block"),a=s.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":a?"warn":"pass",exit_code:o?1:0,assertions:s,assertions_total:s.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:hh(s.map(c=>c.cost),Math.max(0,...s.map(c=>c.cost.duration_ms)))}}function Ji(e){return RA.join(e,"assurance.json")}async function kh(e){let t=await ee(Ji(e));return t===null?mr():Qi(t)}function Qi(e){try{return An(JSON.parse(e))}catch(t){throw new f("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",p.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function Zi(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function tx(e,t){e==="measurement"?Oa(t):e==="assertion"?Na(t):fh(t)}async function pr(e,t){let n=structuredClone(Zi(await kh(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function bh(e,t,n){let r=Zi(await kh(e),t).find(i=>i.id===n);if(!r)throw new be(`assurance ${t} ${n} not found`);return structuredClone(r)}async function es(e,t,n,r={}){tx(t,n);let i=await R(e),s=H(r.author,i.author_default),o=await dn({pmRoot:e,filePath:Ji(e),op:`assurance:${t}:put`,author:s,message:r.message,lockTtlSeconds:Yi,lockWaitMs:Xi,mutate:a=>{let c=a===null?mr():Qi(a),d=Zi(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&LA(d[l],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new $(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),An(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
|
+
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function Ma(e,t,n={}){let r=mr();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),An(r);let i=await R(e),s=H(n.author,i.author_default),o=await dn({pmRoot:e,filePath:Ji(e),op:"assurance:bundle:apply",author:s,message:n.message,lockTtlSeconds:Yi,lockWaitMs:Xi,mutate:a=>{let c=a===null?mr():Qi(a),d=[],l=[],u=(m,_,h)=>{for(let g of _){let y=m.find(w=>w.id===g.id);if(!y){m.push(structuredClone(g)),d.push(`${h}:${g.id}`);continue}if(Z(y)!==Z(g))throw new $(`assurance bundle refuses to replace divergent ${h} ${g.id}`);l.push(`${h}:${g.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),An(c),{raw:`${JSON.stringify(c,null,2)}
|
|
4
|
+
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function Sh(e,t,n,r={}){let i=await R(e),s=H(r.author,i.author_default),o=await dn({pmRoot:e,filePath:Ji(e),op:`assurance:${t}:remove`,author:s,message:r.message,lockTtlSeconds:Yi,lockWaitMs:Xi,mutate:a=>{let c=a===null?mr():Qi(a);if(t==="measurement"){let u=_h(c).get(n);if(u&&u.length>0)throw new $(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new $(`assurance assertion ${n} is referenced by gate`);let d=Zi(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new $(`assurance ${t} ${n} not found`);return d.splice(l,1),An(c),{raw:`${JSON.stringify(c,null,2)}
|
|
5
|
+
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function Ah(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await R(e);await cn({pmRoot:e,op:"assurance:gate:verdict",author:H(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Yi,lockWaitMs:Xi})}async function xh(e,t={}){let n=t.limit??OA;if(!Number.isInteger(n)||n<1||n>1e3)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${1e3}`);return(await Mt(Ru(e),Ft)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,n)}var nx=na("list").properties.outputSession,rx={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:{...nx},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Ch={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."}},Eh={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},oe={type:"string",description:"pm item id, for example pm-abc1."},ix=`Operation name (one of): ${_o.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,sx={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."}},ox={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 G(e,t=[]){return{...Eh,properties:{...Eh.properties,...e},required:t}}var ax=[{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:G({action:{type:"string",enum:[..._o],description:ix},id:oe,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...rx},["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:G({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:G({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:G({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:G({query:{type:"string"},options:{type:"object"},...ox},["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:G({options:{type:"object"},...sx})},{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:G({id:oe,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:G({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:G({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:G({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:oe,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},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:G({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:G({id:oe,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:G({id:oe,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:oe,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:G({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:G({id:oe,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:oe,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:'List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls 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:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:G({subcommand:{type:"string",enum:[...Hd]},id:oe,target:oe,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:G({id:oe,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:G({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:G({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:G({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:G({...Ch,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",...jd],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:[...yo]},description:`Lifecycle roles for add-status: ${yo.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:Ch}},["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:G({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:G({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:G({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."}})}],cx={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"},dx=ax.map(e=>{let t=cx[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:na(t,{properties:n,required:r})}});function Rh(){return dx.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,i)=>r.localeCompare(i)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}var Th=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"]]]),lx=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Uh=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ns=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"]),jh=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"]]),qh=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"]]),Gh=new Map([...qh.entries()].flatMap(([e,t])=>at(t).map(n=>[n,e]))),Kh=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Pa=new Map(Kh.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),ux=10,mx=20,Ih=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."]]),zh=[["init",Um],["install",qm],["uninstall",Gm],["explore",Km],["inventory",Yn],["manage",Ym],["describe",zm],["reload",Xm],["doctor",Jm],["catalog",Qm],["adopt",Zm],["adopt-all",Wm],["activate",Bm],["deactivate",Hm],["migrate",Vm]],px=[...zh.map(([e,t])=>e==="init"?[e,jm]:[e,t]),["upgrade",Ho]],fx=[...zh.map(([e,t])=>[`extension ${e}`,t]),...px.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["package list",Yn],["packages list",Yn],["extension list",Yn],["init",Fm],["config",Dm],["extension",Pm],["package",Bo],["packages",Bo],["install",ep],["create",bp],["item mutate",Sp],["item complete",Ap],["item reopen",xp],["copy",Cp],["focus",Ep],["update",Rp],["update-many",Tp],["upgrade",Ho],["calendar",Vo],["cal",Vo],["context",Yo],["ctx",Yo],["get",Np],["search",Pp],["eval",Fp],["events",Op],["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",Dp],["aggregate",ym],["deps",Lp],["graph",Mp],["guide",$p],["reindex",tp],["history",Cm],["history-compact",Om],["history-attest",Nm],["history-redact",Rm],["history-repair",Tm],["history-author-acknowledge",Im],["merge",Em],["schema",$m],["profile",Lm],["plan",Mm],["restore",op],["delete",ap],["close",np],["close-many",rp],["append",ip],["claim",sp],["release",cp],["start-task",dp],["pause-task",lp],["close-task",up],["comments",wm],["notes",vm],["learnings",km],["files",bm],["files discover",Sm],["files lookup",Am],["docs",xm],["test",mp],["test-runs-worker",[]],["test-all",pp],["telemetry",fp],["test-runs",_p],["gc",hp],["stats",gp],["ops",[]],["duplicates",yp],["validate",vp],["health",wp],["assurance",kp],...qp,["contracts",Up],["completion",jp],["activity",Ip],...[...Uh].map(e=>[e,gm])],fr=new Map(fx);for(let{alias:e,canonical:t}of ze){let n=fr.get(e);n!==void 0&&fr.set(t,n)}function _x(e){let t=Gh.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Oh(e){let t=ze.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:We.includes(e)?pe(e):e.startsWith("extension-")?pe(`extension ${e.slice(10)}`):e.startsWith("package-")?pe(`package ${e.slice(8)}`):e.startsWith("item-")?pe(`item ${e.slice(5)}`):e.startsWith("test-runs-")?pe(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?pe(`templates ${e.slice(10)}`):ns.has(e)?qh.get(e)??pe(e):null}function hx(e,t){let n=P(t);return n!==t||ze.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:at(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function at(e){return e.split("|").map(t=>pe(t)).filter(t=>t.length>0)}function gx(e,t){let n=new Set(t),r=new Set;for(let i of e)if(i.command_path)for(let s of at(i.command_path)){let o=s.split(" ").filter(a=>a.length>0);if(o.length!==0)for(let a=o.length;a>0;a-=1){let c=o.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((i,s)=>i.localeCompare(s))}function ts(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function _r(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function yx(e,t){if(!t)return{...e};let r=_r(e).filter(i=>{let s=i.properties;if(typeof s!="object"||s===null)return!1;let o=s.action;return typeof o!="object"||o===null?!1:o.const===t});return{...e,oneOf:r}}function Fa(e,t){let r=_r(e).filter(i=>{let s=i.properties;if(typeof s!="object"||s===null)return!1;let o=s.action;if(typeof o!="object"||o===null)return!1;let a=o.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function pe(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Wh(e){return e.replace(/\s+/g,"-")}function St(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Nh(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let i=St(r);!i||n.has(i)||(n.add(i),t.push(i))}return t}function Da(e,t,n){n&&(e[t]=!0)}function $h(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?Nt(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function wx(e){let t=$h(e.long,"long"),n=$h(e.short,"short"),r=t??n;if(!r)return null;let i={flag:r};n&&t&&(i.short=n),Da(i,"required",e.required===!0),Da(i,"repeatable",e.repeatable===!0),Da(i,"list",e.list===!0),e.default!==void 0&&(i.default=e.default);let s=St(e.description);s&&(i.description=s);let o=on(e);i.value_arity=o.value_arity;let a=St(e.value_name)??o.value_name;a&&(i.value_name=a);let c=o.value_type??(o.value_name?"string":null);return c&&(i.value_type=c),i}function Bh(e){let t=new Map;for(let r of e){let i=pe(r.target_command);if(i.length===0)continue;let s=t.get(i)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},o=`${r.layer}:${r.name}`;s.sourceDedupe.has(o)||(s.sourceDedupe.add(o),s.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=wx(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;s.dedupe.has(d)||(s.dedupe.add(d),s.flags.push(c))}t.set(i,s)}let n=new Map;for(let[r,i]of t.entries())n.set(r,{flags:i.flags,sources:i.sources.sort((s,o)=>{let a=s.layer.localeCompare(o.layer);return a!==0?a:(s.name??"").localeCompare(o.name??"")})});return n}function vx(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...Wo.filter(({flag:n})=>n.startsWith("--output-"))]}}function kx(e){let t=Bh(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let o=pe(s.command);if(o.length===0)continue;let a=St(s.action)??Wh(o),c=Array.isArray(s.arguments)?s.arguments.map(d=>{let l=St(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:St(d.description)}:null}).filter(d=>d!==null):[];n.set(o,{...s.tier===void 0?{}:{tier:s.tier},...vx(s,t.get(o)?.flags??[]),command:o,action:a,source:{layer:s.layer,name:s.name},description:St(s.description),intent:St(s.intent),arguments:c,examples:Nh(s.examples),failure_hints:Nh(s.failure_hints)})}let r=new Set;for(let s of e.handlers)r.add(pe(s));for(let s of n.keys())r.add(s);for(let s of t.keys())r.add(s);let i=[];for(let s of[...r].sort((o,a)=>o.localeCompare(a))){let o=n.get(s);i.push(bx(s,o,t.get(s)?.flags??[]))}return i}function bx(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Wh(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function Sx(e){let t=e.flag.startsWith("--")?e.flag:void 0,n=Sa({long:t,short:t===void 0?e.flag:void 0});return n!==null&&/[a-z0-9]/iu.test(n)?n:null}function Ax(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 xx(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",i=e.repeatable===!0||e.list===!0;return{type:i?"array":r,...i?{items:{type:r}}:{},...e.default!==void 0?{default:e.default}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function Cx(e){let t=e.command.split("|").map(i=>i.trim()).filter(i=>i.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let i of e.arguments)n[i.name]=Ax(i,e.action),i.required&&r.push(i.name);for(let i of e.flags){let s=Sx(i);!s||n[s]!==void 0||(n[s]=Wo.some(o=>o.flag===i.flag&&o.flag.startsWith("--output-"))?hf[s]:xx(i,e.action),i.required===!0&&r.push(s))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function Ex(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 Rx(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((s,o)=>s.localeCompare(o)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let i=new Set(r.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let o=`${s.flag}|${s.short??""}`;if(!i.has(o))i.add(o),r.flags.push(s);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===o);a&&Ex(a,s)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function Tx(e,t=R){let n={mode:Rt.extensions.policy.mode,trust_mode:Rt.extensions.policy.trust_mode,default_sandbox_profile:Rt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=I(process.cwd(),e.path);if(!await me(sn(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let i=await t(r),s=await _i({pmRoot:r,settings:i,cwd:process.cwd(),noExtensions:!1}),o=await hi({...s,loaded:s.loaded});return{handlers:new Set(o.commands.handlers.map(c=>pe(c.command))),disabledReason:null,commandDefinitions:o.registrations.commands,flagRegistrations:o.registrations.flags,registrations:o.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function Ix(e,t={}){let n=new Map;for(let r of Vd){let i=ns.has(r);if(i&&!t.includePackageOwnedActions)continue;let s=Oh(r);n.set(r,{action:r,provider:i?"extension":"core",requires_extension:i,command_path:s})}if(t.includePackageOwnedActions)for(let r of ns)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Oh(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ze.find(i=>i.alias===r.command)?.canonical??pe(r.command)});return[...n.values()].sort((r,i)=>(r.action??"").localeCompare(i.action??""))}function Ox(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&&(!vt.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?at(e.command_path):[],r=n.some(o=>t.handlers.has(o)||t.handlers.has(P(o))),i=n.map(o=>jh.get(P(o))).find(o=>typeof o=="string"),s=t.disabledReason===null&&r;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(i?`optional_package_not_installed:${i}`:"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 Hh(e){let t=fr.get(e)??Ei,n=Xn(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function Nx(e){return vt.has(P(e))?!1:fr.has(e)}function $x(e){return Uh.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Lh(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function Lx(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function Mx(e){let t=new Map;for(let r of e.definitions){let i=Lh(r.cli_flag);if(!i)continue;let s=r.cli_aliases.map(a=>Lx(a)).find(a=>a!==null),o=r.cli_aliases.map(a=>Lh(a)).filter(a=>a!==null&&a!==i);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},d=s?{flag:i,short:s}:{flag:i},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of o){let m=`${u}|`;c.seen.has(m)||(c.seen.add(m),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[r,i]of t.entries())n.set(r,zo(i.flags));return n}function Mh(e,t){let n=[],r=new Set;for(let i of[...e,...t]){let s=`${i.flag}|${i.short??""}`;r.has(s)||(r.add(s),n.push(i))}return zo(n)}function Fx(e){let t=Sa(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function Dx(e,t,n,r){let i=(n??[]).map(Fx),s=t==="extension"&&(n!==void 0||Px(e,r));return{flags:i,inherited:s?{inherited_flags:fm({readOutput:Ux(e,r)})}:{}}}function Vh(e,t){let n=P(e);return t.find(r=>P(r.command)===n)}function Px(e,t){return Vh(e,t)!==void 0}function Ux(e,t){return Vh(e,t)?.read_output!==void 0}function jx(e,t,n,r){return r&&t!=="extension"&&pm(e)?{inherited_flags:_m(e,hm(n),{expectHashAdmissible:Gp(P(e))})}:{}}function qx(e,t,n,r,i){let s=new Map(t);for(let{alias:o,canonical:a}of ze){let c=t.get(a)??t.get(o);c&&(s.set(o,c),s.set(a,c))}return e.map(o=>{let a=Nx(o),c=a?Hh(o):[],d=n.get($x(o))??[],l=s.get(o),u=Mh(c,d),m=c.length>0&&(l?.flags.length??0)>0?"mixed":a?"core":"extension",_=Dx(o,m,l?.flags,i),h=Mh(u,_.flags);return{command:o,flags:h,..._.inherited,...jx(o,m,h,r),...r?{canonical_command:Xh(o),visibility:Yh(o,i),positionals:lm(o)?.slots??[],flag_invocations:f_(o,h)}:{},provider:m,extension_sources:l?.sources}}).sort((o,a)=>o.command.localeCompare(a.command))}function Gx(e,t=Tt){let n=new Set(e),r=new Map;for(let i of Kh){let s=i.aliases.filter(o=>n.has(o));r.set(i.canonical,{canonical:i.canonical,aliases:s,contracts:[]})}for(let i of t){if(!n.has(i.canonical)||i.registration==="commander"&&!n.has(i.alias))continue;let s=r.get(i.canonical)??{canonical:i.canonical,aliases:[],contracts:[]};s.aliases.includes(i.alias)||s.aliases.push(i.alias),s.contracts.push(i),r.set(i.canonical,s)}return[...r.values()].map(({contracts:i,...s})=>i.length===0?s:{...s,contracts:i}).sort((i,s)=>i.canonical.localeCompare(s.canonical))}function Kx(){return{create_string_options:of,create_repeatable_options:af,update_string_options:cf,update_repeatable_options:df,list_string_options:ef,search_string_options:tf,calendar_string_options:nf,context_string_options:rf,activity_string_options:sf}}function Fh(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=rn(e,"create",n),i=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(i.map(a=>ve("create",a)))].sort((a,c)=>a.localeCompare(c)),o=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:i,required_flags:s,required_type_options:o,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function zx(e){let t={},n={};for(let r of[...e.types].sort((i,s)=>i.localeCompare(s))){let i=e.by_type[r];t[r]=Fh(i,"strict"),n[r]=Fh(i,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Wx(e,t){let n=_r(e);if(n.length===0)return e;let r=!1,i=n.map(s=>{let o=s.properties;if(typeof o!="object"||o===null)return s;let a=o.action;return typeof a!="object"||a===null||a.const!=="create"?s:(r=!0,{...s,"x-create-required-options":t})});return r?{...e,oneOf:i}:e}function Bx(e){let t=ts(e.action)!==void 0||ts(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,i=e.schemaOnly===!0,s=e.flagsOnly===!0,o=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=ts(e.action),l=ts(e.command),u=!r&&!c&&!i&&!s&&!o&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:r,schemaOnly:i,flagsOnly:s,availabilityOnly:o,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function Hx(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new f("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",p.USAGE)}async function Vx(e,t=R){try{return await t(e)}catch{return structuredClone(Rt)}}async function Yx(e,t,n){let r=await Vx(t),i=await Tx(e),s=F(r,i.registrations??M()),o=$t(r.schema),a=kx(i);return{settings:r,runtimeProbe:i,typeRegistry:s,statusRegistry:q(r.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:Mx(o),createRequiredOptionContracts:zx(s),extensionContracts:a,mergedExtensionContracts:Rx(a.filter(c=>rs(n,c.command,a))),extensionFlagMap:Bh(i.flagRegistrations)}}function Dh(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ns.has(e.selectedAction)||e.selectedCommand!==void 0&&vt.has(P(e.selectedCommand)))}function Xx(e,t){let n=Ix(t,{includePackageOwnedActions:Dh(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Yd);return n.filter(i=>!r.has(i.action)&&(e.fullOutput||(t.find(s=>s.action===i.action)?.tier??xa(i.action))!=="internal"))}return Dh(e)&&e.selectedCommand!==void 0&&vt.has(P(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:_x(P(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function Jx(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new f(`Unknown action: "${e.selectedAction}".`,p.USAGE)}function Qx(e,t){return[...new Set([...We.filter(n=>!vt.has(P(n))),...[...fr.keys()].filter(n=>!vt.has(P(n))),...e.flatMap(n=>n.command_path?at(n.command_path).filter(r=>n.provider==="extension"||!vt.has(P(r))||t.some(i=>i.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let i=ze.find(s=>s.alias===r||s.canonical===r);return i===void 0?[r]:[i.alias,i.canonical]}))])].map(n=>pe(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function Zx(e,t){let n=t.slice(0,ux),r=t.length-n.length,i=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),s=t.slice(0,mx),o=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new f(`Command "${e}" is a command namespace. Choose a concrete child command: ${i}.`,p.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:o,nextSteps:[`Retry with a child command, for example: ${o[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function eC(e,t){return new f(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm package install ${t} --project" and retry.`,p.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 tC(e){return new f(`Unknown command: "${e}".`,p.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 nC(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(s=>s.startsWith(`${e.selectedCommand} `));if(r.length>0)throw Zx(e.selectedCommand,r);let i=jh.get(P(e.selectedCommand));throw i?eC(e.selectedCommand,i):tC(e.selectedCommand)}function rC(e,t){let n=Xx(e,t.mergedExtensionContracts);Jx(e,n);let r=Qx(n,t.mergedExtensionContracts);nC(e,r);let i=e.selectedCommand?Gh.get(P(e.selectedCommand)):void 0,s=e.selectedCommand?n.filter(d=>i?d.action===i:hx(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.some(d=>d.action===e.selectedAction))throw new f(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,p.USAGE);let o=e.selectedAction?s.filter(d=>d.action===e.selectedAction):s,a=[...new Map(o.map(d=>Ox(d,t.runtimeProbe)).map(d=>[i?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:s,scopedActionDescriptors:o,selectedPackageOwnedAction:i,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function iC(e){return new Set(_r(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 i=r.const;return typeof i=="string"?i:null}).filter(t=>t!==null))}function sC(e){let t=gf,n=_r(t),r=iC(t),i=e.filter(s=>!r.has(s.action)).map(s=>Cx(s));return i.length>0?{...t,oneOf:[...n,...i]}:t}function Ph(e,t,n){let r=new Set(t.actionDescriptors.map(s=>s.action)),i=e.selectedAction?yx(n,e.selectedAction):e.selectedCommand?Fa(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):Fa(n,r);return e.runtimeOnly&&!e.selectedAction?Fa(i,new Set(t.actions)):i}function oC(e,t,n){let r=sC(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?Wx(Ph(e,n,r),t.createRequiredOptionContracts):Ph(e,n,r);return{mergedSchema:r,filteredSchema:s}}function aC(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?gx(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Yh(e,t){return t.find(n=>P(n.command)===P(e))?.tier??xa(e)}function rs(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||Yh(t,n)!=="internal"}function cC(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(Tt.filter(i=>i.hidden&&(i.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(i=>i.alias));if(e.summary&&!e.fullOutput)for(let i of Pa.keys())r.add(i);return t.filter(i=>!r.has(i)&&rs(e,i,n))}function Xh(e){let t=ze.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Pa.get(n)??n}var dC=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"]]),lC=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function uC(e,t){let n=Ih.get(P(e))??(e.includes(" ")?void 0:Ih.get(Xh(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(d=>at(d.command).some(l=>P(l)===P(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 i=e.split(" "),s=i.at(-1),o=i.slice(0,-1).join(" "),a=dC.get(s),c=lC.get(e)??o;return{intent:a===void 0||o.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function mC(e,t=[],n={}){let r=n.includeFormatBudgets??!0,i=n.includeIntentProvenance??!0;return[...new Set(e.map(pe))].filter(s=>s.length>0).sort((s,o)=>s.localeCompare(o)).map(s=>{let o=Mo(s,{generateFallback:!0}),a=s.split(" ")[0],c=Pa.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),d=new Set([...Hh(s).map(m=>m.flag),...t.filter(m=>at(m.command).some(_=>P(_)===P(s))).flatMap(m=>m.flags.map(_=>_.flag))]),l=(Th.get(P(s))??Th.get(c)??lx).filter(m=>d.has(m)),u=uC(s,t);return{command:s,intent:u.intent,...i||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:o.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...o.default_max_estimated_tokens_by_format}}:{}}})}function pC(e){return e.map(t=>({budget:Mo(t,{generateFallback:!0}),envelope:ih(t)}))}function fC(e){let t=new Map;for(let n of e){let r=ch(n),i=r===void 0?[p.SUCCESS,p.GENERIC_FAILURE,p.USAGE,p.NOT_FOUND,p.CONFLICT,p.DEPENDENCY_FAILED]:r.exit_codes,s=i.join(","),o=t.get(s)??{commands:[],exit_codes:i};o.commands.push(n),t.set(s,o)}return[...t.values()]}function _C(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>at(r.command).some(i=>P(i)===P(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(i=>at(i.command).some(s=>r.has(s)))}return t.extensionContracts.filter(r=>rs(e,r.command,t.extensionContracts))}function hC(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 gC(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=Tl);let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(i=>i.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(([i])=>r===void 0||i===r).map(([i,s])=>[i,[...new Set(s.map(o=>`--${o.cli_flag}`))].sort((o,a)=>o.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...qd],services:[...Gd],policy_modes:[...Kd],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Bd],trust_modes:[...zd],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Wd],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...rl],create_modes:[...il],close_validation_modes:[...sl],workflow_enforcement_modes:[...ol]},e.relationship_kind_contracts=[..._u,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(i=>i.definitions)].sort((i,s)=>i.kind.localeCompare(s.kind)).map(i=>({canonical:i.kind,aliases:[...i.aliases??[]],...i.inverse===void 0?{}:{inverse:i.inverse},ordering:i.ordering,hierarchy:i.hierarchy})))}function yC(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 wC="command_scoped; core rows list inherited host flags for pm contracts --command <command> --flags-only --json";function vC(e,t,n,r,i){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=qx(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let s=new Set(r);e.list_projections=Object.entries(dm).filter(([o])=>s.has(o)).map(([o,a])=>({command:o,default:a,brief_fields:[...cm,"priority"],compact_fields:[...am]})),t.selectedCommand===void 0&&(e.core_inherited_flags_omitted_reason=wC)}e.command_aliases=t.fullOutput?i:i.map(({canonical:s,aliases:o})=>({canonical:s,aliases:o})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function kC(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=Kx();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function bC(e,t,n,r){e.command_summaries=mC(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...iu],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(pe))].filter(i=>au(i)!==void 0).sort((i,s)=>i.localeCompare(s)).map(i=>({command:i,modes:[...cu(i).keys()]}))}:{}},e.grammar_contracts={nouns:Ut.nouns,shared_verbs:Ut.shared_verbs,scope_before_verb:Ut.scope_before_verb,visible_top_level_ceiling:Ut.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Ut.ceiling_raise_requires_pm_item,positional_shape_budget:Ut.positional_shape_budget,positional_shape_count:new Set(Ko.map(({slots:i})=>mm(i))).size,positional_action_count:Go.length,positional_action_parents:[...new Set(Go.map(({parent:i})=>i))].sort((i,s)=>i.localeCompare(s)),...r.includePositionalSignatures?{positional_signatures:Ko}:{}}}async function jP(e,t){let n=Bx(e);Hx(n);let r=I(process.cwd(),t.path),i=await Yx(t,r,n),s=rC(n,i),o=oC(n,i,s),a=aC(n,s),c=cC(n,a,i.extensionContracts),d=hC(n,o,s,c),l=_C(n,i,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&bC(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return d;let m=Gx(s.commandCatalog.filter(_=>rs(n,_,i.extensionContracts)));return n.flagsOnly&&!n.fullOutput||gC(d,i,n),yC(d,n,o,l),vC(d,n,i,c,m),kC(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...dr],gate_triggers:[...st]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=um.map(_=>({..._,reason:_.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=Rh(),d.context_intents=du(),d.read_output_dimensions=ou,d.error_codes=nh,d.command_output_contracts=pC(c),d.diagnostic_output_contracts=su,d.command_exit_contracts={vocabulary:Ea,command_sets:fC(c)}),d}import{createHash as Qh}from"node:crypto";import hr from"node:fs/promises";import gr from"node:path";function Oe(e,t){throw new f(e,p.USAGE,t)}var SC="2026-07-15T06:22:12.276Z",AC=Date.parse(SC),xC=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Jh=e=>typeof e=="string"?e:"",Zh=e=>{let t=e??{},n=Jh(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Jh(t.ts))>=AC);return xC[r][i]};function eg(e,t,n=20,r=new Set,i=!1){let s=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,_]of t.split(/\r?\n/).entries()){let h;try{h=JSON.parse(_)}catch{continue}d+=1;let g=Zh(h);if(g!=="attributed"){if(l+=1,g==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}a[g]+=1,i&&g==="actionable_unknown"&&o.push({item_id:e,line:m+1}),s.length<c&&s.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:s,samples_truncated:a.legacy_unknown+a.actionable_unknown>s.length,actionable_events:o}}var XP=(e,t,n=20,r=new Set)=>eg(e,t,n,r);function tg(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let s=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof s!="object"||s===null||!Array.isArray(s.events)))for(let o of s.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var yr=async(e,t=20,n=!1)=>{let r=gr.join(e,"history"),i;try{i=(await hr.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let s=new Set,o=[],a=[],c=0,d=0,l=0,u=0,m=0,_=0,h="_workspace.jsonl",g=new Set;if(i.includes(h))try{g=tg(await hr.readFile(gr.join(r,h),"utf8"))}catch{g=new Set}for(let w of i){let v;try{v=await hr.readFile(gr.join(r,w),"utf8")}catch{continue}let k=w.slice(0,-6),b=eg(k,v,t-o.length,g,n);c+=1,d+=b.checked_events,l+=b.unknown_event_count,u+=b.legacy_unknown_event_count,m+=b.actionable_unknown_event_count,_+=b.acknowledged_actionable_event_count,b.unknown_event_count>0&&s.add(k),o.push(...b.samples),n&&a.push(...b.actionable_events)}let y=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:_,affected_item_ids:[...s].sort((w,v)=>w.localeCompare(v)),samples:o,samples_truncated:y>o.length,...n?{actionable_events:a}:{}}};function CC(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function EC(e){try{return tg(await hr.readFile(gr.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function RC(e){return(e.item_id===Ft||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function TC(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{Oe(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Zh(i)!=="actionable_unknown"&&Oe(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:Qh("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function ng(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&Oe("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&Oe("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Oe("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let s=CC(t.all_actionable===!0?(await yr(e,0,!0)).actionable_events:r),o=await EC(e),a=new Map;for(let m of s)if(RC(m)||Oe(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!a.has(m.item_id))try{a.set(m.item_id,(await hr.readFile(gr.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Oe(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=s.map(m=>TC(m,o,a.get(m.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Qh("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function JP(e,t,n=50){return(await ng(e,t,n)).plan}function IC(e,t){let n=e.length>0;return n&&t&&Oe("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&Oe("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:OC(e),all_actionable:t}}function OC(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),s=r===Ft||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!s||!Number.isSafeInteger(i)||i<1)&&Oe(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function QP(e,t){let n=IC(bf(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return NC(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:X(t,"planFingerprint")??X(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:X(t,"attributedAuthor")??X(t,"attributed_author")??void 0,reviewer:X(t,"reviewer"),reason:X(t,"reason")})}async function NC(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",s=await ng(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:p.SUCCESS,plan:s.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Oe("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Oe("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==s.plan.plan_fingerprint)throw new f("Author acknowledgment selection changed after preview; no history was mutated.",p.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let a=s.completeCoordinates.filter(({disposition:u})=>s.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:m})=>({item_id:u,line:m}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:p.NO_EFFECT,plan:s.plan};let c=await R(e),d=await cn({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:r}},message:i,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),l=s.plan.actionable_count>0&&s.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:p.PARTIAL_EFFECT}:{outcome:"effect",exit_code:p.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...l,plan:s.plan,history_path:d.historyPath}}async function rg(e,t,n){let r=await Pi(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Ui(r,"docs")}var is=1e6;function Ua(e,t=is,n=.8,r=!1){let i=new Set,s=(l,u)=>{if(i.add(`${l}:${u}`),i.size>t)throw new f(`Duplicate sweep exceeded ${t} candidate pairs; narrow it with statuses or since.`,p.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the duplicate query or increase its similarity threshold. No partial result was returned."})};if(r||n===0){for(let l=0;l<e.length;l+=1)for(let u=0;u<l;u+=1)s(u,l);return i}let o=new Map;for(let{prepared:l}of e)for(let u of l.tokens)o.set(u,(o.get(u)??0)+1);let a=new Map,c=new Map,d=new Map;for(let[l,{prepared:u}]of e.entries()){let m=[...u.tokens].sort((g,y)=>o.get(g)-o.get(y)||g.localeCompare(y)),_=m.length-Math.ceil(n*m.length-1e-12)+1,h=[{index:a,keys:[u.normalized],lengthFilter:!1},{index:c,keys:n<=.99?u.issueCodes:[],lengthFilter:!1},{index:d,keys:m.length===0?[""]:m.slice(0,_),lengthFilter:!0}];for(let g of h)$C(e,l,g,n,s)}return i}function $C(e,t,n,r,i){let s=e[t].prepared.tokens.length;for(let o of n.keys){let a=n.index.get(o)??[];for(let c of a){let d=e[c].prepared.tokens.length;n.lengthFilter&&Math.min(d,s)/Math.max(d,s)+1e-12<r||i(c,t)}a.push(t),n.index.set(o,a)}}var LC=3,ig=20,MC=.8,FC=100,sg=1e3;function og(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`,`likely_duplicate_recovery:${e.recovery.action}:${e.recovery.item_id}`]}async function DC(e,t){let n=e.items[0],r=I(t.cwd??process.cwd(),t.pmRoot),i=q((await R(r)).schema);return ae(n.status,i)?{action:"reopen",item_id:n.id,command:`pm item reopen ${n.id} "<recurrence reason>"`,args:["item","reopen",n.id,"<recurrence reason>"]}:{action:"reuse",item_id:n.id,command:`pm get ${n.id} --full`,args:["get",n.id,"--full"]}}function ja(e){let t=e.limit??LC,n=e.threshold??MC;if(!Number.isSafeInteger(t)||t<0||t>ig)throw new f(`Similarity limit must be an integer from 0 to ${ig}.`,p.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new f("Similarity threshold must be a number from 0 to 1.",p.USAGE);return{limit:t,threshold:n}}function ag(e){let t=e.limit??FC;if(!Number.isSafeInteger(t)||t<0||t>sg)throw new f(`Duplicate cluster limit must be an integer from 0 to ${sg}.`,p.USAGE);let n=e.since===void 0?void 0:new Date(e.since);if(n&&Number.isNaN(n.getTime()))throw new f("Duplicate cluster --since must be a valid ISO timestamp.",p.USAGE);return{limit:t,since:n}}async function PC(e,t){let n=I(e.cwd??process.cwd(),e.pmRoot),r=await R(n),i=F(r),s=e.statuses?.map(u=>u.trim().toLowerCase()).filter(Boolean);if(e.statuses!==void 0&&s?.length===0)throw new f("Duplicate cluster statuses must include at least one lifecycle status or all.",p.USAGE);let o=q(r.schema),a=s?.map(u=>{if(u==="all")return u;let m=re(u,o);if(!m)throw new f(`Unknown duplicate-cluster status "${u}". Allowed: all, ${o.definitions.map(_=>_.id).join(", ")}.`,p.USAGE);return m}),c=a?.includes("all")===!0;if(c&&a?.some(u=>u!=="all"))throw new f('The "all" status cannot be combined with other statuses.',p.USAGE);let d=c?void 0:a,l=d?new Set(d):void 0;return{items:(await he(n,r.item_format,i.type_to_folder,void 0,r.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())),statuses:d}}var wU={buildDuplicateClusters:dg,collectDuplicateCandidatePairs:Ua,createDuplicateUnionFind:cg};function cg(e){let t=Array.from({length:e},(r,i)=>i);return{parent:t,findRoot:r=>{let i=r;for(;t[i]!==i;)i=t[i];for(;t[r]!==r;){let s=t[r];t[r]=i,r=s}return i}}}function UC(e,t,n,r){let i=[];for(let s of t){let[o,a]=s.split(":").map(u=>Number.parseInt(u,10)),c=qo(e[o].prepared,e[a].prepared);if(c.score<n)continue;let d=r.findRoot(o),l=r.findRoot(a);d!==l&&(r.parent[l]=d),i.push({left_id:e[o].item.id,right_id:e[a].item.id,...c})}return i}function dg(e,t,n,r){let i=new Map;for(let a of e.keys()){let c=n.findRoot(a),d=i.get(c)??[];d.push(a),i.set(c,d)}let s=new Map(e.map(({item:a},c)=>[a.id,n.findRoot(c)])),o=new Map;for(let a of t){let c=s.get(a.left_id),d=o.get(c)??[];d.push(a),o.set(c,d)}return[...i.values()].filter(a=>a.length>1).map(a=>{let c=(o.get(n.findRoot(a[0]))??[]).sort((d,l)=>l.score-d.score||d.left_id.localeCompare(l.left_id)||d.right_id.localeCompare(l.right_id));return{id:e[a[0]].item.id,items:a.map(d=>{let l=e[d].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((a,c)=>c.max_score-a.max_score||a.id.localeCompare(c.id)).slice(0,r)}function jC(e,t,n,r,i){return t.filter(s=>!n.has(s.id)).map(s=>({id:s.id,title:s.title,status:s.status,type:s.type,...jo(e,s.title)})).filter(s=>s.score>=r).sort((s,o)=>o.score-s.score||s.id.localeCompare(o.id)).slice(0,i)}async function qC(e,t={}){let n=e.title.trim();if(n.length===0)throw new f("Similarity candidate title must not be empty.",p.USAGE);let{limit:r,threshold:i}=ja(t),s=I(t.cwd??process.cwd(),t.pmRoot),o=await R(s),a=F(o),c=await Ai(s,Object.values(a.type_to_folder)),d=Po(n),l=c&&d.length>0?await Gu({pmRoot:s,expectedSourceCursor:c.source_cursor,query:d.map(_=>`"${_.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(r*10,50)}):null,u=l===null?await he(s,o.item_format,a.type_to_folder,void 0,o.schema):l.items,m=jC(n,u,new Set(e.excludeIds??[]),i,r);return{items:m,count:m.length,threshold:i,source:l?"persistent_index":"metadata_fallback"}}function GC(e,t={}){let{threshold:n}=ja({...t,limit:void 0}),{limit:r}=ag(t),i=new Set;for(let l of e){if(!l.id.trim()||i.has(l.id))throw new f("Duplicate analysis requires unique non-empty item ids.",p.USAGE);i.add(l.id)}let s=[...e].sort((l,u)=>l.id.localeCompare(u.id)).map(l=>({item:l,prepared:Uo(l.title)})),o=Ua(s,is,n,t.exhaustive===!0),a=cg(s.length),c=UC(s,o,n,a),d=dg(s,c,a,r);return{clusters:d,count:d.length,threshold:n,cost:{item_count:s.length,algorithm:t.exhaustive===!0||n===0?"exhaustive":"prefix_exact",possible_pairs:s.length*(s.length-1)/2,pair_limit:is,recall_guarantee:"exact",candidate_pairs:o.size,scored_pairs:o.size}}}async function lg(e={}){ja({...e,limit:void 0});let{since:t}=ag(e),{items:n,statuses:r}=await PC(e,t);return{...GC(n,e),source:"metadata_scan",filters:{statuses:r??null,since:e.since??null}}}async function qa(e,t){if(t.mode==="off")return;let n=await qC(e,t);if(n.count===0)return;let r=await DC(n,t),i=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!i){let s=n.items.map(a=>`${a.id} (${a.status}): ${a.title}`).join("; "),o=r.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new f(`Likely duplicate item(s) found: ${s}. ${o} or pass --allow-duplicate with explicit intent.`,p.CONFLICT,{code:"likely_duplicate",required:`${o}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:r.command,suggested_retry_args:r.args}})}return{mode:t.mode,bypassed:i,result:n,recovery:r}}async function AU(e,t={}){let n=await lg({pmRoot:I(process.cwd(),e.path),exhaustive:t.exhaustive,...t.status===void 0?{}:{statuses:t.status.flatMap(r=>r.split(",").map(i=>i.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(r=>{let i=r.id;return{...r,canonical_id:i,close_command:`pm close <duplicate-id> --duplicate-of ${i}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import{execFile as KC}from"node:child_process";import ug from"node:path";function mg(e,t){return new Promise((n,r)=>{KC("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,s)=>{i?r(i):n(s)})})}function pg(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function TU(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(pg(n),!n)throw new RangeError("Source line range must use start:end.");return n}function zC(e){let t=new Map;for(let n of e.split(`
|
|
6
|
+
`)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function WC(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let s=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,a)=>o.localeCompare(a));n.set(i,s)}return n}async function BC(e){let t=ug.relative(e.workspaceRoot,ug.resolve(e.workspaceRoot,e.sourcePath)),n=await mg(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await mg(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:zC(n),commitItems:WC(r),available:!0}}function HC(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let s=i.source===t,o=s?i.target:i.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let a=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,s?i.kind:a.inverse??i.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function VC(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let s=t.shift(),o=s.kinds.length;i!==void 0&&o>=i||o>=e.maxDepth||(i=HC({current:s,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((s,o)=>s.nodes.join("\0").localeCompare(o.nodes.join("\0"))),r}function YC(e,t,n){let r=Rf(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=VC({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(a=>[a.id,a]))}),s=i[0];if(!s)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(i.map(a=>a.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:s.nodes,kinds:s.kinds,alternative_decision_ids:o.slice(1)}}async function XC(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await BC({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function JC(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function QC(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function fg(e){pg(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await XC(e),r=QC(n),i=new Map;for(let s of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(s.item.id)),a=o.reduce((l,[,u])=>l+u,0),c=YC(s.item.id,e.corpus,t),d=JC({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});i.set(s.item.id,{score:a*100+s.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(s.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...s.files.map(l=>({kind:"linked_file",reference:l.path})),...o.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:s.item.value?.trim()||null,why_now:s.item.why_now?.trim()||null,outcome:s.item.outcome?.trim()||null,objective:s.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}import _g from"node:fs/promises";import Ne from"node:path";var ZC=32768;function Ga(e){return hn(Ne.normalize(e))}async function ss(e){try{return await _g.realpath(e)}catch{return Ne.resolve(e)}}function xn(e,t){let n=Ne.isAbsolute(e.path)?Ne.resolve(e.path):Ne.resolve(t,e.path);return`${Ga(n)}::${e.scope}`}function os(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>os(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))os(i,t?`${t}.${r}`:r,n)}function eE(e){let t=[];return os(e.metadata,"metadata",t),os(e.body,"body",t),t}function tE(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function nE(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let s=new Set,o=i.value.slice(0,ZC);for(let[a,c]of[[n,i.value],[r,o]]){a.lastIndex=0;for(let d of c.matchAll(a)){let l=tE(d[0]);!l||s.has(l)||(s.add(l),t.push({field:i.field,value:l}))}}}return t}async function rE(e,t,n=t){let r=Ne.isAbsolute(e)?Ne.resolve(e):Ne.resolve(n,e),i;try{i=await _g.stat(r)}catch{return}if(!i.isFile())return;let[s,o]=await Promise.all([ss(t),ss(r)]);if(Ao(s,o)){let a=Ne.relative(s,o);return!a||a.startsWith("..")||Ne.isAbsolute(a)?void 0:{path:Ga(a),scope:"project"}}return{path:Ga(r),scope:"global"}}async function iE(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>xn(c,t))),i=new Map,s=nE(eE(e)),o=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{o.set(c,await rE(c,t,n))}));let a=s.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:d}of a){if(!d)continue;let l=xn(d,t),u=i.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(l,u)}return[...i.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:r.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function hg(e,t,n){let r=await Pi(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Ui(r,"files")}async function sE(e,t){let n=await ss(t),r=await Promise.all(e.map(async s=>{let o=s.trim();if(!o)throw new f("Files lookup paths must not be empty.",p.USAGE);if(!Ne.isAbsolute(o))return hn(o);let a=await ss(o);return Ao(n,a)?hn(Ne.relative(n,a)):hn(a)})),i=[...new Set(r)].sort((s,o)=>s.localeCompare(o));if(i.length===0)throw new f("Files lookup requires at least one path.",p.USAGE);return i}function oE(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new f(`Files lookup ${r} must be a non-negative integer.`,p.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function gg(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function yg(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function aE(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(hn(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(yg)}async function cE(e){if(e.explain)return fg({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function dE(e){if([e.strictRead,e.noTruncate,e.explain,Au()].includes(!0))return null;let t=await Ai(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?qu({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function lE(e){let t=[],n=await xi(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=aE({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&i.length>0)throw new f(`Files lookup could not read every item: ${i.join("; ")}`,p.GENERIC_FAILURE);let s=await cE({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(s?[...r].sort((c,d)=>{let l=s.explanations.get(d.item.id).score-s.explanations.get(c.item.id).score;return l!==0?l:yg(c,d)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<r.length,truncated:e.offset+a.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:gg(c.item),files:c.files,...s?{traceability:s.explanations.get(c.item.id)}:{}})),...s?{traceability_receipt:s.receipt}:{}}}async function HU(e,t){let n=I(process.cwd(),t.path),r=_t(n);await z(n);let i=await sE(e.paths,r);if(e.lineRange&&i.length!==1)throw new f("Files lookup line attribution requires exactly one source path.",p.USAGE);let s=await R(n),o=F(s,M()),{offset:a,limit:c}=oE(e),d=await dE({pmRoot:n,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:i,total:d.total,count:d.matches.length,offset:a,limit:c,has_more:a+d.matches.length<d.total,truncated:a+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:gg(l.item),files:l.files}))}:lE({pmRoot:n,settings:s,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function VU(e,t,n){let r=I(process.cwd(),n.path),i=_t(r);await z(r);let s=await R(r),o=F(s,M()),a=await V(r,e,s.id_prefix,s.item_format,o.type_to_folder);if(!a)throw new f(`Item ${e} not found`,p.NOT_FOUND);let c=await le(a,{schema:s.schema}),d=await iE(c.document,i,process.cwd()),l=d.filter(x=>x.status==="addable"),u=d.filter(x=>x.status==="already_linked"),m=t.apply===!0,_=t.note?.trim()||"discovered from item text";if(!m||l.length===0){let x=c.document.metadata.files??[];return{id:a.id,files:x,changed:!1,apply:m,count:x.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let h=H(t.author,s.author_default),g=l.map(x=>({path:x.path,scope:x.scope,note:_})),y=[],w=new Set,v=await Ie({pmRoot:r,settings:s,id:e,op:"files_discover",author:h,message:t.message??"Discover referenced file links",force:t.force,mutate(x){let D=[...x.metadata.files??[]],j=new Set(D.map(K=>xn(K,i)));y=[],w.clear();for(let[K,Ge]of g.entries()){let ge=xn(Ge,i);j.has(ge)||(D.push(Ge),j.add(ge),y.push(Ge),w.add(K))}let T=Df(D),E=t.appendStable?T:Ff(T);return E.length>0?x.metadata.files=E:delete x.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==g.length?[`files_discover_skipped_existing:${g.length-y.length}`]:[]}}}),k=v.item.files??[],b=new Set(y.map(x=>xn(x,i))),A=k.filter(x=>b.has(xn(x,i))),C=l.filter((x,D)=>!w.has(D)),S=[...u,...C];return{id:v.item.id,files:k,changed:A.length>0,apply:!0,count:k.length,candidate_count:d.length,addable_count:l.length,added_count:A.length,skipped_existing_count:S.length,candidates:d,added:A,skipped_existing:S}}var wr=["software-delivery","research","agent-evaluation","operations"];function wg(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function as(e,t,n,r,i){let s=`preset-${e}`,o=i.map(c=>({id:`${s}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),a=o.map(c=>wg(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:a,gates:[{id:`${s}-readiness`,description:n,assertion_ids:a.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function cs(e,t){return e==="software-delivery"?as(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?as(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?as(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):as(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function vg(e,t,n,r={}){return Ma(e,cs(t,n).declarations,r)}async function kg(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(s=>!n.has(s.status))};return await Promise.all(["files","tests","docs"].map(async s=>{let o={id:`derived-active-missing-${s}`,description:`Observed active items missing ${s} evidence.`,source:{kind:"links",link:s,state:"missing"}},c=(await La(o,r)).value,d=wg(`${o.id}-ceiling`,o.id,t,c,"observe"),l=`active-missing-${s}`;return{id:l,population_size:r.items.length,scope:{kind:"active"},observed:c,declarations:{measurements:[o],assertions:[d],gates:[{id:`derived-${l}`,description:`Observe the accepted ${s} evidence baseline.`,assertion_ids:[d.id],triggers:["ci","scheduled"]}]}}}))}function bg(e,t,n={}){return Ma(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function Sg(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return es(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Cg from"node:fs/promises";import{createRequire as uE}from"node:module";import Ce from"node:path";function Ag(e,t){let n=Ce.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Ce.sep}`)&&!Ce.isAbsolute(n))return n.split(Ce.sep).join("/");let r=Ce.resolve(e),i=0xcbf29ce484222325n;for(let o=0;o<r.length;o+=1)i^=BigInt(r.charCodeAt(o)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${Ce.basename(Ce.dirname(e))}/package.json`}function mE(e){return e.includes(`${Ce.sep}.pnpm${Ce.sep}`)?"pnpm":e.includes(`${Ce.sep}node_modules${Ce.sep}`)?"npm":"other"}async function xg(e){try{let t=JSON.parse(await Cg.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function Ka(e){try{return await Cg.realpath(e)}catch{return Ce.resolve(e)}}async function Eg(e,t,n=yu(import.meta.url,["../../.."])){let r=await Ka(t),i=await Ka(Ce.join(n,"package.json")),s=await xg(i),o=new Map;s!==void 0&&o.set(i,{version:s,path:Ag(i,r),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=uE(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await Ka(l),m=await xg(u);if(m===void 0)continue;let _=u,h=o.get(_);if(h){h.consumers.includes(d.name)||(h.consumers.push(d.name),h.consumers.sort((g,y)=>g.localeCompare(y)));continue}o.set(_,{version:m,path:Ag(u,r),layout:mE(u),consumers:[d.name]})}catch{}let a=[...o.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=s===void 0?[]:a.filter(d=>d.version!==s);return{host_version:s??null,copies:a,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${s}:${d.version}:${d.consumers.join("+")}`)}}var Rg=25;function pE(e,t,n=[]){let r=["list","--status",e,...n],i=["--assignee-filter","unassigned"],s=["--updated-before",`-${t}h`];return{unowned:L([...r,...i]),idle:L([...r,...s]),stale:L([...r,...i,...s])}}function Tg(e,t){let n=e.items.length>Rg;return{count:e.count,items:e.items.slice(0,Rg),...n?{truncated:!0}:{},sweep:t}}function Ig(e,t,n=[]){let r=pE(t.in_progress,e.threshold_hours,n),i=(o,...a)=>`pm ${o} <id>${[...a,...n].map(c=>` ${Jr(c)}`).join("")}`,s=[...e.unowned.count>0?[`in_progress_unowned:${e.unowned.count}`]:[],...e.idle.count>0?[`in_progress_idle:${e.idle.count}`]:[]];return{warnings:s,details:s.length===0?void 0:{threshold_hours:e.threshold_hours,threshold_setting:"mutation_guard.stale_in_progress_hours",unowned:Tg(e.unowned,r.unowned),idle:Tg(e.idle,r.idle),item_remedies:{claim:i("claim"),take_over_idle:i("claim","--takeover-stale"),return_to_open:i("update","--status",t.open)}},remediation:{stale_in_progress_items:r.stale,in_progress_unowned:r.unowned,in_progress_idle:r.idle}}}import{createHash as fE}from"node:crypto";import ds from"node:path";var _E="2026-08-09T16:15:18.000Z",Ng=Symbol("pre-durable-disposition-eligible");function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function za(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function Og(e){return ct(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function $g(e,t){if(typeof e!="string")return!1;let n=ds.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!ds.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(ds.posix.basename(n)===`${t}.toon`||ds.posix.basename(n)===`${t}.md`)}function hE(e,t){return typeof e.receipt_id=="string"&&or(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&$g(e.item_path,t)}function Lg(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,s=Array.isArray(i)?new Set(i.flatMap(o=>Og(o)?[o.field]:[])):new Set;return za(t)&&za(n)&&za(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(Og)&&s.size===i.length&&t.length===s.size&&t.every(o=>s.has(o))}function gE(e,t){return hE(e,t)&&Lg(e)}function yE(e,t){return typeof e.receipt_id=="string"&&or(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&$g(e.item_path,t)&&Lg(e)}function wE(e){return e[Ng]===!0}function Mg(e,t){if(!ct(e)||!ct(e.context))return[];let n=e.context.merge;return!ct(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!ct(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:gE(r,t),[Ng]:yE(r,t),...typeof e.ts=="string"&&Eo(e.ts)?{eventTimestamp:e.ts}:{}}])}function Fg(e,t,n){if(!ct(e)||e.op!=="merge_reconcile")return[];if(!ct(e.context)||!ct(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!ct(i)||typeof i.receipt_id!="string"||!or(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!Eo(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function Dg(e,t,n=[]){let r=new Map;for(let o of n){let a=`${o.itemId}\0${o.originalHistoryLine}\0${o.receiptId}\0${o.originalEventTimestamp}`;r.set(a,Math.max(r.get(a)??0,o.auditHistoryLine))}let i=o=>wE(o)&&o.eventTimestamp!==void 0&&El(o.eventTimestamp,_E)<0&&(r.get(`${o.itemId}\0${o.line}\0${o.receiptId}\0${o.eventTimestamp}`)??0)>o.line;return{missing:e.filter(o=>!o.legacySummaryAccepted&&!t.has(o.receiptId)&&!i(o)).map(o=>({item_id:o.itemId,history_line:o.line,...or(o.receiptId)?{receipt_id:o.receiptId}:{receipt_reference_hash:fE("sha256").update(o.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(o=>o.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}function ls(e,t,n=25){let r=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,a)=>o.localeCompare(a)),i=new Set(r),s=t.filter(o=>{let a=Fe(o.status,e);return a!==void 0&&i.has(a)}).map(o=>o.id).sort((o,a)=>o.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:s.length,affected_item_ids:s.slice(0,n),affected_item_ids_truncated:s.length>n}}function us(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}function Ug(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Pe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function vE(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function vr(e,t){let n=Pe(e,t);return{...n,sample:n.sample.map(r=>vE(r))}}function W(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function kE(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var bE={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:W(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:W(e.missing_required,t),missing_optional:W(e.missing_optional,t),missing:W(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:W(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:vr(e.discovered,t),effective:vr(e.effective,t),loaded:vr(e.loaded,t),failed:Pe(e.failed,t),warnings:W(e.warnings,t),activation:{failed:Pe(n.failed,t),warnings:W(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:kE(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Pe(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:W(n.affected_item_ids,t),samples:Pe(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:W(e.item_unreadable,t),item_conflict_markers:Pe(e.item_conflict_markers,t),item_parse_failures:W(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:W(n.tracked_paths,t)},history_unreadable:W(e.history_unreadable,t),history_conflict_markers:Pe(e.history_conflict_markers,t),history_invalid_json:Pe(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:W(n.candidate_items,t),confirmed_items:W(n.confirmed_items,t),resolved_false_positive_items:W(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:W(e.drifted_items,t),merge_receipt_attributed_items:W(e.merge_receipt_attributed_items,t),missing_streams:W(e.missing_streams,t),unreadable_streams:W(e.unreadable_streams,t),hash_mismatches:W(e.hash_mismatches,t),chain_mismatches:W(e.chain_mismatches,t),version_skews:W(e.version_skews,t),workspace_state_mismatches:W(e.workspace_state_mismatches,t),workspace_state_missing:W(e.workspace_state_missing,t),workspace_state_unreadable:W(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:W(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:W(e.stale_items_after,t),skipped:e.skipped})};function Wa(e,t){let n=bE[e.name];return n?n(e.details,t):e.details}function jg(e){return{disabled_by_flag:e.details.disabled_by_flag,loaded_count:Array.isArray(e.details.loaded)?e.details.loaded.length:0,failed_count:0,warning_count:0,restore_with:"pm health --full"}}function SE(e){if(e.name==="extensions"&&e.status==="ok")return jg(e);let t=Wa(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function Ba(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(r=>n.has(r.warning))}function AE(e){let t=W(e.warnings,8);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:SE(n)})),warnings:t.sample,findings:Ba(e,t.sample),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8},generated_at:e.generated_at}}function Pg(e){return e.details.skipped===!0}function xE(e){let t=W(e.warnings,8),n=e.checks.filter(Pg).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!Pg(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:Ba(e,t.sample),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8,omitted_checks:n},generated_at:e.generated_at}}function CE(e,t,n){return n?xE(e):t.brief===!0?AE(e):t.full===!0?e:{...e,checks:e.checks.map(r=>r.name==="extensions"&&r.status==="ok"?{...r,details:jg(r)}:r),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function Ha(e,t,n){let r=e.warning_count??e.warnings.length,i=e.warnings.slice(0,100),s={...e,warning_count:r,warning_limit:100,warnings_truncated:r>100,warnings:i,findings:Ba(e,i)},o=CE(s,t,n);return{...o,warning_count:r,warning_limit:100,warnings_truncated:r>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:r,warnings_truncated:r>o.warnings.length}}:{}}}import dt from"node:fs/promises";import ce from"node:path";import Cn from"node:fs/promises";import kr from"node:path";function qg(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:s,ttl_seconds:o}=n;return typeof r!="string"||typeof i!="string"||typeof s!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:r,owner:i,created_at:s,ttl_seconds:o,pid:n.pid,host_identity:n.host_identity,process_start_identity:n.process_start_identity}}function EE(e,t,n){let r=qg(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let s=n-i,o=Math.floor(s/1e3),a=s>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:o,stale:a,reason:a?"expired":"active"}}}async function Gg(e,t,n){let r=EE(e,t,n);if(r.detail!=="active")return r;let i=qg(t),s=await Vl(i);return s==="unknown"?r:{detail:s==="dead"?"owner_dead":"active",entry:{...r.entry,owner_state:s,pid:i.pid,...s==="dead"?{stale:!0,reason:"owner_dead"}:{}}}}async function RE(e,t,n){let r=await Xl(e,"gc");if(r===null)return!1;try{let i;try{i=await Cn.readFile(e,"utf8")}catch(s){if(B(s))return!0;throw s}if(i!==t)return!1;n&&await Jl(e,t);try{await Cn.unlink(e)}catch(s){if(!B(s))throw s}return!0}finally{await r()}}function TE(e,t,n){t==="owner_dead"&&(e.owner_dead_lock_samples??=[],e.owner_dead_lock_samples.length<20&&e.owner_dead_lock_samples.push(n)),t==="active"?e.active_lock_count+=1:t==="expired"||t==="owner_dead"?e.stale_lock_count+=1:e.unparseable_lock_count+=1}async function Kg(e,t){let n=t??Date.now(),r=kr.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},s;try{s=(await Cn.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(o){if(B(o))return i;throw o}for(let o of s){let a;try{a=await Cn.readFile(kr.join(r,o),"utf8")}catch(l){if(B(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c,entry:d}=await Gg(o,a,n);TE(i,c,d)}return i}async function IE(e,t,n,r,i,s,o){if(!t.dryRun){try{if(!await RE(n,s,o.reason==="owner_dead")){e.warnings.push(`lock_changed_or_busy:${i}`),e.retained.push(r),e.entries.push(o);return}}catch{e.warnings.push(`lock_remove_failed:${i}`),e.retained.push(r),e.entries.push(o);return}if(t.hooks?.onWrite){let a=await t.hooks.onWrite(n);e.warnings.push(...a)}}e.removed.push(r),e.entries.push(o)}async function zg(e,t){let{hooks:n}=t,r=t.now??Date.now(),i=kr.join(e,"locks"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]};await Hl(e,kr.join(i,"gc.lock"),"gc");let o;try{o=(await Cn.readdir(i)).filter(c=>c.endsWith(".lock")).sort()}catch(a){if(B(a))return s;throw a}for(let a of o){s.scanned+=1;let c=kr.join(i,a),d=`locks/${a}`;if(n?.onRead){let m=await n.onRead(c);s.warnings.push(...m)}let l;try{l=await Cn.readFile(c,"utf8")}catch(m){if(B(m)){s.scanned-=1;continue}s.warnings.push(`lock_unreadable:${a}`),s.retained.push(d),s.entries.push({file:a,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let u=await Gg(a,l,r);if(u.detail==="unparseable_json"){s.warnings.push(`lock_unparseable:${a}`),s.retained.push(d),s.entries.push(u.entry);continue}if(u.detail==="invalid_timestamp"){s.warnings.push(`lock_invalid_timestamp:${a}`),s.retained.push(d),s.entries.push(u.entry);continue}if(u.detail==="active"){s.retained.push(d),s.entries.push(u.entry);continue}await IE(s,t,c,d,a,l,u.entry)}return s}var OE=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history record; the repair rebuilds the stream as one audited baseline from the on-disk item, and earlier versions stay unrecorded. When the stream was deleted by mistake, restore it from version control first (pm history-repair --all, with or without --append-only, rebuilds every missing stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"The item's history stream cannot be read; preview salvage, which removes lines that cannot hold a record and an invalid tail after a verified prefix, then apply it without --dry-run. Salvage refuses interior corruption, which needs recovery from version control, and a permission error needs the file's access fixed."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id> --append-only",summary:"The item's history chain is broken; append one record that bridges every break in the stream and keeps every recorded line byte-identical (pm history-repair <id> re-anchors the recorded entries instead). pm health previews the bridge for every chain mismatch, so a break a bridge cannot repair is reported as history_drift_chain_unbridgeable, and a stream no repair can keep as history_drift_unrepairable_stream, instead."},{code:"history_drift_chain_unbridgeable",command:"pm history-repair <id>",summary:"The item's history chain is broken in a way an append-only bridge cannot repair, for example a recorded patch that applies only on top of the unrecorded change (details.repair_refusals names the refusal reason); re-anchor the recorded entries instead (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unrepairable_stream",command:"pm history <id> --verify --full",summary:"Neither history repair can keep this stream (details.repair_refusals names both refusal reasons). Inspect it: a record that no longer matches its seal, or a malformed chain, needs the item's own stream restored from version control or a backup; a stream entry that is a link (reason stream_not_regular_file) needs the item's own stream restored as a regular file. Then run pm history <id> --verify --strict-exit."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_schema_field_option_collision",command:"pm schema rename-field <key> --to <new-key>",summary:"A custom field shadows a built-in option of a command it is registered for; rename it (item values move with it), or re-register the same key with another flag or a narrower --commands list."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Rebuild the history streams of the items without a history record as one audited baseline from each on-disk item."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"Preview salvage of the unreadable history streams, then apply it without --dry-run; interior corruption needs recovery from version control."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Va(e){if(typeof e!="string")return;let t=e.trim();for(let n of OE)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Ya(e){let t={};for(let n of e){let r=Va(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Wg(e){return Object.values(Ya(e))}import{execFile as NE}from"node:child_process";import{realpath as $E}from"node:fs/promises";import Bg from"node:path";import{promisify as LE}from"node:util";var ME=LE(NE),FE=32*1024*1024,DE=1e4,PE=["search/eval-queries.json"];function Xa(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}async function UE(e,t=$E){return t(e).catch(()=>Bg.resolve(e))}async function ms(e){let t=await bt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await UE(e),r=Xa(Bg.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=If.map(s=>`${r}/${Xa(s)}`);try{let{stdout:s}=await ME("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:FE,windowsHide:!0,timeout:DE}),o=new Set(PE.map(d=>`${r}/${d}`)),a=[...new Set(s.split("\0").filter(d=>d.length>0&&!o.has(Xa(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>Jr(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import Hg from"node:path";import{realpath as jE}from"node:fs/promises";async function Vg(e,t){let n=t===null?[]:await Kf(t,[Hg.relative(t,Hg.join(await jE(e),"merge-receipts","00000000-0000-4000-8000-000000000000.json")).replaceAll("\\","/")]);return{rules:n,warnings:n.length>0?[`merge_artifacts_ignored:${n.length}`]:[]}}async function Yg(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await fn(e,pn(n),{gitWorkspaceRoot:t});if(i.status==="ok")return{audit:i,count:0,warnings:[]};let s=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:s,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${s}`]:[]}}function Xg(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}import{lstat as qE}from"node:fs/promises";var Ja="history_drift_chain_mismatch",GE="history_drift_chain_unbridgeable",Zg="history_drift_unrepairable_stream",Jg="history_drift_hash_mismatch",ey="history_drift_missing_stream",KE=["history_drift_unreadable_stream",Zg,"history_drift_version_skew","history_drift_merge_receipt"],zE=new Set([Ja,ey]);function ps(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function WE(e,t){return e instanceof f?typeof e.context.reason=="string"?e.context.reason:e.code??t:t}async function Qg(e,t,n){try{await ji(e,{appendOnly:t,dryRun:!0},n);return}catch(r){return WE(r,t?"append_only_preview_failed":"rewrite_preview_failed")}}async function BE(e,t){let n=[];for(let r of ps(e.check.details.missing_streams)){let[i]=await Promise.allSettled([qE(Me(t,r))]);i.status==="fulfilled"&&i.value.isSymbolicLink()&&n.push({id:r,reason:"stream_not_regular_file",rewrite_refusal:"stream_not_regular_file"})}return n}async function ty(e,t,n){let r=[],i=new Set(ps(e.check.details.version_skews));for(let s of ps(e.check.details.chain_mismatches)){if(i.has(s))continue;let o=await Qg(s,!0,t);if(o===void 0)continue;let a=await Qg(s,!1,t);r.push({id:s,reason:o,...a===void 0?{}:{rewrite_refusal:a}})}return[...r,...await BE(e,n)]}function HE(e,t,n){for(let r of[Ja,ey]){if(!e.startsWith(`${r}:`))continue;let i=e.slice(r.length+1),s=t.get(i);return s===null?[]:[s===void 0?e:`${s}:${i}`]}return e.startsWith(`${Jg}:`)?n.has(e.slice(Jg.length+1))?[]:[e]:[e]}function ny(e,t){let n=ps(e.check.details.version_skews),r=new Map([...n.map(s=>[s,null]),...t.map(s=>[s.id,s.rewrite_refusal===void 0?GE:Zg])]),i=new Set([...n,...t.filter(s=>s.rewrite_refusal!==void 0).map(s=>s.id)]);e.warnings=e.warnings.flatMap(s=>HE(s,r,i)).sort((s,o)=>s.localeCompare(o)),t.length!==0&&(e.check.details={...e.check.details,repair_refusals:t})}function ry(e){if(KE.some(r=>Object.hasOwn(e,r)))return;let t=Object.keys(e),n=t.every(r=>zE.has(r));for(let r of t)n?e[r]="pm history-repair --all --append-only":r!==Ja&&(e[r]="pm history-repair --all")}var VE=5;function fs(e,t){let n=[],r={};for(let s of e){let o=ai(s);if(o.length!==0){for(let a of o)r[a.field]=(r[a.field]??0)+1;n.push({id:s.id,fields:o.map(a=>a.field),reasons:[...new Set(o.map(a=>a.reason))]})}}if(n.length===0)return;n.sort((s,o)=>s.id.localeCompare(o.id));let i=t?n.length:VE;return{details:{items:n.length,by_field:Object.fromEntries(Object.entries(r).sort(([s],[o])=>s.localeCompare(o))),rows:n.slice(0,i),truncated:n.length>i},warning:`validate_metadata_deferred_fields:${n.length}`}}var ay=25,XE=ce.join("runtime","telemetry","events.jsonl"),JE=ce.join("runtime","telemetry","state.json"),QE=2500,ZE=500,cy=sm-3,eR=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function rc(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("extension_disabled_pm_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("in_progress_unowned:")||e.startsWith("in_progress_idle:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function ic(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function En(e){return e.trim().toLowerCase()}function ec(e,t){let n=En(e),r=En(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function sc(e){try{return(await dt.stat(e)).isDirectory()}catch{return!1}}async function tR(e){let t=(await dt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>dt.readdir(ce.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>Gn.some(s=>i.name.endsWith(s))).map(i=>ce.parse(i.name).name)))}async function nR(e,t,n,r){let i=await Te({path:e,scope:"project"}),s=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!s)return{warnings:i,overThreshold:!1,classification:"live"};let o;try{o=await dt.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(s){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function rR(e,t,n){let r=ce.join(e,"history");if(!await sc(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await dt.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),o=t.enabled?t.max_entries:null,a=[],c=[],d=[],l=[];for(let u of i){let m=ce.join(r,u),_=u.slice(0,-6),h=await nR(m,_,t,n);a.push(...h.warnings),h.classification==="tombstone"&&d.push(_),h.classification==="orphaned"&&l.push(_),h.overThreshold&&c.push(_)}return{count:i.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:o,tombstones:d,orphaned:l}}function tc(e,t){return ce.relative(e,t).replaceAll("\\","/")}async function dy(e,t){let n=[...new Set(Object.values(t))].sort((i,s)=>i.localeCompare(s)),r=[];for(let i of n){let s=ce.join(e,i),o=[];try{o=await dt.readdir(s)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&B(a))continue;continue}for(let a of o)Gn.some(c=>a.toLowerCase().endsWith(c))&&r.push(ce.join(s,a))}return r.sort((i,s)=>tc(e,i).localeCompare(tc(e,s))),r}function iR(e){return!(typeof e=="object"&&e!==null&&"code"in e&&B(e))}function sR(e){let t=fs(e,!1);return t===void 0?{}:{curation:{deferred_fields:t.details}}}async function oR(e,t,n){let r=await dy(e,t),i=[],s=[],o=[],a=[],c=gt(M());for(let d of r){let l=tc(e,d),u;try{u=await dt.readFile(d,"utf8")}catch{i.push(l);continue}let m=an(u);if(m){s.push({path:l,...m});continue}try{let _=ci(u,{format:ul(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:si(_.metadata)})}catch{o.push(l)}}return{paths:r,unreadable:i,conflictMarkers:s,parseFailures:o,formatVersions:a}}async function aR(e){let t=ce.join(e,"history"),n=[],r=[],i=[],s=[],o=[],a=[];try{a=(await dt.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){iR(c)&&n.push("history")}for(let c of a){let d=c.slice(0,-6),l;try{l=await dt.readFile(ce.join(t,c),"utf8")}catch{n.push(d);continue}let u=an(l);if(u){r.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,_)=>{if(m.trim())try{let h=JSON.parse(m);s.push(...Mg(h,d).map(g=>({itemId:d,line:_+1,...g}))),o.push(...Fg(h,d,_+1))}catch{i.push({id:d,line:_+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:s,mergeReceiptDispositions:o}}function ly(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function cR(e,t,n,r,i,s){let o=await oR(e,t,n),a=await aR(e),c=oi(o.formatVersions,4,1),d=q(n),l=Fi(s,T=>ae(T,d),ie()),u=await ms(e),m=await bt(e),_=await Vg(e,m),h=await Yg(e,m,r,i),g=m===null?null:await _n(m),y=await gn(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(y.durable_receipt_ids),v=Dg(a.mergeReceiptReferences,w,a.mergeReceiptDispositions),k=v.missing,b=y.receipts.filter(T=>T.state==="pending"),{pendingDecisions:A,lossless:C}=yn(b),S=g?.status==="missing"&&g.missing_keys.length===5&&g.drifted_keys.length===0,x=[...o.unreadable.map(T=>`integrity_item_unreadable:${T}`),...o.conflictMarkers.map(T=>`integrity_item_conflict_marker:${T.path}:L${T.line}`),...o.parseFailures.map(T=>`integrity_item_parse_failed:${T}`),...a.unreadable.map(T=>`integrity_history_unreadable:${T}`),...a.conflictMarkers.map(T=>`integrity_history_conflict_marker:${T.id}:L${T.line}`),...a.invalidJson.map(T=>`integrity_history_invalid_json:${T.id}:L${T.line}`),...c.outdated.map(T=>`integrity_item_outdated_format_version:${T}`),...c.ahead.map(T=>`integrity_item_ahead_format_version:${T}`),...ly(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...g!==null&&g.status!=="ok"?[`merge_driver_configuration_${S?"missing":"drift"}:${g.missing_keys.length+g.drifted_keys.length}`]:[],...h.warnings,..._.warnings,...A.length>0?[`merge_decisions_unreviewed:${A.length}`]:[],...C.length>0?[`merge_receipts_pending:${C.length}`]:[],...Xg({invalidEvidenceCount:y.invalid_evidence_count,missingHistoryReferenceCount:k.length})],D=[...new Set(x)].sort((T,E)=>T.localeCompare(E)),j=D.filter(T=>!T.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:j.length===0?"ok":"warn",ok:j.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:a.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:a.unreadable.length,history_conflict_markers:a.conflictMarkers.length,history_invalid_json:a.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:g===null||g.status==="ok"?0:g.missing_keys.length+g.drifted_keys.length,merge_fence:h.count,ignored_merge_artifacts:_.rules.length,pending_merge_decisions:A.length,lossless_merge_receipts:C.length,invalid_merge_receipt_evidence:y.invalid_evidence_count,missing_merge_receipt_history_references:k.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.acceptedDispositionCount},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,...sR(s),hierarchy_integrity:{...l,relations:Pe(l.relations,8)},history_unreadable:a.unreadable,history_conflict_markers:a.conflictMarkers,history_invalid_json:a.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:g===null?null:{...g,required:i},merge_fence:h.audit,ignored_merge_artifacts:_.rules,pending_merge_decision_items:[...new Set(A.map(T=>T.item_id))].sort((T,E)=>T.localeCompare(E)),lossless_merge_receipt_items:[...new Set(C.map(T=>T.item_id))].sort((T,E)=>T.localeCompare(E)),invalid_merge_receipt_evidence_details:y.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:y.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:k.slice(0,100),missing_merge_receipt_history_reference_details_truncated:k.length>100}},warnings:D,gitWorkspaceRoot:m,pendingMergeReceipts:b}}function dR(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function lR(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:dR(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function uR(e,t){let n=te(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function mR(e){let n=te(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function pR(e){return te(e.reason)??te(e.error)??te(e.message)}function Qa(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function fR(e){let t=[],n=[],r=[];e.forEach((s,o)=>{let a=uR(s.definition,o),c=mR(s.definition);if(c==="applied"){t.push({layer:s.layer,name:s.name,id:a,status:c});return}if(c==="failed"){r.push({layer:s.layer,name:s.name,id:a,status:c,reason:pR(s.definition)});return}n.push({layer:s.layer,name:s.name,id:a,status:c})}),t.sort(Qa),n.sort(Qa),r.sort(Qa);let i=[...r.map(s=>`extension_migration_failed:${s.layer}:${s.name}:${s.id}`),...n.map(s=>`extension_migration_pending:${s.layer}:${s.name}:${s.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function uy(e,t,n,r,i,s,o,a,c){let d=[...new Set(e)].sort((y,w)=>y.localeCompare(w)),l=[...new Set(d.map(y=>ic(y)))].sort((y,w)=>y.localeCompare(w)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,m=c.length>0,_=m?"partial":"full",h=d.map(ca).filter(y=>y!==void 0),g=Nf(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return g&&h.push(g),t>0&&h.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&h.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&h.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&h.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&h.push(`Unknown extension capabilities detected. Allowed capabilities: ${Ld.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&h.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&h.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?h.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&h.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),h.length===0&&h.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:s,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:_,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:h}}async function _R(e,t,n){let r=await $f(_t(e)),i=await _i({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),s=i.loaded.map(S=>lR(S)),o=await Eg(i.loaded,_t(e)),a=await hi({...i,loaded:i.loaded}),[c,d]=await Promise.all([aa(i.roots.project),aa(i.roots.global)]);await Zp(e,a.registrations.migrations);let l=fR(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},m=new Set(c.state.entries.map(S=>En(S.name))),_=new Set(d.state.entries.map(S=>En(S.name))),h=[...new Map(i.loaded.filter(S=>!(S.layer==="project"?m:_).has(En(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,x)=>{let D=`${S.layer}:${S.name}`,j=`${x.layer}:${x.name}`;return D.localeCompare(j)}),g=h.map(S=>`${S.layer}:${S.name}`).sort((S,x)=>S.localeCompare(x)),y=h.filter(S=>ec(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,x)=>S.localeCompare(x)),w=h.filter(S=>!ec(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,x)=>S.localeCompare(x)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],k=[...r.warnings,...i.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...o.warnings],b=da(k),A=la(),C=uy(k,i.failed.length,a.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,g,y,w);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...i,loaded:s,warnings:k,activation:u,author_manifest:r,triage:C,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:A,capability_guidance:b,host_version_census:o}},warnings:k}}function nc(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Ug(e,ay);return{values:n.values,truncated:n.truncated,total:e.length}}function _s(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function hR(){let e=Ju();return e.source_context_source==="env_override"?e.source_context:null}function my(e){let t=0,n=0,r=0,i=0,s=0;for(let o of e.split(`
|
|
7
|
+
`)){let a=o.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,s=Math.max(s,d),d>=cy&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:s}}function gR(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function sy(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function yR(e,t){let n=Vn(e.telemetry.endpoint).trim();return!t||!e.telemetry.enabled||n.length===0||Pt().telemetry_disabled?void 0:{attempted:!0,...await py(n)}}function wR(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,s=n.last_failed_flush_at,o=s&&(!i||s>i),a=!i,c=t.validEntries>=ZE;return(o||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function vR(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function kR(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>im?[`telemetry_schema_version_behind:${t}`]:[]}function bR(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function SR(){return{...Pt(),pm_no_telemetry:_s("PM_NO_TELEMETRY"),telemetry_otel_disabled:_s("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:_s("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:hR()}}function AR(e,t){return e.telemetry.enabled&&t.validEntries>0}function xR(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}function oy(e){try{return decodeURIComponent(e)}catch{return e}}async function py(e){let t=e,n={};try{let r=new URL(e);r.pathname="/healthz",r.search="",r.hash="",(r.username.length>0||r.password.length>0)&&(n.authorization=`Basic ${Buffer.from(`${oy(r.username)}:${oy(r.password)}`).toString("base64")}`,r.username="",r.password=""),t=r.toString()}catch{}try{let r=await fetch(t,{method:"GET",headers:n,signal:AbortSignal.timeout(QE)});return{probe_url:wt(t),ok:r.ok,status:r.status,max_schema_version:(()=>{for(let i of eR){let s=r.headers.get(i)?.trim();if(s&&s.length>0)return s}})()}}catch(r){return{probe_url:wt(t),ok:!1,error:r instanceof Error?Qu(r.message.replaceAll(t,wt(t))):"probe_failed"}}}async function CR(e,t){let n=sy(await ee(e)),r=e===t?n:sy(await ee(t));return{runtimeState:n.runtimeState,spanState:r.runtimeState,stateParseFailed:n.stateParseFailed||r.stateParseFailed}}async function ER(e){let t=tt(process.cwd()),n=await R(t),r=ce.join(ce.dirname(ce.join(t,XE)),yt("events.jsonl")),i=ce.join(t,JE),s=ce.join(ce.dirname(i),yt("state.json")),o=await ee(r),a=o!==null,c=o?Buffer.byteLength(o,"utf8"):0,d=o?my(o):gR(),{runtimeState:l,spanState:u,stateParseFailed:m}=await CR(s,i),_=Vn(n.telemetry.endpoint).trim(),h=wt(_),g=await yR(n,e.checkTelemetry),y=[];m&&y.push("telemetry_state_invalid_json"),y.push(...wR(n,d,l),...vR(g),...kR(g),...bR(n,u));let w=AR(n,d),v=typeof u.pending_otel_spans=="number"?u.pending_otel_spans:0;return{check:{name:"telemetry",status:y.length===0?"ok":"warn",ok:y.length===0,details:{enabled:n.telemetry.enabled,capture_level:n.telemetry.capture_level,endpoint:h,global_pm_root:t,queue_path:r,queue_exists:a,queue_entries:d.validEntries,queue_draining:xR(w,y),queue_invalid_rows:d.invalidRows,queue_rows_total:d.totalRows,queue_size_bytes:c,queue_high_retry_entries:d.highRetryEntries,queue_high_retry_threshold:cy,queue_max_attempts:d.maxAttempts,runtime_state_path:s,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:v,last_otel_attempt_at:u.last_otel_attempt_at??null,last_otel_success_at:u.last_otel_success_at??null,last_otel_failure_at:u.last_otel_failure_at??null,last_otel_failure_error:u.last_otel_failure_error??null,endpoint_probe:g??{attempted:!1},env_overrides:SR()}},warnings:y}}async function RR(e){let t;try{t=await Kg(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,...t.owner_dead_lock_samples?{owner_dead_lock_samples:t.owner_dead_lock_samples,recovery_command:"pm gc --scope locks"}:{},unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function TR(e){let t="metadata",n=e.items,r=await sr(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),s=[],o=[];if(i.length>0){n=await rt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await sr(e.pmRoot,n),s=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,k)=>v.localeCompare(k));let w=new Set(s);o=i.filter(v=>!w.has(v))}let{missingStreams:a,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:_,workspaceStateMissing:h,workspaceStateUnreadable:g}=r,y=[...a.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),..._.map(w=>`history_drift_workspace_state_mismatch:${w}`),...h.map(w=>`history_drift_workspace_state_missing:${w}`),...g.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:s,resolved_false_positive_items:o,authoritative_item_source:i.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:_.length,workspace_state_missing:h.length,workspace_state_unreadable:g.length},missing_streams:a,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:_,workspace_state_missing:h,workspace_state_unreadable:g}},warnings:y}}function IR(e,t){let n=Du(e),r=Bu(n.settings),i=Hu(n.settings,t),s=r.active?Vu(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:s,semanticRuntimeAvailable:!!(r.active&&i.active)}}function OR(){return{refreshed:[],skipped:[],warnings:[]}}async function NR(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?OR():Xu(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function $R(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Yu(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function LR(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function MR(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function fy(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:Fo(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:Fo(r,e.vector_store?.adapter??null)}}function FR(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function DR(e,t,n){return e.enabled&&n.length>0&&t}async function PR(e,t,n,r,i){let s=IR(t,e),o=await Do(e),a=s.semanticRuntimeAvailable?ua(n,o.entries):[],c=await NR({pmRoot:e,snapshot:s,refreshPolicy:r,staleBefore:a}),d=await Do(e),l=s.semanticRuntimeAvailable?ua(n,d.entries):[],u=!s.runtimeDefaults.auto_ollama_defaults_applied,m=$R({strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:s.runtimeEmbeddingIdentity}),_=LR({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),h=nc(a,i),g=nc(l,i),y=DR(r,s.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:_.length===0?"ok":"warn",ok:_.length===0,details:{semantic_runtime_available:s.semanticRuntimeAvailable,compatibility_mode_auto_defaults:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:s.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:s.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:FR(r),...fy(t,s),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:s.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:ay,stale_items_before_total:h.total,stale_items_before:h.values,stale_items_before_truncated:h.truncated,refresh_attempted:y,refresh_skipped_reason:MR(r,s.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:g.total,stale_items_after:g.values,stale_items_after_truncated:g.truncated}},warnings:_}}function UR(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function _y(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new f("--check-only cannot be combined with --refresh-vectors",p.USAGE);if(n&&e.noRefresh===!0)throw new f("--no-refresh cannot be combined with --refresh-vectors",p.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var jR=new Set(["extensions","locks","search"]);function qR(e){let t=new Set(Dd.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(Pd));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of jR)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,s)=>i.localeCompare(s)),optionalDirs:[...n].sort((i,s)=>i.localeCompare(s)),optionalDirSet:n}}async function GR(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:s}=qR(t),o=[],a=[],c=[];for(let d of[...r,...i]){let l=ce.join(e,d);c.push(...await Te({path:l,scope:"project"})),!await sc(l)&&(s.has(d)?a.push(d):o.push(d))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:o,missingOptionalDirs:a,missingDirs:n?[...o,...a]:[...o],hookWarnings:c}}function hy(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=e.summary===!0||t,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function KR(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?he(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):rt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Za(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function zR(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function WR(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function BR(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var oc=e=>e.unknown_event_count??0,ac=e=>e.actionable_unknown_event_count??oc(e);function HR(e,t,n,r,i,s,o){let a=oc(r),c=ac(r),d=a>0,l=c>0,u=i.count>0||o!==void 0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...d?{author_attribution:r}:{},...i.count>0?{stale_in_progress:i}:{},...o===void 0?{}:{in_progress_work:o},...s.outcomes.length>0?{provenance_resolver_outcomes:s.outcomes}:{},...s.invalid_values.length>0?{provenance_invalid_values:s.invalid_values}:{},provenance_sample:s.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function gy(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function VR(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function YR(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function XR(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function yy(e){let t=new Map;for(let[i,s]of Object.entries(e.remediationSources))for(let o of s)t.has(o)||t.set(o,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let s=t.get(i)??"integrity",o=Va(i)?.code??ic(i),a=n.get(s)?.details,c=typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{},d=ca(i)??(o==="agent_guidance_outdated"?"pm init --agent-guidance add":o==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":c[o]),l=rc(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:o,check:s,severity:l,...typeof d=="string"?{remediation:d}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function JR(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1&&ry(e.remediationMap),e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function QR(e){for(let t of e.checks){let n=Ya(e.remediationSources[t.name]);JR({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount});for(let[r,i]of Object.entries(t.name==="storage"?e.storageRemediation:{}))Object.hasOwn(n,r)&&(n[r]=i);Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function ZR(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),i=new Map;for(let o of e.pendingMergeReceipts){let a=i.get(o.item_id)??[];a.push(o),i.set(o.item_id,a)}let s=[];for(let o of n){if(r.has(o))continue;let a=i.get(o);if(!(!a||a.length===0))try{await ji(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global),s.push(o)}catch{}}return[...new Set(s)].sort((o,a)=>o.localeCompare(a))}function eT(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function wy(e,t={}){let n=I(process.cwd(),e.path);await z(n);let r=sn(n),{settings:i,warnings:s}=await Mu(n),o=[...new Set(s)],a=F(i,M()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=_y(t),m=await GR(n,a,c),_=UR(i),h=await ER({checkTelemetry:t.checkTelemetry===!0}),g=await _R(n,i,!!e.noExtensions),y=hy(t),w=[],v=await KR({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:y,itemReadWarnings:w}),k=v,b=ls(q(i.schema),v),C=[...(await Lf({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(ne=>ne.startsWith("agent_guidance_")),..._,...us(b)],S=y.skipDrift?{warnings:[]}:await gi({pmRoot:n,settings:i,itemIds:v.map(ne=>ne.id),commandLabel:"health"}),x=await rR(n,i.history.compact_policy,await tR(n)),D=await yr(n,20,t.verboseAuthorEvents===!0),j=ac(D),T=j>0?[`history_unknown_author_events:${j}`]:[],E=q(i.schema),K=await nm(n,v,{in_progress_status:E.in_progress_status,status_registry:E,threshold_hours:i.mutation_guard.stale_in_progress_hours}),Ge=gy(K.stale),ge=Ig(K,{in_progress:E.in_progress_status,open:E.open_status},Ye(e)),Ze=[...Ge.warnings,...ge.warnings],mt=await Gf(n),pt=mt.warnings,ye=await RR(n),Ke=y.skipIntegrity&&!l?{...Za("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await cR(n,a.type_to_folder,i.schema,i,l,v),ue=y.skipDrift?Za("history_drift"):await TR({pmRoot:n,items:k,settings:i,typeRegistry:a,itemReadWarnings:w}),Qt=[...new Set(w)],Zt=await ZR({gitWorkspaceRoot:Ke.gitWorkspaceRoot,pendingMergeReceipts:Ke.pendingMergeReceipts,historyDriftCheck:ue,global:e});eT(ue,Zt),ny(ue,await ty(ue,e,n));let Ct=y.skipVectors?Za("vectorization"):await PR(n,i,k,u,t.verboseStaleItems===!0),de=[zR(r,i,o),WR(m,c),BR(C,b),h.check,g.check,HR(v,i,x,D,Ge.scan,mt,ge.details),ye.check,Ke.check,ue.check,Ct.check],Ae=VR({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:C,normalizedItemReadWarnings:Qt,telemetryCheck:h,extensionCheck:g,historyPolicyWarnings:S.warnings,historySummary:x,authorAttributionWarnings:T,staleInProgressWarnings:Ze,provenanceWarnings:pt,locksCheck:ye,integrityCheck:Ke,historyDriftCheck:ue,vectorizationCheck:Ct}),fe=XR({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:C,normalizedItemReadWarnings:Qt,telemetryCheck:h,extensionCheck:g,historyPolicyWarnings:S.warnings,historySummary:x,authorAttributionWarnings:T,staleInProgressWarnings:Ze,provenanceWarnings:pt,locksCheck:ye,integrityCheck:Ke,historyDriftCheck:ue,vectorizationCheck:Ct});QR({checks:de,remediationSources:fe,historyDriftedCount:YR(ue),overThresholdCount:x.over_threshold.length,storageRemediation:ge.remediation});let N=Ae.filter(ne=>!rc(ne,l)),ft=yy({warnings:Ae,checks:de,remediationSources:fe,requireMergeDrivers:l}),xe=new Set(ft.filter(ne=>ne.severity==="gate_failing").map(ne=>ne.check)),Pn=new Set(ft.map(ne=>ne.check));for(let ne of de)ne.ok=!xe.has(ne.name),Pn.has(ne.name)&&(ne.status="warn");let we={ok:N.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&N.length>0?p.GENERIC_FAILURE:0},checks:de,warnings:Ae,findings:ft,failed_because:N,generated_at:O()};return Ha(we,t,y.summaryMode)}var Kq={buildHierarchyIntegrityWarnings:ly,buildExtensionHealthTriageSummary:uy,buildHealthFindings:yy,buildCapabilityContractMetadata:la,buildStaleInProgressHealthSummary:gy,buildVectorizationProviderDetails:fy,collectUnknownCapabilityGuidance:da,isAdvisoryHealthWarning:rc,isDirectory:sc,isExpectedUnmanagedExtension:ec,listItemDocumentPaths:dy,normalizeEndpointForDisplay:wt,normalizeExtensionNameForMatch:En,parseTelemetryQueue:my,probeTelemetryEndpointHealth:py,projectHealthResult:Ha,resolveActionableUnknownAuthorEventCount:ac,resolveHealthSkipPolicy:hy,resolveUnknownAuthorEventCount:oc,resolveVectorRefreshPolicy:_y,selectStaleItemDetail:nc,summarizeHealthCheckDetails:Wa,summarizeExtensionList:vr,summarizeRecordList:Pe,summarizeStringList:W,telemetryEnvFlagEnabled:_s,warningCode:ic};function vy(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!Yp(e,t).ok)return{reason:"unverified_history"};let r=eu(),i={reason:"no_proven_transition"};for(let[s,o]of e.entries()){let a=n.has(String(r.metadata.status));r=Pu(r,o.patch,s+1,o.op),n.has(String(r.metadata.status))?a||(i=["create","close","cancel","update","update_audit"].includes(o.op)&&Cl(o.ts)?{timestamp:o.ts,source_index:s+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function ky(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function by(e,t,n,r,i){let s=ky(n),o=t.filter(d=>s.has(d.status)&&!d.closed_at),a=[],c=[];for(let d of r?o:[]){let l;try{let u=await Mt(Me(e,d.id),d.id),{body:m,..._}=d;l=vy(u,{metadata:_,body:m},s)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}a.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:o.length,missing_closed_at_item_ids:o.slice(0,i).map(d=>d.id),missing_closed_at_item_ids_truncated:o.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:a.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:a,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function Sy(e,t){let n=I(process.cwd(),t.path),r=await R(n),i=q(r.schema);await Ie({pmRoot:n,settings:r,id:e.item_id,op:"update",author:H(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(s){if(s.metadata.closed_at)return{changedFields:[]};let o=await Mt(Me(n,s.metadata.id),s.metadata.id),a=ky(i),c=vy(o,s,a);if(!("timestamp"in c)||c.timestamp!==e.value)throw new f("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",p.GENERIC_FAILURE);return s.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}function tT(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function Ay(e){return`${e.item_id} ${e.link_kind}`}function xy(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=tT(i.classification,r.classification),i.owners.set(Ay(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[Ay(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(s=>{let o=t(s.item_id);return{id:s.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:s.link_kind}}).sort((s,o)=>{let a=s.id.localeCompare(o.id);return a!==0?a:s.field.localeCompare(o.field)})}))}function Cy(e,t,n,r,i=40){let s=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,o=new Map(t.map(d=>[d.path,d])),a={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=xy(e,n).map(d=>{let l=[],u=[];for(let _ of d.items){let h=re(_.status,r)??_.status;r.terminal_statuses.has(h)?(u.push(_),h===r.close_status&&(a.legacy_closed_missing_linked_links_count+=1)):l.push(_)}a.missing_linked_links_count+=d.items.length,a.active_missing_linked_links_count+=l.length,a.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(a.active_missing_linked_paths_count+=1);let m=o.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,s),items_truncated:d.items.length>s}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),a.missing_linked_path_rows_count=c.length,a.missing_linked_path_rows=c.slice(0,s),a.missing_linked_path_rows_truncated=c.length>s,a}import Rn from"node:fs/promises";import Tn from"node:path";async function nT(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let s;try{s=await Rn.readdir(Tn.join(e,i))}catch{return}for(let o of s)for(let a of Gn)if(o.toLowerCase().endsWith(a)){r.push({relativePath:`${i}/${o}`,id:o.slice(0,-a.length)});break}})),r.sort((i,s)=>i.relativePath.localeCompare(s.relativePath))}function rT(e,t){let{id:n,relativePath:r,liveItemIds:i,out:s}=e,o=an(t);if(o){s.conflictMarkers.push({id:n,path:r,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=iT(e,t);a!==null&&(a.op==="delete"&&i.has(n)&&s.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(s.repairReconciliations+=1))}function iT(e,t){let{id:n,relativePath:r,out:i}=e,s=null,o=!1,a=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of a){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");s=d}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(s.op==="create"){if(o)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return s}function cc(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function sT(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Rn.readdir(Tn.join(e,"history"))}catch{return n}for(let i of r.sort((s,o)=>s.localeCompare(o))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await Rn.readFile(Tn.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:cc("history stream",o)});continue}rT({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},s)}return n}function Ey(e){let t=an(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function oT(e){let t=[],n=0,r=null;try{r=await ee(sn(e))}catch(s){n+=1,t.push({path:"settings.json",detail:cc("configuration file",s)})}if(r!==null){n+=1;let s=Ey(r);s!==null&&t.push({path:"settings.json",detail:s})}let i;try{i=await Rn.readdir(Tn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of i.sort((o,a)=>o.localeCompare(a))){if(!s.endsWith(".json"))continue;n+=1;let o;try{o=await Rn.readFile(Tn.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:cc("configuration file",c)});continue}let a=Ey(o);a!==null&&t.push({path:`schema/${s}`,detail:a})}return{scanned:n,unparseable:t}}async function Ry(e,t,n,r={}){let i=await nT(e,n),s=new Set(i.map(u=>u.id)),o=new Map;for(let u of i){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((_,h)=>_.localeCompare(h))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Tn.join(e,u.relativePath);return ci(await Rn.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await sT(e,s),l=await oT(e);return{item_files_on_disk:i.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}function Ty(e,t,n){if(t.length===0)return{details:{},warnings:[]};let r=t.filter(i=>i.dropped!==void 0).length;return{details:{[`schema_${e}_definition_loss_count`]:t.length,[`schema_${e}_definition_losses`]:t.slice(0,n),[`schema_${e}_definition_losses_truncated`]:t.length>n},warnings:[...r>0?[`validate_schema_${e}_definition_dropped:${r}`]:[],...t.length>r?[`validate_schema_${e}_definition_partial:${t.length-r}`]:[]]}}async function Iy(e,t,n){let{configured:r}=await Jp(e,t),i=Io(e,r.files?.statuses,To.statuses),s=Io(e,r.files?.types,To.types),o=Ty("status",Jo(Qo(e,i),$l(await Xo(i))??[],"id",(d,l)=>Ol(d,l).loss),n),a=Ty("type",Jo(Qo(e,s),Nl(await Xo(s))??[],"name",d=>dl(d,"schema_file").loss),n),c=[...o.warnings,...a.warnings];return{details:{...o.details,...a.details,...c.length===0?{}:{schema_definition_loss_fix_hint:"A dropped status or type is not registered, and a definition read in part ignores the listed members. Edit or remove the listed entries in the named schema file: give every status an id and every type a name, use strings for names, descriptions, aliases and folders, and agent, human or gate for execution_role."}},warnings:c}}import Sc from"node:fs/promises";import{realpathSync as hT}from"node:fs";import{execFile as gT}from"node:child_process";import Se from"node:path";import{promisify as yT}from"node:util";var aT=["metadata","resolution"],dc=["metadata","resolution","estimates","timestamps","lifecycle"],cT="completed";function lc(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Oy(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Ny(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Oy(n.close_reason)??cT;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${lc(r)}`,gate:"resolution"})}return t}function $y(e){let t=[];for(let n of e){let r=Oy(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${lc(r)}`,gate:"metadata"})}return t}function Ly(e,t){return e.map(n=>{let r=Lu(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function My(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function Fy(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${lc(n.path)}`})}return t}function Dy(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new f(`--fix-scope values must not be empty. Supported values: ${dc.join(", ")}.`,p.USAGE);return new Set(aT)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(dc.includes(i)){n.add(i);continue}throw new f(`Unknown --fix-scope value "${r}". Supported values: ${dc.join(", ")}.`,p.USAGE)}return n}function Py(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function br(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}var dT=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function lT(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=dT.exec(n);if(!r)return null;let i=r[1],s=i.toUpperCase(),o=i.slice(0,i.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(m=>m.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${s}`)||d.includes(`ISSUE CODE \`${s}\``)||d.includes(`\`${s}\``)||d.includes(`[${s}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(o.toUpperCase())||l?s:null}function Uy(e){return typeof e=="string"&&e.trim().length>0}function uT(e){let t=new Set(e.map(a=>a.id.toLowerCase())),n=new Map,r=new Map;for(let a of e){let c=a.id.toLowerCase(),d=new Set([...a.parent===null?[]:[a.parent.toLowerCase()],...a.derivations].filter(l=>l!==c&&t.has(l)));n.set(c,d);for(let l of d){let u=r.get(l)??[];u.push(c),r.set(l,u)}}let s=[...[...n].filter(([,a])=>a.size===0).map(([a])=>a)],o=new Set;for(let a=0;a<s.length;a+=1)for(let c of r.get(s[a])??[]){let d=n.get(c);d.delete(s[a]),d.size===0&&(o.add(c),s.push(c))}return e.filter(a=>!o.has(a.id.toLowerCase()))}function jy(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||Uy(i.duplicate_of))continue;let s=lT(i.title,{...t,evidenceText:i.body});if(s===null)continue;let o=n.get(s);o||(o=[],n.set(s,o)),o.some(a=>a.id===i.id)||o.push({id:i.id,title:i.title,parent:Uy(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(a=>["discovered_from","supersedes","incident_from"].includes(a.kind)).map(a=>a.id.trim().toLowerCase()).filter(a=>a!==i.id.toLowerCase())})}let r=[];for(let[i,s]of n){if(s.length<2)continue;let o=uT(s);if(o.length<2)continue;let a=[...o].sort((c,d)=>c.id.localeCompare(d.id));r.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return r.sort((i,s)=>i.code.localeCompare(s.code))}function qy(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,s)=>i.localeCompare(s))){let i=t.get(r),s={};for(let o of[...i.keys()].sort((a,c)=>a.localeCompare(c)))s[o]=i.get(o);n[r]=s}return n}function Gy(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Ky(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let s of t){let o=Gy(s);if(o.length===0)continue;let a=i.get(o);a?a.push(s):i.set(o,[s])}return e.map(s=>{if(s.includes(",")||s.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:s,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(i.get(Gy(s))??[]).filter(a=>a!==s).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:o.slice(0,r),candidates_truncated:o.length>r}})}function zy(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}async function hs(e){return e.includeBody?rt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):xi(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}var mT=5;async function pT(e,t){let n=t.hashMismatches.filter(s=>s!==Ft);if(n.length===0)return;let r=await R(e),i=F(r,M());for(let s of n){let o=await di(e,s,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let a=await V(e,s,r.id_prefix,r.item_format,i.type_to_folder);if(a===null)throw new f(`Item ${s} not found`,p.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await le(a,{schema:r.schema});if(c.metadata.id!==s)throw new f(`Item identity changed while validating ${s}`,p.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await qf(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(m=>m!==s),...d[u].filter(m=>m===s)].sort((m,_)=>m.localeCompare(_));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==s),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===s)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await o()}}}async function gs(e,t,n){let r=await sr(e,t);await pT(e,r);let s=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,d])=>d>0).map(([d,l])=>`${d}:${l}`),o=n?Number.POSITIVE_INFINITY:mT,a=r.driftedItems.slice(0,o),c=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:c.length>0?"error":s.length===0?"ok":"warn",ok:c.length===0&&s.length===0,details:{identity_discontinuities:c.slice(0,o),identity_discontinuities_count:c.length,identity_discontinuities_truncated:c.length>o,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,o)}},warnings:s}}function uc(e){let t=0,n=new Map,r=new Map,i=[],s=new Set,o=[],a=l=>{n.set(l,t),r.set(l,t),t+=1,i.push(l),s.add(l);for(let m of e.get(l)??[])n.has(m)?s.has(m)&&r.set(l,Math.min(r.get(l),n.get(m))):(a(m),r.set(l,Math.min(r.get(l),r.get(m))));if(r.get(l)!==n.get(l))return;let u=[];for(;i.length>0;){let m=i.pop();if(s.delete(m),u.push(m),m===l)break}u.sort((m,_)=>m.localeCompare(_)),o.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return o.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function ys(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],s=new Set([n]),o=a=>{for(let c of(t.get(a)??[]).filter(d=>r.has(d))){if(c===n&&i.length>1)return i.push(n),!0;if(!s.has(c)){if(s.add(c),i.push(c),o(c))return!0;i.pop(),s.delete(c)}}return!1};return o(n)?[...i]:[...e,n]}function fT(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function _T(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let s=r.resolve(i.kind);if(!s?.hierarchy)continue;let o=n.get(i.id.toLowerCase());o&&(s.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function mc(e,t=ie()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((s,o)=>s.id.localeCompare(o.id))){let s=r.get(i.id),o=fT(i.parent,n);o&&s.push(o),_T(i,r,n,t)}for(let[i,s]of r)r.set(i,[...new Set(s)].sort());return r}function pc(e,t,n=ie()){let r=Fi(e,o=>t?ht(o,t):o==="closed"||o==="canceled",n),i=mc(e,n),s=r.cycles.map(o=>o.item_ids);return{cycle_count:s.length,active_cycle_count:r.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(s.flat())].sort(),cycle_sample_paths:s.map(o=>ys(o,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:r.divergences.map(o=>`${o.child_id}:scalar=${o.scalar_parent_id}:dependencies=${o.dependency_parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`)}}function At(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function fc(e){return At(e).replace(/\/+$/,"")}function Ue(e){let t=te(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function _c(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}var wT=["src","tests","docs"],vT=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],kT=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),bT=["resolution","expected_result","actual_result"],ST=["default","tracked-all","tracked-all-strict"],Wy=["core","strict","custom"],ks=["off","warn","error"],yc=["author","acceptance_criteria","estimated_minutes","close_reason"],Vy=[...yc,"reviewer","risk","confidence","sprint","release"],wc=Array.from(new Set(Vy)),AT={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"},xT={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},CT={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},ET={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},RT={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},TT=32*1024*1024,IT=1e4,vc=40,je=5,OT=4096,NT=255,$T=yT(gT);function Yy(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?Yy(r):r);return t}function LT(e){return{...e,checks:e.checks.map(t=>({...t,details:Yy(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function Ss(e,t){return re(e,t)??e}function Sr(e,t){return t.terminal_statuses.has(Ss(e,t))}function xt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ws(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function MT(e){let t=xt(Ud),n={blocked_reason:xt(Pr.blocked_reason),resolution:xt(Pr.resolution),actual_result:xt(Pr.actual_result)},r=xt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:xt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:xt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:xt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:ws(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:ws(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:ws(i.resolution,n.resolution)?"default":"settings",actual_result:ws(i.actual_result,n.actual_result)?"default":"settings"}}}function Xy(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Wy.includes(t))return t;throw new f(`Unknown --metadata-profile value "${e}". Supported values: ${Wy.join(", ")}.`,p.USAGE)}function Jy(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ks.includes(t))return t;throw new f(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ks.join(", ")}.`,p.USAGE)}function Qy(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ks.includes(t))return t;throw new f(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ks.join(", ")}.`,p.USAGE)}function FT(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>AT[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function DT(e,t,n){let r=FT(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...yc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Vy],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...yc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var PT=new Set(["acceptance_criteria","estimated_minutes"]);function Zy(e,t,n,r){return!r&&PT.has(t)&&Sr(e.status,n)?!1:t==="author"?!te(e.author):t==="acceptance_criteria"?!te(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ss(e.status,n)===n.close_status&&!te(e.close_reason):t==="reviewer"?!te(e.reviewer):t==="risk"?!te(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!te(e.confidence):t==="sprint"?!te(e.sprint):!te(e.release)}function ew(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new f(`Unknown --scan-mode value "${e}". Supported values: ${ST.join(", ")}.`,p.USAGE)}function tw(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Se.resolve(t);let n=Se.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Se.dirname(Se.dirname(n));let i=Se.resolve(process.cwd()),s=By(n),o=By(i),a=Se.relative(s,o);return a.length===0||!a.startsWith("..")&&!Se.isAbsolute(a)?n:i}function By(e){try{return hT.native(e)}catch{return Se.resolve(e)}}function UT(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Ac(e,t,n){let r=t.length>0?Se.join(e,t):e,i;try{i=await Sc.readdir(r,{withFileTypes:!0})}catch(s){if(B(s))return;throw s}for(let s of i){if(s.name.startsWith("."))continue;let o=t.length>0?Se.join(t,s.name):s.name;if(s.isDirectory()){if(kT.has(s.name))continue;await Ac(e,o,n);continue}s.isFile()&&n.push(At(o))}}async function kc(e){let t=[];for(let n of wT)await Ac(e,n,t);for(let n of vT){let r=Se.join(e,n);try{(await Sc.stat(r)).isFile()&&t.push(At(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function nw(e){try{let{stdout:t}=await $T("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:TT,windowsHide:!0,timeout:IT}),n=t.split("\0").map(r=>At(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function jT(e,t){let n=new Set,r=fc(Fd);r.length>0&&n.add(r);let i=fc(Se.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((s,o)=>s.localeCompare(o))}function Hy(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function qT(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await nw(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await kc(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await kc(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function J(e,t=je){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Kt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=J(e,vc);return{values:n.values,truncated:n.truncated,total:e.length}}var GT={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},KT={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function zT(e){let t=e.missing_fields.map(n=>`${GT[n]} "${KT[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function rw(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(o=>typeof o=="string"):Wg(t);if(i.length===0)return;let s=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...s?{fix_hints_truncated:!0}:{}}}function iw(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var WT="validate_metadata_duplicate_issue_codes";function sw(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:je,r=e.slice(0,n);return{rows:r.map(s=>({code:s.code,count:s.count,ids:s.ids,titles:s.titles,remediation_hint:`Items ${s.ids.join(", ")} share issue code "${s.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${WT}:${e.length}`]}}function BT(e,t,n){let r=Object.fromEntries(wc.map(i=>[i,[]]));for(let i of e)for(let s of wc)Zy(i,s,t,n)&&r[s].push(i.id);return r}function HT(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let s=t[i];s.length>0&&r.push(`${xT[i]}:${s.length}`)}return r.push(...n),r}function ow(e,t){let n={};for(let r of e.required_fields){let i=t[r],s=i?i.length:0,o=CT[r];n[o]=s}return n}function aw(e,t,n){let r=[];for(let i of e.required_fields){let s=t[i];if(s)for(let o of s){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:i})}}return r}function VT(e,t,n,r){for(let i of t.required_fields){let s=n[i];if(!s||s.length===0)continue;let o=ET[i],a=RT[i];if(!o||!a)continue;let c=J(s,r?s.length:je);e[o]=c.values,e[a]=c.truncated}}function cw(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:te(n.get(i)?.resolution)})):[]}function dw(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:te(n.get(i)?.type)})):[]}function YT(e,t,n,r,i){let s=new Map(e.map(v=>[v.id,v])),o=t.profile==="strict",a=BT(e,n,o),c=jy(e,{configuredPrefixes:i}),d=sw(c,r),l=HT(t,a,d.warnings),u=ow(t,a),m=aw(t,a,s),_=qy(m),h={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...wc],counts:u,missing_by_type:_,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(h.configured_custom_required_fields=[...t.configured_custom_fields]);let g=fs(e,r);g!==void 0&&(h.deferred_fields=g.details,l.push(g.warning)),VT(h,t,a,r);let y=cw(t,a,s),w=dw(t,a,s);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:h},warnings:l,closeReasonBackfillRows:y,estimateBackfillRows:w}}function XT(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Ss(m.status,t))),s=[],o=[];for(let m of i){let _=bT.filter(h=>!te(m[h]));_.length!==0&&(s.push({id:m.id,missing_fields:_}),o.push({id:m.id,missing_fields:_,close_reason:te(m.close_reason)}))}let a=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:je,d=J(s.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=s.map(m=>zT(m)),u=J(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:i.length,missing_resolution_items:s.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function lw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uw(e,t="pm",n=hu()){let r=new Set(e.map(s=>s.id)),i=[...e].sort((s,o)=>s.id.localeCompare(o.id));return new Map(i.map(s=>{let o=new Set,a=Ue(s.blocked_by);a&&r.has(a)&&o.add(a),(s.dependencies??[]).filter(d=>{let l=Ue(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>Ue(d.id)).filter(d=>d!==void 0&&r.has(d)).forEach(d=>o.add(d));let c=Ue(s.definition_of_ready);return pw(c??"",t).filter(d=>r.has(d)).forEach(d=>o.add(d)),[s.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function mw(e,t,n){let r=Ef(e,n?l=>Sr(l,n):void 0),i=r.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),s=r.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:je,a=J(i,o),c=J(s,o),d=J(r.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+s.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function pw(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${lw(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,s)=>i.localeCompare(s))}function fw(e,t="pm"){let n=uw(e,t),r=uc(n),i=[...new Set(r.flat())].sort((o,a)=>o.localeCompare(a)),s=r.map(o=>ys(o,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:s}}function _w(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function bs(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function hw(e,t){let n=bs(e).split("/").filter(Boolean),r=bs(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function JT(e,t){let n=bs(t),r=bs(e),i=t.endsWith("/")?t:`${t}/`,s=e.startsWith(i),o=n.length>0&&n===r,a=hw(e,t);return!s&&!o&&a===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function QT(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function ZT(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(s=>(r==="docs"?s.docs??[]:s.files??[]).map(o=>({item:s,link:o}))).forEach(({item:s,link:o})=>{if(o.scope!=="project")return;let a=At(o.path);if(a.length===0||a===e)return;let c=JT(e,a);c!==null&&QT(i,s,c.score)&&(i={item:s,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function gw(e,t){return e.map(n=>{let r=_w(n),i=r==="docs_unowned"?"docs":"files",s=ZT(n,r,t),o=s?.id??"<id>";return{path:n,classification:r,owner_candidate:s,remediation_hint:`pm ${i} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function yw(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function eI(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=Ue(e[n]);return i?r.some(s=>i.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function tI(e,t,n,r,i){let s=Ue(t.parent),o=s?n.get(r.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!Sr(o.status,i)}}function nI(e,t,n,r){let i=Ue(e.blocked_by),s=Ue(e.blocked_reason),o=s?.toLowerCase(),a=Ss(e.status,n),c=[];return t.has(a)?(!i&&!s&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&r.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function rI(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!Sr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=eI(c,r);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=Ue(c.parent),u=l?i.get(s.get(l.toLowerCase())??l):void 0;if(u&&Sr(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(tI(c,u,i,s,n))),t){let m=nI(c,o,n,r);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((_,h)=>_.localeCompare(h))})}}return a}function iI(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function vs(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function hc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function sI(e,t,n,r,i){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=vs("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),a=vs("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=vs("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),d=vs("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),l=hc("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=hc("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=hc("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...s,...o?[o]:[],...a?[a]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...m?[m]:[]]}function ww(e){let t=At(e);return t.length>OT||t.split(/[\\/]/).some(n=>n.length>NT)}async function oI(e,t){let n=Se.isAbsolute(t)?t:Se.resolve(e,t);if(ww(n))return!1;try{let r=await Sc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return UT(r,["ENOENT","ENOTDIR"])}}async function aI(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(s=>({item:i,artifact:s,link_kind:"files"})),...(i.docs??[]).map(s=>({item:i,artifact:s,link_kind:"docs"}))]);for(let{item:i,artifact:s,link_kind:o}of r){if(s.scope!=="project")continue;if(Mf(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let a=At(s.path);a.length!==0&&(n.linkedProjectPaths.add(a),await oI(t,s.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:o})))}return n}function cI(e,t,n,r,i,s){let o=r==="tracked-all-strict",a=o&&!i,c=i||o,d=c?[]:jT(t,n),l=d.length===0?[]:e.candidateFiles.filter(_=>Hy(_,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(_=>!Hy(_,d)),m={};if(l.length>0){let _=Kt(l,s);m.pm_internals={count:l.length,paths:_.values,paths_truncated:_.truncated,paths_total:_.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function vw(e,t,n,r,i,s,o,a="pm"){let c=rI(e,t,i,s);iI(c);let d=fw(c.activeItems,a),l=pc(e,i),u=ls(i,e,o?Number.POSITIVE_INFINITY:je),m=[...sI(c,t,n,r,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...us(u)],_=o?Number.POSITIVE_INFINITY:je,h=J(c.closureLikeRows.map(x=>`${x.id}:${x.fields.join(",")}`),_),g=J(c.terminalParentRows.map(x=>`${x.id}:${x.parent_id}:${x.parent_status}`),_),y=J(c.staleBlockerRows.map(x=>`${x.id}:${x.status}:${x.reasons.join(",")}`),_),w=J(d.cycle_item_ids,_),v=J(d.cycle_sample_paths,_),k=J(l.cycle_item_ids,_),b=J(l.cycle_sample_paths,_),A=J(l.cardinality_violation_rows,_),C=J(l.parent_divergence_rows,_),S=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:S?"error":m.length===0?"ok":"warn",ok:!S&&m.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:h.values,active_closure_like_metadata_rows_truncated:h.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:g.values,active_terminal_parent_rows_truncated:g.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:w.values,dependency_cycle_item_ids_truncated:w.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:b.values,parent_cycle_sample_paths_truncated:b.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:A.values,hierarchy_cardinality_violation_rows_truncated:A.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:C.values,hierarchy_parent_divergence_rows_truncated:C.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function kw(e,t,n,r,i,s,o=q(Rt.schema)){let a=await aI(e,t),c=new Map(e.map(E=>[E.id,E])),d=[...new Set(a.missingLinkedPaths)].sort((E,K)=>E.localeCompare(K)),l=await qT(t,r),u=cI(l,n,t,r,i,s),m=u.candidateFiles.filter(E=>!a.linkedProjectPaths.has(E)),_=gw(m,e),h=Ky(d,u.candidateFiles),g=new Map(h.map(E=>[E.path,E.classification])),y=h.filter(E=>E.classification==="moved").length,w=a.staleLinkRows.map(E=>({...E,classification:g.get(E.path)??"deleted"})).sort((E,K)=>E.item_id.localeCompare(K.item_id)||E.path.localeCompare(K.path)||E.link_kind.localeCompare(K.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),m.length>0&&v.push(`validate_files_orphaned_paths:${m.length}`);let k=[...a.remoteLinkedPaths].sort((E,K)=>E.localeCompare(K)),b=Kt(k,s),A=Kt(d,s),C=Kt(m,s),S=Kt(_.map(E=>`${E.path}:${E.classification}:owner_candidate=${E.owner_candidate?.id??"unowned"}`),s),x=s?_:Kt(yw(_),!1).values,D=Kt(zy(h),s),T=Cy(w,h,E=>c.get(E),o,s?1/0:vc);return T.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${T.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:s?"full":"summary",file_list_summary_limit:vc,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:k.length,remote_linked_paths_total:b.total,remote_linked_paths:b.values,remote_linked_paths_truncated:b.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:A.total,missing_linked_paths:A.values,missing_linked_paths_truncated:A.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:h.filter(E=>E.classification==="deleted").length,missing_linked_paths_malformed_count:h.filter(E=>E.classification==="malformed").length,missing_linked_path_classifications:D.values,missing_linked_path_classifications_truncated:D.truncated,...T,orphaned_paths_count:m.length,orphaned_paths_total:C.total,orphaned_paths:C.values,orphaned_paths_truncated:C.truncated,orphaned_path_classifications:S.values,orphaned_path_classifications_truncated:S.truncated,orphaned_path_rows_count:_.length,orphaned_path_rows:x}},warnings:v,staleLinkPruneRows:w}}function dI(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},s)=>{let o=t[s];if(o.trusted)return;let a=_c(i.command??"");n.push(`${r.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${a}`)}),n}async function bw(e,t,n,r){let i=new Set(e.map(A=>A.id.toLowerCase())),s=0,o=0,a=new Set,c=[],d=e.flatMap(A=>(A.tests??[]).map(C=>({item:A,linkedTest:C}))),l=await Wf(Bf()),u=await Hf(r,d.map(({linkedTest:A})=>A),l),m=dI(d,u);for(let{item:A,linkedTest:C}of d){if(typeof C.command!="string"||C.command.trim().length===0)continue;s+=1;let S=zf(C.command,t);if(S.length!==0){o+=S.length;for(let x of S)a.add(x),i.has(x.toLowerCase())||c.push(`${A.id}:${x}:${_c(C.command)}`)}}let _=[...new Set(c)].sort((A,C)=>A.localeCompare(C)),h=[...new Set(_.map(A=>A.split(":")[1]??""))].filter(A=>A.length>0).sort((A,C)=>A.localeCompare(C)),g=[];_.length>0&&g.push(`validate_command_references_stale_pm_ids:${_.length}`),m.length>0&&g.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let y=n?Number.POSITIVE_INFINITY:je,w=J(_,y),v=J(h,y),k=J([...a].sort((A,C)=>A.localeCompare(C)),y),b=J(m,y);return{check:{name:"command_references",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_items:e.length,linked_commands_scanned:s,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:b.values,untrusted_linked_tests_truncated:b.truncated,stale_pm_id_references_count:_.length,stale_pm_ids_count:h.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:g}}function lI(e,t){let n=oi(e.map(c=>({ref:c.id,version:si(c)})),4,1),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:je,s=J(n.outdated,i),o=J(n.ahead,i),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:4,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:r}}var bc="pm validate auto-fix";async function Sw(e,t,n){switch(e.kind){case"set_closed_at":await Sy(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:bc};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new f("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",p.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function gc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Aw(e,t,n){let r=[],i=[],s=new Map;for(let o of e.filter(a=>gc(a)===null))try{await Sw(o,t,n),r.push(o)}catch(a){i.push({fix:o,error:a})}for(let o of e.filter(a=>gc(a)!==null)){let a=gc(o),c=s.get(a);c?c.push(o):s.set(a,[o])}for(let o of s.values()){let a=o[0];if(!a)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await hg(a.item_id,{remove:c,message:bc},t):await rg(a.item_id,{remove:c,message:bc},t),r.push(...o)}catch(d){i.push(...o.map(l=>({fix:l,error:d})))}}return Hp(i.map(o=>o.error)),{applied:r,failed:i}}var jG={applyValidateFix:Sw,applyValidateFixes:Aw,attachValidateFixHints:rw,buildCommandReferencesCheck:bw,buildDependencyReferencesCheck:mw,buildCloseReasonBackfillRows:cw,buildFilesCheck:kw,buildLifecycleCheck:vw,buildLifecycleDependencyGraph:uw,buildLifecycleParentGraph:mc,buildEstimateBackfillRows:dw,buildMetadataCounts:ow,buildMissingFieldOccurrences:aw,buildOrphanedPathRows:gw,classifyOrphanedPath:_w,collectDefaultProjectFileCandidates:kc,collectTrackedGitFileCandidates:nw,detectLifecycleDependencyCycles:fw,detectLifecycleParentCycles:pc,escapeRegExp:lw,extractItemIds:pw,findLifecycleDependencyCycleComponents:uc,isMetadataFieldMissing:Zy,linkedArtifactPathExceedsFilesystemLimits:ww,listFilesRecursive:Ac,resolveDependencyCycleSeverity:Jy,resolveParentCycleSeverity:Qy,resolveFileScanMode:ew,resolveLifecycleDependencyCycleSamplePath:ys,resolveRequestedChecks:iw,resolveValidateMetadataProfile:Xy,resolveWorkspaceRoot:tw,sharedDirectoryPrefixLength:hw,summarizeOrphanedPathRows:yw,summarizeDuplicateIssueCodes:sw,toMeaningfulString:Ue};function uI(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function mI(e,t,n,r){let i=await Ry(e,new Set(t.map(y=>y.id)),n,{schema:r.schema,extensionFieldNames:gt(M())}),s=[];i.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let o=s.length,a=await ms(e);a.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await bt(e),d=await fn(e,pn(r),{gitWorkspaceRoot:c});d.status==="drift"&&s.push(`validate_merge_fence_drift:${d.missing_patterns.length+d.stale_patterns.length}`);let l=c===null?null:await _n(c);l!==null&&l.status!=="ok"&&s.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await gn(c??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:_,lossless:h}=yn(m);_.length>0&&s.push(`validate_merge_decisions_unreviewed:${_.length}`),uI(s,u.invalid_evidence_count);let g=o>0?"error":s.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:g,ok:g==="ok",details:{...i,merge_fence:d,merge_driver_configuration:l,pending_merge_decision_count:_.length,pending_merge_decision_items:[...new Set(_.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),lossless_merge_receipt_count:h.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(h.map(y=>y.item_id))].sort((y,w)=>y.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:s}}async function pI(e,t,n,r){let i=[Xp(n,r),await Qp(t,n,r),await Iy(t,n,r)];for(let s of i)Object.assign(e.check.details,s.details),e.warnings.push(...s.warnings)}function Je(e,t,n){n&&rw(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function fI(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let i=await Of(e.pmRoot,e.items,r?1/0:je,e.sourceIncomplete);Je(t,i,n)}if(e.requestedChecks.has("metadata")){let i=YT(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let s=r?1/0:je,o=await by(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,s);t.closureTimestampFixes=o.fixes,Object.assign(i.check.details,o.details),i.warnings.push(...o.warnings),await pI(i,e.pmRoot,e.settings.schema,s),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",Je(t,i,n)}if(e.requestedChecks.has("resolution")){let i=XT(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,Je(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=vw(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,Je(t,i,n),Je(t,mw(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await kw(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,Je(t,i,n)}return e.requestedChecks.has("command_references")&&Je(t,await bw(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&Je(t,await gs(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&Je(t,lI(e.items,r),n),e.requestedChecks.has("storage_integrity")&&Je(t,await mI(e.pmRoot,e.items,F(e.settings,M()).type_to_folder,e.settings),n),t}function _I(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...$y(t.closeReasonBackfillRows)),r.push(...Ny(t.resolutionBackfillRows)),r.push(...Ly(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...My(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Fy(t.staleLinkPruneRows)),r}async function hI(e,t,n,r,i,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=_I(e,t,n),{applicable:a,gated:c}=Py(o,r),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await Aw(a,i,s);l.push(...m.applied.map(br)),u.push(...m.failed.map(({fix:_,error:h})=>({...br(_),error:h instanceof Error?h.message:String(h)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,_)=>m.localeCompare(_)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(br),applied_fixes:l,gated_fixes:c.map(m=>({...br(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function xw(e,t,n={}){ru(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new f("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",p.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new f("--fix-scope requires --auto-fix.",p.USAGE);let i=Dy(e.fixScope),s=I(process.cwd(),t.path);await z(s);let o=await R(s),a=q(o.schema),c=F(o,M()),d=iw(e),l=[],u=await hs({includeBody:["history_drift","metadata","completeness"].some(j=>d.has(j)),pmRoot:s,settings:o,typeToFolder:c.type_to_folder,warnings:l}),m=l.length>0;if(d.has("history_drift")){let j=await yr(s);j.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${j.actionable_unknown_event_count}`)}let _=typeof e.metadataProfile=="string"?"option":"settings",h=Xy(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),g=DT(h,_,o.validation.metadata_required_fields),y=MT(o),w=Jy(e.dependencyCycleSeverity),v=Qy(e.parentCycleSeverity),k=ew(e.scanMode),b=tw(s),A=await fI({requestedChecks:d,options:e,global:t,pmRoot:s,workspaceRoot:b,settings:o,items:u,statusRegistry:a,metadataPolicy:g,lifecyclePatternPolicy:y,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:k,initialWarnings:[...new Set(l)],sourceIncomplete:m}),C=r?await hI(e,A,o,i,t,n):void 0,S=[...new Set(A.warnings)].sort((j,T)=>j.localeCompare(T)),D={ok:!A.checks.some(j=>j.status==="error"),has_warnings:S.length>0,checks:A.checks,warnings:S,...C!==void 0?{fixes:C}:{},generated_at:O(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?D:{...LT(D),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as gI}from"node:child_process";import{promisify as yI}from"node:util";var wI=yI(gI),vI=16,kI=3e4;function bI(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(s=>typeof s=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function SI(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let s of Object.entries(i).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(r,s))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${s}`);for(let[s,o]of Object.entries(r)){let a=i[s];if(!a)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${s}`);if(o===null||typeof o!==a.type)throw new TypeError(`assurance provider ${e.id} parameter ${s} must be ${a.type}`)}return{...r}}async function AI(e,t,n,r){let i=SI(e,t),s=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...vu(n)}));s.catch(()=>{});let o;try{let a=await Promise.race([s,new Promise((c,d)=>{o=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??kI),o.unref?.()})]);return bI(e,t.key,a)}finally{clearTimeout(o)}}function Ew(e,t,n,r){let i=e;for(let s of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new Xe(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[s]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(s=>typeof s=="string"))return i;throw new Xe(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function Cw(e,t,n,r){let i=e.checks.find(o=>o.name===t);if(!i)throw new Xe(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:Ew(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function xI(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await wI("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function CI(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(vI,t.length)},async()=>{for(;r<t.length;){let s=r;r+=1;let o=t[s],a=await Mt(Me(e,o.id),o.id);n[s]=a.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function Ar(e,t={}){let n=await R(e),r=F(n),i=q(n.schema),o=(t.strict_read===!0?(await Tf(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await rt(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(_=>({..._,id:_.id,status:_.status,type:_.type})),a={path:e},c=M(),d=Object.fromEntries((c?.assurance_providers??[]).map(_=>[_.definition.id,{cost_class:_.runtime_definition.cost_class,network:_.runtime_definition.network}])),l=new Map,u,m;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await xI(e,t.tree_id),items:o,history:t.include_history===!1?[]:await CI(e,o),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...d,...t.provider_capabilities},external:async _=>{if(_.kind==="graph"){let y=Z({operation:_.operation,parameters:_.parameters??{}}),w=l.get(y);w===void 0&&(w=jf(_.operation,void 0,void 0,{..._.parameters,full:!0},a),l.set(y,w));let v=await w;return{value:Ew(v,_.field,_.kind),population_size:o.length,cost:o.length}}if(_.kind==="validate"){u??=xw({counts:!0},a);let y=await u;return Cw(y,_.check,_.field,_.kind)}if(_.kind==="health"){m??=wy(a,{checkOnly:!0,full:!0});let y=await m;return Cw(y,_.check,_.field,_.kind)}let h=t.providers?.[_.provider];if(h)return h(_);let g=Eu(c,_.provider);if(!g)throw new TypeError(`assurance provider ${_.provider} is not registered`);return AI(g.runtime_definition,_,e,t.trigger??"sdk")}}}import{createHash as EI}from"node:crypto";function Rw(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:i}=Ii({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function RI(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let r=n;if(r.fingerprint!==t||typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return r.offset}function TI(e,t,n,r,i,s){let o=Object.fromEntries(ta.map(_=>[_,0])),a=0,c=0,d=0,l=0,u=[],m=EI("sha256").update(i);for(let _ of r){let h=e.membership.get(_),g=n.has(_),y=h.family_ids.length>0;y&&g&&(a+=1),y||(c+=1),g||(d+=1);let w=t.get(_)?.escape_class;w!==void 0&&ta.includes(w)&&(o[w]+=1,l+=1),m.update(Z([_,g,t.get(_)??null,h.id,h.family_ids])),(!s||!y||!g)&&u.push(_)}return{classCounts:o,coveredCount:a,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:m.digest("hex")}}function Tw(e,t,n={}){_f(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let i=new Set,s=new Map;for(let b of t){if(i.has(b.id))throw new TypeError(`Duplicate recurrence item ${b.id}`);i.add(b.id);let A=Ti(b);A!==void 0&&s.set(b.id,A)}let o=uf(e.families,s),a=[...o.membership.keys()].sort(),c=Z({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:m,classifiedCount:_,selected:h,fingerprint:g}=TI(o,s,i,a,c,n.uncoveredOnly===!0),y=RI(n.cursor,g);if(y>h.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=h.slice(y,y+r).map(b=>{let A=o.membership.get(b),C=i.has(b);return{item_id:b,lineage_id:A.id,lineage_item_count:A.item_ids.length,family_ids:A.family_ids,present:C,...C?A.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=y+w.length,k=a.length===0?null:d.production_defect/a.length;return{ok:u===0&&m===0,fingerprint:g,items:w,total:h.length,has_more:v<h.length,...v<h.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:g,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:a.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:m,classified_item_count:_,unclassified_item_count:a.length-_,class_counts:d,escape_rate:_===a.length?k:null,escape_rate_lower_bound:k},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as II}from"node:crypto";var xc,Iw=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],Cc=["measurement","assertion","gate"];function OI(e){if(Iw.includes(e))return e;throw ti({command_path:"assurance",token:e,allowed:Iw,display_name:"assurance action"})}function In(e,t,n){throw new f(t,p.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function NI(e){if(!e)return In("kind",`Assurance declaration kind is required. Expected: ${Cc.join(", ")}`,"pm assurance list measurement");if(Cc.includes(e))return e;throw new f(`Assurance declaration kind is required. Expected: ${Cc.join(", ")}`,p.USAGE)}function Ow(e){if(!e)return In("preset",`Assurance preset is required. Expected: ${wr.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(wr.includes(e))return e;throw new f(`Assurance preset is required. Expected: ${wr.join(", ")}`,p.USAGE)}function Ec(e){return e.owner?.trim()?e.owner.trim():In("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function $I(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new f("assurance definition must be valid JSON",p.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new f("assurance put requires a JSON object definition",p.USAGE);return n}async function LI(e){let[t,n,r]=await Promise.all([pr(e,"measurement"),pr(e,"assertion"),pr(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function Nw(e,t){return t===!0?{id:e.id}:e}async function MI(e,t){let n=t.authorization_decision;if(!n)return[];let r=await Ar(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(o=>o.id===n),s=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!s.has(i.status))throw new f(`Assurance authorization ${n} must name a terminal Decision item`,p.USAGE);return[i.id]}async function FI(e,t){let n=sa(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>1e3))throw new f(`assurance verdict limit must be an integer from 1 through ${1e3}`,p.USAGE);let r=await xh(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function $w(e,t,n){try{return await Ra(()=>bh(e,t,n))}catch(r){if(!(r instanceof f)||r.context.reason!=="assurance_evaluation_refused")throw r;let i=["--pm-path",e,"assurance","list",t,"--output-budget","2000","--json"],s=L(i);throw Object.assign(r.context,{changed:!1,value:n,required:`Choose a configured ${t} declaration ID using the bounded discovery command.`,why:`The requested ${t} declaration does not exist. The registry and history were not changed.`,examples:[s],recovery:{next_best_command:s,suggested_retry:s,suggested_retry_args:i}}),r}}async function DI(e,t,n){if(e==="presets"){if(t.preset??t.id)return cs(Ow(t.preset??t.id),Ec(t));let i=wr.map(s=>{let o=cs(s,"pm-owner");return{id:s,title:o.title,description:o.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return Sn(()=>vg(n,Ow(t.preset??t.id),Ec(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await kg(await Ar(n,{resolve_tree:!1,trigger:"derive"}),Ec(t)),s=t.apply?await Sn(()=>bg(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...s?{applied:s}:{}}}if(!t.id)return In("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new f("assurance promote requires --enforcement warn|block",p.USAGE);let r=await $w(n,"assertion",t.id);return Sn(()=>Sg(n,r,t.enforcement,{author:t.author,message:t.message}))}async function PI(e,t,n){if(!e.id)return In("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new f("assurance run requires a trigger",p.USAGE);if(!st.includes(e.trigger))throw new f(`Unknown assurance trigger ${e.trigger}. Expected: ${st.join(", ")}`,p.USAGE);let i=e.trigger,[s,o]=await Promise.all([LI(t),Ar(t,{...n.workspace,tree_id:e.tree,trigger:i})]),a=await Ra(()=>vh(r,s,o,{trigger:i,dry_run:e.dry_run===!0}));return a.dry_run||await Ah(t,a,{author:e.author,message:e.message}),a}function Lw(e){throw e instanceof f?e:new f(e instanceof Error?e.message:"assurance risk request is invalid",p.USAGE)}function UI(e){if(e.limit!==void 0)throw new f(`assurance ${e.action} does not accept --limit; set limit inside the definition`,p.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new f(`assurance ${e.action} definition must be valid JSON`,p.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?Rw(t):Ii(t)}catch(n){if(e.action==="risk"&&n instanceof ff)throw new f(n.message,p.USAGE,{required:"Supply definition.policy with the project's declared recurrence policy and definition.change with the proposed change; no policy is inferred.",recovery:{suggested_retry:`pm assurance ${e.action} --help`,suggested_retry_args:["assurance",e.action,"--help"]}});return Lw(n)}}function jI(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function qI(e,t,n){let r=Z(t.policy),i=xc?.pm_root===e?xc:void 0,s=new Map(n.map(d=>[d.id,II("sha256").update(Z([lf(d),Ti(d)])).digest("hex")])),o=i?.policy_serialized===r?i:void 0,a=o?jI(o,s):new Set,c=mf(t.policy,o?n.filter(d=>a.has(d.id)):n,o?{previous_index:o.index,changed_item_ids:[...a]}:{});return xc={pm_root:e,policy_serialized:r,item_fingerprints:s,index:c},c}async function GI(e,t){let n=UI(e),r=await Ar(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?pf(qI(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):Tw(n.policy,r.items,n)}catch(i){return Lw(i)}}async function KI(e,t={},n={}){let r=OI(e.action),i=I(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return DI(r,e,i);if(r==="verdicts")return FI(e,i);if(r==="run")return PI(e,i,n);if(["risk","lineages"].includes(r))return GI(e,i);let s=NI(e.kind);if(r==="list")return pr(i,s);if(!e.id)return In("id",`assurance ${r} requires an id`,`pm assurance ${r} ${s} <id>`);let o=e.id;if(r==="show")return $w(i,s,o);if(r==="remove"){let l=await Sn(()=>Sh(i,s,o,{author:e.author,message:e.message}));return Nw(l,e.idOnly)}let a=$I(s,e.definition);if(a.id!==o)throw new f(`Assurance definition id ${a.id} does not match requested id ${o}`,p.USAGE);let c={author:e.author,message:e.message,...s==="assertion"?{authorized_decision_ids:await MI(i,a)}:{}},d=await Sn(()=>es(i,s,a,c));return Nw(d,e.idOnly)}function SK(e,t,n){let r={...e,...t};return KI({action:X(r,"subcommand")??X(r,"assuranceAction")??X(r,"operation")??"",kind:X(r,"kind"),id:X(r,"id"),definition:r.definition,trigger:X(r,"trigger"),tree:X(r,"treeId")??X(r,"tree"),gate:X(r,"gate"),limit:sa(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:X(r,"author"),message:X(r,"message"),preset:X(r,"preset"),owner:X(r,"owner"),apply:r.apply===!0,enforcement:X(r,"enforcement")},n)}import Rc from"node:fs/promises";import Mw from"node:path";var zI=1440*60*1e3,WI=new Set(["committed","compensated"]);function BI(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:n.abandonment!==void 0?"abandoned":typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function HI(e,t,n,r,i){let s=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(s))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=r-s;return WI.has(t)?o>i?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function VI(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],s=BI(await Rc.readFile(e,"utf8")),o=HI(t,s.status,s.updatedAt,r.nowMs,r.retentionMs);return o.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),o.remove&&!r.dryRun&&(await Rc.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:o,warnings:i}}async function Fw(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=Math.max(0,t.retentionDays)*zI,o=Mw.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Rc.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(B(d))return a;throw d}for(let d of c){let l=Mw.join(o,d),u=`transactions/sdk/${d}`,m=await VI(l,u,d,{dryRun:n,hooks:r,nowMs:i,retentionMs:s});a.warnings.push(...m.warnings),a.scanned+=1;let{decision:_}=m;if(!_.remove){a.retained.push(u),a.entries.push(_.entry);continue}a.removed.push(u),a.entries.push(_.entry)}return a}import zt from"node:fs/promises";import Cr from"node:path";import As from"node:fs/promises";import Tc from"node:path";var YI=864e5;function XI(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function JI(e,t){let n;try{n=await As.readdir(e,{withFileTypes:!0})}catch(i){if(B(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let s=Tc.join(e,i.name),o;try{o=await As.readdir(s)}catch(a){B(a)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of o)a.endsWith(".json")&&r.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function Dw(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),s=Math.max(0,t.retentionDays)*YI,o=Tc.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await JI(o,a.warnings);for(let d of c){let l=Tc.join(o,d),u=`checkpoints/${d}`;a.scanned+=1,r?.onRead&&a.warnings.push(...await r.onRead(l));let m;try{m=await As.readFile(l,"utf8")}catch(w){if(B(w)){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let _=XI(m),h=_===null?Number.NaN:Date.parse(_);if(!Number.isFinite(h)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:_,age_seconds:null,stale:!1,reason:"unparseable"});continue}let g=i-h,y={file:u,created_at:_,age_seconds:Math.floor(g/1e3),stale:g>s,reason:g>s?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await As.unlink(l)}catch(w){if(!B(w)){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}r?.onWrite&&a.warnings.push(...await r.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}var xr=["index","embeddings","runtime","locks","checkpoints","transactions"],QI=1440*60*1e3,Pw=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"},{scope:"runtime",relativePath:"runtime/history-stream-summary.json",kind:"file"}];async function ZI(e,t,n){let r=t.relativePath,i=Cr.join(e,r),s=await Te({path:i,scope:"project"});if(t.scope==="runtime"&&await Uw(e))return{removed:!1,redirected:!0,warnings:s};try{let o=await zt.lstat(i);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...s,`not_a_file:${r}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...s,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:s};t.kind==="file"?await zt.unlink(i):await zt.rm(i,{recursive:!0,force:!0});let a=await nt({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...s,...a]}}catch(o){if(B(o))return{removed:!1,warnings:s};throw o}}async function eO(e,t,n){let r=[],i=[],s=[],o=!1;for(let a of Pw.filter(c=>t.includes(c.scope))){if(a.scope==="runtime"&&o){i.push(a.relativePath);continue}let c=await ZI(e,a,n);o||=c.redirected===!0,(c.removed?r:i).push(a.relativePath),s.push(...c.warnings)}if(t.includes("runtime")&&!o&&(o=await Uw(e)),o)s.push("redirected_runtime_directory:runtime");else if(t.includes("runtime")){let a=await tO(e,n);r.push(...a.removed),i.push(...a.retained),s.push(...a.warnings)}return{removed:r,retained:i,warnings:s}}async function Uw(e){try{return!(await zt.lstat(Cr.join(e,"runtime"))).isDirectory()}catch(t){if(B(t))return!1;throw t}}async function tO(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],s=[],o=Date.now()-QI;for(let a of n){let c=Cr.join(e,a.relativePath);if(!await me(c))continue;let d=(await zt.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=Cr.posix.join(a.relativePath,l),m=Cr.join(c,l);s.push(...await Te({path:m,scope:"project"}));let _=await zt.stat(m).catch(h=>{if(!B(h))throw h});if(_){if(_.mtimeMs>o){i.push(u);continue}r.push(u),!t&&(await zt.rm(m,{recursive:!0,force:!0}),s.push(...await nt({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:s}}function nO(e){if(!e||e.length===0)return[...xr];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new f(`--scope requires at least one value (${xr.join(",")})`,p.USAGE);let n=new Set;for(let r of t){if(!xr.includes(r))throw new f(`Invalid --scope value "${r}". Expected one or more of: ${xr.join(", ")}`,p.USAGE);n.add(r)}return xr.filter(r=>n.has(r))}function rO(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),e.removed.includes("runtime/history-stream-summary.json")&&t.push('History stream summary was removed; the next "pm activity" or "pm context" read parses every history stream once to rebuild it.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function BK(e,t={}){let n=I(process.cwd(),e.path);await z(n);let r=await R(n),i=t.dryRun===!0,s=nO(t.scope),{removed:o,retained:a,warnings:c}=await eO(n,s,i),d;if(s.includes("locks")){let _=await zg(n,{dryRun:i,hooks:{onRead:h=>Te({path:h,scope:"project"}),onWrite:h=>nt({path:h,scope:"project",op:"gc:lock_remove"})}});o.push(..._.removed),a.push(..._.retained),c.push(..._.warnings),d={scanned:_.scanned,removed:_.removed.length,retained:_.retained.length}}let l;if(s.includes("transactions")){let _=r.checkpoints.retention_days,h=await Fw(n,{dryRun:i,retentionDays:_,hooks:{onRead:g=>Te({path:g,scope:"project"}),onWrite:g=>nt({path:g,scope:"project",op:"gc:transaction_journal_remove"})}});o.push(...h.removed),a.push(...h.retained),c.push(...h.warnings),l={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:_}}let u;if(s.includes("checkpoints")){let _=r.checkpoints.retention_days,h=await Dw(n,{dryRun:i,retentionDays:_,hooks:{onRead:g=>Te({path:g,scope:"project"}),onWrite:g=>nt({path:g,scope:"project",op:"gc:checkpoint_remove"})}});o.push(...h.removed),a.push(...h.retained),c.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:_}}c.push(...await xu({mode:i?"gc:dry-run":"gc",total_items:Pw.filter(_=>s.includes(_.scope)).length}));let m=rO({dryRun:i,scopes:s,removed:o});return{ok:c.length===0,dry_run:i,scope:s,removed:o,retained:a,warnings:c,...d?{locks:d}:{},...u?{checkpoints:u}:{},...l?{transactions:l}:{},guidance:m,generated_at:O()}}var XK=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function iO(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 xs(e,t){return Ic(e,t,{operation:"close"})}function Ic(e,t,n){let r=iO(e);if(!t||r.closeReason!==void 0)return r;let i=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 f("Close reason text is required because governance.require_close_reason is enabled",p.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:i,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 jw(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,i=e.dependencies??[],s=i.filter(d=>d.kind==="blocked_by"),o=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),o&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let d=new Set(s),l=i.filter(u=>!d.has(u));l.length>0?e.dependencies=l:delete e.dependencies,a.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:a,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...s.length>0?[`closed_removed_predecessors:${e.id}:${s.map(d=>d.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${s.length}`]:[]]};let c=[...new Set([...n?[n]:[],...s.map(d=>d.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}var sO=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function oO(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 f(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,p.USAGE)}function Gw(e){let t=[];for(let n of sO){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function Kw(e,t,n={}){let r=Gw(e);if(r.length===0)return;let i={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},s=r.map(a=>`--${a.key.replaceAll("_","-")}`),o=[...t,"update",e.id,...r.flatMap((a,c)=>[s[c],i[a.key]?.trim()||"<value>"])];return{missing:s,suggested_retry:L(o),suggested_retry_args:o}}async function aO(e,t,n){let r=new Set,i=t;for(;typeof i=="string"&&i.trim().length>0;){let s=i.trim();if(s===n)return!0;if(r.has(s))return!1;r.add(s),i=(await e(s))?.duplicate_of}return!1}function cO(e){return typeof e!="string"||e.trim().length===0}async function dO(e,t,n,r){let i=n?.trim();if(!i)return;if(i===r)throw new f("An item cannot be closed as a duplicate of itself.",p.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=F(t,M()),o=new Map,a=async d=>{if(o.has(d))return o.get(d)??null;let l=await V(e,d,t.id_prefix,t.item_format,s.type_to_folder);if(!l)return o.set(d,null),null;let{document:u}=await le(l,{schema:t.schema});return o.set(d,u.metadata),u.metadata},c=await a(i);if(!c)throw new f(`Duplicate target "${i}" was not found. Create or locate the canonical item first.`,p.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 ${i}" --duplicate-of ${i}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await aO(a,c.duplicate_of,r))throw new f(`Circular duplicate reference detected. Target "${i}" points back to "${r}".`,p.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 f(`Duplicate target "${i}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,p.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 lO(e,t,n){return e.filter(r=>r.parent===t&&!ae(r.status,n)).map(r=>r.id).sort((r,i)=>r.localeCompare(i))}function uO(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),i=zp(e),s=t.trim().toLowerCase(),o=n.blocked_statuses;return e.filter(a=>o.has(a.status)).map(a=>({item:a,blockerIds:i.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let d=r.get(c);return d!==void 0&&ae(d.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function mO(e,t,n,r,i,s,o){let a=uO(n,r,s),c=[],d=[],l=[],u=[],m;for(let _ of a)try{let h=await Ie({pmRoot:e,settings:t,id:_.id,op:"update",author:i,message:`Auto-unblocked after blocker ${r} closed`,mutate(g){let y=g.metadata.dependencies??[],w=y.filter(k=>{let b=k.id.trim().toLowerCase();return k.kind!=="blocked_by"||!_.blocker_ids.includes(b)});g.metadata.status=s.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 (${_.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:${h.item.id}:resolved_blockers=${_.blocker_ids.join(",")}`),d.push(h.item.id)}catch(h){let g=h instanceof Error?h.message.replace(/\s+/g," ").trim():"unknown";Jn(h)?(m??=h,l.push(_.id)):u.push({id:_.id,reason:g}),c.push(`auto_unblock_failed:${_.id}:${g}`)}if(m!==void 0){let _=await Vp(m,e),h=[...s.blocked_statuses].sort().join(",");throw hO(_,{closedId:r,unblockedIds:d,conflictIds:l,failed:u,openStatus:s.open_status,blockedStatuses:h,commandScope:o})}return c}var lt=10,Oc=20,pO=[{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 fO(e){for(let t of pO){let n=e[t.list];if(Array.isArray(n))for(;n.length>t.floor&&!Zu(e);)n.pop(),Reflect.set(e,t.omitted,Number(e[t.omitted])+1)}return e}function qw(e){let t=e.length-lt;return`${e.slice(0,lt).join(", ")}${t>0?`, and ${t} more`:""}`}var _O="post_close_auto_unblock_refused";function hO(e,t){let{closedId:n,conflictIds:r,failed:i,commandScope:s}=t,o=String(e.context.item_id),a=h=>L([...s,"update",h,"--status",t.openStatus,"--unset","blocked_by","--unset","blocked_reason","--expect-hash",`${h}=<item_hash>`]),c=i.slice(0,lt).map(h=>({id:h.id,reason:tu(h.reason,160)})),d=i.length===0?"":` Auto-unblocking also failed for ${qw(i.map(h=>h.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.`,l=L([...s,"list","--status",t.blockedStatuses,"--fields","id,title,blocked_by,dependencies","--limit","200"]),u=[...r.slice(0,lt).flatMap(h=>[L([...s,"get",h,"--json"]),a(h)]),...c.map(h=>L([...s,"get",h.id,"--json"]))],m=r.length>lt||i.length>lt||u.length>Oc,_=u.slice(0,m?Oc-1:Oc);return new f(`${n} was closed, but auto-unblocking ${o} was refused. ${e.message}`,e.exitCode,{...e.context,reason:_O,examples:fu(o,!1,{scopeArgs:s}).examples,required:`The close of ${n} is complete; do not retry it. Only unblocking ${r.length===1?o:`the guarded dependents it refused (${qw(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(o)}${r.length===1?"":" for each id"}.${d}${m?` This refusal does not list a step for every dependent left blocked; list them with ${l}, and while it reports has_more, continue with --after <next_cursor>.`:""}`,nextSteps:m?[..._,l]:_,details:fO({...structuredClone(e.context.details),pending_unblock:r.slice(0,lt),pending_unblock_omitted:Math.max(0,r.length-lt),auto_unblock_failed:c,auto_unblock_failed_omitted:Math.max(0,i.length-lt)}),side_effects:[{path:`history/${n}.jsonl`,op:"close"},...t.unblockedIds.map(h=>({path:`history/${h}.jsonl`,op:"update"}))]})}async function mz(e,t,n){if(!Jn(e)||!e.context.side_effects?.some(s=>`${s.op}:${s.path}`==`close:history/${t}.jsonl`))return;let r=String(e.context.item_id);return{warnings:[...e.context.side_effects.filter(s=>s.op==="update").map(s=>s.path.slice(8,-6)).map(s=>`auto_unblocked:${s}`),`auto_unblock_refused:${r}:item_revision_conflict`],dependent_revision_conflict:{item_id:r,error:Zr(e),...await Bp(e,n)}}}function gO(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:i,key:s}of r){if(typeof i!="string")continue;let o=i.trim();o.length!==0&&(e[s]=o,n.push(s))}return n}function yO(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:i,value:s}of r)cO(e[i])&&(e[i]=s,n.push(i));return n}function wO(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(([i,s])=>t.has(i)||s===void 0||s.trim().length===0?[]:[`${i}=${s}`]);return e.force===!0?[...r,"--force"]:r}function vO(e,t,n){let r=t.map(y=>y.label),i=t.map(y=>`--${y.key.replaceAll("_","-")}`),s=i.flatMap(y=>[y,"<value>"]),o=[...n.commandScope,"update",e.id,...s],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),l=pu(n.pmRoot),u=typeof n.options.author=="string"&&n.options.author.trim().length===0,m=d.length>0?`its lifecyclePolicy override (${d.join(", ")}) has no CLI spelling`:u?"its explicitly blank author has no CLI spelling (pm close refuses an empty --author)":l===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(m!==void 0)return new f(a,p.USAGE,{code:"close_validation_missing_fields",required:`Pass ${t.map(y=>y.key).join(", ")} on the same SDK close; ${m}, so no CLI retry reproduces it.`,recovery:{missing:i,next_best_command:L(o)},nextSteps:["Retry the same SDK close with the missing evidence supplied, inside the same lifecycle policy and revision guards.",c]});let _=n.closeReason===void 0?[]:[`--reason=${n.closeReason}`],h=l.map(y=>`--expect-hash=${y}`),g=[...n.commandScope,"close",e.id,..._,...wO(n.options,new Set(i)),...h,...s];return new f(a,p.USAGE,{code:"close_validation_missing_fields",required:`Supply ${i.join(", ")}: pm close accepts them and records them in the same write as the closure.`,recovery:{missing:i,suggested_retry:L(g),suggested_retry_args:g,next_best_command:L(o)},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 kO(e,t,n,r){let i=t.map(a=>jl(a.field).flag),s=[...r.author?.trim()?[`--author=${r.author}`]:[],...r.force===!0?["--force"]:[]],o=[...n,"update",e.id,...s,...i.flatMap(a=>[a,"<value>"])];return new f(`Cannot close item ${e.id}: deferred fields still have no value (${t.map(a=>a.field).join(", ")}). Supply them or use --validate-close warn.`,p.USAGE,{code:"close_validation_deferred_fields",required:`Supply ${i.join(", ")}: each was deferred at create (${t.map(a=>`${a.field}: ${a.reason}`).join("; ")}).`,recovery:{missing:i,next_best_command:L(o)},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 bO(e,t,n){let r=ai(e);if(r.length===0)return[];if(t==="strict")throw kO(e,r,n.commandScope,n.options);return[`close_validation_deferred_fields:${e.id}:${r.map(i=>i.field).join(",")}`]}function SO(e,t,n,r){let i=[];if(t!=="off"){i.push(...bO(e,t,r));let s=Gw(e);if(s.length>0){let o=s.map(a=>a.label);if(t==="strict")throw vO(e,s,r);i.push(`close_validation_missing_fields:${e.id}:${o.join(",")}`)}if(n.length>0){if(t==="strict")throw new f(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,p.USAGE);i.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return i}return n.length>0&&i.push(`closed_with_active_children:${e.id}:${n.join(",")}`),i}function AO(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function xO(e){let t=["assignee","claim_principal"].filter(n=>e[n]!==void 0);for(let n of t)delete e[n];return[...t]}function CO(e,t){if(ae(e.status,t.statusRegistry)&&!t.force)throw new f(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,p.CONFLICT,{recovery:Kw(e,t.commandScope,t.options)});let n=gO(e,t.options),r=yO(e,t.duplicateOf),i=SO(e,t.validateCloseMode,t.activeChildIds,t);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let o=["status","closed_at",...s?["completed_at"]:[],...AO(e,t.closeReason),...n];if(rm(e)&&(e.plan_mode="completed",o.push("plan_mode")),t.duplicateOf!==void 0){o.push("duplicate_of");for(let c of r)o.includes(c)||o.push(c)}o.push(...xO(e));let a=jw(e,t.lifecyclePolicy);return o.push(...a.changedFields),i.push(...a.warnings),{changedFields:o,...i.length>0?{warnings:i}:{}}}async function EO(e,t,n,r){let i=I(process.cwd(),r.path),s=Ye(r);await z(i);let o=await R(i),a=q(o.schema),c=H(n.author,o.author_default),d=F(o,M()).type_to_folder,l=await V(i,e,o.id_prefix,o.item_format,d);if(!l)throw await Dt(i,e,o.id_prefix,d);let u=await dO(i,o,n.duplicateOf,l.id),m={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},_=xs({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},m.requireCloseReason).closeReason,h=oO(n.validateClose)??o.governance.close_validation_default,g=await he(i,o.item_format,d,void 0,o.schema),y=lO(g,l.id,a),w=O(),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([...s,"update",l.id,"--completed-at","<ISO>"])}.`}:{}},b=await un({pmRoot:i,settings:o,id:l.id,op:"close",author:c,message:n.message,force:n.force,resolveHistoryContext:()=>({completion:{timestamp:k.timestamp,source:k.source}}),mutate(C){return n.completedAt===void 0&&C.metadata.completed_at!==void 0&&(k={timestamp:C.metadata.completed_at,source:"existing"}),CO(C.metadata,{pmRoot:i,commandScope:s,statusRegistry:a,force:n.force,options:n,duplicateOf:u,validateCloseMode:h,activeChildIds:y,closeReason:_,closedAt:w,completedAt:v,lifecyclePolicy:m})}}),A=h==="warn"?Kw(b.item,s):void 0;return{item:b.item,changed_fields:b.changedFields,...A?{follow_up:{kind:"complete_close_evidence",missing:A.missing,suggested_command:A.suggested_retry,suggested_command_args:A.suggested_retry_args}}:{},warnings:[...b.warnings,...await mO(i,o,g,l.id,c,a,s)],completion:k}}function Cs(e,t,n,r){return EO(e,t,n,r)}function zw(e){return[...e].sort().join("\0")}function RO(e,t,n){let r=e.successors.get(t);r?r.push(n):e.successors.set(t,[n]);let i=e.predecessors.get(n);i?i.push(t):e.predecessors.set(n,[t])}function Ww(e,t,n,r,i){let s=t.resolve(i);if(s?.ordering!==!0)return;let o=Cf(r),a=o===void 0?void 0:e.canonicalIds.get(o.toLowerCase());if(a===void 0)return;let c=(s.precedence??"source_before_target")==="source_before_target";RO(e,c?n:a,c?a:n)}function TO(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},r=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0);for(let i of r){let s=i.id.trim();n.canonicalIds.set(s.toLowerCase(),s)}for(let i of r){let s=i.id.trim();Ww(n,t,s,i.blocked_by,"blocked_by");for(let o of i.dependencies??[])typeof o!="object"||o===null||Ww(n,t,s,o.id,typeof o.kind=="string"?o.kind:"related")}for(let i of[n.successors,n.predecessors])for(let s of i.values())s.sort();return n}function IO(e,t){let n=new Set([t]),r=[t];for(;r.length>0;){let i=r.pop();for(let s of[e.successors,e.predecessors])for(let o of s.get(i)??[])n.has(o)||(n.add(o),r.push(o))}return n}function OO(e,t){let n=new Map;for(let r of t){let i=(e.successors.get(r)??[]).filter(s=>t.has(s));i.length>0&&n.set(r,i)}return n}function Bw(e,t,n){let r=TO(e,t),i=r.canonicalIds.get(n.trim().toLowerCase());if(i===void 0)return{cycles:[],successors:new Map,canonical:n};let s=OO(r,IO(r,i));return{cycles:Pf(s).filter(o=>o.includes(i)),successors:s,canonical:i}}function NO(e,t,n){let r=new Set(t),i=r.has(n)?n:t[0];if(e.get(i)?.includes(i))return[i,i];for(let s of e.get(i)??[]){if(!r.has(s))continue;let o=$O(e,r,i,s);if(o)return o}return[...t,t[0]]}function $O(e,t,n,r){let i=[[r]],s=new Set([n,r]);for(;i.length>0;){let o=i.shift(),a=o.at(-1);for(let c of e.get(a)??[]){if(c===n)return[n,...o,n];!t.has(c)||s.has(c)||(s.add(c),i.push([...o,c]))}}}function Es(e,t,n){let r=ie(),i=Bw(e,r,n),s=Bw(t,r,n),o=new Set(i.cycles.map(zw)),a=new Set(oa(e,void 0,r).map(d=>`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`));return[...oa(t,void 0,r).filter(d=>d.holder_id.toLowerCase()===n.trim().toLowerCase()&&!a.has(`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`)).map(d=>`ordering_storage_contradiction_created:${Uf(d)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...s.cycles.filter(d=>!o.has(zw(d))).map(d=>`ordering_cycle_created:${NO(s.successors,d,s.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}function Rs(e,t){let n=t.resolve(e);return n?.hierarchy===!0||n?.outgoing==="one"||n?.incoming==="one"}function Hw(e,t,n,r,i){let s=JSON.stringify([t,n,r]),o=e.get(s);o===void 0&&(o={kind:t,direction:n,node_id:r,endpoints:new Set},e.set(s,o)),o.endpoints.add(i)}function Vw(e,t){let n=new Map;for(let r of e)for(let i of r.dependencies??[]){let s=t.resolve(i.kind);s===void 0||s.hierarchy||(s.outgoing==="one"&&Hw(n,s.kind,"outgoing",r.id,i.id),s.incoming==="one"&&Hw(n,s.kind,"incoming",i.id,r.id))}return n}function Ts(e,t,n=ie()){let r=Vw(e,n),i=Vw(t,n);for(let s of[...i.keys()].sort()){let o=i.get(s);if(o.endpoints.size<=1)continue;let a=r.get(s);if(![...o.endpoints].every(c=>a?.endpoints.has(c)))throw new f(`Relationship ${o.kind} permits only one ${o.direction} endpoint for ${o.node_id}.`,p.USAGE,{code:"dependency_cardinality_created",field:"dependencies",value:o.kind,relationship_cardinality:{kind:o.kind,direction:o.direction,node_id:o.node_id,endpoint_ids:[...o.endpoints].sort()},required:"The final dependency set must satisfy the active relationship kind's one-edge cardinality.",nextSteps:["Drop extra --dep seeds, or remove conflicting rows with update --dep-remove before adding another edge.","Choose another kind only when its declared semantics match the intended relationship."]})}}var LO={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 MO(e){return LO[e]}function $c(e){return MO(e)!==void 0}function Lc(){return $o.map(e=>e.field).join(", ")}var FO=Object.freeze({fields:[],reason:void 0,optionKeys:new Set});function DO(e){return(e??[]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function Yw(e,t){let n=tn(t,"defer"),r=tn(t,"defer-reason"),i=DO(e.defer),s=e.deferReason?.trim();if(i.length===0){if(s!==void 0&&s.length>0)throw new f(`${r} needs ${n}: name the fields whose values are not known yet.`,p.USAGE,{code:"create_deferral_fields_required",required:`Pass ${n} with ${r}, or drop ${r}.`,nextSteps:[`Deferrable fields: ${Lc()}.`]});return FO}let o=new Map;for(let c of i){let d=Lo(c);if(d===void 0)throw new f(`${n} cannot defer "${c}". Deferrable fields: ${Lc()}.`,p.USAGE,{code:"create_deferral_field_unsupported",required:`Defer only ${Lc()}; supply every other field, or clear a repeatable option with its --clear-* flag.`});o.set(d.field,d)}if(s===void 0||s.length===0)throw new f(`${n} requires ${r}: record why the deferred values are not known yet.`,p.USAGE,{code:"create_deferral_reason_required",required:`Pass ${r} "<why>", for example the system the record was imported from.`});let a=$o.filter(c=>o.has(c.field));return{fields:a,reason:s,optionKeys:new Set(a.map(c=>c.option))}}function Mc(e,t,n,r,i={}){let s=e.fields.filter(c=>{let d=t[c.option];return typeof d=="string"&&d.trim().length>0||i[c.field]!==void 0||n.has(c.field)});if(s.length===0)return;let o=tn(r,"defer"),a=s.map(c=>c.field).join(", ");throw new f(`Cannot both defer and set ${a}: ${o} records a value as not known yet.`,p.USAGE,{code:"create_deferral_conflict",required:`Drop ${o} for ${a}, or drop the value (or unset) you supplied for it.`})}function Xw(e){if(e.fields.length!==0)return ql(e.fields.map(t=>({field:t.field,reason:e.reason})))}function Jw(e,t=[]){let r=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(o=>typeof o=="string").flatMap(o=>o.split(",")).map(o=>Lo(o)).filter(o=>o!==void 0),i=new Set(r.map(o=>o.field)),s=t.filter(o=>o.commands.includes("create")&&i.has(o.metadata_key)).flatMap(o=>Fl(o));return[...r.map(o=>o.option),...s]}function Qw(e,t,n,r,i={}){let s=new Set(t.fields.map(l=>l.field)),o=n.filter(l=>l.commands.includes("create")),a=l=>l.required!==!0&&s.has(l.metadata_key),c=new Set(o.filter(a).map(l=>`--${l.cli_flag}`)),d=new Set(o.filter(l=>!a(l)&&Dl(l,r)&&ri(i,l)===void 0).map(l=>`--${l.cli_flag}`));return e.filter(l=>!c.has(l)||d.has(l))}var PO="hierarchy-integrity";async function Is(e){let t=e.required?await di(e.pmRoot,PO,e.ttlSeconds,e.author,!1,!1,e.waitMs,{waitPolicy:"progress"}):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}function Os(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ns(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function $s(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(nl.includes(t))return t;let n=Re(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new f("Confidence must be an integer 0..100 or one of low|med|medium|high",p.USAGE);return n}function Ls(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new f("Regression must be one of true|false|1|0",p.USAGE)}var Zw=[["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 Ms(e){let t=Zw.find(([r])=>r===e)?.[1]??e.replaceAll(/_([a-z])/gu,(r,i)=>i.toUpperCase()),n=[["update",ea],["create",Zo]].flatMap(([r,i])=>i.flatMap(s=>{if(s.target!==t)return[];let o=s.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:r,flag:o}]}));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:i})=>`Use the declared core mutation: pm ${r}${r==="update"?" <id>":""} ${i} <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 tv={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 ev(e){return e.flatMap(t=>[t.flag,...t.short===void 0?[]:[t.short],...t.aliases??[]])}function nv(e){if(e==="update_many"){let i=nv("update"),s=ev(Xn("update-many"));return{options:new Set([...i.options,...s.map(o=>No(o))]),flags:new Set([...i.flags,...s])}}let t=e==="update"?ea:Zo,n=ev([...Xn(e),...Ei]),r=[...t.flatMap(i=>[i.target,...i.keys]),...n.map(i=>No(i)),...e==="update"?UO:[]];return{options:new Set(r),flags:new Set(n)}}function jO(e,t){let n=tv[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 qO(e,t,n,r){return e.definitions.some(i=>i.metadata_key===t.metadata_key&&i.commands.includes(n)&&ri(r,i)!==void 0)}function Fs(e,t,n){let r=tv[t],i=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([s])=>s!=="field"));return s=>{let o=Il(s),a=e.definitions.filter(_=>_.metadata_key===o||_.key===o),c=a.find(_=>_.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:[s]},nextSteps:[`The project schema declares "${c.key}" for ${c.commands.join(", ")} only; ${r.name} cannot set it.`,d]};if(i!==void 0&&qO(e,c,t,i))return{recovery:{provided_fields:[s]},nextSteps:[`This invocation already sets "${c.key}" through a declared flag or option; drop the --field ${s} assignment so the field receives one value.`,d]};let l=nv(t),u=Ml(c,e,l,t),m=u===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} ${Oo(u)} <value>`;return{recovery:{provided_fields:[s],...u===void 0?{}:{suggested_flags:[Oo(u)]}},nextSteps:[m,jO(Ll(c,e,l.options,t),t),d]}}}var GO=new Set(["event","meeting","reminder","milestone","decision","adr"]);function rv(e,t,n,r){if(GO.has(t.trim().toLowerCase())||n!==r.open_status)return;let i=Fe("in_progress",r);if(!(i===void 0||i===r.open_status))return{command:`pm claim ${e} --start`,to_status:i}}function sv(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 f(`${t} must be one of true|false|1|0|yes|no`,p.USAGE)}function Fc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function qe(e,t,n,r=n){if(!t.includes(e))throw new f(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,p.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 ov=["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 iv(e,t,n){if(!KO(e,n))return;let r=Re(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new f(`--event ${t} must be an integer >= 1`,p.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 f("--event recur_until must be at or after start",p.USAGE);return r}function WO(e){return Array.from(new Set(Fc(e).map(t=>qe(t.toLowerCase(),cl,"event weekday")))).sort((t,n)=>vo(t)-vo(n))}function BO(e){return Array.from(new Set(Fc(e).map(t=>{let n=Re(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new f("--event recur_by_month_day values must be integers 1..31",p.USAGE);return n}))).sort((t,n)=>t-n)}function HO(e,t){return Array.from(new Set(Fc(e).map(n=>se(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function av(e,t,n,r){let i=e.recur_freq?.trim(),s=e.recur_interval?.trim(),o=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![i,s,o,a,c,d,l].some(k=>k!==void 0))return;if(!i)throw new f("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",p.USAGE);let m=qe(i.toLowerCase(),al,"event recurrence frequency"),_=iv(s,"recur_interval",r),h=iv(o,"recur_count",r),g=zO(a,t,n),y=WO(c),w=BO(d),v=HO(l,n);return{freq:m,interval:_,count:h,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 On(e,t=ie()){let n=t.resolve(e);if(n)return n.kind;let r=new Set(wo),i=[...wo,...t.list().filter(({kind:s})=>!r.has(s)).flatMap(({kind:s,aliases:o})=>[s,...o])];throw new f(`Invalid dependency kind value "${e}". Allowed: ${i.join(", ")}`,p.USAGE,{field:"kind",value:e,recovery:{allowed_values:i},required:`dependency kind must be one of: ${i.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function Er(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new f(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,p.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 Rr(e,t,n=ie()){for(let r of t??[])try{gu(e,r.id,r.kind,n)}catch(i){throw new f(Zr(i),p.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function cv(e,t){return(await le(e,{schema:t})).document.metadata.created_at}async function VO(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await V(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:cv(n,t.schema)}function YO(e){let t=e.registry.require(e.dependency.kind);return new f(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,p.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 XO(e){let t=e.dependencies.filter(i=>e.registry.resolve(i.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(i.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:i,located:s})=>s===null?[]:[[i,s]])),r=new Map(await Promise.all([...new Set(t.map(({id:i})=>i))].map(async i=>[i,await cv(n.get(i),e.context.schema)])));for(let i of e.holders){let s=await VO(i,e.context);if(s!==void 0)for(let o of t){let a=r.get(o.id),c=Date.parse(s),d=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw YO({holder:i,dependency:o,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function Ds(e){let t=e.registry??ie(),n=(e.dependencies??[]).filter(o=>!Kp(o.source_kind)),r=[...new Set(n.map(o=>o.id))],i=await Promise.all(r.map(async o=>({target:o,located:await V(e.pmRoot,o,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=i.filter(({located:o})=>o===null).map(({target:o})=>o).sort((o,a)=>o<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new f(`Dependency target${s.length===1?"":"s"} not found: ${s.join(", ")}`,p.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:s,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${s.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await XO({dependencies:n,missingTargets:s,resolutions:i,holders:e.holders??[],registry:t,context:e}),s.map(o=>`dependency_target_unresolved:${o}`)}var dv="--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.",JO="--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).",QO=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,ZO=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,uv=1e3,Dc=60*uv,e0=60*Dc;function lv(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new f(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,p.USAGE);return n.toISOString()}function t0(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new f(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,p.USAGE);let i=r.replace(/^([+-]?\d+)mo$/i,"$1m"),s=QO.exec(r);if(s){let c=s[1]==="-"?-1:1,d=Number.parseInt(s[2],10)*c;return lv(n.getTime()+d*Dc,r)}let o=ZO.exec(r);if(o){let[,c,d,l,u]=o;if(d||l||u){let _=c==="-"?-1:1,h=Number.parseInt(d??"0",10),g=Number.parseInt(l??"0",10),y=Number.parseInt(u??"0",10),w=h*e0+g*Dc+y*uv;return lv(n.getTime()+_*w,r)}}let a=i.startsWith("+")||i.startsWith("-")?i:`+${i}`;return se(a,n,"event.duration")}function mv(e,t,n,r){if(t&&n)throw new f(JO,p.USAGE);if(n){let s=t0(e,n);if(s<e)throw new f(dv,p.USAGE);return s===e?void 0:s}if(!t)return;let i=se(t,r,"event.end");if(i<e)throw new f(dv,p.USAGE);if(i!==e)return i}var n0=["at","date","text","title"],r0=["start","date","end","duration","title","description","location","timezone","all_day",...ov],i0=["key","value"];function pv(e,t){return t==="trimmed"?e?.trim():e}function s0(e,t){return t==="defined"?e!==void 0:!!e}function Ps(e,t,n){return e.map(r=>{let i=_e(r,"--reminder");$e(i,"--reminder",n0);let s=pv(i.at??i.date,n.valueMode),o=pv(i.text??i.title,n.valueMode);if(!s||!o)throw new f("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",p.USAGE);let a=o.trim();if(!a)throw new f("--reminder text must not be empty",p.USAGE);return{at:se(s,t,"reminder.at"),text:a}})}function Us(e,t,n){return e.map(r=>{let i=_e(r,"--event");$e(i,"--event",r0);let s=(i.start??i.date)?.trim();if(!s)throw new f("--event requires start=<iso|relative> or date=<iso|relative>",p.USAGE);let o=se(s,t,"event.start"),a=i.end?.trim(),c=i.duration?.trim(),d=mv(o,a,c,t),l=i.title,u=i.description,m=i.location,_=i.timezone,h=l?.trim(),g=u?.trim(),y=m?.trim(),w=_?.trim(),v=[["title",l,h],["description",u,g],["location",m,y],["timezone",_,w]];for(let[C,S,x]of v)if(S!==void 0&&!x)throw new f(`--event ${C} must not be empty`,p.USAGE);let k=i.all_day?.trim(),b=av(i,o,t,n.recurrenceEmptyNumericGuard),A=s0(k,n.allDayEmptyGuard)?sv(k,"--event all_day"):void 0;return{start_at:o,end_at:d,title:h,description:g,location:y,all_day:A,timezone:w,recurrence:b}})}function js(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new f("--type-option values must not be empty",p.USAGE);let i,s;if(r.includes(",")||r.includes(`
|
|
8
|
+
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=_e(r,"--type-option");$e(a,"--type-option",i0),i=a.key?.trim(),s=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 f("--type-option requires key=value or key=<name>,value=<value> entries",p.USAGE);i=r.slice(0,d).trim(),s=r.slice(d+1).trim()}if(!i||!s)throw new f("--type-option requires key and value",p.USAGE);t[i]=s}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}var o0=["strict","progressive"],a0=["lightweight"],gv=new Set(["Reminder","Meeting","Event"]),c0=new Set(["author","created_at","text"]),qs=new Map(wf.map(e=>[e.optionKey,e.canonical]));function d0(e,t){let n=re(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new f(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,p.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function l0(e,t){let n=e.default_status;if(n!==void 0){let r=re(n,t);if(r)return r}return t.open_status}function Pc(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new f(`Invalid created_at timestamp "${e}"`,p.USAGE);return new Date(n).toISOString()}var u0=Oi();function yv(e){if(Be(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let s=t.unset?[...t.unset]:[];s.includes(i)||s.push(i),t.unset=s};Qn(t.template)&&(t.template=void 0);let r=new Set([...qs.keys(),"rank"]);for(let i of r){if(Be(e,i))continue;let s=t[i];if(typeof s!="string"||!Qn(s))continue;let o=i==="rank"?"order":qs.get(i)??i;n(o),t[i]=void 0}return Ve(e,$i(t,u0))}function Ee(e){if(e!==void 0)return e}var fv=["id","kind","type","author","created_at","source_kind"],Gs=["path","scope","note"];function m0(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let o=s.trim(),a=Ks(o,fv);Er(o,a);let c=a?_e(s,"--dep"):{id:o,kind:"related"};a&&$e(c,"--dep",fv);let d=Ee(c.id),l=p0(Ee(c.kind??c.type));if(!d||!l)throw new f("--dep requires id and kind, or a bare item id to create a related dependency",p.USAGE);if(d.trim().toLowerCase()==="undefined")throw new f(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,p.USAGE);let u=rr(Ee(c.source_kind)),m=Qr(c.author,"--dep author");return{id:ir(d,n,u),kind:On(l),created_at:Pc(c.created_at,t),author:m??r,source_kind:u??"cli:create:dep",author_source:m?"asserted":"detected"}}),explicitEmpty:!1})}function p0(e){return typeof e=="string"?ie().resolve(e)?.kind??e.trim():e}function Ks(e,t){return Xd(e,t)?!0:Kr(e)}function Bt(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(ke(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(o=>{let a=o.trim(),c=()=>{if(a.length===0)throw new f(`${e} requires text=<value>`,p.USAGE);return{created_at:n,author:r,text:a}},d;try{d=_e(o,e)}catch(m){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw m}if(Object.keys(d).filter(m=>!c0.has(m)).length>0)return{created_at:Pc(d.created_at,n),author:Qr(d.author,`${e} author`)??r,text:a};let u=d.text??"";if(u==="")throw new f(`${e} requires text=<value>`,p.USAGE);return{created_at:Pc(d.created_at,n),author:Qr(d.author,`${e} author`)??r,text:u}}),explicitEmpty:!1})}function Uc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),i=Ks(r,Gs);go(r,"--file","file path",i);let s=i?_e(n,"--file"):{path:r};if(i&&$e(s,"--file",Gs),!s.path)throw new f("--file requires path=<value> or a bare file path",p.USAGE);return{path:s.path,scope:qe(s.scope??"project",Br,"file scope"),note:Ee(s.note)}}),explicitEmpty:!1})}function jc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),i=Ks(r,Sl);go(r,"--test","test command",i);let s=i?Al(_e(n,"--test"),"--test"):{command:r},o=Ee(s.command),a=Ee(s.path);if(!o)throw new f("--test requires command=<value> or a bare command (path=<value> is optional metadata)",p.USAGE);let c=Ee(s.timeout_seconds),d=Ee(s.timeout);if(c&&d&&c!==d)throw new f("--test timeout and timeout_seconds must match when both are provided",p.USAGE);let l=c??d;return{command:o,path:a,scope:qe(s.scope??"project",Br,"test scope"),timeout_seconds:l?Re(l,"timeout_seconds"):void 0,pm_context_mode:Zf(s.pm_context_mode,"--test"),workspace_context_mode:e_(s.workspace_context_mode,"--test"),env_set:Xf(s.env_set,"--test"),env_clear:Jf(s.env_clear,"--test"),shared_host_safe:Qf(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:fa(s.assert_stdout_contains),assert_stdout_regex:_a(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:fa(s.assert_stderr_contains),assert_stderr_regex:_a(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:t_(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:n_(s.assert_json_field_equals,"--test"),assert_json_field_gte:r_(s.assert_json_field_gte,"--test"),note:Ee(s.note),phase:Vf(s.phase,"--test")}}),explicitEmpty:!1})}function qc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),i=Ks(r,Gs),s=i?_e(n,"--doc"):{path:r};if(i&&$e(s,"--doc",Gs),!s.path)throw new f("--doc requires path=<value> or a bare doc path",p.USAGE);return{path:s.path,scope:qe(s.scope??"project",Br,"doc scope"),note:Ee(s.note)}}),explicitEmpty:!1})}function f0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Ps(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function _0(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--event","Use --clear-events to clear linked events."),{values:Us(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function h0(e,t,n,r=[]){let i=[...Md.filter(s=>e[s]!==void 0),...r.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(i))}function g0(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function _v(e,t,n){let r=jn("create",e);if(!r)throw new f(`Unsupported ${n} entry "${e}" for type "${t}"`,p.CONFLICT);return r}function y0(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 wv(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 w0(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(_v(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(_v(r,e.name,"required_create_repeatables"));return n}function v0(e,t,n,r){for(let i of e)if(!(!wv(t,i)&&!n.has(i)))throw new f(`Option ${ve("create",i)} is disabled for type "${r}" by command_option_policies`,p.USAGE)}function k0(e,t,n){if(t!=="strict")return;let r=e.filter(s=>n.has(s)&&!$c(s));if(r.length===0)return;let i=[...new Set(r.map(s=>ve("create",s)))].sort((s,o)=>s.localeCompare(o));throw new f(`Strict create mode requires concrete values for ${i.join(", ")}; --unset cannot satisfy a required scalar option (only repeatable options accept an explicit --clear-* empty set)`,p.USAGE)}function b0(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ke(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:js(e),explicitEmpty:!1})}async function S0(e){return await zr(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 A0(e){return It(e)?await S0(e):e}function x0(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 f(`Invalid --create-mode value "${e}". Allowed: ${o0.join(", ")}`,p.USAGE)}function C0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new f("--schedule-preset must not be empty",p.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new f(`Invalid --schedule-preset value "${e}". Allowed: ${a0.join(", ")}`,p.USAGE)}function E0(e,t,n){let r=x0(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new f("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",p.USAGE);return"progressive"}function R0(e,t,n,r,i,s){let o=e.name,a=y0(t),c=w0(e,n),d=rn(e,"create",c);if(d.errors.length>0)throw new f(d.errors.join("; "),p.CONFLICT);v0(d.disabled,a,r,o),k0(d.required,n,r);let l=m=>m==="author"&&i!=="unknown"||m==="status"&&e.default_status!==void 0||s.has(m)||r.has(m)&&$c(m)?!0:wv(a,m),u=d.required.filter(m=>!l(m));return[...new Set(u.map(m=>ve("create",m)))].sort((m,_)=>m.localeCompare(_))}var vv=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function T0(e,t){let n=[];for(let r of e){let i=r.match(vv);i&&i[2]===t&&n.push(i[1])}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function I0(e,t){return e.filter(n=>{let r=n.match(vv);return!r||r[2]!==t})}function O0(e,t,n,r){let i=I0(e,t);if(i.length===0)return;let s=kv(n,[],[],r.open_status);throw new f(i.join("; "),p.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function N0(e,t){let r=e.options.find(i=>i.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function $0(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 kv(e,t,n,r){let i=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],o=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of o){if(a.has(c))continue;let d=Sv[c];i.push(...d?[d]:$0(c,e.name,r)),a.add(c)}for(let c of n){let d=N0(e,c);i.push("--type-option",`${c}=${d}`)}return i.join(" ")}function Gc(e,t,n="cli"){let r=e?.trim();if(!r){let i=n==="sdk";throw t==="--title"?e!==void 0?new f(i?"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.",p.USAGE):new f(i?'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.',p.USAGE):new f(`Missing required option ${i?tn("sdk",t.replace(/^--/u,"")):t}`,p.USAGE)}return r}function L0(e,t,n){let r={};for(let[i,s]of Object.entries(e))r[i]=Array.isArray(s)?[...s]:s;for(let[i,s]of Object.entries(t))s!==void 0&&(r[i]=Array.isArray(s)?[...s]:s);return M0(r,t,n),Ve(t,r)}function M0(e,t,n){let r=[...ia(t.unset,n).optionKeys,...Jw(t.defer,n?.definitions)].flatMap(i=>i==="order"?[i,"rank"]:i==="tags"?[i,"addTags"]:[i]);for(let i of r)Reflect.get(t,i)===void 0&&Reflect.deleteProperty(e,i)}function F0(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function D0(){let e=M();return e?e.commands.some(t=>t.action==="templates-show"||F0(t.command)==="templates show"):!1}function P0(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new f(`Templates package returned invalid payload for template "${t}". Expected an options object.`,p.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new f(`Templates package returned invalid options for template "${t}".`,p.GENERIC_FAILURE);let r={};for(let[i,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[i]=s;continue}if(Array.isArray(s)&&s.every(o=>typeof o=="string")){r[i]=[...s];continue}throw new f(`Templates package returned unsupported option value for "${i}" in template "${t}".`,p.GENERIC_FAILURE)}return r}async function U0(e,t,n){if(!D0())throw new f("--template requires the templates package. Install it first (for example: pm install templates --project).",p.USAGE);let r=await Cu({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled)throw Object.hasOwn(r,"cause")?tm("templates show",r):new f(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.`,p.USAGE);return P0(r.result,e)}function Y(e,t,n){return e.has(t)||n===void 0?void 0:Ee(n)}function Wt(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var j0=new Set(["milestone","meeting","reminder","event"]);function bv(e,t,n,r){let i=t!==void 0,s=n!==void 0&&n.length>0,o=r!==void 0&&r.length>0;return j0.has(e.toLowerCase())&&!i&&!s&&!o}function q0(e,t,n,r,i){let s=[];return e.toLowerCase()==="event"&&(i===void 0||i.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),bv(e,n,r,i)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function G0(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 i=await Ql(r);return i===void 0?{parent:e,parentSource:void 0}:{parent:i,parentSource:"focus"}}async function K0(e,t,n,r,i,s,o){let a=mn(yi(i,o),t.id_prefix);if(Ri(a))return{parent:a,warnings:[]};if(vi(r,a,t.id_prefix,o),await V(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let d=De(a,t.id_prefix);return{parent:a,warnings:wi(d,s,o).warnings}}async function z0(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await K0(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy,e.audience)}async function W0(e){if(e.explicitId===void 0)return Tu(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});er(e.explicitId,"create","id");let t=e.explicitId.trim();if(t.length===0||Iu(t))throw new f("--id must not be empty or use a placeholder token",p.USAGE);let n=De(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new f("--id must contain only letters, numbers, and dashes after normalization",p.USAGE);return n}function hv(e,t,n,r,i,s){let o=Y(e,t,n);if(o===void 0)return{value:void 0,warnings:[]};let a=bi(r,o,i,s);return{value:a.value,warnings:a.warnings}}async function B0(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:i,blockedBy:s,status:o,statusExplicit:a,nowValue:c,author:d}=e,l=e.dependencyValues;if(s===void 0)return{dependencyValues:l,status:o};let u=De(s,n.id_prefix),m=await V(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!m)return{dependencyValues:l,status:o};if((l??[]).some(g=>g.id===m.id&&g.kind==="blocked_by")||(l=[...l??[],{id:m.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:l,status:o};let h=i.blocked_statuses.has("blocked")?"blocked":[...i.blocked_statuses].sort((g,y)=>g.localeCompare(y))[0]??i.open_status;return{dependencyValues:l,status:h}}function H0(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let i=t.governance.create_default_type?.trim();if(i&&i.length>0&&et(i,n)){e.type=i;return}et("Task",n)&&(e.type="Task")}function V0(e,t){return e.options.filter(n=>jn("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 f(`Template custom type option "${n.key}" must be a string, number, or boolean value`,p.USAGE)})}async function Y0(e,t,n,r,i){let s=e,o=[];if(s.template!==void 0){let h=s.template.trim();if(h.length===0)throw new f("--template must not be empty. Omit --template to disable template usage.",p.USAGE);let g=await U0(h,t,n);s=yv(tr("create",L0(g,s,$t(r.schema))))}if(s.type===void 0&&H0(s,r,i),s.type===void 0)throw new f("Missing required option --type <value>",p.USAGE);let a=et(s.type,i);if(!a){let h=Ou(s.type),g=h?et(h,i):void 0;if(g)o.push(`type_coercion:${s.type.trim()}:${g}`),s.type=g,a=g;else throw new f(Si(s.type,i.types,ni(n,r.schema)),p.USAGE)}let c=Yr(a,i);if(!c)throw new f(`Invalid type value "${s.type}"`,p.USAGE);let d=c.name,l=V0(c,s),u=l.map(h=>`${h.key}=${String(s[h.key])}`);if(u.length>0){s.typeOption=[...u,...s.typeOption??[]];for(let h of l)delete s[h.key]}let m=C0(s.schedulePreset);if(m!==void 0&&!gv.has(d))throw new f(`--schedule-preset ${m} is only supported for Reminder, Meeting, or Event types`,p.USAGE);let _=E0(s.createMode,m,r.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:d,schedulePreset:m,createMode:_,warnings:o}}function X0(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),i=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of i)if(s.enabled){if(s.values&&s.values.length>0)throw new f(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,p.USAGE);n.add(s.metadataKey),r.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function J0(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,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let s=qs.get(r)??r;throw new f(`Cannot combine --unset ${s} with ${ve("create",r)}`,p.USAGE)}}function Q0(e){if(Be(e))return;let t=(n,r)=>{if(Be(e,r))return;let i=qs.get(r),s=i?`Use --unset ${i} to clear this field.`:void 0;Ni(n,ve("create",r),s)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function Z0(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new f(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,p.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new f(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,p.USAGE)}var Sv={"--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 eN(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:i,openStatus:s,type:o,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(h=>{let g=h.type==="boolean"?"<true|false>":h.type==="array"?"<json-array>":h.type==="object"?"<json-object>":h.type==="number"?"<number>":h.type==="string_array"||h.repeatable?"<value>":"<string>";return{example:`--${h.cli_flag} ${g}`,description:`--${h.cli_flag} maps to ${h.metadata_key} (${h.type}${h.repeatable?", repeatable":""})`}}),l=[kv(n,r,i,s),...d.map(h=>h.example)].join(" "),u=[`Run "pm create --help --type ${o}" for type-aware required option guidance.`,...t.filter(h=>h==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+o+").")];a==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),gv.has(o)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(h=>h.description).join("; ")}.`);let m=[...new Set(t.flatMap(h=>{let g=h.split(" ",1)[0],y=Sv[g];return y?[y]:[]}))];m.length>0&&u.push(`If the truthful value is an empty collection, use ${m.join(", ")} instead of inventing metadata.`);let _=t.length===1?`Missing required option ${t[0]} for type "${o}"`:`Missing required options ${t.join(", ")} for type "${o}"`;throw new f(_,p.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${o}" in one invocation.`,examples:[...m.map(h=>`pm create --type ${o} ${h} ...`),l],nextSteps:u,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...m,...t,"--create-mode progressive"]}:void 0})}function tN(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new f("Cannot combine --unset tags with --add-tags",p.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?jr(t.tags):[];return Gr(n,t.addTags)}function nN(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new f("--order and --rank must match when both are provided",p.USAGE);let n=t.order??t.rank,r=Wt(e,"order",n,i=>Re(i,"order"));if(r!==void 0&&!Number.isInteger(r))throw new f("Order must be an integer",p.USAGE);return r}function rN(e,t,n,r,i,s){if(r.completedAt!==void 0&&e!==t.close_status)throw new f("--completed-at requires a terminal create status.",p.USAGE);let o=e!==t.close_status?void 0:r.completedAt===void 0?s:se(r.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:o,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:i}:{explicit:r.closeReason};return{closeReason:Ic(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:o,warnings:[]}}async function iN(e){let{pmRoot:t,type:n,id:r,settings:i,typeRegistry:s,author:o,extensionFieldNames:a,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:m,similarityCandidate:_,allowDuplicate:h}=e,g=ll(t,n,r,i.item_format,s.type_to_folder),y=Me(t,r),w=ie(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(C=>Rs(C.kind,w)),k=await Is({pmRoot:t,author:o,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:v}),b=v,A=[];try{let C=await li(t,r,i.locks.ttl_seconds,o,!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let S=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await he(t,i.item_format,s.type_to_folder,void 0,i.schema):void 0,x=await V(t,r,i.id_prefix,i.item_format,s.type_to_folder);if(x)throw new f(`Item "${r}" already exists`,p.CONFLICT,{code:"item_already_exists",id:x.id,path:x.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 ${x.id}.`]});if(S){Ts(S,[...S,c.metadata],w);let E=q(i.schema);Di(S,[...S,c.metadata],r,K=>ae(K,E),w)}let D=await Uu({pmRoot:t,settings:i,operation:"create",author:o,before:null,after:c});await Su({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,author:o,sdk:Wu({pmRoot:t,settings:i,typeToFolder:s.type_to_folder})});let j=await Ku(t,o,{required:i.governance.duplicate_detection_mode==="strict"&&h!==!0}),T=[];try{i.governance.duplicate_detection_mode==="strict"&&h!==!0&&await qa(_,{pmRoot:t,mode:"strict",threshold:i.governance.duplicate_detection_threshold,limit:i.governance.duplicate_detection_limit,allowDuplicate:!1}),await C.fence(async()=>{await Le(g,Wl(c,{format:i.item_format,schema:i.schema,extensionFieldNames:a}));try{let E=uu({nowIso:m,author:o,op:"create",before:d,after:c,message:l,context:D.decisions.length===0?void 0:{workflow_policies:D.decisions}});await mu(y,E)}catch(E){throw await tl(g),E}}),b&&(await k(),b=!1),T=await zu({pmRoot:t,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:g,document:c})}finally{await j()}A=[...D.warnings,...S?Es(S,[...S,c.metadata],r):[],...T,...await nt({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await nt({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],ku({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:bu(c.metadata,u),changed_fields:u})}finally{await C.release()}}finally{b&&await k()}return A}async function jW(e,t){let n=tr("create",e),r=He(n),i=yv(await A0(n)),s=I(process.cwd(),t.path);await z(s);let o=await R(s),a=q(o.schema),c=$t(o.schema),d=F(o,M()),l=await Y0(i,t,s,o,d);i=l.resolvedOptions;let{typeDefinition:u,type:m,createMode:_}=l,h=ia(i.unset,c),{explicitUnsets:g,clearOptionKeys:y}=X0(i,h);J0(i,h),Q0(i);let w=Yw(i,r);Mc(w,i,h.metadataKeys,r);let v=H(Ee(i.author),o.author_default),k=R0(u,i,_,y,v,w.optionKeys),b=O(),A=m0(i.dep,b,o.id_prefix,v),C=Bt("--comment",i.comment,b,v),S=Bt("--note",i.note,b,v),x=Bt("--learning",i.learning,b,v),D=Uc(i.file),j=jc(i.test);j.values=await qi(j.values,v,b);let T=qc(i.doc),E=f0(i.reminder,b),K=_0(i.event,b),Ge=b0(i.typeOption),ge=qn(m,Ge.values,d),Ze=M(),mt=gt(Ze),pt=pi(i.field,Ze,Ms,Fs(c,"create",i)),ye=Pl(i,c,m);Mc(w,i,h.metadataKeys,r,ye.values),ye.missing_required_flags=Qw(ye.missing_required_flags,w,c.definitions,m,i);let Ke=new Set(ye.missing_required_flags),ue=c.definitions.filter(Q=>Ke.has(`--${Q.cli_flag}`));Z0(pt,ye,h);let Qt=T0(ge.errors,m),Zt=Qt.map(Q=>`--type-option ${Q}=<value>`),Ct=[...new Set([...k,...Zt,...ye.missing_required_flags])].sort((Q,fo)=>Q.localeCompare(fo));eN({combinedMissingFlags:Ct,typeDefinition:u,missingRequiredCreateFlags:k,missingRequiredTypeOptionKeys:Qt,openStatus:a.open_status,type:m,createMode:_,missingRequiredRuntimeFields:ue}),O0(ge.errors,m,u,a);let de=await W0({pmRoot:s,settings:o,typeRegistry:d,explicitId:i.id}),Ae=i.status!==void 0?d0(i.status,a):l0(u,a),fe=i.priority!==void 0?ki(i.priority):2,N=h.metadataKeys,ft=tN(N,i),xe=Wt(N,"deadline",i.deadline,Q=>se(Q,new Date(b),"deadline")),Pn=Wt(N,"estimated_minutes",i.estimatedMinutes,Q=>Wr(Q,"estimated-minutes")),we=Y(N,"acceptance_criteria",i.acceptanceCriteria),ne=Y(N,"definition_of_ready",i.definitionOfReady),Mr=nN(N,i),oo=Y(N,"goal",i.goal),Fr=Y(N,"objective",i.objective),mb=Y(N,"value",i.value),pb=Y(N,"impact",i.impact),fb=Y(N,"outcome",i.outcome),_b=Y(N,"why_now",i.whyNow),hb=Y(N,"assignee",i.assignee),gb=N.has("author")?void 0:Ee(i.author)??v,yb=Y(N,"parent",i.parent),Sd=await G0(yb,i,N,s),ao=Sd.parent,wb=Sd.parentSource,vb=Y(N,"reviewer",i.reviewer),kb=Wt(N,"risk",i.risk,Q=>qe(Os(Q),Hr,"risk")),bb=Wt(N,"confidence",i.confidence,Q=>$s(Q)),Sb=i.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Ad=o.validation.sprint_release_format,Et=[...l.warnings,...q0(m,de,xe,E.values,K.values)],xd=await z0({itemId:de,parent:ao,pmRoot:s,settings:o,typeRegistry:d,policy:Sb,audience:r});ao=xd.parent,Et.push(...xd.warnings);let Cd=hv(N,"sprint",i.sprint,"sprint",Ad,r),Ab=Cd.value;Et.push(...Cd.warnings);let Ed=hv(N,"release",i.release,"release",Ad,r),xb=Ed.value;Et.push(...Ed.warnings);let Rd=Y(N,"blocked_by",i.blockedBy),Td=await B0({pmRoot:s,settings:o,typeRegistry:d,statusRegistry:a,blockedBy:Rd,dependencyValues:A.values,status:Ae,statusExplicit:i.status!==void 0,nowValue:b,author:v}),co=Td.dependencyValues;Rr(de,co),Et.push(...await Ds({pmRoot:s,dependencies:co,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:d.type_to_folder,allowUnresolved:i.allowUnresolvedDeps,holders:[{id:de,createdAt:b}],schema:o.schema})),Ae=Td.status;let Cb=Y(N,"blocked_reason",i.blockedReason),Eb=Y(N,"unblock_note",i.unblockNote),Rb=Y(N,"reporter",i.reporter),Tb=Wt(N,"severity",i.severity,Q=>qe(Ns(Q),Vr,"severity")),Ib=Y(N,"environment",i.environment),Ob=Y(N,"repro_steps",i.reproSteps),Id=Y(N,"resolution",i.resolution),Nb=Y(N,"expected_result",i.expectedResult),$b=Y(N,"actual_result",i.actualResult),Lb=Y(N,"affected_version",i.affectedVersion),Mb=Y(N,"fixed_version",i.fixedVersion),Fb=Y(N,"component",i.component),Db=Wt(N,"regression",i.regression,Q=>Ls(Q)),Pb=Y(N,"customer_impact",i.customerImpact),lo=Gc(i.title,"--title",r),uo=i.description??"",Dr=i.body??"",Od=await qa({title:lo,description:uo,body:Dr},{pmRoot:s,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:i.allowDuplicate});Et.push(...og(Od));let mo=rN(Ae,a,o,i,Id,b),Ub=mo.closeReason,jb=Ae===a.close_status?b:void 0,qb=mo.completedAt;Et.push(...mo.warnings);let en=zl({id:de,title:lo,description:uo,type:m,type_options:ge.normalized,status:Ae,closed_at:jb,completed_at:qb,close_reason:Ub,priority:fe,tags:ft,created_at:b,updated_at:b,deadline:xe,assignee:hb,author:gb,estimated_minutes:Pn,acceptance_criteria:we,deferred_fields:Xw(w),definition_of_ready:ne,order:Mr,goal:oo,objective:Fr,value:mb,impact:pb,outcome:fb,why_now:_b,parent:ao,reviewer:vb,risk:kb,confidence:bb,sprint:Ab,release:xb,blocked_by:Rd,blocked_reason:Cb,unblock_note:Eb,reporter:Rb,severity:Tb,environment:Ib,repro_steps:Ob,resolution:Id,expected_result:Nb,actual_result:$b,affected_version:Lb,fixed_version:Mb,component:Fb,regression:Db,customer_impact:Pb,dependencies:co,comments:C.values,notes:S.values,learnings:x.values,files:D.values,tests:j.values,docs:T.values,reminders:E.values,events:K.values,...pt,...ye.values});vl(en),fi(en,Ze),ju(en,s);let Gb=Bl({metadata:en,body:Dr},{schema:o.schema,extensionFieldNames:mt}),Kb={metadata:{},body:""},Nd=[...g].sort((Q,fo)=>Q.localeCompare(fo)),zb=g0(i.message,Nd),$d=h0(en,Dr,Nd,[...Object.keys(pt),...Object.keys(ye.values??{})]),Wb=await iN({pmRoot:s,type:m,id:de,settings:o,typeRegistry:d,author:v,extensionFieldNames:mt,afterDocument:Gb,beforeDocument:Kb,historyMessage:zb,changedFields:$d,nowValue:b,similarityCandidate:{title:lo,description:uo,body:Dr},allowDuplicate:i.allowDuplicate}),po=structuredClone(en);_==="strict"&&g.has("dependencies")&&(po.dependencies=[]);let Bb=rv(de,m,Ae,a);return bv(m,xe,E.values,K.values)&&lu(`[pm] warning: ${m} '${de}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${de} --deadline <ISO>' or 'pm update ${de} --event "start=<ISO>,end=<ISO>"'.`),{item:po,changed_fields:$d,warnings:[...Zn("create",i,r==="sdk",po),...Et,...Wb],...Object.fromEntries([["parent_source",wb],["next_transition",Bb],["similarity_advisory",Od]].filter(Q=>Q[1]!==void 0))}}function Ht(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:Fe("in_progress",e)??e.open_status}import{AsyncLocalStorage as sN}from"node:async_hooks";var oN="strict",Ws="start_blocked_by_open_dependency";function Av(e,t,n){if(t===void 0)return!1;let r=Lt(Ht(n),n);return Lt(t,n)===r&&Lt(e??"",n)!==r}function zs(e,t,n){let r=i=>De(i.trim(),n).toLowerCase();return r(e)===r(t)}var aN=new Set(["cli:create:blocked_by","cli:update:blocked_by"]);function Kc(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===De(t.trim(),n).toLowerCase()&&aN.has(e.source_kind?.trim().toLowerCase()??"")}function cN(e,t,n){let r=e.dependencies??[],i=r.filter(o=>o.kind==="blocked_by");if(r.some(o=>o.kind!=="blocked_by"&&Bn(o.kind)==="blocked_by"&&zs(o.id,t,n)))return L(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&zs(e.blocked_by,t,n))){let o=i.filter(a=>zs(a.id,t,n));return o.length===1&&o.every(a=>a.id===mn(a.id,n,void 0))?L(["update",e.id,"--dep-remove",`id=${o[0].id},kind=blocked_by`]):L(["get",e.id,"--fields","blocked_by,dependencies"])}return i.filter(o=>zs(o.id,t,n)).every(o=>Kc(o,e.blocked_by,n))?L(["update",e.id,"--unset","blocked_by"]):L(["get",e.id,"--fields","blocked_by,dependencies"])}var dN=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function lN(e,t){try{return(await Wp(e)).filter(n=>!n.resolved)}catch(n){let r=em(n)?n.context.code:void 0;if(!t||typeof r!="string"||!dN.has(r))throw n;return r}}async function xv(e){let t=e.settings.governance.start_blocker_enforcement??oN;if(t==="off")return[];let n=F(e.settings,M()).type_to_folder,r=e.metadata.id,i=await lN({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n,metadata:e.metadata},t==="warn"||e.force===!0);if(typeof i=="string")return[`start_blocker_unverifiable:${r}:${i}`];if(i.length===0)return[];let s=i.map(o=>o.id).join(",");if(t==="warn")return[`start_with_open_blockers:${r}:${s}`];if(e.force===!0)return[`start_blocker_override:${r}:${s}`];throw new f(`Cannot start ${r}: ${i.length===1?"its blocker":`${i.length} of its blockers`} ${s} ${i.length===1?"is":"are"} still open.`,p.CONFLICT,{code:"start_blocked_by_open_dependency",item_id:r,required:`Finish or close the open blocker${i.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:[...i.filter(o=>o.external!==!0).slice(0,3).map(o=>L(["get",o.id])),cN(e.metadata,i[0].id,e.settings.id_prefix),"pm next"],details:{enforcement:t,open_blockers:i.map(o=>({id:o.id,title:o.title,status:o.status,external:o.external===!0}))}})}async function Bs(e){if(e.requested===!1||!Av(e.fromStatus,e.metadata.status,e.registry))return[];let t=await xv(e),n=zc.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var zc=new sN;function Cv(e){return zc.run({warnings:new Set},e)}async function Ev(e){let t=zc.getStore();if(t===void 0)return[];let n=Av(e.metadata.status,Ht(e.registry),e.registry)?await xv(e):[];for(let r of n)t.warnings.add(r);return n}var Rv="terminal_state_unchanged";function Tv(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function uN(e,t){return re(e,t)===t.close_status}function mN(e){let t=n=>yf.includes(n.trim().toLowerCase());return vf(e.unset??[],t).some(t)}function Iv(e){!e.settings.governance.require_close_reason||!mN(e.options)||xs({explicit:e.options.closeReason},!0)}function Wc(e,t,n,r=!1){if(!uN(e.status,n))return!1;let i=Tv(t.closeReason);return r&&t.closeReason!==void 0&&i===void 0||i!==void 0&&i!==Tv(e.close_reason)?!1:t.completedAt===void 0||se(t.completedAt,new Date,"completed-at")===e.completed_at}async function Ov(e){let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Dt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await le(t,{schema:e.settings.schema});return n.metadata}async function Nv(e,t,n,r,i){if(n.length===0)return{item:t,changed_fields:[],warnings:[...e.workflowTransitionWarnings,Rv]};let s=Ve(e.options,{...e.options,status:void 0,closeReason:void 0,completedAt:void 0}),o=await r(e.id,s,e.global);return Wc(o.item,e.options,e.statusRegistry,e.settings.governance.require_close_reason)?{item:o.item,changed_fields:o.changed_fields,warnings:[...e.workflowTransitionWarnings,...o.warnings,Rv]}:i(o)}function Nn(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Nu({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Fe(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Fe(e.toStatus,e.statusRegistry)??e.toStatus,i=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${$u(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new f(i,p.USAGE);return`workflow_transition_not_allowed: ${i}`}function Hs(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",i=Date.parse(r),s=Number.isFinite(i)?new Date(i).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function Bc(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 $v(e,t,n){let r=t.filter(i=>!e.some(s=>Bc(s,i)));if(r.length!==0)throw new f(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,p.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r.map(i=>({...i,id:i.id??"*"})),available_dependencies:e.map(i=>({id:i.id,kind:i.kind,source_kind:i.source_kind,author:i.author,created_at:i.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 Lv(e,t){if(!Array.isArray(e)||e.length===0)return;let n=s=>(Array.isArray(s)?s:[]).filter(o=>typeof o=="object"&&o!==null&&typeof o.id=="string"),r=new Map;for(let s of n(t)){let o=Hs(s);r.set(o,(r.get(o)??0)+1)}let i=[];for(let s of n(e)){let o=Hs(s),a=r.get(o)??0;a>0?r.set(o,a-1):i.push(`${s.id}/${s.kind}`)}return i.length>0?i.join(","):void 0}var pN=(()=>{let e=new Map;for(let t of Li)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Vs=new Map(Li.map(e=>[e.optionKey,e.canonical])),fN=Li.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),_N=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),hN=Oi({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function Kv(e){if(Be(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=i=>{let s=t.unset?[...t.unset]:[];s.includes(i)||s.push(i),t.unset=s},r=new Set([...Vs.keys(),"rank"]);for(let i of r){if(Be(e,i))continue;let s=t[i];if(typeof s!="string"||!Qn(s))continue;let o=i==="rank"?"order":Vs.get(i)??i;n(o),t[i]=void 0}return Ve(e,$i(t,hN))}function WB(e,t,n,r=["update"]){return[...Xc([...e],t,n,r).metadataKeys]}function Xc(e,t,n=[],r=["update"]){return kf({raw:e,supportedFields:fN,resolveDefinition:i=>{let s=n.find(a=>{let c=a.toLowerCase();return c===i||c.replaceAll("_","-")===i||c.replaceAll("-","_")===i});return pN.get(i)??r.map(a=>ra(i,a,t)).find(a=>a!==void 0)??(s?{optionKey:"field",metadataKey:s}:void 0)}})}var Mv=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 Fv(e){let t=e.disallowedFlags.flatMap(r=>{let i=Mv.get(r);return i?[i(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let i=Mv.get(r);return i?[`Replace ${r} with: ${i(e.id)}`]:[]});return new f(e.message,p.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function gN(e,t,n){let r=t.ownershipMetadataBypass===!0,i=t.ownershipDependencyBypass===!0;if(!r&&!i)return;if(r&&i)throw new f("Choose only one package-provided ownership bypass mode.",p.USAGE);let s=(c,d,l)=>{c&&l.push(d)};if(i){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new f("The dependency ownership bypass requires at least one --dep value",p.USAGE);if(c.length>0)throw Fv({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 o=[];s(t.status!==void 0,"--status",o),s(t.closeReason!==void 0,"--close-reason",o),s(t.assignee!==void 0,"--assignee",o),s(t.parent!==void 0,"--parent",o),s(t.blockedBy!==void 0,"--blocked-by",o),s(t.blockedReason!==void 0,"--blocked-reason",o),s(t.unblockNote!==void 0,"--unblock-note",o),s(t.dep!==void 0,"--dep",o),s(t.depRemove!==void 0,"--dep-remove",o),s(t.replaceDeps===!0,"--replace-deps",o),s(t.replaceTests===!0,"--replace-tests",o),s(t.replaceFiles===!0,"--replace-files",o),s(t.replaceDocs===!0,"--replace-docs",o),s(t.note!==void 0,"--note",o),s(t.learning!==void 0,"--learning",o),s(t.test!==void 0,"--test",o),s(t.reminder!==void 0,"--reminder",o),s(t.event!==void 0,"--event",o),s(t.clearDeps===!0,"--clear-deps",o),s(t.clearComments===!0,"--clear-comments",o),s(t.clearNotes===!0,"--clear-notes",o),s(t.clearLearnings===!0,"--clear-learnings",o),s(t.clearFiles===!0,"--clear-files",o),s(t.clearTests===!0,"--clear-tests",o),s(t.clearDocs===!0,"--clear-docs",o),s(t.clearReminders===!0,"--clear-reminders",o),s(t.clearEvents===!0,"--clear-events",o);let a=[...n].filter(c=>_N.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(o.push(...a),o.length>0)throw Fv({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: ${o.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:o})}function yN(e,t){let n=re(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new f(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,p.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function wN(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:zv(e)}function zv(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new f(`Invalid dependency created_at timestamp "${e}"`,p.USAGE);return new Date(t).toISOString()}function Vt(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var vN=["id","kind","type","author","created_at","source_kind"],kN=["id","kind","type","author","created_at","source_kind"];function Wv(e){return e.startsWith("```")||e.includes(`
|
|
9
|
+
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Kr(e)}function Jc(e){return typeof e=="string"?ie().resolve(e)?.kind??e.trim():e}function bN(e,t,n,r){return e?(ke(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let o=s.trim(),a=Wv(o);Er(o,a);let c=a?_e(s,"--dep"):{id:o,kind:"related"};a&&$e(c,"--dep",vN);let d=c.id?.trim(),l=Jc((c.kind??c.type)?.trim());if(!d||!l)throw new f("--dep requires id and kind, or a bare item id to add a related dependency",p.USAGE);if(d.toLowerCase()==="undefined")throw new f(`--dep id must not use placeholder token "${d}". Use --clear-deps to clear dependencies.`,p.USAGE);let u=rr(Vt(c.source_kind)),m=Vt(c.author);return{id:ir(d,t,u),kind:On(l),created_at:wN(c.created_at,n),author:m??r,source_kind:u??"cli:update:dep",author_source:m?"asserted":"detected"}})}):{additions:[]}}function SN(e,t){return e?(ke(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new f("--dep-remove requires id or key/value selectors",p.USAGE);let i=Wv(r);if(Er(r,i,"--dep-remove"),i){let s=_e(r,"--dep-remove");$e(s,"--dep-remove",kN);let o=s.id?.trim();if(s.id===void 0)return AN(s);if(!o)throw new f("--dep-remove key/value form requires a non-empty id=<value>",p.USAGE);if(o.toLowerCase()==="undefined")throw new f(`--dep-remove id must not use placeholder token "${o}"`,p.USAGE);let a=Jc(Vt(s.kind??s.type)),c=rr(Vt(s.source_kind)),d=Vt(s.author),l=Vt(s.created_at);return{id:ir(o,t,c),kind:a?On(a):void 0,source_kind:c,author:d,created_at:l?zv(l):void 0}}if(r.toLowerCase()==="undefined")throw new f(`--dep-remove id must not use placeholder token "${r}"`,p.USAGE);return{id:De(r,t)}})):[]}function AN(e){let t=Jc(Vt(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 f("--dep-remove key/value form requires id=<value>, or kind=<kind> alone to remove every row of that kind",p.USAGE);return{kind:On(t)}}function Ys(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function xN(e,t,n,r,i){let s=[...e??[]],o=!1;if(t===void 0){let a=s.filter(c=>i===void 0||!Kc(c,i.value,i.idPrefix));return a.length!==s.length&&(s=a,o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}return s.some(a=>a.kind==="blocked_by"&&a.id===t)||(s.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}async function CN(e,t,n,r,i,s){if(e===void 0||t)return{};let o=e.trim();if(o.length===0)return{};let a=await V(n,De(o,r),r,i,s);return a?{id:a.id}:{unresolved:o}}function EN(e,t,n,r,i,s){let o=xN(e.dependencies,t,n,r,s);o.changed&&(o.dependencies===void 0?delete e.dependencies:e.dependencies=o.dependencies,i.includes("dependencies")||i.push("dependencies"))}function RN(e){return`${e.path}::${e.scope}`}function TN(e){return`${e.path}::${e.scope}`}function IN(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function Dv(e,t){let n=jn("update",e);if(!n)throw new f(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,p.CONFLICT);return n}function ON(e,t,n){let r=new Set,i=(s,o)=>{o&&r.add(s)};if(i("title",e.title!==void 0),i("description",e.description!==void 0),i("body",e.body!==void 0),i("status",e.status!==void 0),i("closeReason",e.closeReason!==void 0),i("priority",e.priority!==void 0),i("type",e.type!==void 0),i("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),i("deadline",e.deadline!==void 0),i("estimatedMinutes",e.estimatedMinutes!==void 0),i("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),i("definitionOfReady",e.definitionOfReady!==void 0),i("order",e.order!==void 0||e.rank!==void 0),i("goal",e.goal!==void 0),i("objective",e.objective!==void 0),i("value",e.value!==void 0),i("impact",e.impact!==void 0),i("outcome",e.outcome!==void 0),i("whyNow",e.whyNow!==void 0),i("author",e.author!==void 0),i("message",e.message!==void 0),i("assignee",e.assignee!==void 0),i("parent",e.parent!==void 0),i("reviewer",e.reviewer!==void 0),i("risk",e.risk!==void 0),i("confidence",e.confidence!==void 0),i("sprint",e.sprint!==void 0),i("release",e.release!==void 0),i("blockedBy",e.blockedBy!==void 0),i("blockedReason",e.blockedReason!==void 0),i("unblockNote",e.unblockNote!==void 0),i("reporter",e.reporter!==void 0),i("severity",e.severity!==void 0),i("environment",e.environment!==void 0),i("reproSteps",e.reproSteps!==void 0),i("resolution",e.resolution!==void 0),i("expectedResult",e.expectedResult!==void 0),i("actualResult",e.actualResult!==void 0),i("affectedVersion",e.affectedVersion!==void 0),i("fixedVersion",e.fixedVersion!==void 0),i("component",e.component!==void 0),i("regression",e.regression!==void 0),i("customerImpact",e.customerImpact!==void 0),i("dep",e.dep!==void 0),i("depRemove",e.depRemove!==void 0),i("dep",e.replaceDeps===!0),i("comment",e.comment!==void 0),i("note",e.note!==void 0),i("learning",e.learning!==void 0),i("file",e.file!==void 0),i("test",e.test!==void 0),i("test",e.replaceTests===!0),i("file",e.replaceFiles===!0),i("doc",e.replaceDocs===!0),i("doc",e.doc!==void 0),i("reminder",e.reminder!==void 0),i("event",e.event!==void 0),i("typeOption",e.typeOption!==void 0),i("field",e.field!==void 0),i("force",e.force===!0),i("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),i("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),i("dep",e.clearDeps===!0),i("comment",e.clearComments===!0),i("note",e.clearNotes===!0),i("learning",e.clearLearnings===!0),i("file",e.clearFiles===!0),i("test",e.clearTests===!0),i("doc",e.clearDocs===!0),i("reminder",e.clearReminders===!0),i("event",e.clearEvents===!0),i("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=Xc(e.unset,t,n,e.runtimeFieldCommands);for(let o of s.optionKeys)i(o,!0)}return r}function NN(e,t,n,r,i){let s=Yr(e,n);if(!s)throw new f(`Invalid type value "${e}"`,p.USAGE);let o=rn(s,"update",[]);if(o.errors.length>0)throw new f(o.errors.join("; "),p.CONFLICT);let a=ON(t,r,i);for(let c of o.disabled)if(a.has(Dv(c,e)))throw new f(`Option ${ve("update",c)} is disabled for type "${e}" by command_option_policies`,p.USAGE);for(let c of o.required)if(!a.has(Dv(c,e)))throw new f(`Missing required option ${ve("update",c)} for type "${e}"`,p.USAGE)}var $N=new Set(["order","rank"]),LN=ko.filter(e=>!$N.has(e)),Bv=["tags","closeReason",...LN],MN=["title","description","body","status","closeReason","completedAt","priority","type",...ko,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],FN=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>se(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Wr(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"}],DN=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>qe(Os(e),Hr,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>$s(e)}],PN=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>qe(Ns(e),Vr,"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=>Ls(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Yc(e,t,n){for(let r of e){let i=t[r.optionKey],s=n.clearItemMetadataKeys.has(r.metadataKey);if(!(i===void 0&&!s)){if(s){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof i!="string")throw new f(`${ve("update",String(r.optionKey))} must be a string value`,p.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(i,n):i.trim(),n.changedFields.push(r.metadataKey)}}}async function UN(e){return Kv(await zr(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 jN(e){let t=tr("update",e);return It(t)?await UN(t):Kv(t)}function qN(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 Hc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new f(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,p.USAGE);if(e.enabled&&e.clearEnabled)throw new f(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,p.USAGE)}function GN(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new f("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",p.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 f("--replace-deps requires at least one --dep entry",p.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new f("--replace-deps cannot be combined with --dep-remove",p.USAGE);Hc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Hc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Hc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function KN(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 f(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,p.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function zN(e){let t={};for(let n of Bv)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function WN(e,t){let n=zN(e);for(let[r,i]of Object.entries(n)){if(!i||!t.optionKeys.has(r))continue;let s=Vs.get(r)??r;throw new f(`Cannot combine --unset ${s} with ${ve("update",r)}`,p.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new f("Cannot combine --unset acceptance-criteria with --add-ac",p.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new f("Cannot combine --unset acceptance-criteria with --remove-ac",p.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new f("Cannot combine --unset tags with --add-tags",p.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new f("Cannot combine --unset tags with --remove-tags",p.USAGE)}}function BN(e){if(Be(e))return;let t=(n,r)=>{if(Be(e,r))return;let i=Vs.get(r),s=i?`Use --unset ${i} to clear this field.`:void 0;Ni(n,ve("update",r),s)};for(let n of Bv)t(e[n],String(n));t(e.order??e.rank,"order"),ke(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),ke(e.event,"--event","Use --clear-events to clear linked events.")}function HN(e,t){let n={};for(let r of MN)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 VN(e){let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Dt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await le(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function YN(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return he(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function XN(e){e.before&&(Ts(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Di(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>ae(t,e.statusRegistry),ie()))}function JN(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new f("--order and --rank must match when both are provided",p.USAGE)}async function QN(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=He(e.options),n=mn(yi(e.options.parent,t),e.settings.id_prefix);if(Ri(n))return{resolvedParentValue:n,warnings:[]};if(vi(e.id,n,e.settings.id_prefix,t),await V(e.pmRoot,n,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:n,warnings:[]};let i=De(n,e.settings.id_prefix);return{resolvedParentValue:n,warnings:wi(i,e.parentReferencePolicy,t).warnings}}function ZN(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function e$(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await V(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await Dt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await le(t,{schema:e.settings.schema}),r=e.options.type!==void 0?et(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",i=Nn({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return i?[i]:[]}async function t$(e){if(!e.fieldFlags.status||re(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;Iv(e);let n=Object.entries(e.fieldFlags).filter(([s,o])=>o&&s!=="status"&&s!=="closeReason"&&s!=="completedAt").map(([s])=>s),r=await Ov(e);if(Wc(r,e.options,e.statusRegistry,e.settings.governance.require_close_reason))return Nv(e,r,n,Tr,s=>Pv(e,s));let i;if(n.length>0){let s=Ve(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0});i=await Tr(e.id,s,e.global)}return Pv(e,i)}async function Pv(e,t){let n=await Cs(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...Zn("update",e.options,He(e.options)==="sdk",n.item),...e.workflowTransitionWarnings,...(t?.warnings??[]).filter(s=>!s.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:i}}function n$(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Gc(t.title,"--title",He(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")),re(e.metadata.status,n)??e.metadata.status}var r$=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function i$(e,t){for(let n of r$)e[n]!==void 0&&(delete e[n],t.push(n))}function s$(e,t,n,r,i){let s=yN(n,t.statusRegistry);if(e.metadata.status=s,i.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,i.push("closed_at","completed_at");return}!ae(s,t.statusRegistry)&&ae(r,t.statusRegistry)&&i$(e.metadata,i)}function o$(e,t,n,r){if(t.options.status!==void 0&&s$(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!ae(e.metadata.status,t.statusRegistry))throw new f("--completed-at can only be set on a terminal item",p.USAGE);e.metadata.completed_at=se(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function a$(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 i=t.options.closeReason?.trim()??"";if(i.length===0)throw new f(ho(He(t.options),"close-reason"),p.USAGE);e.metadata.close_reason=i}r.push("close_reason");return}t.options.status!==void 0&&ae(n,t.statusRegistry)&&!ae(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function c$(e,t,n,r){o$(e,t,n,r),a$(e,t,n,r)}function d$(e,t,n){let r=et(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=ki(t.options.priority),n.push("priority")),t.options.type!==void 0){let i=et(t.options.type,t.typeRegistry);if(!i)throw new f(Si(t.options.type,t.typeRegistry.types,ni(t.pmRoot,t.settings.schema)),p.USAGE);e.metadata.type=i,r=i,n.push("type")}return NN(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),l$(e,t,r,n),r}function l$(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let s=js(t.options.typeOption??[]),o=qn(n,s,t.typeRegistry);if(o.errors.length>0)throw new f(o.errors.join("; "),p.USAGE);e.metadata.type_options=o.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let i=qn(n,e.metadata.type_options,t.typeRegistry);if(i.errors.length>0)throw new f(`Current type options are incompatible with type "${n}". ${i.errors.join("; ")}. Use --clear-type-options to clear them.`,p.USAGE);e.metadata.type_options=i.normalized}function u$(e,t){let n=new Set(t.map(i=>Ys(i))),r=new Set;return e.filter(i=>{if(!n.has(Ys(i)))return!0;let s=Hs(i);return r.has(s)?!1:(r.add(s),!0)})}function m$(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=u$(r,t.dependencyUpdates.additions);let i=new Set(r.map(s=>Ys(s)));for(let s of t.dependencyUpdates.additions){let o=Ys(s);i.has(o)||(r.push(s),i.add(o))}}t.dependencyRemovals.length>0&&($v(r,t.dependencyRemovals,e.metadata.id),r=r.filter(i=>!t.dependencyRemovals.some(s=>Bc(i,s)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function p$(e,t,n){Vc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Vc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Vc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Vc(e,t,n,r,i,s){n===void 0&&!i.has(t)||(i.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],s.push(t))}function f$(e,t,n){Uv(e,"files",t.options.file,t.fileUpdates.values,RN,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),_$(e,t,n),Uv(e,"docs",t.options.doc,t.docUpdates.values,TN,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Uv(e,t,n,r,i,s,o,a){if(!(n===void 0&&!o.has(t))){if(s)e.metadata[t]=r;else if(o.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>i(l)));for(let l of r){let u=i(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}a.push(t)}}function _$(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=jv(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=jv([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function jv(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let i=IN(r);n.has(i)||(t.push(r),n.add(i))}return t}function h$(e,t,n){let r=t.options.addTags,i=t.options.removeTags,s=Array.isArray(r)&&r.length>0||Array.isArray(i)&&i.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let o=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?jr(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Qd(Gr(o,r),i),n.changedFields.push("tags")}Yc(FN,t.options,n),y$(e,t,n.changedFields)}function g$(e,t,n){let r=t.options.addAc,i=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(i)&&i.length>0))return;let s=Jd(qr(e.metadata.acceptance_criteria),r,i);if(s.unmatchedRemovals.length>0)throw new f(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,p.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let o=s.criteria.join("; ");e.metadata.acceptance_criteria!==o&&(o===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=o,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function y$(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 i=Re(r??"","order");if(!Number.isInteger(i))throw new f("Order must be an integer",p.USAGE);e.metadata.order=i}n.push("order")}}function w$(e,t,n,r){v$(e,t,n.changedFields),k$(e,t,n.changedFields),Yc(DN,t.options,n),qv(e,t,"sprint",r,n.changedFields),qv(e,t,"release",r,n.changedFields),b$(e,t,n.changedFields),Yc(PN,t.options,n)}function v$(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 f(ho(He(t.options),"assignee",". Use --unset assignee to clear it."),p.USAGE);wl(r,"--assignee"),e.metadata.assignee=r}n.push("assignee")}}function k$(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 qv(e,t,n,r,i){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=bi(n,t.options[n]??"",t.settings.validation.sprint_release_format,He(t.options));e.metadata[n]=s.value,r.push(...s.warnings)}i.push(n)}}function b$(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)&&EN(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n,{value:r,idPrefix:t.settings.id_prefix})}function S$(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Ps(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=Us(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function A$(e,t,n){Gv(e,t.runtimeFieldRegistry.definitions.map(i=>i.metadata_key),t.clearItemMetadataKeys,n),Gv(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[i,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(i)){let o=i.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(d=>d.metadata_key===i)?.cli_flag??o;throw new f(`Cannot combine --unset ${o} with --${c}`,p.USAGE)}Un(e[i],s)||(e[i]=s,n.push(i))}let r=pi(t.options.field,t.extensionRegistrations,Ms,Fs(t.runtimeFieldRegistry,(t.options.runtimeFieldCommands??[]).includes("update_many")?"update_many":"update",t.options));for(let i of Object.keys(r))if(t.clearItemMetadataKeys.has(i))throw new f(`Cannot combine --unset ${i.replaceAll("_","-")} with --field ${i}=...`,p.USAGE);for(let[i,s]of Object.entries(r))Un(e[i],s)||(e[i]=s,n.push(i))}function Gv(e,t,n,r){for(let i of t)!n.has(i)||e[i]===void 0||(delete e[i],r.push(i))}function x$(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(i=>{let s=t[i];return s!==void 0&&(!Array.isArray(s)||!Un(s,n[i]??[]))});if(r!==void 0)throw new f(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,p.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 C$(e,t){x$(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,i=[],s=[],o=n$(e,t.options,t.statusRegistry,i),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:i,nowValue:t.nowValue};c$(e,t,o,i),d$(e,t,i),m$(e,t,i),p$(e,t,i),f$(e,t,i),h$(e,t,c),g$(e,t,c),w$(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&Rr(e.metadata.id,e.metadata.dependencies),re(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,i.includes("assignee")||i.push("assignee")),S$(e,t,i),A$(a,t,i),fi(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys});let d=e.metadata,l=[...new Set(i)].filter(m=>m==="body"?e.body!==r:!Un(n[m],d[m])),u=Lv(n.dependencies,d.dependencies);return u!==void 0&&s.push(`dependencies_removed:${e.metadata.id}:${u}`),t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${qr(n.acceptance_criteria).length}:${qr(d.acceptance_criteria).length}`),{changedFields:l,warnings:s}}async function Hv(e,t,n,r={}){er(e,"update","id");let i=await jN(t),s=I(process.cwd(),n.path);await z(s);let o=await R(s),a=q(o.schema),c=$t(o.schema),d=M(),l=gt(d),u=F(o,d),m=o.governance.workflow_enforcement??"off",_=m==="off"?[]:ln(o.schema),h=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(i.allowMissingParent===!0)][o.validation.parent_reference],g=Xc(i.unset,c,l,i.runtimeFieldCommands),y=new Set(g.optionKeys),w=new Set(g.metadataKeys);GN(i),KN({definitions:qN(i),options:i,clearOptionKeys:y,clearItemMetadataKeys:w}),gN(e,i,w),WN(i,g),BN(i);let v=H(i.author,o.author_default),k=new Date,b=k.toISOString(),A=bN(i.dep,o.id_prefix,b,v);Rr(e,A.additions);let C=await Ds({pmRoot:s,dependencies:A.additions,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:u.type_to_folder,allowUnresolved:i.allowUnresolvedDeps,holders:[{id:e}],schema:o.schema}),S=SN(i.depRemove,o.id_prefix),x=Bt("--comment",i.comment,b,v),D=i.ownershipMetadataBypass===!0&&x.values?{...x,values:x.values.map(fe=>({...fe,author:v}))}:x,j=Bt("--note",i.note,b,v),T=Bt("--learning",i.learning,b,v),E=Uc(i.file),K=jc(i.test);K.values=await qi(K.values,v,b);let Ge=qc(i.doc),ge=[],Ze=await QN({id:e,options:i,unsetTargets:g,pmRoot:s,settings:o,typeRegistry:u,parentReferencePolicy:h}),mt=await CN(i.blockedBy,w.has("blocked_by"),s,o.id_prefix,o.item_format,u.type_to_folder),pt=mt.id,ye=[...Ze.warnings,...ZN(mt)],Ke=Ul(i,c,i.runtimeFieldCommands),ue=HN(i,Ke);if(!Object.values(ue).some(Boolean))return VN({pmRoot:s,id:e,settings:o,typeRegistry:u});ge.push(...await e$({options:i,fieldFlags:ue,workflowEnforcement:m,typeWorkflows:_,statusRegistry:a,typeRegistry:u,pmRoot:s,id:e,settings:o}));let Zt=await t$({options:i,fieldFlags:ue,statusRegistry:a,workflowTransitionWarnings:ge,global:n,id:e,pmRoot:s,settings:o,typeRegistry:u});if(Zt)return Zt;JN(i);let Ct=ie(),de=ue.parent&&!w.has("parent")||A.additions.some(fe=>Rs(fe.kind,Ct)),Ae=await Is({pmRoot:s,author:v,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:de});try{let fe=await YN({fieldFlags:ue,clearedMetadataKeys:w,pmRoot:s,settings:o,typeToFolder:u.type_to_folder}),N,ft,xe=await un({pmRoot:s,settings:o,typeToFolder:u.type_to_folder,id:e,op:E$(i,r),author:v,message:i.message,resolveHistoryContext:()=>ft,force:i.force,bypassAssigneeConflict:i.ownershipMetadataBypass===!0||i.ownershipDependencyBypass===!0,extensionFieldNames:l,skipNoop:!0,async mutate(we){let ne=we.metadata.status;N=R$({document:we,recurrenceReason:r.recurrenceReason,requestedStatus:i.status,statusRegistry:a}),ft=N?{recurrence:N}:void 0,fe=fe?.map(Fr=>Fr.id===we.metadata.id?structuredClone(we.metadata):Fr);let Mr=C$(we,{options:i,settings:o,typeRegistry:u,statusRegistry:a,runtimeFieldRegistry:c,extensionRegistrations:d,extensionFieldNames:l,clearItemMetadataKeys:w,dependencyUpdates:A,dependencyRemovals:S,commentUpdates:D,noteUpdates:j,learningUpdates:T,fileUpdates:E,testUpdates:K,docUpdates:Ge,resolvedParentValue:Ze.resolvedParentValue,resolvedBlockedByDependencyId:pt,runtimeFieldUpdates:Ke,nowValue:k,nowIso:b,author:v,pmRoot:s});XN({before:fe,document:we,statusRegistry:a});let oo=await Bs({pmRoot:s,settings:o,metadata:we.metadata,fromStatus:ne,registry:a,force:i.force===!0});return{...Mr,warnings:[...Mr.warnings,...oo]}}});await Ae();let Pn=fe?Es(fe,fe.map(we=>we.id===xe.item.id?xe.item:we),xe.item.id):[];return{item:xe.item,changed_fields:xe.changedFields,warnings:[...Zn("update",i,He(i)==="sdk",xe.item),...ge,...ye,...C,...Pn,...xe.warnings],...N===void 0?{}:{lifecycle_transition:N}}}finally{await Ae()}}function E$(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function R$(e){if(e.recurrenceReason===void 0)return;let t=re(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!ae(t,e.statusRegistry))throw new f(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,p.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=re(n,e.statusRegistry)??n,i=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(o=>{let a=i[o];return typeof a=="string"?[[o,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:s}}async function Tr(e,t,n){return Hv(e,t,n)}async function BB(e,t,n,r){er(r,"reopen","reason");let i=await Hv(e,t,n,{recurrenceReason:r});if(i.lifecycle_transition===void 0)throw new f(`Item ${e} did not produce the required recurrence receipt.`,p.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{...i,lifecycle_transition:i.lifecycle_transition}}import{createHash as T$}from"node:crypto";import{readFileSync as I$}from"node:fs";function Xs(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new f("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",p.USAGE);let n=typeof e.handoff=="string"?Fe(e.handoff,t):void 0;if(n===void 0||ht(n,t)||n===t.in_progress_status)throw new f("--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.",p.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new f("--handoff requires --message with implementation evidence and the next verification step.",p.USAGE);return n}function Vv(e,t,n,r,i){if(ht(e.status,r)||!e.assignee?.trim())throw new f("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",p.CONFLICT);let s=n.governance.workflow_enforcement??"off",o=Nn({enforcement:s,typeWorkflows:s==="off"?[]:ln(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),a={from_status:e.status,to_status:t,message:i},c=e.status===t?[]:["status"];return e.status=t,{receipt:a,warnings:o?[o]:[],changedFields:c}}var Jv="no_available_next_item",yH="stale_claim_takeover_refused";function Qv(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 Zv(e,t){return Qv(e)===t}function O$(e){return Zv(e,"already_claimed_by")}async function Zc(e,t,n,r={}){let i=I(process.cwd(),n.path);await z(i);let s=await R(i),o=q(s.schema),a=H(r.author,s.author_default),c=ui(a),d=r.takeoverStale===!0;$$(d,t);let l=null,u=!1,m={},_,h=[],g=await un({pmRoot:i,settings:s,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,resolveHistoryContext:()=>_===void 0?void 0:{stale_claim_takeover:_},async mutate(w,v){let b=w.metadata.assignee??"",A=w.metadata.claim_principal?.trim()||b;if(l=b.trim().length>0?b:null,ht(w.metadata.status,o)&&!t)throw new f(`Cannot claim terminal item ${w.metadata.id} without --force`,p.CONFLICT);if(l!==null&&A!==c){let K=await N$({pmRoot:i,storageId:v.storageId,metadata:w.metadata,holder:b,author:a,thresholdHours:s.mutation_guard.stale_in_progress_hours,force:t,ifAvailable:r.ifAvailable===!0,takeoverStale:d});if(K.kind==="skip")return u=!0,h.push(`claim_skipped_held_by:${Co(b)}`),{changedFields:[]};_=K.takeover,h.push(K.warning)}let S={assignee:a,claim_principal:c},x=["assignee","claim_principal"].filter(K=>w.metadata[K]!==S[K]);Object.assign(w.metadata,S);let D=w.metadata.status,{changedFields:j,warnings:T,...E}=q$(w.metadata,r.start===!0,s,o);return T.push(...await j$({pmRoot:i,settings:s,metadata:w.metadata,fromStatus:D,registry:o,force:t,start:r.start===!0})),m=E,h.push(...T),{changedFields:[...x,...j],warnings:h}}}),y=ek(await tk("claim",g.item.id,n,u,()=>i_({pmRoot:i,settings:s,principal:c,itemId:g.item.id})));return h.push(...y.warnings),{item:xo(g.item),changed_fields:g.changedFields,claimed_by:u&&l!==null?Ot(l):a,previous_assignee:l===null?null:Ot(l),forced:t,...u?{skipped:!0}:{},...h.length>0?{warnings:h}:{},...Qc("suggestions",y.suggestions),...m,..._===void 0?{}:{takeover:_}}}async function N$(e){if(e.ifAvailable&&!e.takeoverStale)return{kind:"skip"};if(e.force)return{kind:"take",warning:`claim_takeover:${Co(e.holder)}->${e.author}`};let t=await o_(e.pmRoot,e.storageId,e.holder,{updated_at:e.metadata.updated_at,threshold_hours:e.thresholdHours}),n=e.takeoverStale?L$(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 D$(e.metadata.id,t,e.takeoverStale)}function $$(e,t){if(!(!e||!t))throw new f("--takeover-stale cannot be combined with --force",p.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 L$(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 M$={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 F$(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:`${M$[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 D$(e,t,n){let r=t.activity,i=r.stale_policy,s={item_id:e,claimed_by:t.holder,claimed_at:t.since,claim_source:t.source,claim_activity:r},o="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=F$(e,r);return new f(`Item ${e} is ${t.phrase}, and its claim is not stale under ${i.setting} (${c.reason}).`,p.CONFLICT,{code:"stale_claim_takeover_refused",...s,required:`The claim must be idle for at least ${i.threshold_hours}h (${i.setting}) before --takeover-stale may take it.`,why:`${o} 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 f(`Item ${e} is already ${t.phrase}. Use --force to take over, or --if-available to skip without failing.`,p.CONFLICT,{code:"already_claimed_by",...s,why:o,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.",...i.stale?[`Re-run with --takeover-stale: the claim has been idle ${r.idle_hours}h, past ${i.setting}=${i.threshold_hours}.`]:[],a]})}var P$="claim_semantic_attribution_unrecorded";function ek(e){return e?{warnings:[e.warning],suggestions:[e.suggestion]}:{warnings:[],suggestions:[]}}function Qc(e,t){return t.length>0?{[e]:t}:{}}var U$="release_semantic_attribution_unrecorded";async function tk(e,t,n,r,i){if(!r)try{await i();return}catch(s){let o=Qv(s)??"unexpected_error",a=Ye(n);return{warning:e==="claim"?P$:U$,suggestion:`The ${e} of ${t} is saved, but the session attribution that names this agent's active work was not updated (${o}); nothing needs a retry. If ${L([...a,"health"])} reports a stale lock, remove it with ${L([...a,"gc","--scope","locks"])}.`}}}function wH(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new f(n?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",p.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 f("Specify either an item id or --next, not both",p.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 j$(e){return e.start?Bs(e):Ev(e)}function q$(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(ht(e.status,r))throw new f(`Cannot start terminal item ${e.id}; reopen it with pm item reopen before starting it`,p.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 i=Ht(r),s=n.governance.workflow_enforcement??"off",o=Nn({enforcement:s,typeWorkflows:s==="off"?[]:ln(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:i}),a={from_status:e.status,to_status:i},c=e.status===i?[]:["status"];return e.status=i,{start:a,changedFields:c,warnings:o?[o]:[]}}async function vH(e,t,n={},r={}){if(n.takeoverStale===!0)throw new f("--takeover-stale cannot be combined with --next",p.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 i=G$(n.maxAttempts),s=await R(I(process.cwd(),t.path)),o={...n,author:H(n.author,s.author_default)},a=await a_({...r,callerAuthor:o.author,limit:String(i)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return K$(c.slice(0,i),e,t,o)}function G$(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new f("--max-attempts must be an integer from 1 to 100",p.USAGE);return t}async function K$(e,t,n,r={},i=Zc){let s=0,o=[],a=()=>o.length>0?{start_refused:[...o]}:{};for(let c of e){s+=1;try{let d=await i(c.id,t,n,r),l={...d,recommendation:c,attempts:s,available:!0,...a()};if(!d.skipped)return l}catch(d){if(Zv(d,Ws)){o.push(c.id);continue}if(!O$(d))throw d}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:H(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,...a(),warnings:[Jv]};throw z$(s,o,r.start===!0)}function z$(e,t,n){let r=e===0,i="Every ranked candidate was claimed by another agent before this atomic selection completed.";return r?i="No ready items matched the specified filters or selection criteria.":t.length>0&&(i=`${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 f(r?"No actionable items matched the selection filters":"No actionable item remained available to claim",r?p.NOT_FOUND:p.CONFLICT,{code:Jv,why:i,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 W$(e){if(e===void 0)return[];let t=e.trim();if(Ot(t)===t)return t.startsWith("-")?[`--author=${t}`]:["--author",t]}var nk="release_claim_ended_by_close";function rk(e,t,n,r,i){let s=W$(i),o=s===void 0?void 0:L([...Ye(r),"claim",e,"--force",...s]),a=o===void 0||kl(o)!==o?"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 ${o} only when that takeover is approved.`;return new f(`A close of ${e} already ended your claim, and ${t} has claimed it since; ${n} cannot move or release another holder's claim.`,p.CONFLICT,{code:nk,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 ik(e){let t=e.assignee?.trim();return t?e.claim_principal?.trim()||t:void 0}async function sk(e,t,n){let r=I(process.cwd(),t.path),i=await R(r),s=ui(H(n,i.author_default)),o=F(i,M()).type_to_folder,a=await V(r,e,i.id_prefix,i.item_format,o);if(!a)return _=>_();let c=Me(r,a.id),d=Xv(c),{document:l}=await le(a,{schema:i.schema}),u=ik(l.metadata);if(u!==void 0&&u!==s&&await ha(r,a.id,s))throw rk(a.id,Ot(l.metadata.assignee.trim()),"--pause",t,n);let m=Yv(l.metadata,d);return _=>mi({pmRoot:r,id:a.id,validate:h=>{if(Yv(h.metadata,Xv(c))!==m)throw new f(`${a.id} changed while the pause was judged, so nothing was written.`,p.CONFLICT,{code:B$,item_id:a.id,nextSteps:[`Check the current holder with ${L([...Ye(t),"get",a.id])}, reconfirm any override, then re-run the original pause command unchanged.`]})}},_)}var B$="pause_item_changed";function Yv(e,t){return JSON.stringify([ik(e)??null,e.status,e.updated_at,t])}function Xv(e){try{return T$("sha256").update(I$(e)).digest("hex")}catch{return"absent"}}async function Js(e,t,n,r={}){let i=I(process.cwd(),n.path);await z(i);let s=await R(i),o=H(r.author,s.author_default),a=ui(o),c=r.ownershipReleaseBypass===!0,d=null,l=q(s.schema),u=Xs(r,l);if(u!==void 0&&c)throw new f("Ownership-release bypass only clears ownership; it cannot change a handoff status.",p.USAGE);let m,_,h;try{h=await Ie({pmRoot:i,settings:s,id:e,op:"release",author:o,message:r.message,force:t,bypassAssigneeConflict:c,...c?{}:{callerClaimScope:({storageId:w,callerPrincipal:v})=>ha(i,w,v)},mutate(w,v){if(v.callerClaimScoped===!0){let b=Ot(w.metadata.assignee.trim());if(u!==void 0)throw rk(w.metadata.id,b,"--handoff",n,r.author);return _=b,{changedFields:[],warnings:[`${nk}:${w.metadata.id}:${b}`]}}d=w.metadata.assignee??null;let k=u===void 0?void 0:Vv(w.metadata,u,s,l,r.message);return m=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){ar(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=ek(await tk("release",h.item.id,n,!1,()=>s_({pmRoot:i,principal:a,itemId:h.item.id}))),y=_===void 0?H$(h.item,l):{warnings:[],suggestions:[`A close of ${h.item.id} already ended your claim; ${_} claimed it afterwards and keeps it. The item was not changed.`]};return{item:xo(h.item),released_by:o,changed_fields:h.changedFields,previous_assignee:d===null?null:Ot(d),forced:t,...m===void 0?{}:{handoff:m},...Qc("warnings",[...h.warnings,...y.warnings,...g.warnings]),...Qc("suggestions",[...y.suggestions,...g.suggestions])}}function H$(e,t){return Lt(e.status,t)===Lt(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:[]}}async function ed(e,t,n){try{return await n()}catch(r){let i=r instanceof f?r.context:{},s=new f(r instanceof Error?r.message:String(r),r instanceof f?r.exitCode:p.GENERIC_FAILURE,{...i,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${i.why?` ${i.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...i.nextSteps??[]]});throw s.cause=r,s}}async function MH(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new f("--start cannot be combined with --next or --if-available for an explicit item",p.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 R(I(process.cwd(),n.path)),i=Ht(q(r.schema));return Cv(async()=>{let s=await Zc(e,t.force===!0,n,Mi(t,{},["start"])),o=s.item.id,a=await ed(o,"claim",()=>Tr(o,Mi(t,{status:i},["assignee","start","next","ifAvailable","maxAttempts","takeoverStale"]),n)).catch(async c=>{throw await V$(c,s,n,t.author)});return{id:o,action:"start_task",claim:s,update:a}})}async function V$(e,t,n,r){if(!(e instanceof f)||e.code!==Ws||t.previous_assignee!==null)return e;let i=String(t.item.id);try{await mi({pmRoot:I(process.cwd(),n.path),id:i,validate:o=>{if(o.metadata.assignee!==t.claimed_by||o.metadata.claim_principal!==t.item.claim_principal)throw new f("The claim this start took is no longer its own.",p.CONFLICT)}},()=>Js(i,!1,n,{author:r,message:"Release the claim: a blocker opened before its start could be recorded"}))}catch{return e}let s=e.cause instanceof f?e.cause:e;return new f(s.message,s.exitCode,{...s.context,why:`${s.context.why??""} A blocker opened after this start's claim, so the claim was released and no ownership remains.`.trim()})}async function FH(e,t,n){let r=await R(I(process.cwd(),n.path)),i=q(r.schema);Xs({...t,pause:!0},i);let s=await sk(e,n,t.author),o=i.open_status,a=await s(()=>Tr(e,Mi(t,{status:o},["assignee","pause"]),n)),c=a.item.id,d=await ed(c,"update",()=>Js(c,t.force===!0,n,t));return{id:c,action:"pause_task",update:a,release:d}}async function DH(e,t,n,r){let i=await Cs(e,t,n,r),s=i.item.id,o=await ed(s,"close",()=>Js(s,n.force===!0,r,n));return{id:s,action:"close_task",close:i,release:o}}import Ir from"node:crypto";import{cp as ok,lstat as Y$,mkdir as Yt,readFile as Ln,readdir as nd,rename as dk,rm as id,writeFile as Qs}from"node:fs/promises";import U from"node:path";var lk="https://schema.unbrained.dev/pm/workspace-snapshot/v1",YH=["create","list","inspect","restore","delete"],uk=U.join("runtime","workspace-snapshots"),X$=new Set(["checkpoints","locks","runtime","search","transactions"]),J$=/^[a-z0-9][a-z0-9._-]*$/,$n="sdk-workspace-transaction",td={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},mk={renameEntry:dk,removeEntry:async e=>{await id(e,{recursive:!0,force:!0})}},rd=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 Yl(this.lockPath,$n);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await Ln(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!==$n||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await Le(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
|
|
10
|
+
`)}finally{await t()}}};async function pk(e,t=""){let n=await nd(U.join(e,t),{withFileTypes:!0}),r=[];for(let i of n.sort((s,o)=>s.name.localeCompare(o.name))){if(t.length===0&&X$.has(i.name))continue;let s=U.posix.join(t.replaceAll(U.sep,"/"),i.name);if(i.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${s}`);if(i.isDirectory())r.push(...await pk(e,s));else if(i.isFile())r.push(s);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${s}`)}return r}async function fk(e){let t=await pk(e),n=Ir.createHash("sha256"),r=[],i=0;for(let o of t){let a=await Ln(U.join(e,o));r.push(a),i+=a.byteLength,n.update(o),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let s=n.digest("hex");return{manifest:{schema:lk,fingerprint:s,files:t,bytes:i},contents:r}}function ak(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
|
|
11
|
+
`).filter(t=>t.trim().length>0).length}async function Q$(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let i=t.slice(r,r+32),s=await Promise.all(i.map(async o=>[o,await Ln(U.join(e,o))]));for(let[o,a]of s)n.set(o,a)}return n}function sd(e){if(!J$.test(e))throw new f("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",p.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 _k(e,t){return wu(`workspace_snapshot_${e}`,t,{codes:{capacity:td.capacity.code,permission:td.permission.code,resource:td.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 Xt(e){return U.join(e,uk)}function hk(e){return new f(`Unknown workspace snapshot: ${e}`,p.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 gk(e,t){try{return JSON.parse(await Ln(e,"utf8"))}catch(n){throw B(n)?hk(t):n}}async function ck(e,t,n){try{await id(e,{recursive:n})}catch(r){throw B(r)?hk(t):r}}async function Z$(e,t,n=mk){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 eL(e,t,n,r,i){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await i?.()}catch(s){throw await r.renameEntry(n,t),await r.removeEntry(e),s}await r.removeEntry(n)}async function tL(e,t){return sd(t),/^[a-f0-9]{64}$/.test(t)?t:(await gk(U.join(Xt(e),"refs",`${t}.json`),t)).fingerprint}async function nL(e,t={}){if(t.name!==void 0&&(sd(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new f("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",p.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 fk(e),i=Xt(e),s=U.join(i,"objects",n.fingerprint),o=!1;try{o=(await Y$(s)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&B(a)))throw a}if(!o){let a=U.join(i,"objects",`.create-${process.pid}-${Ir.randomUUID()}`);await _k("create_object",async()=>{await Yt(U.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let l=U.join(a,"files",d);await Yt(U.dirname(l),{recursive:!0}),await Qs(l,r[c])}await Qs(U.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
|
|
12
|
+
`,"utf8"),await Yt(U.dirname(s),{recursive:!0})}),o=await Z$(a,s)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=U.join(i,"refs");await Yt(c,{recursive:!0});let d=U.join(c,`.ref-${process.pid}-${Ir.randomUUID()}`);await Qs(d,`${JSON.stringify(a,null,2)}
|
|
13
|
+
`,"utf8"),await dk(d,U.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:o}}async function od(e,t){let n=await tL(e,t),r=await gk(U.join(Xt(e),"objects",n,"manifest.json"),t);if(r.schema!==lk||r.fingerprint!==n)throw new f(`Snapshot manifest identity mismatch: ${t}`,p.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 rL(e){let t=Xt(e),n=await nd(U.join(t,"objects")).catch(i=>{if(i instanceof Error&&"code"in i&&B(i))return[];throw i}),r=await nd(U.join(t,"refs")).catch(i=>{if(i instanceof Error&&"code"in i&&B(i))return[];throw i});return{objects:await Promise.all(n.filter(i=>/^[a-f0-9]{64}$/.test(i)).sort().map(i=>od(e,i))),references:await Promise.all(r.filter(i=>i.endsWith(".json")).sort().map(async i=>JSON.parse(await Ln(U.join(t,"refs",i),"utf8"))))}}async function iL(e,t){let n=await od(e,t),{manifest:r,contents:i}=await fk(e),s=new Map(r.files.map((u,m)=>[u,i[m]])),o=await Q$(U.join(Xt(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),d=new Set([...a,...c]);for(let u of d){let m=s.get(u),_=o.get(u);m!==void 0&&_!==void 0&&m.equals(_)&&d.delete(u)}let l=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let m=ak(s.get(u)),_=ak(o.get(u));return{path:u,current_entries:m,target_entries:_,removed_entries:Math.max(0,m-_)}}).filter(u=>u.removed_entries>0).sort((u,m)=>u.path.localeCompare(m.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!a.has(u)).length,removed_item_count:[...a].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:l.length,removed_history_entry_count:l.reduce((u,m)=>u+m.removed_entries,0),affected_history_streams:l,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function sL(e,t,n={}){if(n.force!==!0)throw new f("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",p.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",i=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,o=await li(e,$n,i,r,!1,!1,s),a=o.release,c=new rd(Xr(e,$n),r,i);c.start(),await c.refreshNow();let d,l=!1,u=!1;try{let m=await iL(e,t),_=await od(e,t),h=await nL(e),g=_.fingerprint,y=Xt(e),w=U.join(y,"objects",g,"files"),v=U.dirname(e),k=U.basename(e);d=U.join(v,`.${k}.restore-${Ir.randomUUID()}`);let b=U.join(v,`.${k}.backup-${Ir.randomUUID()}`);await _k("restore_stage",async()=>{await Yt(d,{recursive:!0}),await ok(w,d,{recursive:!0,force:!1}),await Yt(U.join(d,"runtime"),{recursive:!0}),await ok(y,U.join(d,uk),{recursive:!0,force:!1})});let A=await cn({pmRoot:d,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${h.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:h.manifest.fingerprint,changed_file_count:m.changed_file_count,removed_file_count:m.removed_file_count,removed_item_count:m.removed_item_count,affected_history_stream_count:m.affected_history_stream_count,removed_history_entry_count:m.removed_history_entry_count},lockTtlSeconds:i,lockWaitMs:s}),C=U.relative(d,A.historyPath).replaceAll("\\","/");await c.stop(),u=!0;let S=Xr(d,$n),x=d;return await o.fence(async()=>{await Yt(U.dirname(S),{recursive:!0}),await Qs(S,await Ln(Xr(e,$n)),{flag:"wx"}),l=!0,await eL(x,e,b,mk,async()=>{c.start(),u=!1,await c.refreshNow()})}),await c.stop(),u=!0,{manifest:_,plan:m,recovery_fingerprint:h.manifest.fingerprint,audit_history_path:C,audit_operation:"workspace_snapshot_restore"}}catch(m){throw d!==void 0&&!l&&await Promise.allSettled([id(d,{recursive:!0,force:!0})]),m}finally{try{u||await c.stop()}catch{}finally{await a()}}}async function XH(e,t){return(await sL(e,t,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function JH(e,t){sd(t);let n=Xt(e);if(!/^[a-f0-9]{64}$/.test(t))return await ck(U.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await rL(e);if(r.some(i=>i.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await ck(U.join(n,"objects",t),t,!0),{deleted:"object",target:t}}function yk(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function wk(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?L([...r,"merge","report"],n):e==="history_evidence_invalid"?L([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?L([...r,"merge","reconcile"],n):e==="history_repair_required"?L([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?L([...r,"merge","install"],n):null}function vk(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(r=>typeof r=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(r=>typeof r=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function lV(e){let t=I(process.cwd(),e.path);await z(t);let n=await R(t),r=F(n,M()),i=[],s=await hs({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),o=await bt(t),[a,c,d,l]=await Promise.all([fn(t,pn(n),{gitWorkspaceRoot:o}),o===null?Promise.resolve(null):_n(o),gn(o??t,{includeLossless:!0,pmRoot:t}),gs(t,s,!1)]),{pendingDecisions:u,lossless:m}=yn(d.receipts),_=[...new Set(u.map(w=>w.item_id))].sort((w,v)=>w.localeCompare(v)),h=l.check.details,g=vk(h),y=yk({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:m.length,historyEvidenceValid:g.evidence_valid,driftedItemCount:g.drifted_item_count,fence:a,drivers:c});return{ok:y==="ready",state:y,merge_fence:{committed:a,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:_.slice(0,25),pending_item_ids_truncated:_.length>25,lossless_count:m.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:g,next_action:{command:wk(y,t),reason:y},warnings:[...new Set(i)].sort((w,v)=>w.localeCompare(v)),generated_at:O()}}function uV(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
|
|
14
|
+
`)}var mV={commandForWorkspacePositionState:wk,normalizeWorkspaceHistoryDrift:vk,selectWorkspacePositionState:yk};import{createHash as aL}from"node:crypto";import{execFile as cL}from"node:child_process";import Sk from"node:path";import{promisify as dL}from"node:util";var kk=1;function oL(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 ad(e){if(e===null)return{format_version:kk,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new f("Improvement ledger contains invalid JSON.",p.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==kk||!Array.isArray(t.observations))throw new f("Improvement ledger has an unsupported shape or format version.",p.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!oL(r))throw new f("Improvement ledger contains an invalid observation.",p.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}var lL=dL(cL),uL=50,bk=1e3,mL=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Ak(e){let t=e.trim().toLowerCase();if(!mL.test(t))throw new f(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,p.USAGE,{code:"invalid_improvement_metric"});return t}function pL(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new f("Improvement direction must be higher, lower, or target.",p.USAGE,{code:"invalid_improvement_observation"});return t}function Or(e,t){let n=e?.trim();if(n){if(n.length>256)throw new f(`${t} must not exceed 256 characters.`,p.USAGE,{code:"invalid_improvement_observation"});return n}}function fL(e){let t=e??uL;if(!Number.isSafeInteger(t)||t<0||t>bk)throw new f(`Improvement observation limit must be an integer from 0 to ${bk}.`,p.USAGE,{code:"invalid_improvement_observation_limit"});return t}function xk(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new f(`${t} must be an ISO timestamp.`,p.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function _L(e,t,n){if(!Number.isFinite(n.value))throw new f("Improvement observation value must be finite.",p.USAGE,{code:"invalid_improvement_observation"});let r=Ak(n.metric),i=pL(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||i==="target"&&n.threshold===void 0)throw new f("Target-directed observations require a finite threshold.",p.USAGE,{code:"invalid_improvement_observation"});let s=await gL(e,n.revision),o=Or(n.source,"source"),a=Or(n.itemId,"itemId"),c=Or(n.unit,"unit"),d=Or(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,r,o??"manual",a??"workspace"].join(":")),l={metric:r,value:n.value,direction:i,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:xk(n.observedAt??O(),"observedAt"),...s,author:H(n.author,t.author_default),...a===void 0?{}:{item_id:a},...o===void 0?{}:{source:o},...d===void 0?{}:{idempotency_key:d}};return{id:aL("sha256").update(Z(l)).digest("hex").slice(0,24),...l}}function hL(e,t){let n=t.idempotency_key?e.observations.find(i=>i.idempotency_key===t.idempotency_key):e.observations.find(i=>i.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 f(`Improvement observation retry key already records a different value for ${t.metric}.`,p.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(i=>i.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new f(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,p.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function gL(e,t){let n=Or(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await lL("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:_t(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function yL(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,i=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:i,sample_count:e.length}}async function Ck(e,t={}){let n=I(process.cwd(),t.path);await z(n);let r=await R(n),i=await _L(n,r,e),s=Sk.join(n,"improvement-ledger.json"),o=await dn({pmRoot:n,filePath:s,op:"improvement_observe",author:i.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${i.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=ad(a),d=hL(c,i);return d?{raw:a,result:d}:(c.observations.push(i),c.observations.sort((l,u)=>l.observed_at.localeCompare(u.observed_at)||l.metric.localeCompare(u.metric)||l.id.localeCompare(u.id)),{raw:`${Z(c)}
|
|
15
|
+
`,result:i})}});return{changed:o.changed,observation:o.result,ledger_path:"improvement-ledger.json"}}async function Ek(e={}){let t=I(e.cwd??process.cwd(),e.pmRoot);await z(t);let n=e.metric===void 0?void 0:Ak(e.metric),r=e.since===void 0?void 0:xk(e.since,"since"),i=fL(e.limit),o=ad(await ee(Sk.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 o){let d=a.get(c.metric)??[];d.push(c),a.set(c.metric,d)}return{observations:[...o].reverse().slice(0,i),total:o.length,truncated:o.length>i,trends:[...a].map(([,c])=>yL(c)).sort((c,d)=>c.metric.localeCompare(d.metric)),source:"audited_workspace_singleton"}}function wL(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 vL(e,t,n){let r=t,i=new Set([e.id]);for(;r!==void 0&&!i.has(r.id);)i.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function kL(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,i)=>r.entries[0].ts.localeCompare(i.entries[0].ts)||r.id.localeCompare(i.id)),t.push(...n.map(r=>r.children))}}function Rk(e=Wn,t=zn){return t.map(n=>{let r=e.filter(i=>((n==="model"?i.model_environment_keys:i.provenance_environment_keys?.[n])?.length??0)>0||i.provenance_resolvers?.[n]!==void 0).map(i=>i.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function LV(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let i=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};i.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?i.observed+=1:r.agent_provenance?.model===null?i.unavailable+=1:i.legacy_missing+=1,n.set(r.agent_harness,i)}return[...n.values()].map(r=>{let i=r.observed+r.unavailable;return{...r,coverage:i===0?null:r.observed/i,inert:i>=t&&r.observed===0}}).sort((r,i)=>r.harness.localeCompare(i.harness))}function Tk(e,t=zn,n=1){let r=new Map;for(let i of e)if(i.agent_harness)for(let s of t){let o=`${i.agent_harness}\0${s}`,a=r.get(o)??{harness:i.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=i.agent_provenance?.[s];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(o,a)}return[...r.values()].map(i=>{let s=i.observed+i.unavailable;return{...i,coverage:s===0?null:i.observed/s,inert:s>=n&&i.observed===0}}).sort((i,s)=>i.harness.localeCompare(s.harness)||i.dimension.localeCompare(s.dimension))}function MV(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 i=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let l=`${c.agent_harness}\0${d}`,u=i.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let m=c.agent_provenance?.[d];m?.value&&(u.observed+=1,u.by_source[m.source]=(u.by_source[m.source]??0)+1),i.set(l,u)}let s=[...i.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[l])=>d.localeCompare(l)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),o=s.filter(c=>c.entries>=r),a=o.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:o.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:s,failures:a}}function FV(e){let t=[...e].sort((s,o)=>s.ts.localeCompare(o.ts)||s.author.localeCompare(o.author)||s.op.localeCompare(o.op)||s.before_hash.localeCompare(o.before_hash)||s.after_hash.localeCompare(o.after_hash)),n=new Map,r=new Map;for(let s of t){let o=s.agent_episode,a=wL(s),c=`${a.source}:${a.id}`,d=n.get(c);if(d){d.entries.push(s);continue}let l={id:a.id,...o?.label===void 0?{}:{label:o.label},...o?.parent_id===void 0?{}:{parent_id:o.parent_id},source:a.source,entries:[s],children:[]};n.set(c,l),o!==void 0&&r.set(a.id,l)}let i=[];for(let s of n.values()){let o=s.parent_id?r.get(s.parent_id):void 0;o&&vL(s,o,r)?o.children.push(s):i.push(s)}return kL(i),i}var bL=1e4,Ik=1e5,SL=1e3,AL=30,xL=["append","comment","docs","file","learning","note","test_run"];function CL(e){let t=e??bL;if(!Number.isSafeInteger(t)||t<1||t>Ik)throw new f(`History analytics event limit must be an integer from 1 to ${Ik}.`,p.USAGE,{code:"invalid_history_analytics_limit"});return t}function Ok(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new f("History analytics minimum sample must be an integer from 1 to 10000.",p.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function EL(e){let t=e?.trim();if(!t)return new Date(Date.now()-AL*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let i=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(i)||i<1)throw new f("History analytics --since duration must be positive.",p.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-i*s).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new f("History analytics --since must be an ISO timestamp or negative duration such as -30d.",p.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function Zs(e,t){let n=CL(t.eventLimit),r=EL(t.since),i=[],s=r,o=!1;for(;i.length<n;){let a=await c_({pmRoot:e,since:s,limit:Math.min(SL,n-i.length),full:!0}),c=a.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(i.push(...c),o=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:i,receipt:{since:r,events:i.length,truncated:o,...o?{next_cursor:s}:{},source:"history_event_index"}}}function RL(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function TL(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 IL(e){return xL.some(t=>e.startsWith(t))}function Nk(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 OL(e,t,n){let r=new Map,i=new Map,s=new Map;for(let o of t){let a=RL(o.entry,e),c=TL(o.entry),d=i.get(o.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&i.set(o.item_id,l),!a)continue;let u=Nk(r,a);u.events+=1,IL(o.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,s.set(o.item_id,a)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:r,lastCloseValue:s}}function NL(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let i=new Set((r.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of i){let o=t.get(s);o&&(Nk(e,o).defectEscapes+=1)}}}function $L(e,t,n,r){let i=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:i==="available"?t.closes/r:null,rework_rate:i==="available"?t.reopens/t.closes:null,defect_escape_rate:i==="available"?t.defectEscapes/t.closes:null,sample_status:i}}function LL(e,t,n,r,i,s){let{buckets:o,lastCloseValue:a}=OL(e,t,r);return NL(o,a,n),{dimension:e,status:o.size===0?"unavailable":"available",rows:[...o].map(([c,d])=>$L(c,d,i,s)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function ML(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,i=Date.parse(n),s=Date.parse(r);return!Number.isFinite(i)||!Number.isFinite(s)?1:Math.max(1,(s-i)/864e5)}function FL(e,t,n){let r=Rk(t),i=Tk(e,zn,n),s=i.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),o=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:i,inert:s,undeclared:o,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...o.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function KV(e,t=Wn,n={}){return cd(await Zs(e,n),t,n)}function cd(e,t=Wn,n={}){let r=Ok(n.minimumSample);return{...FL(e.events.map(i=>i.entry),t,r),window:e.receipt}}async function zV(e,t,n,r={}){return dd(await Zs(e,r),t,n,r)}function dd(e,t,n,r={}){let i=Ok(r.minimumSample),s=ML(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(o=>LL(o,e.events,t,n,i,s)),minimum_sample:i,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}import PL from"node:fs/promises";import Lk from"node:path";function eo(e,t,n,r,i,s="min"){let o=i==="min"?e-t:t-e,a=s==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return o<0||o===0&&r!==null&&a<0}function DL(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,i=null,s=null,o=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 l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,m=Date.parse(u);Number.isNaN(m)||(eo(m,o,u,i,"min")&&(o=m,i=u),eo(m,a,u,s,"max","max")&&(a=m,s=u))}return{id:e,bytes:n,lines:r,oldest_ts:i,newest_ts:s}}function $k(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),i=e.map(({id:_,raw:h})=>DL(_,h)),s=0,o=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let _ of i){if(s+=_.lines,o+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);eo(h,d,_.id,a?.id??null,"min")&&(d=h,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);eo(h,l,_.id,c?.id??null,"max")&&(l=h,c={id:_.id,ts:_.newest_ts})}}let u=r===0?[]:[...i].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),m=r===0?[]:[...i].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:s,total_bytes:o,largest_by_bytes:u,deepest_by_lines:m,oldest_entry:a,newest_entry:c}}function UL(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function jL(e,t,n,r,i){let s=nr(e,"type",r),o=new Set(s.rows.map(m=>m.key)),a=t.filter(m=>!o.has(m)),d=(i?[...s.rows,...a.map(m=>({label:m,key:m,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(m=>({type:m.key??m.label,total:m.total,open:m.buckets.open,in_progress:m.buckets.in_progress,blocked:m.buckets.blocked,draft:m.buckets.draft,closed:m.buckets.closed,canceled:m.buckets.canceled,other:m.buckets.other})),l=UL([...n]);for(let m of e)l[m.status]+=1;let u=Object.fromEntries(Object.entries(l).filter(([,m])=>i||m>0));return{byType:d,byStatus:u,omitted:i?0:a.length+Object.values(l).filter(m=>m===0).length}}function qL(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function GL(e){let t=Lk.join(e,"history");if(!await me(t))return[];await Te({path:t,scope:"project"});let n=(await PL.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,s)=>i.localeCompare(s)),r=[];for(let i of n){let s=Lk.join(t,i),o=await ee(s);o!==null&&(await Te({path:s,scope:"project"}),r.push({id:i.slice(0,-6),raw:o}))}return r}async function KL(e,t){let n=[],r=O();for(let i of d_(t.observe,r))n.push(await Ck({metric:i.name,value:i.value,direction:t.direction,unit:i.unit,threshold:i.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function zL(e,t,n){let r={};return t.byAssignee&&(r.assignee=nr(e,"assignee",n)),t.byTag&&(r.tag=nr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=nr(e,"priority",n)),r}async function WL(e,t,n,r,i){let s={since:i.since,eventLimit:i.eventLimit,minimumSample:i.minimumSample},o=i.provenanceCoverage||i.fleetAttribution?await Zs(e,s):void 0;return{provenanceCoverage:i.provenanceCoverage&&o?cd(o,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:i.fleetAttribution&&o?dd(o,t,r,s):void 0}}function BL(e,t,n,r,i){let s=Object.keys(i.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...i.metadataCoverage?{metadata_coverage:i.metadataCoverage}:{},...s?{breakdowns:i.breakdowns}:{},...i.storage?{storage:i.storage}:{},...i.fieldUtilization?{field_utilization:i.fieldUtilization}:{},...i.improvementLedger?{improvement_ledger:i.improvementLedger}:{},...i.recordedObservations.length>0?{recorded_observations:i.recordedObservations}:{},...i.provenanceCoverage?{provenance_coverage:i.provenanceCoverage}:{},...i.fleetAttribution?{fleet_attribution:i.fleetAttribution}:{},generated_at:O()}}async function u2(e,t={}){let n=I(process.cwd(),e.path);await z(n);let r=await R(n),i=await KL(e,t),s=F(r,M()),o=q(r.schema),a=t.fieldUtilization?await rt(n,r.item_format,s.type_to_folder,void 0,r.schema):await he(n,r.item_format,s.type_to_folder,void 0,r.schema);await gi({pmRoot:n,settings:r,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=Sf(o),d=jL(a,s.types,o.definitions.map(k=>k.id),c,t.includeEmpty===!0),l=await GL(n),u=0;for(let k of l)u+=qL(k.raw);let m=t.storage?$k(l):void 0,_=t.metadataCoverage?Af(a,c):void 0,h=zL(a,t,c),g=t.fieldUtilization?xf(a):void 0,y=t.measurements===!0||i.length>0?await Ek({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:v}=await WL(n,a,r,o.terminal_statuses,t);return BL({items:a.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:_,breakdowns:h,storage:m,fieldUtilization:g,improvementLedger:y,recordedObservations:i,provenanceCoverage:w,fleetAttribution:v})}import HL from"node:fs/promises";import ut from"node:path";var Uk=ut.join("runtime","telemetry","state.json"),Nr=ut.join("runtime","telemetry"),VL=20,md=Tt.filter(e=>e.lifecycle==="deprecated"),Mk=["status","flush","stats","clear"],Fk=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},ld=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Dk=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},YL=e=>({command:ld(e.event.command,"<unknown>"),eventType:ld(e.event.event_type,"unknown"),eventSchemaVersion:Dk(e.event.schema_version),clientSchemaVersion:Dk(e.client_schema_version)}),XL=()=>({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:{}}),JL=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},QL=e=>{let t=e?.command_resolution;return ld(t,"")||void 0},jk=(e,t)=>{e[t]=(e[t]??0)+1},ZL=(e,t)=>{let n=JL(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=QL(t);r!==void 0&&jk(e.resolution_counts,r)},eM=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Pk=(e,t)=>{t!==void 0&&e.add(t)},tM=(e,t)=>{let n=YL(t),r=e.get(n.command)??XL();r.count+=1,r.max_attempts=Math.max(r.max_attempts,eM(t.attempts)),jk(r.event_type_counts,n.eventType),Pk(r.event_schema_versions,n.eventSchemaVersion),Pk(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&ZL(r,t.event.payload),e.set(n.command,r)},nM=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((s,o)=>s-o),i=Object.entries(t.resolution_counts).sort((s,o)=>s[0].localeCompare(o[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,o)=>s[0].localeCompare(o[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,o)=>s-o),client_schema_versions:[...t.client_schema_versions].sort((s,o)=>s-o),...r.length>0?{duration_p50_ms:Fk(r,.5),duration_p95_ms:Fk(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}:{},...i.length>0?{command_resolution_counts:Object.fromEntries(i)}:{}}},rM=e=>{let t=(e??"status").trim().toLowerCase();if(Mk.includes(t))return t;throw ti({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Mk,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},pd=()=>{throw new f("--limit must be a positive integer",p.USAGE)},qk=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?pd():e,iM=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?pd():qk(Number.parseInt(t,10))},sM=e=>e===void 0?VL:typeof e=="number"?qk(e):typeof e=="string"?iM(e):pd(),oM=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},aM=e=>{try{let t=JSON.parse(e);return oM(t)?t:void 0}catch{return}},cM=e=>e===null?[]:e.split(`
|
|
16
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),Gk=e=>{let t=cM(e),n=[],r=0;for(let i of t){let s=aM(i);s===void 0?r+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},dM=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lM=e=>{try{let t=JSON.parse(e);return dM(t)?t:{}}catch{return{}}},no=async e=>{let t=await ee(e);return t===null||t.trim().length===0?{}:lM(t)};function Kk(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 uM(e,t,n){let r=Object.create(null);for(let[i,s]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(i)||i<t||i>n||typeof s!="object"||s===null||Array.isArray(s))continue;let o=s;!Number.isSafeInteger(o.count)||o.count<1||typeof o.last_seen!="string"||!o.last_seen.startsWith(i)||(r[i]={count:o.count,last_seen:o.last_seen})}return r}function ud(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,i=new Date().toISOString().slice(0,10);for(let s of md){let o=r[s.alias];if(typeof o!="object"||o===null||Array.isArray(o))continue;let a=o;if(a.canonical!==s.canonical||typeof a.days!="object"||a.days===null||Array.isArray(a.days))continue;let c=uM(a.days,t,i);Object.keys(c).length>0&&(n[s.alias]={canonical:s.canonical,days:c})}return n}async function mM(e,t,n){let r=Kk(n),i=await no(t),s=ud(i.alias_usage,r);if(JSON.stringify(i.alias_usage??{})===JSON.stringify(s))return s;try{await Ci(async()=>{let o=await no(t);if(o.alias_usage===void 0)return;let a=ud(o.alias_usage,r);JSON.stringify(o.alias_usage)!==JSON.stringify(a)&&await Le(t,`${JSON.stringify({...o,alias_usage:a},null,2)}
|
|
17
|
+
`)},e,250)}catch{}return s}async function x2(e){let t=md.find(r=>r.alias===e);if(!t||Pt().telemetry_disabled)return!1;let n=tt(process.cwd());try{return await Ci(async()=>{let r=await R(n);if(!r.telemetry.enabled||Pt().telemetry_disabled)return!1;let i=ut.join(n,Uk),s=await no(i),o=ud(s.alias_usage,Kk(r.telemetry.retention_days)),a=new Date().toISOString().slice(0,10),c=o[e]?.days[a];return o[e]={canonical:t.canonical,days:{...o[e]?.days,[a]:{count:Math.min(Number.MAX_SAFE_INTEGER,(c?.count??0)+1),last_seen:O()}}},await Le(i,`${JSON.stringify({...s,alias_usage:o},null,2)}
|
|
18
|
+
`),!0},n,250)}catch{return!1}}var to=e=>e??null,ro=async e=>{let t=await R(e),n=ut.join(e,Nr,yt("events.jsonl")),r=ut.join(e,Nr,yt("state.json")),i=await ee(n),s=Gk(i),o=await no(r),a=Pt();return{enabled:t.telemetry.enabled&&!a.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:a,endpoint:wt(Vn(t.telemetry.endpoint)),queue_path:n,state_path:r,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(i??"","utf8"),last_attempted_flush_at:to(o.last_attempted_flush_at),last_successful_flush_at:to(o.last_successful_flush_at),last_failed_flush_at:to(o.last_failed_flush_at),last_failed_flush_error:to(o.last_failed_flush_error)}},pM=e=>{let t=new Map;for(let n of e)tM(t,n);return[...t.entries()].map(([n,r])=>nM(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},fM=async(e,t)=>({action:"telemetry",subcommand:"status",status:await ro(t.globalPmRoot),generated_at:O()}),_M=async(e,t)=>{let n=await ro(t.globalPmRoot);await om(t.globalPmRoot);let r=await ro(t.globalPmRoot),i=Math.max(0,n.queue_entries-r.queue_entries),s=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:i,queue_progressed:i>0,queue_empty:s,queue_drained:s,status:r,generated_at:O()}},hM=async(e,t)=>{let n=sM(e.limit),r=await ee(t.queuePath),i=Gk(r),s=pM(i.entries),o=s.slice(0,n),a=await R(t.globalPmRoot),c=await mM(t.globalPmRoot,ut.join(t.globalPmRoot,Uk),a.telemetry.retention_days),d=Object.entries(c).map(([l,u])=>{let m=Object.values(u.days);return{alias:l,canonical:u.canonical,count:m.reduce((_,h)=>Math.min(Number.MAX_SAFE_INTEGER,_+h.count),0),last_seen:m.map(_=>_.last_seen).sort().at(-1)}}).sort((l,u)=>u.count-l.count||l.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_rows_total:i.rows_total,truncated:s.length>o.length,stats:o,alias_usage:d,zero_use_aliases:md.map(l=>l.alias).filter(l=>c[l]===void 0),alias_usage_retention_days:a.telemetry.retention_days,generated_at:O()}},gM=async(e,t)=>Ci(async()=>{let n=await R(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 Fu(t.globalPmRoot,n,"telemetry:clear");let i=ut.join(t.globalPmRoot,Nr),s=await me(i);return await HL.rm(i,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:s&&!await me(i),queue_exists_after:await me(t.queuePath),state_exists_after:await me(t.statePath),status:await ro(t.globalPmRoot),generated_at:O()}},t.globalPmRoot),yM={status:fM,flush:_M,stats:hM,clear:gM};async function C2(e,t){let n=rM(e.subcommand),r=tt(process.cwd());return yM[n](e,{globalPmRoot:r,queuePath:ut.join(r,Nr,yt("events.jsonl")),statePath:ut.join(r,Nr,yt("state.json"))})}var wM=(e,t)=>{if(e===void 0)return;let n=re(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new f(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,p.USAGE)}return n},vM=e=>{if(e===void 0)return;let t=Re(e,"timeout");if(t<=0)throw new f("timeout must be a positive number",p.USAGE);return t},zk=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new f(`${t} must be a non-negative integer`,p.USAGE);return n},kM=e=>e instanceof Error?e.message:String(e),bM=()=>{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)}`},SM=e=>e.trim().replaceAll(/\s+/g," "),AM=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),xM=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),CM=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},EM=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},io=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Wk=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),RM=e=>typeof e=="number"?e:void 0,TM=e=>{let t={assert_stdout_contains:io(e.assert_stdout_contains),assert_stdout_regex:io(e.assert_stdout_regex),assert_stderr_contains:io(e.assert_stderr_contains),assert_stderr_regex:io(e.assert_stderr_regex),assert_stdout_min_lines:RM(e.assert_stdout_min_lines),assert_json_field_equals:Wk(e.assert_json_field_equals),assert_json_field_gte:Wk(e.assert_json_field_gte)};return JSON.stringify(t)},IM=e=>{let t=_d(e.command);return t!==void 0?`command:${e.scope}:${SM(t)}`:`path:${e.scope}:${_d(e.path)??""}`},fd=e=>{let t=AM(e.env_set),n=xM(e.env_clear),r=CM(e.pm_context_mode),i=EM(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",o=TM(e);return`${IM(e)}:${t}:${n}:${r}:${i}:${s}:${o}`},OM=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,NM=e=>{let t=0,n=0,r=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"||i.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},$M=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},so=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
19
|
+
`)}catch{}},LM=async(e,t,n)=>{let r=[],i=0;for(let s of e){let o=await p_(s.id,{run:!1},{...t,path:n});i+=o.tests.length,r.push({item:s,tests:o.tests})}return{itemTests:r,linkedTests:i}},MM=async e=>{let t=q(e.settings.schema),n=F(e.settings,M()),r=wM(e.options.status,t),i=zk(e.options.limit,"--limit"),s=zk(e.options.offset,"--offset")??0,a=(await he(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>r?d.status===r:!0).sort((d,l)=>d.id.localeCompare(l.id));return{filteredItems:i===void 0?a.slice(s):a.slice(s,s+i),statusFilter:r,limitFilter:i,offsetFilter:s}},Bk=e=>{let t=e.filter(Gi).map(({provenance:n,provenance_invalid:r,updated_by:i,updated_at:s,note:o,timeout_seconds:a,...c})=>c);return t.length===0?"":Z(t)},Hk=(e,t)=>t.length===0?fd(e):`${fd(e)}:setup[${t}]`,FM=e=>{let t=new Map;for(let{tests:n}of e){let r=Bk(n);for(let i of n){if(Gi(i))continue;let s=Hk(i,r);if(!t.has(s)){t.set(s,i.timeout_seconds);continue}t.set(s,OM(t.get(s),i.timeout_seconds))}}return t};function DM(e,t){try{bl(e.command);return}catch(n){if(!(n instanceof f)||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 PM=(e,t)=>{let n=[],r=[],i=Yf(e.tests),s=Bk(i),o=ma();return{plans:i.map(c=>{let d=Gi(c),l=d?fd(c):Hk(c,s),u=o.blocked(c);if(u)return{test:c,key:l,duplicate:!1,refusal:u};let m=DM(c,e.item.id);if(m)return{test:c,key:l,duplicate:!1,refusal:o.record(c,m)};if(d)return n.push(c),{test:c,key:l,duplicate:!1,refusal:void 0};if(t.seenTestKeys.has(l))return{test:c,key:l,duplicate:!0,refusal:void 0};t.seenTestKeys.add(l),r.push(l);let _=t.effectiveTimeoutByKey.get(l);return n.push(_===void 0?c:{...c,timeout_seconds:_}),{test:c,key:l,duplicate:!1,refusal:void 0}}),testsToRun:n,reservedKeys:r}},UM=(e,t,n)=>{if(e.some(r=>r.phase==="setup"&&r.status!=="passed"))for(let r of t)n.seenTestKeys.delete(r)},jM=async(e,t)=>{let{plans:n,testsToRun:r,reservedKeys:i}=PM(e,t),s=r.length>0?await m_(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}):[];UM(s,i,t);let o=0,a=ma(),c=n.map(({test:m,key:_,duplicate:h,refusal:g})=>{if(g)return a.blocked(m)??g;if(!h){let y=s[o];return o+=1,a.blocked(m)??a.record(m,y)}return a.blocked(m)??{command:m.command,path:m.path,status:"skipped",error:`Duplicate linked test skipped (key=${_}).`}}),d=NM(c),l=pa(c),u=await KM(e,d,c,t);return{passed:d.passed,failed:d.failed,skipped:d.skipped,trackingWarnings:u,failureCategories:l,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:l}}},qM=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),GM=e=>e?!0:void 0,KM=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let i=qM(t,r.options);await l_({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:i?"failed":"passed",started_at:r.runStartedAt,finished_at:O(),recorded_at:O(),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:GM(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}})}catch(i){return Jn(i)?(r.revisionConflicts.push(i),[]):[`test_result_tracking_failed:${e.item.id}:${kM(i)}`]}return[]},zM=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},_d=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},WM=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:tt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:FM(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:H(e.options.author,e.settings.author_default),trackingRunId:bM(),trackingAttempt:zM(),trackingResumedFrom:_d(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),BM=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:pa([]),trackingWarnings:[]},i=e.failOnEmptyTestRun===!0&&t===0;return i&&(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:i}},HM=async(e,t,n)=>{for(let[i,s]of e.entries()){so(t.options,`item ${i+1}/${e.length} start id=${s.item.id} linked_tests=${s.tests.length}`);let o=await jM(s,t);$M(n.failureCategories,o.failureCategories),n.passed+=o.passed,n.failed+=o.failed,n.skipped+=o.skipped,n.trackingWarnings.push(...o.trackingWarnings),n.results.push(o.result),so(t.options,`item ${i+1}/${e.length} end id=${s.item.id} status=${o.failed===0?"passed":"failed"} passed=${o.passed} failed=${o.failed} skipped=${o.skipped}`)}let[r]=t.revisionConflicts;if(r!==void 0)throw r},VM=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(i=>i.run_results),r=u_(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}`)},YM=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}),XM=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(" "),JM=async(e,t)=>{let n=I(process.cwd(),t.path);await z(n);let r=await R(n),i=await MM({pmRoot:n,settings:r,options:e}),s=vM(e.timeout),o=O(),a=await LM(i.filteredItems,t,n);return so(e,XM({...i,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:i.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:s,runStartedAt:o}},QM=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}},H2=async(e,t)=>{let n=await JM(e,t),{accumulation:r,failOnEmptyTestRunTriggered:i}=BM(e,n.linkedTests,n.filteredItems),s=WM({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await HM(n.itemTests,s,r),VM(e,r);let o=QM({options:e,accumulation:r,failOnEmptyTestRunTriggered:i});return so(e,`end status=${o.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),YM({ok:o.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:o.failOnSkippedTriggered,failOnEmptyTestRunTriggered:i})};import RF from"node:os";import Mn from"node:fs/promises";import{spawn as Qk}from"node:child_process";import{createHash as ZM,randomBytes as eF}from"node:crypto";import $r from"node:path";var Zk=new Set(["queued","running"]),wd=new Set(["passed","failed","stopped","canceled"]),tF=3e3,nF=3e3,rF=3e4,eb=100,Vk=100;function tb(){return Date.now()}function nb(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function iF(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function sF(){let e=Date.now().toString(36),t=eF(3).toString("hex");return`tr-${e}-${t}`}function oF(e,t,n){let r={kind:e,command:nb(t),pm_root:$r.resolve(n)};return ZM("sha256").update(JSON.stringify(r)).digest("hex")}function Fn(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function aF(e){await nn(ml(e)),await nn(bo(e)),await nn(pl(e)),await nn(fl(e)),await nn(gl(e))}async function rb(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new f(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,p.GENERIC_FAILURE)}}async function Qe(e,t){let n={...t,updated_at:O()};await Le(So(e,t.id),`${JSON.stringify(n,null,2)}
|
|
20
|
+
`)}async function Dn(e,t){let n=So(e,t),r=await ee(n);return r?rb(r,n):null}async function cF(e){let t=bo(e);return await me(t)?(await Mn.readdir(t,{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".json")).map(r=>$r.join(t,r.name)).sort((r,i)=>i.localeCompare(r)):[]}function dF(e){let t=e.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(t)return Number.parseInt(t[1],10)*1024}async function lF(e){if(process.platform==="linux")try{let t=await Mn.readFile(`/proc/${e}/status`,"utf8");return dF(t)}catch{return}}function uF(e){let t=e.lastIndexOf(")");if(t<0)return{};let r=e.slice(t+2).trim().split(/\s+/),i=Number.parseInt(r[11],10),s=Number.parseInt(r[12],10);return!Number.isFinite(i)||!Number.isFinite(s)?{}:{cpu_user_seconds:i/Vk,cpu_system_seconds:s/Vk}}async function mF(e){if(process.platform!=="linux")return{};try{let t=await Mn.readFile(`/proc/${e}/stat`,"utf8");return uF(t)}catch{return{}}}async function gd(e){let t=e.child_pid??e.worker_pid;if(!Fn(t))return;let n=await lF(t),r=await mF(t),i=e.started_at?Date.parse(e.started_at):Number.NaN,s=Number.isFinite(i)?Math.max(0,(tb()-i)/1e3):void 0;return{recorded_at:O(),rss_bytes:n,cpu_user_seconds:r.cpu_user_seconds,cpu_system_seconds:r.cpu_system_seconds,uptime_seconds:s}}function hd(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function pF(e,t){if(!t||typeof t!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};let n=t;if(e==="test-all"){let a=n.totals??{};return{summary:{items:typeof a.items=="number"?a.items:void 0,linked_tests:typeof a.linked_tests=="number"?a.linked_tests:void 0,passed:hd(a.passed),failed:hd(a.failed),skipped:hd(a.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}let r=Array.isArray(n.run_results)?n.run_results:[],i=0,s=0,o=0;for(let a of r){if(!a||typeof a!="object")continue;let c=a.status;if(c==="passed"){i+=1;continue}if(c==="failed"||c==="refused"){s+=1;continue}o+=1}return{summary:{passed:i,failed:s,skipped:o,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}function fF(e){let t=e.trim();if(t.length===0)return null;let n=t.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){let d=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:d,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:O(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}let r=t.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!r)return null;let i=Number.parseInt(r[1],10),s=Number.parseInt(r[2],10),o=r[4]?Number.parseInt(r[4],10):void 0,a=t.match(/\scommand="((?:\\.|[^"\\])*)"/),c=a?a[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:i,linked_test_total:s,current_command:c,elapsed_ms:Number.isFinite(o)?o:void 0,heartbeat_at:O(),phase:r[3]?.toLowerCase()==="end"?"finished":"running"}}function _F(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.length>0)}function yd(e,t){if(t<=0)return[];let n=_F(e);return n.length<=t?n:n.slice(n.length-t)}async function ib(e){let t=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(t&&t.length>0){let i=$r.resolve(e,t);if(await me(i))return i}let n=$r.resolve(e,"dist","cli.js");if(await me(n))return n;let r=process.argv[1]?.trim();if(r&&r.length>0){let i=$r.resolve(e,r);if(await me(i))return i}throw new f("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",p.GENERIC_FAILURE)}async function Lr(e,t){if(!Zk.has(t.status)||Fn(t.worker_pid)||t.finished_at)return t;let r={...t,status:"failed",finished_at:O(),error:t.error??"Background test run worker exited before writing terminal status."};return await Qe(e,r),r}async function vd(e){await aF(e.pmRoot);let t=nb(e.commandArgs);if(t.length===0)throw new f("Background test run requires command arguments.",p.USAGE);let n=oF(e.kind,t,e.pmRoot),r=await bd(e.pmRoot,{});for(let l of r){let u=await Lr(e.pmRoot,l);if(u.fingerprint===n&&!(!Zk.has(u.status)||!Fn(u.worker_pid)))return{started:!1,run:{...u,duplicate_of:u.id},duplicate_of:u.id}}let i=sF(),s=O(),o=_l(e.pmRoot,i),a=hl(e.pmRoot,i),c=yl(e.pmRoot,i);await Mn.writeFile(o,"","utf8"),await Mn.writeFile(a,"","utf8");let d={id:i,kind:e.kind,status:"queued",created_at:s,updated_at:s,requested_by:e.requestedBy,fingerprint:n,command_args:t,command_label:iF(t),pm_root:e.pmRoot,global_pm_root:e.globalPmRoot,target_id:e.targetId,status_filter:e.statusFilter,attempt:typeof e.attempt=="number"&&Number.isFinite(e.attempt)&&e.attempt>=1?Math.floor(e.attempt):1,resumed_from:e.resumedFrom,resumed_by:e.resumedBy,stdout_path:o,stderr_path:a,result_path:c,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:s}};return await Qe(e.pmRoot,d),{started:!0,run:d}}async function kd(e){let t=await Dn(e.pmRoot,e.runId);if(!t)throw new f(`Background test run ${e.runId} not found`,p.NOT_FOUND);if(wd.has(t.status))throw new f(`Background test run ${t.id} is already terminal (${t.status}).`,p.CONFLICT);let n=await ib(process.cwd()),r=[];e.noExtensions===!0&&r.push("--no-extensions"),r.push("--path",t.pm_root,"test-runs-worker",t.id);let i={...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:t.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(t.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:t.resumed_from??"",FORCE_COLOR:"0"},s=Qk(process.execPath,[n,...r],{cwd:process.cwd(),env:i,detached:!0,stdio:"ignore",windowsHide:!0});s.unref();let o={...t,status:"queued",worker_pid:s.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:O()}};return await Qe(e.pmRoot,o),o}async function Yk(e,t,n){await e,await Mn.appendFile(t,n,"utf8")}function sb(e,t){let n=Number.parseInt(process.env[e]??"",10);return Number.isFinite(n)&&n>0?n:t}function hF(e){return{...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,FORCE_COLOR:"0"}}function gF(e,t){return t?["--no-extensions",...e.command_args]:[...e.command_args]}function yF(e,t){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await Qe(e,t)}catch{}})},async flush(){await n}}}function Xk(e,t){try{e.kill(t)}catch{}}async function wF(e,t,n,r){if(n.stopRequested)return;n.stopRequested=!0,e.stop_requested_at=O(),e.progress={...e.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:O()},r(),Xk(t,"SIGTERM"),setTimeout(()=>Xk(t,"SIGKILL"),sb("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",nF)).unref?.()}function vF(e,t,n){return{phase:n,message:e,heartbeat_at:O(),item_index:t.item_index,item_total:t.item_total,item_id:t.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function kF(e,t,n,r){return{phase:r,message:e,heartbeat_at:O(),item_index:n.item_index??t.progress?.item_index,item_total:n.item_total??t.progress?.item_total,item_id:n.item_id??t.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function Jk(e,t,n){let r=fF(t);if(!r)return!1;let i=e.progress?.phase==="stopping"?"stopping":"running";return e.progress=r.item_id?vF(t,r,i):kF(t,e,r,i),r.phase==="finished"&&!n&&(e.progress.phase="running"),!0}function bF(e){if(e.trim().length===0)return null;try{return JSON.parse(e)}catch{return null}}function SF(e,t,n){return n?"stopped":e===0&&t.failed===0&&t.fail_on_skipped_triggered!==!0?"passed":"failed"}function AF(e,t){return{phase:"finished",message:t?"Background run stopped.":`Background run finished with status=${e.status}.`,heartbeat_at:O(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function xF(e,t,n){if(t!==null){await Le(e.result_path,`${JSON.stringify(t,null,2)}
|
|
21
|
+
`);return}await Le(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:yd(n,eb)},null,2)}
|
|
22
|
+
`)}async function ob(e,t,n=!1){let r=await Dn(e,t);if(!r)throw new f(`Background test run ${t} not found`,p.NOT_FOUND);let i={...r,status:"running",started_at:r.started_at??O(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:O()}},s=await ib(process.cwd()),o=hF(i);await Qe(e,i);let a=gF(i,n),c=Qk(process.execPath,[s,...a],{cwd:process.cwd(),env:o,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});i.child_pid=c.pid;let d=yF(e,i),l=d.schedule,u=Promise.resolve(),m=Promise.resolve(),_="",h="",g={stopRequested:!1},y=()=>{wF(i,c,g,l)};process.on("SIGTERM",y),process.on("SIGINT",y);let w=setInterval(()=>{(async()=>(i.resource=await gd(i),i.progress.heartbeat_at=O(),l()))()},sb("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",tF));w.unref?.(),c.stdout?.on("data",S=>{let x=S.toString("utf8");_+=x,u=Yk(u,i.stdout_path,x)}),c.stderr?.on("data",S=>{let x=S.toString("utf8");m=Yk(m,i.stderr_path,x),h+=x;let D=h.split(/\r?\n/);h=D.pop();let j=!1;for(let T of D){let E=T.trimEnd();E.length>0&&Jk(i,E,g.stopRequested)&&(j=!0)}j&&l()});let v=null,k=null;try{({code:v,signal:k}=await new Promise(S=>{c.on("close",(x,D)=>{S({code:x,signal:D})})}))}finally{clearInterval(w),process.off("SIGTERM",y),process.off("SIGINT",y)}await u,await m;let b=h.trimEnd();b.length>0&&Jk(i,b,g.stopRequested)&&l(),h="";let A=bF(_),C=pF(i.kind,A);return i.summary=C.summary,i.exit_code=typeof v=="number"?v:void 0,i.signal=k??void 0,i.finished_at=O(),i.status=SF(i.exit_code,C.summary,g.stopRequested),i.progress=AF(i,g.stopRequested),i.resource=await gd(i),await xF(i,A,_),await Qe(e,i),await d.flush(),i}async function bd(e,t){let n=await cF(e),r=[];for(let c of n){let d=await ee(c);if(!d)continue;let l=await rb(d,c);r.push(l)}let i=[];for(let c of r)i.push(await Lr(e,c));let o=(t.status?i.filter(c=>c.status===t.status):i).sort((c,d)=>{let l=Date.parse(d.updated_at)-Date.parse(c.updated_at);return Number.isFinite(l)&&l!==0?l:d.id.localeCompare(c.id)}),a=typeof t.limit=="number"&&t.limit>=0?t.limit:void 0;return a===void 0?o:o.slice(0,a)}async function ab(e,t){let n=await Dn(e,t);if(!n)throw new f(`Background test run ${t} not found`,p.NOT_FOUND);let r=await Lr(e,n),i=Fn(r.worker_pid),s=Fn(r.child_pid);r.status==="running"&&!s&&!r.finished_at&&!i&&(r.status="failed",r.finished_at=O(),r.error=r.error??"Background run process exited unexpectedly.",await Qe(e,r)),r.status==="running"&&(r.resource=await gd(r),await Qe(e,r));let o=r.progress?.heartbeat_at,a=o?Date.parse(o):Number.NaN,c=Number.isFinite(a)?Math.max(0,tb()-a):void 0,d=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(d)&&d>0?d:rF,u=r.status==="running"?c!==void 0&&c>l?"stale":"healthy":"inactive";return{run:r,health:{state:u,last_heartbeat_at:o,heartbeat_lag_ms:c,worker_alive:i,child_alive:s}}}function CF(e,t){let n=t?"SIGKILL":"SIGTERM";if(!Fn(e.worker_pid)||!e.worker_pid)return"none";try{return process.kill(e.worker_pid,n),n}catch{return"none"}}function EF(e,t){return{phase:"stopping",message:t==="none"?"Run marked stopped.":`Stop requested via ${t}.`,heartbeat_at:O(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function cb(e,t,n=!1){let r=await Dn(e,t);if(!r)throw new f(`Background test run ${t} not found`,p.NOT_FOUND);let i=await Lr(e,r);if(wd.has(i.status))return{run:i,signal_sent:"none"};let s=CF(i,n);return s==="none"&&(i.status="stopped",i.finished_at=i.finished_at??O()),i.stop_requested_at=O(),i.progress=EF(i,s),await Qe(e,i),{run:i,signal_sent:s}}async function db(e,t,n,r=!1){let i=await Dn(e,t);if(!i)throw new f(`Background test run ${t} not found`,p.NOT_FOUND);let s=await Lr(e,i);if(!wd.has(s.status))throw new f(`Background test run ${t} is not terminal and cannot be resumed.`,p.CONFLICT);let o=await vd({pmRoot:s.pm_root,globalPmRoot:s.global_pm_root,kind:s.kind,commandArgs:s.command_args,requestedBy:n,targetId:s.target_id,statusFilter:s.status_filter,resumedFrom:s.id,resumedBy:n,attempt:s.attempt+1});if(!o.started)return o.run;let a=await kd({pmRoot:e,runId:o.run.id,noExtensions:r}),c={...s,resumed_by:a.id};return await Qe(e,c),a}async function lb(e,t,n,r){let i=await Dn(e,t);if(!i)throw new f(`Background test run ${t} not found`,p.NOT_FOUND);let s=typeof r=="number"&&Number.isFinite(r)&&r>=0?Math.floor(r):eb,o=n==="stdout"||n==="both"?await ee(i.stdout_path)??"":"",a=n==="stderr"||n==="both"?await ee(i.stderr_path)??"":"";return{run:i,stream:n,tail:s,stdout:n==="stdout"||n==="both"?yd(o,s):[],stderr:n==="stderr"||n==="both"?yd(a,s):[]}}var TF=["queued","running","passed","failed","stopped","canceled"],IF=["stdout","stderr","both"];function OF(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(TF.includes(t))return t;throw new f(`Invalid --status value "${e}"`,p.USAGE)}function NF(e){if(e===void 0||e.trim().length===0)return"stderr";let t=e.trim().toLowerCase();if(IF.includes(t))return t;throw new f(`Invalid --stream value "${e}"`,p.USAGE)}function $F(){try{let e=RF.userInfo().username.trim();if(e.length>0)return e}catch{}}function ub(e,t){let n=[e,Zl(),t,process.env.USER,process.env.LOGNAME,process.env.USERNAME,$F()];for(let r of n){if(typeof r!="string")continue;let i=r.trim();if(i.length>0)return i}return"unknown"}async function Jt(e){await z(e)}async function fY(e,t){let n=I(process.cwd(),t.path),r=tt(process.cwd());await Jt(n);let i=await R(n),s=ub(e.author,i.author_default),o=await vd({pmRoot:n,globalPmRoot:r,kind:e.kind,commandArgs:e.commandArgs,requestedBy:s,targetId:e.targetId,statusFilter:e.statusFilter});return o.started?{started:!0,run:await kd({pmRoot:n,runId:o.run.id,noExtensions:e.noExtensions===!0})}:{started:!1,duplicate_of:o.duplicate_of,run:o.run}}async function _Y(e,t){let n=I(process.cwd(),t.path);await Jt(n);let r=OF(e.status),i=Hn(e.limit,"limit"),s=await bd(n,{status:r,limit:i});return{runs:s,count:s.length,filters:{status:r,limit:i}}}async function hY(e,t){let n=I(process.cwd(),t.path);await Jt(n);let r=await ab(n,e);return{run:r.run,health:r.health}}async function gY(e,t,n){let r=I(process.cwd(),n.path);await Jt(r);let i=NF(t.stream),s=Hn(t.tail,"tail"),o=await lb(r,e,i,s);return{run:o.run,stream:o.stream,tail:o.tail,stdout:o.stdout,stderr:o.stderr}}async function yY(e,t,n){let r=I(process.cwd(),n.path);await Jt(r);let i=await cb(r,e,t.force===!0);return{run:i.run,signal_sent:i.signal_sent}}async function wY(e,t,n){let r=I(process.cwd(),n.path);await Jt(r);let i=await R(r),s=ub(t.author,i.author_default),o=await db(r,e,s,t.noExtensions===!0);return{resumed_from:e,run:o}}async function vY(e,t){let n=I(process.cwd(),t.path);await Jt(n);let r=await ob(n,e,t.noExtensions===!0);return{id:r.id,status:r.status,exit_code:r.exit_code}}export{aS as a,f_ as b,MF as c,tD as d,lS as e,jt as f,nD as g,uS as h,h_ as i,rD as j,ar as k,iD as l,pS as m,_S as n,sD as o,w_ as p,uD as q,mD as r,F_ as s,pD as t,fD as u,_D as v,Sa as w,hD as x,gD as y,yD as z,wD as A,vD as B,tA as C,kn as D,nA as E,AD as F,xD as G,xa as H,CD as I,ED as J,RD as K,sA as L,TD as M,ID as N,OD as O,ND as P,Ca as Q,Q_ as R,LD as S,J_ as T,nh as U,_A as V,bn as W,vA as X,ih as Y,AA as Z,HD as _,Ea as $,ah as aa,CA as ba,JD as ca,QD as da,ch as ea,ZD as fa,eP as ga,$ as ha,be as ia,Xe as ja,Sn as ka,Ra as la,lh as ma,st as na,dr as oa,LA as pa,Oa as qa,Na as ra,fh as sa,An as ta,mr as ua,La as va,ZA as wa,vh as xa,pr as ya,bh as za,es as Aa,Ma as Ba,Sh as Ca,Ah as Da,xh as Ea,Nx as Fa,jP as Ga,SC as Ha,Zh as Ia,XP as Ja,yr as Ka,JP as La,IC as Ma,OC as Na,QP as Oa,NC as Pa,rg as Qa,og as Ra,wU as Sa,qC as Ta,GC as Ua,lg as Va,qa as Wa,AU as Xa,TU as Ya,fg as Za,hg as _a,HU as $a,VU as ab,wr as bb,cs as cb,vg as db,kg as eb,bg as fb,Sg as gb,Eg as hb,Rg as ib,pE as jb,Ig as kb,_E as lb,gE as mb,yE as nb,wE as ob,Mg as pb,Fg as qb,Dg as rb,ls as sb,us as tb,wy as ub,Kq as vb,vy as wb,by as xb,Sy as yb,Cy as zb,Ry as Ab,LT as Bb,jG as Cb,xw as Db,Ar as Eb,Rw as Fb,Tw as Gb,Iw as Hb,Cc as Ib,KI as Jb,SK as Kb,Fw as Lb,BK as Mb,XK as Nb,iO as Ob,xs as Pb,Ic as Qb,jw as Rb,mz as Sb,EO as Tb,Cs as Ub,Es as Vb,Ts as Wb,Zw as Xb,Ds as Yb,MO as Zb,$c as _b,jW as $b,Ht as ac,oN as bc,Ws as cc,Av as dc,xv as ec,WB as fc,bN as gc,jN as hc,GN as ic,Tr as jc,BB as kc,yH as lc,O$ as mc,Zc as nc,wH as oc,vH as pc,Js as qc,MH as rc,FH as sc,DH as tc,lk as uc,YH as vc,nL as wc,od as xc,rL as yc,iL as zc,sL as Ac,XH as Bc,JH as Cc,lV as Dc,uV as Ec,mV as Fc,Ck as Gc,Ek as Hc,wL as Ic,Rk as Jc,LV as Kc,Tk as Lc,MV as Mc,FV as Nc,Zs as Oc,FL as Pc,KV as Qc,cd as Rc,zV as Sc,dd as Tc,u2 as Uc,Mk as Vc,x2 as Wc,C2 as Xc,H2 as Yc,fY as Zc,_Y as _c,hY as $c,gY as ad,yY as bd,wY as cd,vY as dd};
|
|
23
|
+
//# sourceMappingURL=chunk-U7RBJGLF.js.map
|