@unbrained/pm-cli 2026.9.8 → 2026.9.10
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/.agents/skills/pm-user/SKILL.md +2 -2
- package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +1 -1
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +38 -2
- package/dist/cli/command-namespaces.d.ts +9 -0
- package/dist/cli/command-namespaces.js +2 -0
- package/dist/cli/help-content.js +1 -1
- package/dist/cli/help-json-payload.d.ts +5 -1
- package/dist/cli/help-json-payload.js +2 -2
- package/dist/cli/main.d.ts +1 -0
- package/dist/cli/main.js +3 -3
- package/dist/cli/register-list-query.js +4 -4
- package/dist/cli/register-mutation.d.ts +0 -5
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-operations.d.ts +0 -5
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +154 -154
- package/dist/cli-bundle/chunks/chunk-4SFBH77G.js +2233 -0
- package/dist/cli-bundle/chunks/{chunk-LEZOUXG6.js → chunk-74RGSPLL.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-7WIHZI2M.js +5 -0
- package/dist/cli-bundle/chunks/{chunk-JAAEYHUA.js → chunk-EOCKPCEY.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GLQMKUGP.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-FLDWYEND.js → chunk-I6XT3DLQ.js} +62 -60
- package/dist/cli-bundle/chunks/chunk-MACGGTLQ.js +29 -0
- package/dist/cli-bundle/chunks/chunk-NKOYVKFM.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-YVEQ2AMO.js → chunk-P6BEYAON.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-G5ADGQ2D.js → chunk-PYUITRSV.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-T3AMFUCN.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-XOD2PCB6.js → chunk-TSWEX72T.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-YKQTETJI.js +235 -0
- package/dist/cli-bundle/chunks/{register-list-query-KSK3R63M.js → register-list-query-CUIW7SSE.js} +7 -7
- package/dist/cli-bundle/chunks/register-mutation-5F5CYUWZ.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-XIZPLPQY.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-BQ5SVD4B.js → register-setup-JVGPCAIL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RXT4P5QH.js → chunk-26O2WB73.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5YU75QLV.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-EE5QSM4Z.js → chunk-7N5MRONP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-B2CMFYRZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-OPFHFGDD.js → chunk-CRY5MHEI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-COPBO5HW.js → chunk-F6WKFXBT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-HJVARYM3.js → chunk-FHUARRMA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3WRPWLA7.js → chunk-M36SF4GE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-OROZM37I.js +177 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7MBUII7U.js → chunk-PNGYYQY7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SL5YVVPV.js +58 -0
- package/dist/cli-bundle/focused-chunks/chunk-TPOL4TWE.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-RMWES4M6.js → chunk-U5SHHU7E.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XSMA2W6Q.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZAWAL2CG.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZDNAWWQI.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DUN4IXYN.js → chunk-ZJHYQOTM.js} +2 -2
- package/dist/cli-bundle/main.js +26 -26
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +29 -29
- 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 +42 -42
- 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 +10 -10
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/policy/workflow-policy-schema.d.ts +312 -0
- package/dist/core/policy/workflow-policy-schema.js +2 -0
- package/dist/core/policy/workflow-policy-store.d.ts +24 -0
- package/dist/core/policy/workflow-policy-store.js +2 -0
- package/dist/core/policy/workflow-policy.d.ts +139 -0
- package/dist/core/policy/workflow-policy.js +2 -0
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/settings-validator.d.ts +1 -0
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.js +1 -1
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.d.ts +11 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +4 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -3
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -0
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/completion.js +375 -347
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/validate.d.ts +3 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workflow-completeness.d.ts +32 -0
- package/dist/sdk/governance/workflow-completeness.js +2 -0
- package/dist/sdk/governance/workflow-policy.d.ts +47 -0
- package/dist/sdk/governance/workflow-policy.js +4 -0
- package/dist/sdk/governance.d.ts +1 -0
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/index.d.ts +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/lifecycle-transitions.d.ts +1 -1
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/recurrence-parsers.d.ts +1 -1
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/task-composition.d.ts +17 -0
- package/dist/sdk/lifecycle/task-composition.js +2 -0
- package/dist/sdk/lifecycle/update.js +1 -1
- package/dist/sdk/package-import-adapters.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/search-contracts.d.ts +27 -0
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/query/search.d.ts +6 -4
- package/dist/sdk/query/search.js +2 -2
- package/dist/sdk/query/workspace-contracts.d.ts +3 -0
- package/dist/sdk/query/workspace-contracts.js +2 -0
- package/dist/sdk/read-output-contracts.d.ts +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-public-contracts.d.ts +2 -1
- package/dist/sdk/runtime.d.ts +73 -9
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/schema.d.ts +2 -1
- package/dist/sdk/schema.js +1 -1
- package/dist/types.d.ts +4 -0
- package/dist/types.js +1 -1
- package/docs/COMMANDS.md +36 -24
- package/docs/COMMAND_NAMESPACES.md +65 -0
- package/docs/CONFIGURATION.md +12 -1
- package/docs/LIFECYCLE_COMMANDS.md +77 -0
- package/docs/README.md +3 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +5 -0
- package/docs/TESTING.md +10 -0
- package/docs/WORKFLOW_POLICIES.md +129 -0
- package/docs/generated/AGENT_CAPABILITY_ROUTING.md +6 -6
- package/docs/generated/AGENT_COMMAND_SURFACE.md +19 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +23 -5
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +11 -5
- package/marketplace.json +2 -2
- package/package.json +5 -5
- 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/README.md +4 -2
- 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/README.md +6 -4
- 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-codex/.codex-plugin/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3BZZA6A3.js +0 -5
- package/dist/cli-bundle/chunks/chunk-AMRDVX36.js +0 -235
- package/dist/cli-bundle/chunks/chunk-DAM4CBBR.js +0 -2202
- package/dist/cli-bundle/chunks/chunk-KR3RP4FH.js +0 -3
- package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +0 -2
- package/dist/cli-bundle/chunks/chunk-QOEKOECV.js +0 -29
- package/dist/cli-bundle/chunks/chunk-RHSFOMHU.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-IQ5C7U6O.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-DWVHR2NC.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IAUOUGVR.js +0 -177
- package/dist/cli-bundle/focused-chunks/chunk-KOOMJ54F.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-MZDXX7JY.js +0 -56
- package/dist/cli-bundle/focused-chunks/chunk-QHNETP77.js +0 -9
- package/dist/cli-bundle/focused-chunks/chunk-SDOL6FM2.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-SQV4AAUC.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-WE3IUNIW.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-YALOUBWJ.js +0 -2
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
import{n as Vm,o as xo,p as Qm,q as Zm,r as aa,s as No,t as eu,u as ca,v as Fo,y as wu,z as bu}from"./focused-chunks/chunk-WE3IUNIW.js";import{a as Au,f as Tu,h as Wt,m as Lu,o as qo,r as Nu,s as Fu,t as Mu,x as $u}from"./focused-chunks/chunk-KOOMJ54F.js";import{$ as Qp,$a as Mt,Aa as _f,Ab as Ya,Ba as hf,Bb as vs,Ca as gf,Cb as Pn,Da as yf,Db as Ja,Ea as vf,Eb as Xa,Fa as wf,Fb as Hf,Ga as xn,Gb as Vf,H as dr,Hb as Wf,I as w,Ib as Ln,J as Bp,Jb as Qa,K as Hp,Ka as bf,Kb as Yf,L as Ge,La as kf,M as Vp,Ma as Sf,N as Da,Na as Ef,Nb as ws,O as Wp,Oa as Af,P as Ua,Pa as Tf,Q as us,Qa as Cf,R as Ga,Ra as Xt,S as On,Sa as Rf,T as Yp,Ta as If,U as ja,Ua as fs,Ub as Zf,V as ke,Va as Of,Vb as t_,W as qa,Wa as xf,Wb as n_,X as Pe,Xa as Pf,Xb as r_,Y as Jp,Ya as Lf,Z as Xp,Za as Nf,_ as Ka,_a as _s,a as Ea,aa as za,ab as Ff,b as Tp,bb as hs,eb as ur,i as jp,ia as Zp,ib as Mf,j as qp,jb as gs,ka as mr,kb as xb,la as ef,lb as $f,ma as ps,mb as Df,na as tf,nb as Ba,oa as nf,ob as Uf,pa as rf,pb as Gf,qa as of,qb as jf,ra as sf,rb as qf,sa as af,sb as Kf,ta as cf,tb as zf,ua as lf,ub as pr,va as df,vb as Ha,wa as mf,wb as Va,xa as uf,xb as ys,ya as pf,yb as Wa,za as ff,zb as Bf}from"./focused-chunks/chunk-MZDXX7JY.js";import{e as zm,g as Bm,h as Hm,k as Wm,q as Xm}from"./focused-chunks/chunk-HJVARYM3.js";import{b as ku,c as $o,e as Su,f as Eu,g as fb}from"./focused-chunks/chunk-RMWES4M6.js";import{R as ha,V as vu,a as Nd,b as Fd,c as Md,d as $d,f as Dd}from"./focused-chunks/chunk-SQV4AAUC.js";import{a as Sp,b as Ep,c as Ss}from"./focused-chunks/chunk-COPBO5HW.js";import{K as zp,b as Ap}from"./focused-chunks/chunk-7MBUII7U.js";import{$ as Nb,Ca as rc,Ra as gr,Sa as oc,W as Pb,X as ec,Y as tc,Z as ks,_ as Lb,c as xa,e as Pa,g as kp,h as Fp,i as Mp,j as $p,k as Dp,l as Up,m as Gp,n as _r,o as Za,ra as nc,wa as hr,ya as e_}from"./focused-chunks/chunk-SDOL6FM2.js";import{A as be,C as mt,D as Rp,E as ns,F as Nt,G as fe,H as Cn,I as rs,J as os,M as ss,Ma as In,N as is,Na as Pp,O as Ip,Oa as $a,P as as,Pa as Lp,Q as cs,R as Rn,S as Ma,T as ls,Ta as Np,U as Op,V as xp,W as ar,a as Sn,ab as bs,b as wp,c as En,d as La,db as Xf,e as bp,eb as fr,f as ir,g as Jt,h as Wo,hb as Qf,i as Yo,j as Jo,k as Xo,o as Qo,p as Lt,pb as ut,q as An,r as Zo,rb as Es,s as Tn,t as es,u as le,v as ts,w as Na,wb as Nn,x as Ke,y as Fa,z as Cp}from"./focused-chunks/chunk-DUN4IXYN.js";import{c as jm,f as qm,g as Km,i as Oo,j as Ct,k as tu,l as nu,m as ru}from"./focused-chunks/chunk-EE5QSM4Z.js";import{a as Du,b as Uu,c as Gu}from"./focused-chunks/chunk-OPFHFGDD.js";import{$ as pm,$a as ia,A as io,Aa as Lm,B as Vd,Ba as go,C as Wd,Ca as Nm,D as Yd,Da as Fm,E as ao,Ea as Mm,F as Jd,Fa as yo,G as Xd,Ga as vo,H as Qd,Ha as wo,I as co,Ia as bo,J as lo,Ja as Zn,K as Zd,Ka as $m,L as mo,La as Dm,Ma as er,N as em,Na as ko,O as Xn,Oa as So,P as tm,Pa as Eo,Q as nm,Qa as Ao,R as rm,Ra as Um,S as om,Sa as Tt,T as sm,Ta as To,U as im,Ua as Co,V as am,Va as Ro,W as cm,Wa as Io,X as lm,Y as dm,Z as mm,Za as Gm,_ as um,aa as fm,ab as F,ba as _m,ca as Qn,d as ra,da as hm,e as Ud,ea as gm,fa as uo,ga as po,h as Gd,ha as ym,i as oa,ia as vm,j as Vt,ja as wm,ka as bm,l as jd,la as km,ma as Sm,na as Em,oa as Am,q as sa,qa as Tm,ra as Cm,s as ro,sa as Rm,t as oo,ta as Im,u as so,ua as Om,v as qd,va as xm,w as Kd,wa as fo,x as zd,xa as _o,y as Bd,ya as ho,z as Hd,za as Pm}from"./focused-chunks/chunk-YALOUBWJ.js";import{$ as Ca,A as Ib,Ab as ms,B as Ob,C as kn,D as C,Da as cp,Fa as Oa,G as Ku,H as Bo,I as zu,Ia as lp,J as Bu,Ja as dp,K as Hu,Ka as Ze,L as Vu,M as Wu,Ma as mp,Na as up,O as ee,Oa as A,P as Aa,Pa as Oe,Q as ne,Ra as pp,Rb as Kp,S as Ta,Sa as fp,T as Yu,Ta as Ot,U as qe,V as Xe,Va as Ue,Vb as Jf,W as Ju,Wa as sr,X as Xu,Z as Qu,_ as Zu,a as De,ab as xt,b as _b,ba as ep,c as hb,cb as Pt,d as gb,da as Ra,e as yb,eb as _p,fa as tp,fb as R,ga as np,gb as q,ha as rp,hb as se,ia as op,ib as hp,ja as sp,k as Ko,kb as pe,l as ju,lb as gp,m as qu,mb as Vo,n as bn,na as Ie,nb as dt,o as nr,oa as It,ob as yp,p as vb,pb as ie,q as wb,qa as Ia,qb as vp,r as bb,ra as Ho,rb as xe,s as kb,sa as rr,sb as cr,t as Sb,ta as ip,tb as lr,u as Eb,ua as Qe,ub as ds,v as Ab,va as ap,vb as Ft,w as Tb,wa as or,x as Cb,y as zo,z as Rb}from"./focused-chunks/chunk-IAUOUGVR.js";import{b as Et,c as Yr,d as Jr,f as ct,h as Po,i as lt,j as Rt,k as Ym,m as $,n as Lo,o as Je,q as Jm}from"./focused-chunks/chunk-3WRPWLA7.js";import{C as Go,G as k,K as jo,M as oe,P as we,V as Iu,a as Do,aa as Ou,ba as xu,e as tr,ea as wn,ia as Pu,j as Cu,l as Ru,n as ga,o as ya,p as va,q as wa,r as ba,s as ka,t as Sa,u as O,v as yn,w as Yt,x as V,y as Uo,z as vn}from"./focused-chunks/chunk-RXT4P5QH.js";import{$ as l,$a as Sd,$c as yu,Aa as x,Ac as ua,B as ud,Ba as ye,C as pd,Ca as Xr,D as fd,Da as hn,E as _d,Ea as Wn,F as hd,Fa as vd,Fb as eo,G as gd,Ga as E,Gb as Ld,H as Wi,Ha as wd,Hb as to,Hc as sb,I as Yi,Ia as st,Ib as Ht,Ic as ib,J as Ji,Ja as ue,Jb as no,K as Xi,Ka as it,Kb as Jn,L as Qi,M as Zi,Ma as Ye,Na as Qr,P as Wr,Pb as ou,Qb as su,Rb as iu,Sb as au,Sc as ab,Ta as gn,Tb as cu,U as ea,Ub as lu,Uc as cb,Va as bd,Vb as la,Vc as lb,W as yd,Wb as du,Wc as pa,Xa as na,Xc as fa,Ya as Yn,Yb as mu,Yc as _a,Z as St,Za as kd,Zb as uu,Zc as gu,aa as d,ac as da,ad as db,bb as Zr,bc as pu,cc as ma,cd as mb,db as Ed,dd as ub,eb as Ad,ed as pb,gb as Td,hb as Cd,ib as Rd,ja as L,jb as Id,ka as zt,kb as Od,kc as tb,la as At,lb as xd,lc as nb,ma as Z,mb as Pd,mc as rb,na as te,nc as ob,o as Br,oc as Mo,p as md,pa as _n,pb as Bt,pc as fu,q as Hr,qb as at,r as Vi,rc as _u,v as Kt,va as ta,vc as hu,w as ot,wa as Vn,x as pn,xa as ve,y as fn,z as Vr}from"./focused-chunks/chunk-QHNETP77.js";import{AsyncLocalStorage as OF}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="176b4ac2-2c47-50d6-beee-62e1d3dc9281")}catch{}})();function o_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Fb(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function sc(e,t){let n=Fb(t),r=n==="brief"?n:o_(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:o_(e.filters)?e.filters:{},projection:r}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3046466c-614c-5e2b-a156-df96fba8c483")}catch{}})();async function s_(e,t){let n=E(t??process.cwd(),e),r=await A(n);return pe(n,r.item_format,x(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c84b11c-502f-5c33-a757-5757402357b4")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e8137f8b-745a-5ef5-9e7e-14b7d032c1ea")}catch{}})();var Mb=new Map;function ic(){Mb.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c7a926a-46a2-560c-ae95-33b92b8c820e")}catch{}})();var $b={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function i_(e){return Object.fromEntries(mu.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var a_={ctx:{action:"context"},...$b,...i_("extension"),...i_("package"),...Object.fromEntries(uu.map(e=>[`package-${e}`,{action:e}]))};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9133d39d-b2fb-5f99-8fd3-87a7d2f8df6d")}catch{}})();var ac="PmCliError";function Db(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=l.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function c_(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new d(e,Db(t.exitCode??l.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function As(e){if(!(e instanceof Error)||e.name!==ac)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3113ad4b-282a-50af-a836-8e9abfde7d7e")}catch{}})();function cc(e){let t=Sd();for(let n of e)t.register(n);return t}function l_(e,t){return{client:t,isItemNotFoundError:n=>As(n)&&n.exitCode===l.NOT_FOUND,getItemAt:(n,r)=>kp(n,r,{pmRoot:e}),openRelationshipEventStore:n=>Ep.open({pmRoot:e,nodes:n.nodes,registry:cc(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new Ad(n.nodes,n.edges,cc(n.definitions)),analyzeRelationshipImpact:(n,r,o)=>Ap(n,r,o),validateRelationshipEvents:n=>{let r=new Sp(n.nodes,{registry:cc(n.definitions)});return n.events.map(o=>r.append({...o,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>Tp({...n,pmRoot:e})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2766f4e-6354-55bb-9e40-676273ee901f")}catch{}})();async function d_(e,t,n=Iu){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=t,o=Array.isArray(r.warnings)?r.warnings.filter(s=>typeof s=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{readFile as Ub}from"node:fs/promises";import Gb from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c64f304d-9081-5bad-8187-7bf6b65e4a07")}catch{}})();var lc="context-intents.json";function Ts(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jb(e,t,n){if(!Ts(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function m_(e,t){let n=Array.isArray(e)?e:Ts(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,o)=>jb(r,t,o))}async function qb(e){let t=Gb.join(e,lc),n;try{n=await Ub(t,"utf8")}catch(o){if(zt(o))return[];throw await _p(e),o}let r;try{r=JSON.parse(n)}catch(o){let s=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${lc}: ${s}`,{cause:o})}return m_(r,lc)}function Kb(e){if(!Ts(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Ts(n)?n.contextIntents??n.context_intents:void 0}function zb(e){return e.flatMap(t=>{let n=Kb(t.module);return n===void 0?[]:m_(n,`package ${t.name}`)})}async function Bb(e){let t=await qb(e.pmRoot),n=zb(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function dc(e,t){let n=await Bb(e);return await xu(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="663579ae-aebb-524c-81c9-9aed44e40f35")}catch{}})();async function u_(e,t,n){if(t.body===void 0)throw new d("Missing required --body text",l.USAGE);let r=Nt(),o=E(process.cwd(),n.path);await R(o);let s=await A(o),i=C(t.author,s.author_default),c=(await r.resolveValue(t.body,"--body",Rp(t,"body"))).trim();if(c.length===0)throw new d("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",l.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let m=await ie({pmRoot:o,settings:s,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
|
|
1
|
+
import{n as tu,o as Go,p as su,q as au,r as fa,s as Ko,t as cu,u as _a,v as zo,y as Ru,z as Iu}from"./focused-chunks/chunk-ZDNAWWQI.js";import{a as Lu,f as Nu,h as Xt,m as ju,o as Xo,r as qu,s as Ku,t as zu,x as Bu}from"./focused-chunks/chunk-5YU75QLV.js";import{$ as af,$a as Gf,$b as m_,Aa as vf,Ab as Za,Ba as wf,Bb as ec,Ca as bf,Cb as Ci,Da as kf,Db as tc,Ea as Sf,Eb as e_,Fa as Ef,Fb as nc,Ga as Af,Gb as Ri,H as je,Ha as Tf,Hb as Fn,I as w,Ia as Cf,Ib as rc,J as Zp,Ja as Rf,Jb as oc,K as ef,Ka as If,Kb as t_,L as qe,La as Mn,Lb as n_,M as tf,Mb as r_,N as Ba,Nb as $n,O as nf,Ob as ic,P as Ha,Pa as Of,Pb as o_,Q as bi,Qa as xf,R as Va,Ra as Pf,S as Nn,Sa as Lf,Sb as Ii,T as rf,Ta as Nf,U as Wa,Ua as Mf,V as Ee,Va as Ff,W as Ya,Wa as en,X as Le,Xa as $f,Y as of,Ya as Df,Z as sf,Za as Si,Zb as c_,_ as Ja,_a as Uf,_b as d_,a as xa,aa as Xa,ab as jf,ac as u_,b as Np,bb as qf,cb as Kf,db as Ei,eb as Ut,fb as zf,gb as Ai,i as Yp,ia as cf,j as Jp,jb as vr,ka as yr,la as lf,ma as ki,na as df,nb as Bf,oa as mf,ob as Ti,pb as Gb,qb as Hf,rb as Vf,sb as Qa,ta as uf,tb as Wf,ua as pf,ub as Yf,va as ff,vb as Jf,wa as _f,wb as Xf,xa as hf,xb as Qf,ya as gf,yb as Zf,za as yf,zb as wr}from"./focused-chunks/chunk-SL5YVVPV.js";import{e as Qm,g as Zm,h as eu,k as nu,q as iu}from"./focused-chunks/chunk-FHUARRMA.js";import{b as Ou,c as Ho,e as xu,f as Pu,g as Sb}from"./focused-chunks/chunk-U5SHHU7E.js";import{R as Sa,V as Cu,a as qd,b as Kd,c as zd,d as Bd,f as Hd}from"./focused-chunks/chunk-ZAWAL2CG.js";import{a as xp,b as Pp,c as Pi}from"./focused-chunks/chunk-F6WKFXBT.js";import{K as Qp,b as Lp}from"./focused-chunks/chunk-PNGYYQY7.js";import{$ as Kb,Ca as dc,Sa as Er,Ta as mc,W as jb,X as ac,Y as cc,Z as xi,_ as qb,c as Da,e as Ua,g as Op,h as Kp,i as zp,j as Bp,k as Hp,l as Vp,m as Wp,n as kr,o as sc,ra as lc,wa as Sr,ya as l_}from"./focused-chunks/chunk-XSMA2W6Q.js";import{A as Se,C as ht,D as Fp,E as mi,F as $t,G as he,H as xn,I as ui,J as pi,M as fi,Ma as Ln,N as _i,Na as Gp,O as $p,Oa as za,P as hi,Pa as jp,Q as gi,R as Pn,S as Ka,T as yi,Ta as qp,U as Dp,V as Up,W as _r,a as Cn,ab as Oi,b as Rp,c as Rn,d as Ga,db as s_,e as Ip,eb as br,f as fr,g as Zt,h as ri,hb as a_,i as oi,j as ii,k as si,o as ai,p as Ft,pb as gt,q as In,r as ci,rb as Li,s as On,t as li,u as de,v as di,w as ja,wb as Dn,x as Be,y as qa,z as Mp}from"./focused-chunks/chunk-ZJHYQOTM.js";import{c as Ym,f as Jm,g as Xm,i as Uo,j as Ot,k as lu,l as du,m as mu}from"./focused-chunks/chunk-7N5MRONP.js";import{a as Hu,b as Vu,c as Wu}from"./focused-chunks/chunk-CRY5MHEI.js";import{$ as km,$a as Jt,A as _o,Aa as qm,B as nm,Ba as Ao,C as rm,Ca as Km,D as om,Da as zm,E as ho,Ea as Bm,F as im,Fa as To,G as sm,Ga as Co,H as am,Ha as Ro,I as go,Ia as Io,J as yo,Ja as sr,K as cm,Ka as Hm,L as vo,La as Oo,Ma as ar,N as lm,Na as xo,O as or,Oa as Po,P as dm,Pa as Lo,Q as mm,Qa as No,R as um,Ra as Vm,S as pm,Sa as It,T as fm,Ta as Mo,U as _m,Ua as Fo,V as hm,Va as $o,W as gm,Wa as Do,X as ym,Y as vm,Z as wm,Za as Wm,_ as bm,aa as Sm,ab as N,ba as Em,ca as ir,d as ma,da as Am,e as Wd,ea as Tm,fa as wo,ga as bo,h as Yd,ha as Cm,i as ua,ia as Rm,j as Yt,ja as Im,ka as Om,l as Jd,la as xm,ma as Pm,na as Lm,oa as Nm,q as pa,qa as Mm,ra as Fm,s as uo,sa as $m,t as po,ta as Dm,u as fo,ua as Um,v as Xd,va as Gm,w as Qd,wa as ko,x as Zd,xa as So,y as em,ya as Eo,z as tm,za as jm}from"./focused-chunks/chunk-B2CMFYRZ.js";import{$ as Na,$a as Ge,$b as i_,A as Db,Ab as vi,B as Ub,Bb as Dt,C as Tn,D as C,Da as hp,Fa as $a,G as Xu,Gb as wi,H as ei,I as Qu,Ia as gp,J as Zu,Ja as yp,K as ep,Ka as tt,L as tp,M as np,Ma as vp,Na as wp,O as Z,Oa as A,P as Pa,Pa as xe,Q as te,S as La,T as rp,U as ze,V as Ze,Va as ur,W as op,X as ip,Xa as bp,Xb as Xp,Ya as kp,Z as sp,Za as Lt,_ as ap,a as Ue,ab as pr,b as Eb,ba as cp,c as Ab,d as Tb,da as Ma,e as Cb,fa as lp,ga as dp,gb as Nt,ha as mp,ia as up,ib as Mt,ja as pp,k as Qo,kb as Sp,l as Yu,lb as R,m as Ju,mb as q,n as An,na as Oe,nb as oe,o as lr,oa as Pt,ob as Ep,p as Rb,q as Ib,qa as Fa,qb as _e,r as Ob,ra as ti,rb as Ap,s as xb,sa as dr,sb as ni,t as Pb,ta as fp,tb as _t,u as Lb,ua as et,ub as Tp,v as Nb,va as _p,vb as ie,w as Mb,wa as mr,wb as Cp,x as Fb,xb as Pe,y as Zo,yb as hr,z as $b,zb as gr}from"./focused-chunks/chunk-OROZM37I.js";import{b as Ct,c as so,d as ao,f as pt,h as jo,i as ft,j as xt,k as ru,m as F,n as qo,o as Qe,q as ou}from"./focused-chunks/chunk-M36SF4GE.js";import{C as Yo,G as k,K as Jo,M as re,P as ke,V as $u,a as Vo,aa as Du,ba as Uu,e as cr,ea as En,ia as Gu,j as Mu,l as Fu,n as Ea,o as Aa,p as Ta,q as Ca,r as Ra,s as Ia,t as Oa,u as O,v as kn,w as Qt,x as W,y as Wo,z as Sn}from"./focused-chunks/chunk-26O2WB73.js";import{$ as l,$a as Pd,Aa as x,Ac as db,B as bd,Ba as we,Bc as mb,C as kd,Ca as co,Cc as ub,D as Sd,Da as vn,Dc as pb,E as Ed,Ea as Zn,Ec as Bo,F as Ad,Fa as Rd,Fb as tr,Fc as ku,G as Td,Ga as E,Gb as da,H as ta,Ha as Id,Hb as nr,Hc as Su,I as na,Ia as lt,Ib as Vd,J as ra,Ja as fe,K as oa,Ka as dt,L as ia,Lc as Eu,M as sa,Ma as Xe,Mb as ut,Na as lo,Nb as le,P as io,Pb as rr,Qc as va,Ta as wn,U as aa,Ub as bn,Va as Od,W as Cd,Xa as la,Xc as fb,Ya as er,Yc as _b,Z as Tt,Za as xd,aa as d,bb as mo,db as Ld,dc as uu,eb as Nd,ec as pu,fc as fu,gb as Md,gc as _u,gd as hb,hb as Fd,hc as hu,ib as $d,ic as gu,id as gb,ja as L,jb as Dd,jc as ha,jd as yb,ka as Vt,kb as Ud,kc as yu,kd as wa,la as Rt,lb as Gd,ld as ba,ma as Q,mb as jd,mc as vu,md as ka,na as ee,nc as wu,nd as Au,o as no,p as wd,pa as yn,pb as Wt,pd as Tu,q as ro,qb as mt,qc as ga,qd as vb,r as ea,rc as bu,sc as ya,sd as wb,td as bb,ud as kb,v as Ht,va as ca,w as ct,wa as Qn,x as hn,xa as be,y as gn,z as oo}from"./focused-chunks/chunk-TPOL4TWE.js";import{AsyncLocalStorage as jM}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="176b4ac2-2c47-50d6-beee-62e1d3dc9281")}catch{}})();function p_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function zb(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function uc(e,t){let n=zb(t),r=n==="brief"?n:p_(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:p_(e.filters)?e.filters:{},projection:r}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3046466c-614c-5e2b-a156-df96fba8c483")}catch{}})();async function f_(e,t){let n=E(t??process.cwd(),e),r=await A(n);return _e(n,r.item_format,x(r,null).type_to_folder,void 0,r.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c84b11c-502f-5c33-a757-5757402357b4")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e8137f8b-745a-5ef5-9e7e-14b7d032c1ea")}catch{}})();var Bb=new Map;function pc(){Bb.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b841f903-6276-5067-842f-6a6bff114cec")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c7a926a-46a2-560c-ae95-33b92b8c820e")}catch{}})();var Hb={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function __(e){return Object.fromEntries(vu.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var h_={ctx:{action:"context"},...Hb,...__("extension"),...__("package"),...Object.fromEntries(wu.map(e=>[`package-${e}`,{action:e}]))};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9133d39d-b2fb-5f99-8fd3-87a7d2f8df6d")}catch{}})();var fc="PmCliError";function Vb(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=l.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function g_(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new d(e,Vb(t.exitCode??l.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function Ni(e){if(!(e instanceof Error)||e.name!==fc)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3113ad4b-282a-50af-a836-8e9abfde7d7e")}catch{}})();function _c(e){let t=Pd();for(let n of e)t.register(n);return t}function y_(e,t){return{client:t,isItemNotFoundError:n=>Ni(n)&&n.exitCode===l.NOT_FOUND,getItemAt:(n,r)=>Op(n,r,{pmRoot:e}),openRelationshipEventStore:n=>Pp.open({pmRoot:e,nodes:n.nodes,registry:_c(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new Nd(n.nodes,n.edges,_c(n.definitions)),analyzeRelationshipImpact:(n,r,o)=>Lp(n,r,o),validateRelationshipEvents:n=>{let r=new xp(n.nodes,{registry:_c(n.definitions)});return n.events.map(o=>r.append({...o,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>Np({...n,pmRoot:e})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2766f4e-6354-55bb-9e40-676273ee901f")}catch{}})();async function v_(e,t,n=$u){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=t,o=Array.isArray(r.warnings)?r.warnings.filter(i=>typeof i=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{readFile as Wb}from"node:fs/promises";import Yb from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c64f304d-9081-5bad-8187-7bf6b65e4a07")}catch{}})();var hc="context-intents.json";function Mi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jb(e,t,n){if(!Mi(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function w_(e,t){let n=Array.isArray(e)?e:Mi(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,o)=>Jb(r,t,o))}async function Xb(e){let t=Yb.join(e,hc),n;try{n=await Wb(t,"utf8")}catch(o){if(Vt(o))return[];throw await Sp(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${hc}: ${i}`,{cause:o})}return w_(r,hc)}function Qb(e){if(!Mi(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Mi(n)?n.contextIntents??n.context_intents:void 0}function Zb(e){return e.flatMap(t=>{let n=Qb(t.module);return n===void 0?[]:w_(n,`package ${t.name}`)})}async function ek(e){let t=await Xb(e.pmRoot),n=Zb(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function gc(e,t){let n=await ek(e);return await Uu(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="663579ae-aebb-524c-81c9-9aed44e40f35")}catch{}})();async function b_(e,t,n){if(t.body===void 0)throw new d("Missing required --body text",l.USAGE);let r=$t(),o=E(process.cwd(),n.path);await R(o);let i=await A(o),s=C(t.author,i.author_default),c=(await r.resolveValue(t.body,"--body",Fp(t,"body"))).trim();if(c.length===0)throw new d("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",l.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let m=await ie({pmRoot:o,settings:i,id:e,op:"append",author:s,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
|
|
2
2
|
|
|
3
3
|
`:"";return u.body=`${u.body.trimEnd()}${p}${c}
|
|
4
|
-
`,{changedFields:["body"]}}});return{item:m.item,appended:c,changed_fields:m.changedFields}}import{readFile as Hb}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a5fc27e-3f5a-59e0-998e-be5da72913dd")}catch{}})();function Rs(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,be(e,t)}function p_(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new d(`Structured context events are append-only and cannot be ${t}.`,l.USAGE,{code:"structured_event_immutable"})}function mc(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Qt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Fn(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=le(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function uc(e){return typeof e=="object"&&e!==null&&"code"in e}function wr(e,t){if(!mt(e))throw new d(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,l.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function Vb(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new d(`Specify ${t} text using only one input source: --add, --stdin, or --file`,l.USAGE);let r=Nt(),o=mt(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",o)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return wr(e,"--stdin"),{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new d("--file path cannot be empty",l.USAGE);if(s==="-")return wr(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await Hb(s,"utf8"),emptyFlag:"--file"}}catch(i){if(uc(i)&&zt(i))throw new d(`--file path not found: ${s}. Use --file - to read stdin.`,l.USAGE);let a=i instanceof Error?i.message:String(i);throw new d(`Failed to read --file path "${s}": ${a}. Use --file - to read stdin.`,l.USAGE)}}async function Is(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new d("Specify only one of --edit or --delete",l.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new d("--delete cannot be combined with replacement text",l.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new d("--delete must be a positive integer",l.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new d("--edit must be a positive integer",l.USAGE);let n=await Vb(e,t);if(e.edit!==void 0){if(!n)throw new d("--edit requires replacement text from --add, --stdin, or --file",l.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function vr(e,t){throw e instanceof d&&e.exitCode===l.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new d(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function __(e){return e==="comments"?"--stdin":"--add -"}function Wb(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let o=__(t.collectionKey),s=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new d(`--add value "${r}" looks like an option, not annotation text. Use ${o} to read stdin, or use text=${r} for literal dash-leading text.`,l.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${s} ${o}`,`${s} --add text=${r}`]})}function Yb(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new d(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,l.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new d(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,l.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 Jb(e,t,n,r,o,s){let i=Qt(e.metadata,t),a=o?i.findIndex(c=>c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],entryIndex:a+1}:(i.push(s({created_at:k(),author:n,text:r})),e.metadata[t]=i,{changedFields:[t],entryIndex:i.length})}async function Mn(e,t,n,r){Yb(r,t);let o=E(process.cwd(),n.path);await R(o);let s=await A(o),i=x(s,O()),a=ar(t.limit);if(r.input.mode==="list"){let g=await q(o,e,s.id_prefix,s.item_format,i.type_to_folder);if(!g)throw new d(`Item ${e} not found`,l.NOT_FOUND);let y=await se(g,{schema:s.schema}),h=Qt(y.document.metadata,r.collectionKey);return Cs(g.id,r.collectionKey,h,a,t.includeMeta===!0)}let c=C(t.author,s.author_default);if(r.input.mode==="delete"){let g=r.deleteOp??r.op,y;try{y=await ie({pmRoot:o,settings:s,id:e,op:g,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(v){let b=Qt(v.metadata,r.collectionKey),S=f_(r.input.index,b.length,r.collectionKey);return p_(b[S],"deleted"),b.splice(S,1),v.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(v){vr(v,r.conflictGuidance)}let h=Qt(y.item,r.collectionKey);return Cs(y.item.id,r.collectionKey,h,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";Wb(m,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new d(`${r.input.emptyFlag??"--add"} text cannot be empty`,l.USAGE);if(r.input.mode==="edit"){let g=r.editOp??r.op,y;try{y=await ie({pmRoot:o,settings:s,id:e,op:g,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(v){let b=Qt(v.metadata,r.collectionKey),S=f_(r.input.index,b.length,r.collectionKey),T=b[S];return p_(T,"edited"),b[S]={...T,text:u,edited_at:k()},v.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(v){vr(v,r.conflictGuidance)}let h=Qt(y.item,r.collectionKey);return Cs(y.item.id,r.collectionKey,h,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:h[r.input.index-1]},t.fullHistory===!0)}let p,f=0;try{p=await ie({pmRoot:o,settings:s,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(g){let y=Jb(g,r.collectionKey,c,u,t.ifAbsent===!0,r.createEntry);return f=y.entryIndex,{changedFields:y.changedFields}}})}catch(g){vr(g,r.conflictGuidance)}let _=Qt(p.item,r.collectionKey);return Cs(p.item.id,r.collectionKey,_,a,t.includeMeta===!0,{action:"add",entryIndex:f,entry:_[f-1],changedCount:t.ifAbsent===!0?Math.min(p.changedFields.length,1):void 0},t.fullHistory===!0)}function f_(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,s=t===1?`1 ${r}`:`${t} ${n}`;throw new d(`${o} index ${e??"(missing)"} out of range (item has ${s})`,l.USAGE)}return e-1}function Xb(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 Cs(e,t,n,r,o,s,i=!1){let a=s===void 0||i?mc(n,s!==void 0&&i?void 0:r):s.entry===void 0?[]:[s.entry],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...s?.changedCount===void 0?{}:{changed:s.changedCount===1},...[o,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...Xb(t,s,c)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f366dd76-73b4-55c4-8c63-2913d0a0c380")}catch{}})();async function h_(e,t,n){return[...await Promise.resolve().then(()=>Xu(Ye(e,t),t)).catch(()=>[])].reverse().find(s=>s.patch.some(i=>i.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="90cfbd3e-1656-54cc-a9f8-66bffe14685f")}catch{}})();var g_="no_available_next_item";function y_(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function br(e,t,n,r={}){let o=E(process.cwd(),n.path);await R(o);let s=await A(o),i=$(s.schema),a=C(r.author,s.author_default),c=kn(a),m=null,u=!1,p=[],f=await ie({pmRoot:o,settings:s,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",h=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,Jm(_.metadata.status,i)&&!t)throw new d(`Cannot claim terminal item ${_.metadata.id} without --force`,l.CONFLICT);if(m!==null&&h!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let T=await h_(o,_.metadata.id,y);throw new d(`Item ${_.metadata.id} is already ${T}. Use --force to take over, or --if-available to skip without failing.`,l.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}p.push(`claim_takeover:${m}->${a}`)}let b={assignee:a,claim_principal:c},S=["assignee","claim_principal"].filter(T=>_.metadata[T]!==b[T]);return Object.assign(_.metadata,b),{changedFields:S,warnings:p}}});return u||await ec({pmRoot:o,settings:s,principal:c,itemId:f.item.id}),{item:f.item,changed_fields:f.changedFields,claimed_by:u&&m!==null?m:a,previous_assignee:m,forced:t,...u?{skipped:!0}:{},...p.length>0?{warnings:p}:{}}}async function v_(e,t,n={},r={}){let o=Qb(n.maxAttempts),s=await A(E(process.cwd(),t.path)),i={...n,author:C(n.author,s.author_default)},a=await hr({...r,callerAuthor:i.author,limit:String(o)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return Zb(c.slice(0,o),e,t,i)}function Qb(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new d("--max-attempts must be an integer from 1 to 100",l.USAGE);return t}async function Zb(e,t,n,r={},o=br){let s=0;for(let a of e){s+=1;try{let c=await o(a.id,t,n,r),m={...c,recommendation:a,attempts:s,available:!0};if(!c.skipped)return m}catch(c){if(!y_(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:C(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[g_]};let i=s===0;throw new d(i?"No actionable items matched the selection filters":"No actionable item remained available to claim",i?l.NOT_FOUND:l.CONFLICT,{code:g_,why:i?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[i?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function Os(e,t,n,r={}){let o=E(process.cwd(),n.path);await R(o);let s=await A(o),i=C(r.author,s.author_default),a=kn(i),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await ie({pmRoot:o,settings:s,id:e,op:"release",author:i,message:r.message,force:t,bypassAssigneeConflict:c,mutate(_){return m=_.metadata.assignee??null,!m&&!_.metadata.claim_principal?{changedFields:[]}:(delete _.metadata.assignee,delete _.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(_){vr(_,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await tc({pmRoot:o,principal:a,itemId:u.item.id});let p=$(s.schema),f=Aa(u.item.status,p)===Aa(p.in_progress_status,p);return{item:u.item,released_by:i,previous_assignee:m,forced:t,...f?{warnings:["released_unclaimed_in_progress"],suggestions:[`${u.item.id} remains ${u.item.status} and unclaimed. If work is paused, run pm pause-task ${u.item.id} to move it to ${p.open_status}.`]}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e63a8049-309b-57f2-ba48-cd0a550c11ab")}catch{}})();var ek=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function w_(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 pc(e,t){return fc(e,t,{operation:"close"})}function fc(e,t,n){let r=w_(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new d("Close reason text is required because governance.require_close_reason is enabled",l.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function _c(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],s=o.filter(m=>m.kind==="blocked_by"),i=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),i&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let m=o.filter(u=>u.kind!=="blocked_by");m.length>0?e.dependencies=m:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...s.map(m=>m.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[t.orderingEdges==="preserve"?`closed_preserved_predecessors:${e.id}:${c.join(",")}`:`closed_removed_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="49e375b7-49a8-5b6f-89c8-be70d334b78f")}catch{}})();var tk=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function nk(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 d(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,l.USAGE)}function b_(e){let t=[];for(let n of tk){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function k_(e,t,n={}){let r=b_(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},s=r.map(a=>`--${a.key.replaceAll("_","-")}`),i=["--pm-path",t,"update",e.id,...r.flatMap((a,c)=>[s[c],o[a.key]?.trim()||"<value>"])];return{missing:s,suggested_retry:tr(i),suggested_retry_args:i}}async function rk(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let s=o.trim();if(s===n)return!0;if(r.has(s))return!1;r.add(s),o=(await e(s))?.duplicate_of}return!1}function ok(e){return typeof e!="string"||e.trim().length===0}async function sk(e,t,n,r){let o=n?.trim();if(!o)return;if(o===r)throw new d("An item cannot be closed as a duplicate of itself.",l.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=x(t,O()),i=new Map,a=async m=>{if(i.has(m))return i.get(m)??null;let u=await q(e,m,t.id_prefix,t.item_format,s.type_to_folder);if(!u)return i.set(m,null),null;let{document:p}=await se(u,{schema:t.schema});return i.set(m,p.metadata),p.metadata},c=await a(o);if(!c)throw new d(`Duplicate target "${o}" was not found. Create or locate the canonical item first.`,l.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await rk(a,c.duplicate_of,r))throw new d(`Circular duplicate reference detected. Target "${o}" points back to "${r}".`,l.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 d(`Duplicate target "${o}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,l.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 ik(e,t,n){return e.filter(r=>r.parent===t&&!ne(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function ak(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),o=Jf(e),s=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:o.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let m=r.get(c);return m!==void 0&&ne(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function ck(e,t,n,r,o,s){let i=ak(n,r,s),a=[];for(let c of i)try{let m=await ie({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(g=>{let y=g.id.trim().toLowerCase();return g.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=s.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let u=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${u}`)}return a}function lk(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:s}of r){if(typeof o!="string")continue;let i=o.trim();i.length!==0&&(e[s]=i,n.push(s))}return n}function dk(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:s}of r)ok(e[o])&&(e[o]=s,n.push(o));return n}function mk(e,t,n,r){let o=[];if(t!=="off"){let s=b_(e);if(s.length>0){let i=s.map(a=>a.label);if(t==="strict"){let a=s.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(m=>[m,"<value>"])];throw new d(`Cannot close item ${e.id}: missing ${i.join(", ")}. Populate fields or use --validate-close warn.`,l.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:tr(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}o.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new d(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,l.USAGE);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function uk(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function pk(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function fk(e,t){if(ne(e.status,t.statusRegistry)&&!t.force)throw new d(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,l.CONFLICT,{recovery:k_(e,t.pmRoot,t.options)});let n=lk(e,t.options),r=dk(e,t.duplicateOf),o=mk(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let i=["status","closed_at",...s?["completed_at"]:[],...uk(e,t.closeReason),...n];if(Lp(e)&&(e.plan_mode="completed",i.push("plan_mode")),t.duplicateOf!==void 0){i.push("duplicate_of");for(let c of r)i.includes(c)||i.push(c)}i.push(...pk(e));let a=_c(e,t.lifecyclePolicy);return i.push(...a.changedFields),o.push(...a.warnings),{changedFields:i,...o.length>0?{warnings:o}:{}}}async function S_(e,t,n,r){let o=E(process.cwd(),r.path);await R(o);let s=await A(o),i=$(s.schema),a=C(n.author,s.author_default),c=x(s,O()).type_to_folder,m=await q(o,e,s.id_prefix,s.item_format,c);if(!m)throw await dt(o,e,s.id_prefix,c);let u=await sk(o,s,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=pc({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=nk(n.validateClose)??s.governance.close_validation_default,g=await pe(o,s.item_format,c,void 0,s.schema),y=ik(g,m.id,i),h=k(),v=n.completedAt===void 0?h:oe(n.completedAt,new Date(h),"completed-at"),b=await ie({pmRoot:o,settings:s,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(T){return fk(T.metadata,{pmRoot:o,statusRegistry:i,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:h,completedAt:v,lifecyclePolicy:p})}}),S=_==="warn"?k_(b.item,o):void 0;return{item:b.item,changed_fields:b.changedFields,...S?{recovery:S}:{},warnings:[...b.warnings,...await ck(o,s,g,m.id,a,i)]}}function pt(e,t,n,r){return S_(e,t,n,r)}import _k from"fast-json-patch";import hc from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f22715f-cfb9-5c75-b4c5-e9719416c2b9")}catch{}})();async function E_(e,t,n){let r=await hp(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:A_(n),recovered:!0}}function hk(e,t){return wp(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function A_(e){let t=La(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Xe(Qe(t))}async function gk(e,t,n,r){let o=await Jt(e,t,n,r),s=o.located?await pp({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:s.warnings}}function yk(e,t){let n=or(e),r=or(t),o=_k.compare(n,r),s=new Set;for(let i of o){if(i.path==="/body"||i.path.startsWith("/body/")){s.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];s.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(s).sort((i,a)=>i.localeCompare(a))}async function vk(e){let t=await Nf({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>E_(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function wk(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:A_(t),originalRaw:null}}function bk(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new d(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,l.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function kk(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await te(e.existingItemPath,e.resolvedOriginalRaw),await hc.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await te(e.existingItemPath,e.resolvedOriginalRaw);return}await hc.rm(e.restoredItemPath,{force:!0})}async function Sk(e){return[...await V({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await V({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function Zt(e,t,n,r){let o=E(process.cwd(),r.path);await R(o);let s=await A(o),i=x(s,O()),a=await gk(o,e,s,i.type_to_folder),c=a.id,{raw:m,entries:u}=await Ju(a.historyPath,c);if(u.length===0)throw new d(`No history exists for ${c}; restore is unavailable.`,l.NOT_FOUND);let p=hk(t,u),f=bp(La(u,p.historyIndex),p),_=ap(f,{schema:s.schema});if(_.metadata.id!==c)throw new d(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,l.GENERIC_FAILURE);let y=(a.located?await E_(a.located,s,u):null)?.raw??null,h=C(n.author,s.author_default),v=await we(o,c,s.locks.ttl_seconds,h,!!n.force,s.governance.force_required_for_stale_lock,s.locks.wait_ms);try{let{loadedItemUnderLock:b,existingItemPath:S}=await vk({pmRoot:o,subject:a,settings:s,typeRegistry:i,historyRawBeforeLock:m,currentItemRawBeforeLock:y,history:u}),T="toon",I=wk(b,u),D=bk({document:I.document,author:h,force:n.force,enforcement:s.governance.ownership_enforcement,resolvedId:c}),N=yk(I.document,_);await Uo({pm_root:o,operation:"restore",before:I.document,after:_,changed_fields:N,sdk:Vo({pmRoot:o,settings:s,typeToFolder:i.type_to_folder})});let X=qe(_,{format:T,schema:s.schema}),K=it(o,_.metadata.type,c,T,i.type_to_folder),W=await xt(o,h),Q=[];try{await te(K,X),S&&K!==S&&await hc.rm(S);let wt=Ie({nowIso:k(),author:h,op:"restore",before:I.document,after:_,message:n.message});try{await It(a.historyPath,wt)}catch(Ve){throw await kk({existingItemPath:S,resolvedOriginalRaw:I.originalRaw,restoredItemPath:K}),Ve}Q=await Pt({pmRoot:o,preferredFormat:s.item_format,typeToFolder:i.type_to_folder,schema:s.schema,itemPath:K,previousItemPath:S??void 0,document:_})}finally{await W()}let Ce=await Sk({restoredItemPath:K,historyPath:a.historyPath,before:I.document,after:_});yn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:I.document.metadata.status,status:_.metadata.status,previous:Yt(I.document.metadata,N),current:Yt(_.metadata,N),changed_fields:N});let j=u[p.historyIndex],ce=Sn(u,!0);return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,version:ce===null?null:ce+p.historyIndex+1,entry_ts:j.ts,entry_op:j.op},changed_fields:N,warnings:[...b?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...D,...Q,...Ce]}}finally{await v()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aec6f8e2-5fd0-53f3-8262-c6b49741ff96")}catch{}})();var C_=1,gc="close-many",Ek=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function Ak(e,t){return _r(e,t,{includePagination:!1})}function Tk(e,t){return _r(e,t)}function Ck(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new d("--ids requires at least one non-empty item ID",l.USAGE)}function Rk(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function Ik(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new d("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",l.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function Ok(e,t){let n=$(t.schema),r=x(t,O()),o=await pe(e,t.item_format,r.type_to_folder,void 0,t.schema),s=new Map,i=new Map;for(let a of o){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),ne(a.status,n)))continue;let c=s.get(a.parent);c?c.push(a.id):s.set(a.parent,[a.id])}for(let a of s.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:s,parentByChild:i}}function T_(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,s=t.get(e),i=[],a=new Set,c=!1;for(;s!==void 0&&!a.has(s);){let m=n?.get(s);if(m!==void 0){o+=m+1;break}a.add(s),i.push(s),o+=1,s=t.get(s)}if(s!==void 0&&a.has(s)&&(c=!0),!c){n?.set(e,o);for(let[m,u]of i.entries())n?.set(u,o-m-1)}return o}async function xk(e){let t=await Jo(e.pmRoot,gc,e.rollbackId,C_),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Xo(t.items,(o,s)=>Zt(o,s,{author:e.options.author,message:n,force:!0},e.global));return{...Wt({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function Pk(e,t,n,r,o){return e.map(s=>{let i=(t.get(s.id)??[]).filter(c=>!n.has(c)),a=!R_(s,r,o);return{id:s.id,title:typeof s.title=="string"?s.title:"",status:s.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function Lk(e){let t=await Yo(e.pmRoot,gc,e.checkpointId,{schema_version:C_,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function Nk(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await pt(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){t.push({id:r.id,status:"failed",error:gn(o)})}}return{rows:t,closedIds:n}}function Fk(e){return typeof e.rollback=="string"?e.rollback:void 0}function Mk(e,t){if(t.trim().length===0)throw new d("--rollback requires a checkpoint id",l.USAGE);if(e.dryRun===!0)throw new d("--dry-run cannot be combined with --rollback",l.USAGE);if(Tk(e.list,e.status))throw new d("Rollback mode does not accept filter options",l.USAGE)}function $k(e){if(!Ak(e.list,e.status))throw new d(`close-many requires at least one filter to scope the close (for example: ${Ek}). Refusing to match every item.`,l.USAGE)}function Dk(e,t){let n=new Map;return[...e].sort((r,o)=>{let s=T_(o.id,t,n)-T_(r.id,t,n);return s!==0?s:r.id.localeCompare(o.id)})}function R_(e,t,n){return n||!ne(e.status,t)}function Uk(e,t,n){return new Set(e.filter(r=>R_(r,t,n)).map(r=>r.id))}async function Gk(e){$k(e.options);let t=$(e.settings.schema),n=Ik(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await ut(e.options.status,Rk(e.options.list),e.global),{childrenByParent:s,parentByChild:i}=await Ok(e.pmRoot,e.settings),a=Dk(o.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],m=c.length===0?[]:(await ut(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,u=new Set(m.map(f=>f.id)),p=Uk(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!u.has(f)),planRows:Pk(a,s,p,t,r)}}function jk(e){return{outcome:"effect",exit_code:l.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function qk(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return Lk({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function I_(e,t){let n=E(process.cwd(),t.path);await R(n);let r=await A(n),o=e.dryRun===!0,s=Fk(e);if(Ck(e.list),s!==void 0)return Mk(e,s),xk({pmRoot:n,rollbackId:s,options:e,global:t});let i=await Gk({pmRoot:n,settings:r,options:e,global:t});if(o)return jk(i);let a=new Set(i.planRows.filter(v=>v.action==="close").map(v=>v.id)),c=k(),m=Wo(gc,c),u=await qk({context:i,options:e,closableIds:a,checkpointId:m,nowValue:c}),p={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:i.validateCloseMode,force:i.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await Nk({matched:i.matched,closableIds:a,reason:i.reason,closeOptions:p,global:t}),g=f.filter(v=>v.status==="closed").length,y=f.filter(v=>v.status==="skipped").length,h=f.filter(v=>v.status==="failed").length;return{...Wt({applied:g,skipped:y,failed:h,unmatched:i.unmatchedIds?.length??0}),mode:"apply",matched_count:i.matched.length,dry_run:!1,...i.reason!==void 0?{reason:i.reason}:{},filters:i.listed.filters,...i.validateCloseMode?{validate_close:i.validateCloseMode}:{},...u?{checkpoint:u}:{},closed_count:g,skipped_count:y,failed_count:h,rows:f,ids:_,...i.unmatchedIds!==void 0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}import{readFile as Kk}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="29e1738e-026c-5714-b279-30e45951d256")}catch{}})();async function yc(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",s=Number(n)+Number(r)+Number(o);if(s===0)return;if(s>1)throw new d("Specify comment text using only one input source: --add, --stdin, or --file",l.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",mt(e))??"",emptyFlag:"--add"};if(r)return wr(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new d("--file path cannot be empty",l.USAGE);if(i==="-")return wr(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await Kk(i,"utf8"),emptyFlag:"--file"}}catch(a){if(uc(a)&&zt(a))throw new d(`--file path not found: ${i}. Use --file - to read stdin.`,l.USAGE);let c=a instanceof Error?a.message:String(a);throw new d(`Failed to read --file path "${i}": ${c}. Use --file - to read stdin.`,l.USAGE)}}async function zk(e,t){let n=e.edit,r=e.delete,o=n!==void 0,s=r!==void 0;if(o&&s)throw new d("Specify only one of --edit or --delete",l.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new d("--edit must be a positive integer",l.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new d("--delete must be a positive integer",l.USAGE);if(s){if(await yc(e,t)!==void 0)throw new d("--delete does not take comment text",l.USAGE);return{mode:"delete",index:r}}if(o){let c=await yc(e,t);if(c===void 0)throw new d("--edit requires replacement text via positional [text], --add, --stdin, or --file",l.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let i=await yc(e,t);return i===void 0?{mode:"list"}:{mode:i.emptyFlag==="--add"?"add":i.emptyFlag==="--stdin"?"stdin":"file",value:i.value,emptyFlag:i.emptyFlag}}async function O_(e,t,n){let r=Nt(),o=await zk(t,r),s=o.mode==="add"||o.mode==="edit",i=o.value??"";return Mn(e,t,n,{input:{...o,rawValue:t.add??i,value:s?Fn(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm comments pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="99f91321-fd91-5ec6-8d09-1493f40dacb1")}catch{}})();async function x_(e,t,n){return Mn(e,t,n,{input:await Is(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Fn(r),createEntry:r=>r,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm learnings pm-a1b2 --add "review learning" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eab6a65d-8f97-593e-8609-6ae452b1c5aa")}catch{}})();function Bk(e){if(e===void 0)return;if(e.trim().length===0)throw new d("--add-json must contain a JSON value",l.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new d("--add-json must be valid JSON",l.USAGE,{code:"structured_event_json_invalid"})}return t}function Hk(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function Vk(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new d("--since must be a valid ISO timestamp",l.USAGE,{code:"structured_event_since_invalid"});return t}async function P_(e,t,n){let r=Bk(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new d("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",l.USAGE,{code:"structured_event_input_conflict"});let s=r===void 0?void 0:Bt(r),i=[t.since,t.eventType].some(g=>g!==void 0),a=Vk(t.since),c=ar(t.limit),m=await Mn(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await Is(s===void 0?t:{add:s},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:g=>Fn(g),createEntry:g=>r===void 0?g:{...g,format:"json",data:r,event_type:Hk(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm notes pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}}),u=t.eventType?.trim(),p=m.notes.filter(g=>{let y=[g.format==="json",g.data!==void 0].every(Boolean),h=[a===void 0,Date.parse(g.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),v=[!u,g.event_type===u].includes(!0);return[!i,[y,h,v].every(Boolean)].includes(!0)}),f=i?mc(p,c):p,_=f.filter(g=>g.format==="json").length;return{...m,notes:f,count:f.length,...i?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e2e87672-508a-5aef-b728-42e40544cf3c")}catch{}})();function kr(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new d(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,l.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 Sr(e,t,n=Ft()){for(let r of t??[])try{Ed(e,r.id,r.kind,n)}catch(o){throw new d(gn(o),l.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function L_(e,t){return(await se(e,{schema:t})).document.metadata.created_at}async function Wk(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await q(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:L_(n,t.schema)}function Yk(e){let t=e.registry.require(e.dependency.kind);return new d(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,l.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 Jk(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:s})=>s===null?[]:[[o,s]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await L_(n.get(o),e.context.schema)])));for(let o of e.holders){let s=await Wk(o,e.context);if(s!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(s),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw Yk({holder:o,dependency:i,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function en(e){let t=e.registry??Ft(),n=(e.dependencies??[]).filter(i=>!fu(i.source_kind)),r=[...new Set(n.map(i=>i.id))],o=await Promise.all(r.map(async i=>({target:i,located:await q(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=o.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new d(`Dependency target${s.length===1?"":"s"} not found: ${s.join(", ")}`,l.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 Jk({dependencies:n,missingTargets:s,resolutions:o,holders:e.holders??[],registry:t,context:e}),s.map(i=>`dependency_target_unresolved:${i}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c45ead8e-c9ed-5b59-84e5-b8e077e84010")}catch{}})();function xs(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ps(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ls(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Vr.includes(t))return t;let n=fe(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new d("Confidence must be an integer 0..100 or one of low|med|medium|high",l.USAGE);return n}function Ns(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new d("Regression must be one of true|false|1|0",l.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="add1928e-08d1-5ead-9a4e-0f1a9b6580fc")}catch{}})();var Xk=new Set(["none","null"]);function Fs(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function ze(e){return e===void 0?!1:Xk.has(e.trim().toLowerCase())}function Ms(e,t,n){if(!ze(e))return;let r=n?` ${n}`:"";throw new d(`${t} no longer accepts "none" or "null".${r}`.trim(),l.USAGE)}function Se(e,t,n){if(!e||e.length===0||!e.some(s=>ze(s)))return;let o=n?` ${n}`:"";throw new d(`${t} no longer accepts "none" or "null".${o}`.trim(),l.USAGE)}function $s(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new d(`${n.valueFlag} entries must be strings.`,l.USAGE);let o=r;if(!o.some(a=>ze(a)))continue;if(o.filter(a=>!ze(a)).length>0)throw new d(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,l.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4cf64466-2612-5a12-a1ba-79fa2ed7c50d")}catch{}})();function F_(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 d(`${t} must be one of true|false|1|0|yes|no`,l.USAGE)}function vc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Ee(e,t,n){if(!t.includes(e))throw new d(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,l.USAGE);return e}var M_=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Qk(e,t){return t==="defined"?e!==void 0:!!e}function N_(e,t,n){if(!Qk(e,n))return;let r=fe(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new d(`--event ${t} must be an integer >= 1`,l.USAGE);return r}function Zk(e,t,n){let r=e?oe(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new d("--event recur_until must be at or after start",l.USAGE);return r}function eS(e){return Array.from(new Set(vc(e).map(t=>Ee(t.toLowerCase(),gd,"event weekday")))).sort((t,n)=>Wi(t)-Wi(n))}function tS(e){return Array.from(new Set(vc(e).map(t=>{let n=fe(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new d("--event recur_by_month_day values must be integers 1..31",l.USAGE);return n}))).sort((t,n)=>t-n)}function nS(e,t){return Array.from(new Set(vc(e).map(n=>oe(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function $_(e,t,n,r){let o=e.recur_freq?.trim(),s=e.recur_interval?.trim(),i=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![o,s,i,a,c,m,u].some(S=>S!==void 0))return;if(!o)throw new d("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",l.USAGE);let f=Ee(o.toLowerCase(),hd,"event recurrence frequency"),_=N_(s,"recur_interval",r),g=N_(i,"recur_count",r),y=Zk(a,t,n),h=eS(c),v=tS(m),b=nS(u,n);return{freq:f,interval:_,count:g,until:y,by_weekday:h.length>0?h:void 0,by_month_day:v.length>0?v:void 0,exdates:b.length>0?b:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ae7fdf9b-e2d5-511e-90db-cf0bc121628d")}catch{}})();var D_="--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.",rS="--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).",oS=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,sS=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,G_=1e3,wc=60*G_,iS=60*wc;function U_(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new d(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,l.USAGE);return n.toISOString()}function aS(e,t){let n=new Date(e),r=t.trim(),o=oS.exec(r);if(o){let a=o[1]==="-"?-1:1,c=Number.parseInt(o[2],10)*a;return U_(n.getTime()+c*wc,r)}let s=sS.exec(r);if(s){let[,a,c,m,u]=s;if(c||m||u){let f=a==="-"?-1:1,_=Number.parseInt(c??"0",10),g=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),h=_*iS+g*wc+y*G_;return U_(n.getTime()+f*h,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return oe(i,n,"event.duration")}function j_(e,t,n,r){if(t&&n)throw new d(rS,l.USAGE);if(n){let s=aS(e,n);if(s<e)throw new d(D_,l.USAGE);return s===e?void 0:s}if(!t)return;let o=oe(t,r,"event.end");if(o<e)throw new d(D_,l.USAGE);if(o!==e)return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dfce9924-8453-5ded-a5df-47477caa9fe7")}catch{}})();var cS=["at","date","text","title"],lS=["start","date","end","duration","title","description","location","timezone","all_day",...M_],dS=["key","value"];function q_(e,t){return t==="trimmed"?e?.trim():e}function mS(e,t){return t==="defined"?e!==void 0:!!e}function Ds(e,t,n){return e.map(r=>{let o=le(r,"--reminder");Ke(o,"--reminder",cS);let s=q_(o.at??o.date,n.valueMode),i=q_(o.text??o.title,n.valueMode);if(!s||!i)throw new d("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",l.USAGE);let a=i.trim();if(!a)throw new d("--reminder text must not be empty",l.USAGE);return{at:oe(s,t,"reminder.at"),text:a}})}function Us(e,t,n){return e.map(r=>{let o=le(r,"--event");Ke(o,"--event",lS);let s=(o.start??o.date)?.trim();if(!s)throw new d("--event requires start=<iso|relative> or date=<iso|relative>",l.USAGE);let i=oe(s,t,"event.start"),a=o.end?.trim(),c=o.duration?.trim(),m=j_(i,a,c,t),u=o.title,p=o.description,f=o.location,_=o.timezone,g=u?.trim(),y=p?.trim(),h=f?.trim(),v=_?.trim(),b=[["title",u,g],["description",p,y],["location",f,h],["timezone",_,v]];for(let[D,N,X]of b)if(N!==void 0&&!X)throw new d(`--event ${D} must not be empty`,l.USAGE);let S=o.all_day?.trim(),T=$_(o,i,t,n.recurrenceEmptyNumericGuard),I=mS(S,n.allDayEmptyGuard)?F_(S,"--event all_day"):void 0;return{start_at:i,end_at:m,title:g,description:y,location:h,all_day:I,timezone:v,recurrence:T}})}function Gs(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new d("--type-option values must not be empty",l.USAGE);let o,s;if(r.includes(",")||r.includes(`
|
|
5
|
-
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=le(r,"--type-option");Ke(a,"--type-option",dS),o=a.key?.trim(),s=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),m=a;if(a<=0&&c>0&&(m=c),m<=0||m===r.length-1)throw new d("--type-option requires key=value or key=<name>,value=<value> entries",l.USAGE);o=r.slice(0,m).trim(),s=r.slice(m+1).trim()}if(!o||!s)throw new d("--type-option requires key and value",l.USAGE);t[o]=s}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4db3d1b3-68f3-5f74-b6f0-9847b3b00fc0")}catch{}})();var uS="hierarchy-integrity";async function js(e){let t=e.required?await we(e.pmRoot,uS,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7f554437-f1bd-5d81-85ad-fe00ad66d06c")}catch{}})();var pS=new Set(["event","meeting","reminder","milestone","decision","adr"]);function K_(e,t,n,r){if(pS.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=Lo("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm start-task ${e}`,to_status:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="70971b2a-c025-50a8-918f-871fc8adfd2a")}catch{}})();var ft=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],fS=new Set(ft);function z_(e){return Qo(e,ft)}function qs(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!fS.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw new d(`${t} provides key "${o}" more than once after case normalization`,l.USAGE);n[i]=s}if(r.length>0)throw new d(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${ft.join(", ")}.`,l.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new d(`${t} command and cmd must match when both are provided`,l.USAGE);let{cmd:o,...s}=n;return{...s,command:s.command??o}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="800bdce7-d4d2-5702-9ceb-d83ac4a95fb0")}catch{}})();var rn=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",mr,ef,"FORCE_COLOR"]),Bs=/^[A-Za-z_][A-Za-z0-9_]*$/,nn=["schema","tracker","auto"],B_=["source","isolated","snapshot"];function Er(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new d(`${t} env_set must include at least one KEY=VALUE assignment`,l.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new d(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,l.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1);if(!Bs.test(i))throw new d(`${t} env_set key "${i}" is invalid`,l.USAGE);if(rn.has(i.toUpperCase()))throw new d(`${t} env_set key "${i}" is reserved for sandbox safety`,l.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function Ar(e,t){if(!e)return;let n=In(e,{separators:/[;,\n]/});if(n.length===0)throw new d(`${t} env_clear must include at least one environment variable name`,l.USAGE);for(let r of n){if(!Bs.test(r))throw new d(`${t} env_clear key "${r}" is invalid`,l.USAGE);if(rn.has(r.toUpperCase()))throw new d(`${t} env_clear key "${r}" is reserved for sandbox safety`,l.USAGE)}return n}function Hs(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new d(`${t} ${n} must be one of true|false|1|0|yes|no`,l.USAGE)}function Vs(e,t){if(!e)return;let n=e.trim().toLowerCase();if(nn.includes(n))return n;throw new d(`${t} pm_context_mode must be one of: ${nn.join(", ")}`,l.USAGE)}function on(e,t){if(!e)return;let n=e.trim().toLowerCase();if(B_.includes(n))return n;throw new d(`${t} workspace_context_mode must be one of: ${B_.join(", ")}`,l.USAGE)}function sn(e){if(!e)return;let t=In(e,{separators:/[;\n]/});return t.length>0?t:void 0}function $n(e,t,n){let r=sn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(s){throw new d(`${t} ${n} includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`,l.USAGE)}return r}}function Ws(e,t){if(!e)return;let n=fe(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new d(`${t} assert_stdout_min_lines must be an integer >= 0`,l.USAGE);return n}function Ys(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new d(`${t} assert_json_field_equals must include at least one path=value assignment`,l.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new d(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,l.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0||a.length===0)throw new d(`${t} assert_json_field_equals entries must include non-empty path and value`,l.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function Js(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new d(`${t} assert_json_field_gte must include at least one path=value assignment`,l.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new d(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,l.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0||a.length===0)throw new d(`${t} assert_json_field_gte entries must include non-empty path and value`,l.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new d(`${t} assert_json_field_gte value for "${i}" must be numeric`,l.USAGE);r[i]=c}return Object.keys(r).length>0?r:void 0}var _S=new Set(ft);function Xs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hS(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!_S.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw t(`provides key "${o}" more than once after case normalization`);n[i]=s}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${ft.join(", ")}.`);return n}function tn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function Ks(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=o.filter(i=>i.length>0);return s.length>0?s:void 0}function H_(e,t,n){let r=Ks(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`)}return r}}function zs(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function gS(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:zs(n,"timeout_seconds",t),s=r===void 0?void 0:zs(r,"timeout",t);if(o!==void 0&&s!==void 0&&o!==s)throw t("timeout and timeout_seconds must match when both are provided");let i=o??s;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function yS(e,t){let n=tn(e,"scope",t);if(n===void 0)return"project";if(!ot.includes(n))throw t(`field "scope" must be one of: ${ot.join(", ")}`);return n}function vS(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Xs(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Bs.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(rn.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=s}return Object.keys(r).length>0?r:void 0}function wS(e,t){let n=Ks(e,"env_clear",t);if(n){for(let r of n){if(!Bs.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(rn.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function bS(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function kS(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=zs(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function SS(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Xs(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(s)}return Object.keys(r).length>0?r:void 0}function ES(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Xs(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=zs(s,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function AS(e,t,n){let r=f=>new d(`${n} ${t} ${f}`,l.USAGE);if(!Xs(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${ft.join(", ")}.`);let o=hS(e,r),s=tn(o,"command",r),i=tn(o,"cmd",r);if(s!==void 0&&i!==void 0&&s!==i)throw r("command and cmd must match when both are provided");let a=s??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=tn(o,"path",r),m=tn(o,"pm_context_mode",r);if(m!==void 0&&!nn.includes(m))throw r(`field "pm_context_mode" must be one of: ${nn.join(", ")}`);let u=on(tn(o,"workspace_context_mode",r),`${n} ${t}`),p=tn(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:yS(o,r),timeout_seconds:gS(o,r),pm_context_mode:m,workspace_context_mode:u,env_set:vS(o,r),env_clear:wS(o,r),shared_host_safe:bS(o,"shared_host_safe",r),assert_stdout_contains:Ks(o,"assert_stdout_contains",r),assert_stdout_regex:H_(o,"assert_stdout_regex",r),assert_stderr_contains:Ks(o,"assert_stderr_contains",r),assert_stderr_regex:H_(o,"assert_stderr_regex",r),assert_stdout_min_lines:kS(o,r),assert_json_field_equals:SS(o,r),assert_json_field_gte:ES(o,r),note:p!==void 0&&p.trim().length>0?p.trim():void 0}}function V_(e,t){let n=e.trim();if(n.length===0)throw new d(`${t} requires a JSON object or array of objects describing linked-test entries`,l.USAGE);let r;try{r=JSON.parse(n)}catch(s){throw new d(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,l.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new d(`${t} array must include at least one linked-test entry object`,l.USAGE);return o.map((s,i)=>AS(s,o.length>1?`entry ${i+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0562fd00-217b-5e1f-8004-df4574f8b796")}catch{}})();var bc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],kc=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],W_=[...bc,...kc],Qs=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function Zs(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let o=r.trim().toLowerCase();if(!o)throw new d("--unset values must not be empty",l.USAGE);if(ze(o))throw new d('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',l.USAGE);let s=e.resolveDefinition(o);if(!s)throw new d(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,l.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function ei(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let s of o){if(s.allow_unset===!1)continue;let i=new Set;if(typeof s.key=="string"&&s.key.length>0&&i.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&i.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(i.add(s.cli_flag.replaceAll("-","_").toLowerCase()),i.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let a of s.cli_aliases)typeof a!="string"||a.length===0||(i.add(a.replaceAll("-","_").toLowerCase()),i.add(a.toLowerCase()));if(i.has(r))return{optionKey:s.key,metadataKey:s.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var TS={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function CS(e){return TS[e]}function Sc(e){return CS(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b09a9308-0725-5761-9850-a85beb926e42")}catch{}})();var RS=["strict","progressive"],IS=["lightweight"],Q_=new Set(["Reminder","Meeting","Event"]),OS=new Set(["author","created_at","text"]),Ac=[...W_,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...Qs],xS=(()=>{let e=new Map;for(let t of Ac)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),ti=new Map(Ac.map(e=>[e.optionKey,e.canonical])),PS=Ac.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function LS(e,t){let n=ee(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new d(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n}function NS(e,t){let n=e.default_status;if(n!==void 0){let r=ee(n,t);if(r)return r}return t.open_status}function Ec(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new d(`Invalid created_at timestamp "${e}"`,l.USAGE);return new Date(n).toISOString()}var FS=Fs();function Z_(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s};ze(t.template)&&(t.template=void 0);let r=new Set([...ti.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!ze(s))continue;let i=o==="rank"?"order":ti.get(o)??o;n(i),t[o]=void 0}return be(e,$s(t,FS))}function he(e){if(e!==void 0)return e}function MS(e,t){return Zs({raw:e,supportedFields:PS,resolveDefinition:n=>xS.get(n)??ei(n,"create",t)})}var Y_=["id","kind","type","author","created_at","source_kind"],ni=["path","scope","note"];function $S(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let i=s.trim(),a=ri(i,Y_);kr(i,a);let c=a?le(s,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",Y_);let m=he(c.id),u=DS(he(c.kind??c.type));if(!m||!u)throw new d("--dep requires id and kind, or a bare item id to create a related dependency",l.USAGE);if(m.trim().toLowerCase()==="undefined")throw new d(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,l.USAGE);let p=cr(he(c.source_kind)),f=he(c.author);return{id:lr(m,n,p),kind:Ee(u,Kt,"dependency kind"),created_at:Ec(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function DS(e){return typeof e=="string"?Zr(e)??e.trim():e}function ri(e,t){return Qo(e,t)?!0:ts(e)}function cn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Se(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(i=>{let a=i.trim(),c=()=>{if(a.length===0)throw new d(`${e} requires text=<value>`,l.USAGE);return{created_at:n,author:r,text:a}},m;try{m=le(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!OS.has(f)).length>0)return{created_at:Ec(m.created_at,n),author:he(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new d(`${e} requires text=<value>`,l.USAGE);return{created_at:Ec(m.created_at,n),author:he(m.author)??r,text:p}}),explicitEmpty:!1})}function Tc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),o=ri(r,ni);Na(r,"--file","file path",o);let s=o?le(n,"--file"):{path:r};if(o&&Ke(s,"--file",ni),!s.path)throw new d("--file requires path=<value> or a bare file path",l.USAGE);return{path:s.path,scope:Ee(s.scope??"project",ot,"file scope"),note:he(s.note)}}),explicitEmpty:!1})}function Cc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),o=ri(r,ft);Na(r,"--test","test command",o);let s=o?qs(le(n,"--test"),"--test"):{command:r},i=he(s.command),a=he(s.path);if(!i)throw new d("--test requires command=<value> or a bare command (path=<value> is optional metadata)",l.USAGE);let c=he(s.timeout_seconds),m=he(s.timeout);if(c&&m&&c!==m)throw new d("--test timeout and timeout_seconds must match when both are provided",l.USAGE);let u=c??m;return{command:i,path:a,scope:Ee(s.scope??"project",ot,"test scope"),timeout_seconds:u?fe(u,"timeout_seconds"):void 0,pm_context_mode:Vs(s.pm_context_mode,"--test"),workspace_context_mode:on(s.workspace_context_mode,"--test"),env_set:Er(s.env_set,"--test"),env_clear:Ar(s.env_clear,"--test"),shared_host_safe:Hs(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:sn(s.assert_stdout_contains),assert_stdout_regex:$n(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:sn(s.assert_stderr_contains),assert_stderr_regex:$n(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Ws(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:Ys(s.assert_json_field_equals,"--test"),assert_json_field_gte:Js(s.assert_json_field_gte,"--test"),note:he(s.note)}}),explicitEmpty:!1})}function Rc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),o=ri(r,ni),s=o?le(n,"--doc"):{path:r};if(o&&Ke(s,"--doc",ni),!s.path)throw new d("--doc requires path=<value> or a bare doc path",l.USAGE);return{path:s.path,scope:Ee(s.scope??"project",ot,"doc scope"),note:he(s.note)}}),explicitEmpty:!1})}function US(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Ds(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function GS(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--event","Use --clear-events to clear linked events."),{values:Us(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function jS(e,t,n,r=[]){let o=[...Wr.filter(s=>e[s]!==void 0),...r.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(o))}function qS(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function J_(e,t,n){let r=Vn("create",e);if(!r)throw new d(`Unsupported ${n} entry "${e}" for type "${t}"`,l.CONFLICT);return r}function KS(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 eh(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 zS(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(J_(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(J_(r,e.name,"required_create_repeatables"));return n}function BS(e,t,n,r){for(let o of e)if(!(!eh(t,o)&&!n.has(o)))throw new d(`Option ${ve("create",o)} is disabled for type "${r}" by command_option_policies`,l.USAGE)}function HS(e,t,n){if(t!=="strict")return;let r=e.filter(s=>n.has(s)&&!Sc(s));if(r.length===0)return;let o=[...new Set(r.map(s=>ve("create",s)))].sort((s,i)=>s.localeCompare(i));throw new d(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,l.USAGE)}function VS(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Gs(e),explicitEmpty:!1})}async function WS(e){return await ns(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 YS(e){return mt(e)?await WS(e):e}function JS(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 d(`Invalid --create-mode value "${e}". Allowed: ${RS.join(", ")}`,l.USAGE)}function XS(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new d("--schedule-preset must not be empty",l.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new d(`Invalid --schedule-preset value "${e}". Allowed: ${IS.join(", ")}`,l.USAGE)}function QS(e,t,n){let r=JS(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new d("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",l.USAGE);return"progressive"}function ZS(e,t,n,r){let o=e.name,s=KS(t),i=zS(e,n),a=hn(e,"create",i);if(a.errors.length>0)throw new d(a.errors.join("; "),l.CONFLICT);BS(a.disabled,s,r,o),HS(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&Sc(u)?!0:eh(s,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>ve("create",u)))].sort((u,p)=>u.localeCompare(p))}var th=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function eE(e,t){let n=[];for(let r of e){let o=r.match(th);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function tE(e,t){return e.filter(n=>{let r=n.match(th);return!r||r[2]!==t})}function nE(e,t,n,r){let o=tE(e,t);if(o.length===0)return;let s=nh(n,[],[],r.open_status);throw new d(o.join("; "),l.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 rE(e,t){let r=e.options.find(o=>o.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function oE(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function nh(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],i=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of i)a.has(c)||(o.push(...oE(c,e.name,r)),a.add(c));for(let c of n){let m=rE(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function Ic(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new d("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",l.USAGE):new d('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.',l.USAGE):new d(`Missing required option ${t}`,l.USAGE);return n}function sE(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=Array.isArray(o)?[...o]:o;for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=Array.isArray(o)?[...o]:o);return n}function iE(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function aE(){let e=O();return e?e.commands.some(t=>t.action==="templates-show"||iE(t.command)==="templates show"):!1}function cE(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new d(`Templates package returned invalid payload for template "${t}". Expected an options object.`,l.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new d(`Templates package returned invalid options for template "${t}".`,l.GENERIC_FAILURE);let r={};for(let[o,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[o]=s;continue}if(Array.isArray(s)&&s.every(i=>typeof i=="string")){r[o]=[...s];continue}throw new d(`Templates package returned unsupported option value for "${o}" in template "${t}".`,l.GENERIC_FAILURE)}return r}async function lE(e,t,n){if(!aE())throw new d("--template requires the templates package. Install it first (for example: pm install templates --project).",l.USAGE);let r=await Go({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let o=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new d(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${o}`,l.USAGE)}return cE(r.result,e)}function z(e,t,n){return e.has(t)||n===void 0?void 0:he(n)}function an(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var dE=new Set(["milestone","meeting","reminder","event"]);function rh(e,t,n,r){let o=t!==void 0,s=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return dE.has(e.toLowerCase())&&!o&&!s&&!i}function mE(e,t,n,r,o){let s=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),rh(e,n,r,o)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function uE(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await Ko(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function pE(e,t,n,r,o,s){let i=ds(is(o),t.id_prefix);if(Mo(i))return{parent:i,warnings:[]};if(cs(r,i,t.id_prefix),await q(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let c=Ue(i,t.id_prefix);return{parent:i,warnings:as(c,s).warnings}}async function fE(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await pE(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function _E(e){if(e.explicitId===void 0)return sr(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new d("--id must be a string",l.USAGE);let t=e.explicitId.trim();if(t.length===0||Ip(t))throw new d("--id must not be empty or use a placeholder token",l.USAGE);let n=Ue(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new d("--id must contain only letters, numbers, and dashes after normalization",l.USAGE);return n}function X_(e,t,n,r,o){let s=z(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let i=ls(r,s,o);return{value:i.value,warnings:i.warnings}}async function hE(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:s,status:i,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(s===void 0)return{dependencyValues:u,status:i};let p=Ue(s,n.id_prefix),f=await q(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:i};if((u??[]).some(y=>y.id===f.id&&y.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:i};let g=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((y,h)=>y.localeCompare(h))[0]??o.open_status;return{dependencyValues:u,status:g}}function gE(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let o=t.governance.create_default_type?.trim();if(o&&o.length>0&&ye(o,n)){e.type=o;return}ye("Task",n)&&(e.type="Task")}function yE(e,t){return e.options.filter(n=>Vn("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 d(`Template custom type option "${n.key}" must be a string, number, or boolean value`,l.USAGE)})}async function vE(e,t,n,r,o){let s=e,i=[];if(s.template!==void 0){let g=s.template.trim();if(g.length===0)throw new d("--template must not be empty. Omit --template to disable template usage.",l.USAGE);let y=await lE(g,t,n);s=Z_(sE(y,s))}if(s.type===void 0&&gE(s,r,o),s.type===void 0)throw new d("Missing required option --type <value>",l.USAGE);let a=ye(s.type,o);if(!a){let g=xp(s.type),y=g?ye(g,o):void 0;if(y)i.push(`type_coercion:${s.type.trim()}:${y}`),s.type=y,a=y;else throw new d(Ct(s.type,o.types,Rt(n,r.schema)),l.USAGE)}let c=Xr(a,o);if(!c)throw new d(`Invalid type value "${s.type}"`,l.USAGE);let m=c.name,u=yE(c,s),p=u.map(g=>`${g.key}=${String(s[g.key])}`);if(p.length>0){s.typeOption=[...p,...s.typeOption??[]];for(let g of u)delete s[g.key]}let f=XS(s.schedulePreset);if(f!==void 0&&!Q_.has(m))throw new d(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,l.USAGE);let _=QS(s.createMode,f,r.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function wE(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of o)if(s.enabled){if(s.values&&s.values.length>0)throw new d(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,l.USAGE);n.add(s.metadataKey),r.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function bE(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=ti.get(r)??r;throw new d(`Cannot combine --unset ${s} with ${ve("create",r)}`,l.USAGE)}}function kE(e){let t=(n,r)=>{let o=ti.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;Ms(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 SE(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new d(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,l.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new d(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,l.USAGE)}var EE={"--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 AE(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:s,type:i,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(g=>{let y=g.type==="boolean"?"<true|false>":g.type==="array"?"<json-array>":g.type==="object"?"<json-object>":g.type==="number"?"<number>":g.type==="string_array"||g.repeatable?"<value>":"<string>";return{example:`--${g.cli_flag} ${y}`,description:`--${g.cli_flag} maps to ${g.metadata_key} (${g.type}${g.repeatable?", repeatable":""})`}}),u=[nh(n,r,o,s),...m.map(g=>g.example)].join(" "),p=[`Run "pm create --help --type ${i}" for type-aware required option guidance.`,...t.filter(g=>g==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+i+").")];a==="strict"&&(p.push('For staged onboarding, retry with "--create-mode progressive".'),Q_.has(i)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&p.push(`Required custom field formats: ${m.map(g=>g.description).join("; ")}.`);let f=[...new Set(t.flatMap(g=>{let y=g.split(" ",1)[0],h=EE[y];return h?[h]:[]}))];f.length>0&&p.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let _=t.length===1?`Missing required option ${t[0]} for type "${i}"`:`Missing required options ${t.join(", ")} for type "${i}"`;throw new d(_,l.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${i}" in one invocation.`,examples:[...f.map(g=>`pm create --type ${i} ${g} ...`),u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function TE(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new d("Cannot combine --unset tags with --add-tags",l.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Lt(t.tags):[];return Tn(n,t.addTags)}function CE(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new d("--order and --rank must match when both are provided",l.USAGE);let n=t.order??t.rank,r=an(e,"order",n,o=>fe(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new d("Order must be an integer",l.USAGE);return r}function RE(e,t,n,r,o,s){if(r.completedAt!==void 0&&e!==t.close_status)throw new d("--completed-at requires a terminal create status.",l.USAGE);let i=e!==t.close_status?void 0:r.completedAt===void 0?s:oe(r.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:i,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:fc(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function IE(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:s,author:i,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:g}=e,y=it(t,n,r,o.item_format,s.type_to_folder),h=Ye(t,r),v=Ft(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(D=>v.resolve(D.kind)?.hierarchy),S=await js({pmRoot:t,author:i,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:b}),T=b,I=[];try{let D=await we(t,r,o.locks.ttl_seconds,i,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let N=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await pe(t,o.item_format,s.type_to_folder,void 0,o.schema):void 0;if(await q(t,r,o.id_prefix,o.item_format,s.type_to_folder))throw new d(`Item "${r}" already exists`,l.CONFLICT);if(N){let Q=$(o.schema);ms(N,[...N,c.metadata],r,Ce=>ne(Ce,Q),v)}await Uo({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:Vo({pmRoot:t,settings:o,typeToFolder:s.type_to_folder})});let K=await xt(t,i,{required:o.governance.duplicate_detection_mode==="strict"&&g!==!0}),W=[];try{o.governance.duplicate_detection_mode==="strict"&&g!==!0&&await Nn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await te(y,qe(c,{format:o.item_format,schema:o.schema,extensionFieldNames:a}));try{let Q=Ie({nowIso:f,author:i,op:"create",before:m,after:c,message:u});await It(h,Q)}catch(Q){throw await _n(y),Q}T&&(await S(),T=!1),W=await Pt({pmRoot:t,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:y,document:c})}finally{await K()}I=[...N?Ss(N,[...N,c.metadata],r):[],...W,...await V({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await V({path:h,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],yn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Yt(c.metadata,p),changed_fields:p})}finally{await D()}}finally{T&&await S()}return I}async function $t(e,t){let n=Z_(await YS(e)),r=E(process.cwd(),t.path);await R(r);let o=await A(r),s=$(o.schema),i=Je(o.schema),a=x(o,O()),c=await vE(n,t,r,o,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=MS(n.unset,i),{explicitUnsets:_,clearOptionKeys:g}=wE(n,f);bE(n,f),kE(n);let y=ZS(m,n,p,g),h=k(),v=C(he(n.author),o.author_default),b=$S(n.dep,h,o.id_prefix,v),S=cn("--comment",n.comment,h,v),T=cn("--note",n.note,h,v),I=cn("--learning",n.learning,h,v),D=Tc(n.file),N=Cc(n.test);N.values=await Ln(N.values,v,h);let X=Rc(n.doc),K=US(n.reminder,h),W=GS(n.event,h),Q=VS(n.typeOption),Ce=Wn(u,Q.values,a),j=O(),ce=Et(j),wt=Yr(n.field,j),Ve=Ku(n,i,u),Mi=new Set(Ve.missing_required_flags),$i=i.definitions.filter(H=>Mi.has(`--${H.cli_flag}`));SE(wt,Ve,f);let Hn=eE(Ce.errors,u),jt=Hn.map(H=>`--type-option ${H}=<value>`),Ql=[...new Set([...y,...jt,...Ve.missing_required_flags])].sort((H,Hi)=>H.localeCompare(Hi));AE({combinedMissingFlags:Ql,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:Hn,openStatus:s.open_status,type:u,createMode:p,missingRequiredRuntimeFields:$i}),nE(Ce.errors,u,m,s);let Re=await _E({pmRoot:r,settings:o,typeRegistry:a,explicitId:n.id}),bt=n.status!==void 0?LS(n.status,s):NS(m,s),Di=n.priority!==void 0?Rn(n.priority):2,P=f.metadataKeys,$e=TE(P,n),rt=an(P,"deadline",n.deadline,H=>oe(H,new Date(h),"deadline")),jr=an(P,"estimated_minutes",n.estimatedMinutes,H=>Cn(H,"estimated-minutes")),kt=z(P,"acceptance_criteria",n.acceptanceCriteria),Ui=z(P,"definition_of_ready",n.definitionOfReady),We=CE(P,n),Gi=z(P,"goal",n.goal),qr=z(P,"objective",n.objective),ww=z(P,"value",n.value),bw=z(P,"impact",n.impact),kw=z(P,"outcome",n.outcome),Sw=z(P,"why_now",n.whyNow),Ew=z(P,"assignee",n.assignee),Aw=P.has("author")?void 0:he(n.author)??v,Tw=z(P,"parent",n.parent),Zl=await uE(Tw,n,P,r),ji=Zl.parent,Cw=Zl.parentSource,Rw=z(P,"reviewer",n.reviewer),Iw=an(P,"risk",n.risk,H=>Ee(xs(H),pn,"risk")),Ow=an(P,"confidence",n.confidence,H=>Ls(H)),xw=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,ed=o.validation.sprint_release_format,qt=[...c.warnings,...mE(u,Re,rt,K.values,W.values)],td=await fE({itemId:Re,parent:ji,pmRoot:r,settings:o,typeRegistry:a,policy:xw});ji=td.parent,qt.push(...td.warnings);let nd=X_(P,"sprint",n.sprint,"sprint",ed),Pw=nd.value;qt.push(...nd.warnings);let rd=X_(P,"release",n.release,"release",ed),Lw=rd.value;qt.push(...rd.warnings);let od=z(P,"blocked_by",n.blockedBy),sd=await hE({pmRoot:r,settings:o,typeRegistry:a,statusRegistry:s,blockedBy:od,dependencyValues:b.values,status:bt,statusExplicit:n.status!==void 0,nowValue:h,author:v}),qi=sd.dependencyValues;Sr(Re,qi),qt.push(...await en({pmRoot:r,dependencies:qi,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Re,createdAt:h}],schema:o.schema})),bt=sd.status;let Nw=z(P,"blocked_reason",n.blockedReason),Fw=z(P,"unblock_note",n.unblockNote),Mw=z(P,"reporter",n.reporter),$w=an(P,"severity",n.severity,H=>Ee(Ps(H),fn,"severity")),Dw=z(P,"environment",n.environment),Uw=z(P,"repro_steps",n.reproSteps),id=z(P,"resolution",n.resolution),Gw=z(P,"expected_result",n.expectedResult),jw=z(P,"actual_result",n.actualResult),qw=z(P,"affected_version",n.affectedVersion),Kw=z(P,"fixed_version",n.fixedVersion),zw=z(P,"component",n.component),Bw=an(P,"regression",n.regression,H=>Ns(H)),Hw=z(P,"customer_impact",n.customerImpact),Ki=Ic(n.title,"--title"),zi=n.description??"",Kr=n.body??"",ad=await Nn({title:Ki,description:zi,body:Kr},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});qt.push(...Es(ad));let Bi=RE(bt,s,o,n,id,h),Vw=Bi.closeReason,Ww=bt===s.close_status?h:void 0,Yw=Bi.completedAt;qt.push(...Bi.warnings);let zr=Ta({id:Re,title:Ki,description:zi,type:u,type_options:Ce.normalized,status:bt,closed_at:Ww,completed_at:Yw,close_reason:Vw,priority:Di,tags:$e,created_at:h,updated_at:h,deadline:rt,assignee:Ew,author:Aw,estimated_minutes:jr,acceptance_criteria:kt,definition_of_ready:Ui,order:We,goal:Gi,objective:qr,value:ww,impact:bw,outcome:kw,why_now:Sw,parent:ji,reviewer:Rw,risk:Iw,confidence:Ow,sprint:Pw,release:Lw,blocked_by:od,blocked_reason:Nw,unblock_note:Fw,reporter:Mw,severity:$w,environment:Dw,repro_steps:Uw,resolution:id,expected_result:Gw,actual_result:jw,affected_version:qw,fixed_version:Kw,component:zw,regression:Bw,customer_impact:Hw,dependencies:qi,comments:S.values,notes:T.values,learnings:I.values,files:D.values,tests:N.values,docs:X.values,reminders:K.values,events:W.values,...wt,...Ve.values});try{Jr(zr,j)}catch(H){throw new d(H instanceof Error?H.message:"Invalid extension item field values",l.USAGE)}let Jw=Xe({metadata:zr,body:Kr},{schema:o.schema,extensionFieldNames:ce}),Xw={metadata:{},body:""},cd=[..._].sort((H,Hi)=>H.localeCompare(Hi)),Qw=qS(n.message,cd),ld=jS(zr,Kr,cd,[...Object.keys(wt),...Object.keys(Ve.values??{})]),Zw=await IE({pmRoot:r,type:u,id:Re,settings:o,typeRegistry:a,author:v,extensionFieldNames:ce,afterDocument:Jw,beforeDocument:Xw,historyMessage:Qw,changedFields:ld,nowValue:h,similarityCandidate:{title:Ki,description:zi,body:Kr},allowDuplicate:n.allowDuplicate}),dd=structuredClone(zr);p==="strict"&&_.has("dependencies")&&(dd.dependencies=[]);let eb=K_(Re,u,bt,s);return rh(u,rt,K.values,W.values)&&ep(`[pm] warning: ${u} '${Re}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Re} --deadline <ISO>' or 'pm update ${Re} --event "start=<ISO>,end=<ISO>"'.`),{item:dd,changed_fields:ld,warnings:[...qt,...Zw],...Object.fromEntries([["parent_source",Cw],["next_transition",eb],["similarity_advisory",ad]].filter(H=>H[1]!==void 0))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="72049bed-5c91-5582-916d-8b530d124b8a")}catch{}})();var Lc=[...bc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...kc,...Qs],OE=(()=>{let e=new Map;for(let t of Lc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),oi=new Map(Lc.map(e=>[e.optionKey,e.canonical])),xE=Lc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),PE=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),LE=Fs({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function mh(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s},r=new Set([...oi.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!ze(s))continue;let i=o==="rank"?"order":oi.get(o)??o;n(i),t[o]=void 0}return be(e,$s(t,LE))}function uh(e,t,n=[]){return Zs({raw:e,supportedFields:xE,resolveDefinition:r=>{let o=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return OE.get(r)??ei(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var oh=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 sh(e){let t=e.disallowedFlags.flatMap(r=>{let o=oh.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=oh.get(r);return o?[`Replace ${r} with: ${o(e.id)}`]:[]});return new d(e.message,l.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function NE(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new d("Choose only one package-provided ownership bypass mode.",l.USAGE);let s=(c,m,u)=>{c&&u.push(m)};if(o){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new d("The dependency ownership bypass requires at least one --dep value",l.USAGE);if(c.length>0)throw sh({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let i=[];s(t.status!==void 0,"--status",i),s(t.closeReason!==void 0,"--close-reason",i),s(t.assignee!==void 0,"--assignee",i),s(t.parent!==void 0,"--parent",i),s(t.blockedBy!==void 0,"--blocked-by",i),s(t.blockedReason!==void 0,"--blocked-reason",i),s(t.unblockNote!==void 0,"--unblock-note",i),s(t.dep!==void 0,"--dep",i),s(t.depRemove!==void 0,"--dep-remove",i),s(t.replaceDeps===!0,"--replace-deps",i),s(t.replaceTests===!0,"--replace-tests",i),s(t.replaceFiles===!0,"--replace-files",i),s(t.replaceDocs===!0,"--replace-docs",i),s(t.note!==void 0,"--note",i),s(t.learning!==void 0,"--learning",i),s(t.test!==void 0,"--test",i),s(t.reminder!==void 0,"--reminder",i),s(t.event!==void 0,"--event",i),s(t.clearDeps===!0,"--clear-deps",i),s(t.clearComments===!0,"--clear-comments",i),s(t.clearNotes===!0,"--clear-notes",i),s(t.clearLearnings===!0,"--clear-learnings",i),s(t.clearFiles===!0,"--clear-files",i),s(t.clearTests===!0,"--clear-tests",i),s(t.clearDocs===!0,"--clear-docs",i),s(t.clearReminders===!0,"--clear-reminders",i),s(t.clearEvents===!0,"--clear-events",i);let a=[...n].filter(c=>PE.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw sh({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${i.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:i})}function FE(e,t){let n=ee(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new d(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n}function ME(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=ee(e.fromStatus,e.statusRegistry)??e.fromStatus,r=ee(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${ru(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new d(o,l.USAGE);return`workflow_transition_not_allowed: ${o}`}function $E(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:ph(e)}function ph(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new d(`Invalid dependency created_at timestamp "${e}"`,l.USAGE);return new Date(t).toISOString()}function Dn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var DE=["id","kind","type","author","created_at","source_kind"],UE=["id","kind","type","author","created_at","source_kind"];function fh(e){return e.startsWith("```")||e.includes(`
|
|
6
|
-
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:ts(e)}function _h(e){return typeof e=="string"?Zr(e)??e.trim():e}function ii(e,t,n,r){return e?(Se(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let i=s.trim(),a=fh(i);kr(i,a);let c=a?le(s,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",DE);let m=c.id?.trim(),u=_h((c.kind??c.type)?.trim());if(!m||!u)throw new d("--dep requires id and kind, or a bare item id to add a related dependency",l.USAGE);if(m.toLowerCase()==="undefined")throw new d(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,l.USAGE);let p=cr(Dn(c.source_kind)),f=Dn(c.author);return{id:lr(m,t,p),kind:Ee(u,Kt,"dependency kind"),created_at:$E(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function GE(e,t){return e?(Se(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new d("--dep-remove requires id or key/value selectors",l.USAGE);let o=fh(r);if(kr(r,o,"--dep-remove"),o){let s=le(r,"--dep-remove");Ke(s,"--dep-remove",UE);let i=s.id?.trim();if(!i)throw new d("--dep-remove key/value form requires id=<value>",l.USAGE);if(i.toLowerCase()==="undefined")throw new d(`--dep-remove id must not use placeholder token "${i}"`,l.USAGE);let a=_h(Dn(s.kind??s.type)),c=cr(Dn(s.source_kind)),m=Dn(s.author),u=Dn(s.created_at);return{id:lr(i,t,c),kind:a?Ee(a,Kt,"dependency kind"):void 0,source_kind:c,author:m,created_at:u?ph(u):void 0}}if(r.toLowerCase()==="undefined")throw new d(`--dep-remove id must not use placeholder token "${r}"`,l.USAGE);return{id:Ue(r,t)}})):[]}function si(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function jE(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),s=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function qE(e,t,n,r){let o=[...e??[]],s=!1;if(t===void 0){let i=o.filter(a=>a.kind!=="blocked_by");return i.length!==o.length&&(o=i,s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(i=>i.kind==="blocked_by"&&i.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function KE(e,t,n,r,o,s){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await q(n,Ue(i,r),r,o,s);return a?{id:a.id}:{unresolved:i}}function zE(e,t,n,r,o){let s=qE(e.dependencies,t,n,r);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,o.includes("dependencies")||o.push("dependencies"))}function BE(e){return`${e.path}::${e.scope}`}function HE(e){return`${e.path}::${e.scope}`}function VE(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function hh(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function ih(e,t){let n=Vn("update",e);if(!n)throw new d(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,l.CONFLICT);return n}function WE(e,t,n){let r=new Set,o=(s,i)=>{i&&r.add(s)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=uh(e.unset,t,n);for(let i of s.optionKeys)o(i,!0)}return r}function YE(e,t,n,r,o){let s=Xr(e,n);if(!s)throw new d(`Invalid type value "${e}"`,l.USAGE);let i=hn(s,"update",[]);if(i.errors.length>0)throw new d(i.errors.join("; "),l.CONFLICT);let a=WE(t,r,o);for(let c of i.disabled)if(a.has(ih(c,e)))throw new d(`Option ${ve("update",c)} is disabled for type "${e}" by command_option_policies`,l.USAGE);for(let c of i.required)if(!a.has(ih(c,e)))throw new d(`Missing required option ${ve("update",c)} for type "${e}"`,l.USAGE)}var JE=new Set(["order","rank"]),XE=ta.filter(e=>!JE.has(e)),gh=["tags","closeReason",...XE],QE=["title","description","body","status","closeReason","completedAt","priority","type",...ta,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],ZE=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>oe(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Cn(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"}],eA=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Ee(xs(e),pn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Ls(e)}],tA=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Ee(Ps(e),fn,"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=>Ns(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Pc(e,t,n){for(let r of e){let o=t[r.optionKey],s=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!s)){if(s){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new d(`${ve("update",String(r.optionKey))} must be a string value`,l.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function nA(e){return mh(await ns(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 Nc(e){return mt(e)?await nA(e):mh(e)}function rA(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 Oc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new d(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,l.USAGE);if(e.enabled&&e.clearEnabled)throw new d(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,l.USAGE)}function Fc(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new d("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",l.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 d("--replace-deps requires at least one --dep entry",l.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new d("--replace-deps cannot be combined with --dep-remove",l.USAGE);Oc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Oc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Oc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function oA(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 d(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,l.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function sA(e){let t={};for(let n of gh)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function iA(e,t){let n=sA(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=oi.get(r)??r;throw new d(`Cannot combine --unset ${s} with ${ve("update",r)}`,l.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new d("Cannot combine --unset acceptance-criteria with --add-ac",l.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new d("Cannot combine --unset acceptance-criteria with --remove-ac",l.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new d("Cannot combine --unset tags with --add-tags",l.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new d("Cannot combine --unset tags with --remove-tags",l.USAGE)}}function aA(e){let t=(n,r)=>{let o=oi.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;Ms(n,ve("update",r),s)};for(let n of gh)t(e[n],String(n));t(e.order??e.rank,"order"),Se(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Se(e.event,"--event","Use --clear-events to clear linked events.")}function cA(e,t){let n={};for(let r of QE)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.runtimeFields=Object.keys(t).length>0,n}async function lA(e){let t=await q(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 se(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function dA(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return pe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function mA(e){e.before&&ms(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>ne(t,e.statusRegistry),Ft())}function uA(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new d("--order and --rank must match when both are provided",l.USAGE)}async function pA(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=ds(is(e.options.parent),e.settings.id_prefix);if(Mo(t))return{resolvedParentValue:t,warnings:[]};if(cs(e.id,t,e.settings.id_prefix),await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=Ue(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:as(r,e.parentReferencePolicy).warnings}}function fA(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function _A(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await q(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 se(t,{schema:e.settings.schema}),r=e.options.type!==void 0?ye(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=ME({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function hA(e){if(!e.fieldFlags.status||ee(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],o=[];if(n.length>0){let a=be(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),c=await _t(e.id,a,e.global);o=c.changed_fields,r.push(...c.warnings)}let s=await pt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...e.workflowTransitionWarnings,...r,...s.warnings,"auto_routed_from_update_to_close"];return{item:s.item,changed_fields:[...o,...s.changed_fields],warnings:i}}function gA(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Ic(t.title,"--title"),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),ee(e.metadata.status,n)??e.metadata.status}var yA=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function vA(e,t){for(let n of yA)e[n]!==void 0&&(delete e[n],t.push(n))}function wA(e,t,n,r,o){let s=FE(n,t.statusRegistry);if(e.metadata.status=s,o.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!ne(s,t.statusRegistry)&&ne(r,t.statusRegistry)&&vA(e.metadata,o)}function bA(e,t,n,r){if(t.options.status!==void 0&&wA(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!ne(e.metadata.status,t.statusRegistry))throw new d("--completed-at can only be set on a terminal item",l.USAGE);e.metadata.completed_at=oe(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function kA(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new d("--close-reason must not be empty",l.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&ne(n,t.statusRegistry)&&!ne(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function SA(e,t,n,r){bA(e,t,n,r),kA(e,t,n,r)}function EA(e,t,n){let r=ye(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=Rn(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=ye(t.options.type,t.typeRegistry);if(!o)throw new d(Ct(t.options.type,t.typeRegistry.types,Rt(t.pmRoot,t.settings.schema)),l.USAGE);e.metadata.type=o,r=o,n.push("type")}return YE(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),AA(e,t,r,n),r}function AA(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=Gs(t.options.typeOption??[]),i=Wn(n,s,t.typeRegistry);if(i.errors.length>0)throw new d(i.errors.join("; "),l.USAGE);e.metadata.type_options=i.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let o=Wn(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new d(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,l.USAGE);e.metadata.type_options=o.normalized}function TA(e,t){let n=new Set(t.map(o=>si(o))),r=new Set;return e.filter(o=>{if(!n.has(si(o)))return!0;let s=jE(o);return r.has(s)?!1:(r.add(s),!0)})}function CA(e,t,n){let r=t.filter(o=>!e.some(s=>hh(s,o)));if(r.length!==0)throw new d(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,l.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function RA(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=TA(r,t.dependencyUpdates.additions);let o=new Set(r.map(s=>si(s)));for(let s of t.dependencyUpdates.additions){let i=si(s);o.has(i)||(r.push(s),o.add(i))}}t.dependencyRemovals.length>0&&(CA(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(s=>hh(o,s)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function IA(e,t,n){xc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),xc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),xc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function xc(e,t,n,r,o,s){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],s.push(t))}function OA(e,t,n){ah(e,"files",t.options.file,t.fileUpdates.values,BE,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),xA(e,t,n),ah(e,"docs",t.options.doc,t.docUpdates.values,HE,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function ah(e,t,n,r,o,s,i,a){if(!(n===void 0&&!i.has(t))){if(s)e.metadata[t]=r;else if(i.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(u=>o(u)));for(let u of r){let p=o(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function xA(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=ch(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=ch([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function ch(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=VE(r);n.has(o)||(t.push(r),n.add(o))}return t}function PA(e,t,n){let r=t.options.addTags,o=t.options.removeTags,s=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Lt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=es(Tn(i,r),o),n.changedFields.push("tags")}Pc(ZE,t.options,n),NA(e,t,n.changedFields)}function LA(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let s=Zo(An(e.metadata.acceptance_criteria),r,o);if(s.unmatchedRemovals.length>0)throw new d(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,l.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let i=s.criteria.join("; ");e.metadata.acceptance_criteria!==i&&(i===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=i,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function NA(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=fe(r??"","order");if(!Number.isInteger(o))throw new d("Order must be an integer",l.USAGE);e.metadata.order=o}n.push("order")}}function FA(e,t,n,r){MA(e,t,n.changedFields),$A(e,t,n.changedFields),Pc(eA,t.options,n),lh(e,t,"sprint",r,n.changedFields),lh(e,t,"release",r,n.changedFields),DA(e,t,n.changedFields),Pc(tA,t.options,n)}function MA(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 d("--assignee must not be empty. Use --unset assignee to clear it.",l.USAGE);e.metadata.assignee=r}n.push("assignee")}}function $A(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 lh(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=ls(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,r.push(...s.warnings)}o.push(n)}}function DA(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&zE(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function UA(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Ds(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 GA(e,t,n){dh(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),dh(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let i=o.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===o)?.cli_flag??i;throw new d(`Cannot combine --unset ${i} with --${c}`,l.USAGE)}at(e[o],s)||(e[o]=s,n.push(o))}let r=Yr(t.options.field,t.extensionRegistrations);for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new d(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,l.USAGE);for(let[o,s]of Object.entries(r))at(e[o],s)||(e[o]=s,n.push(o))}function dh(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function jA(e,t){let n=structuredClone(e.metadata),r=e.body,o=[],s=[],i=gA(e,t.options,t.statusRegistry,o),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};SA(e,t,i,o),EA(e,t,o),RA(e,t,o),IA(e,t,o),OA(e,t,o),PA(e,t,c),LA(e,t,c),FA(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"))&&Sr(e.metadata.id,e.metadata.dependencies),ee(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),UA(e,t,o),GA(a,t,o);try{Jr(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(p){throw new d(p instanceof Error?p.message:"Invalid extension item field values",l.USAGE)}let m=e.metadata,u=[...new Set(o)].filter(p=>p==="body"?e.body!==r:!at(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${An(n.acceptance_criteria).length}:${An(m.acceptance_criteria).length}`),{changedFields:u,warnings:s}}async function yh(e,t,n,r={}){t=await Nc(t);let o=E(process.cwd(),n.path);await R(o);let s=await A(o),i=$(s.schema),a=Je(s.schema),c=O(),m=Et(c),u=x(s,c),p=s.governance.workflow_enforcement??"off",f=p==="off"?[]:tu(s.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],g=uh(t.unset,a,m),y=new Set(g.optionKeys),h=new Set(g.metadataKeys);Fc(t),oA({definitions:rA(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:h}),NE(e,t,h),iA(t,g),aA(t);let v=C(t.author,s.author_default),b=new Date,S=b.toISOString(),T=ii(t.dep,s.id_prefix,S,v);Sr(e,T.additions);let I=await en({pmRoot:o,dependencies:T.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),D=GE(t.depRemove,s.id_prefix),N=cn("--comment",t.comment,S,v),X=t.ownershipMetadataBypass===!0&&N.values?{...N,values:N.values.map($e=>({...$e,author:v}))}:N,K=cn("--note",t.note,S,v),W=cn("--learning",t.learning,S,v),Q=Tc(t.file),Ce=Cc(t.test);Ce.values=await Ln(Ce.values,v,S);let j=Rc(t.doc),ce=[],wt=await pA({id:e,options:t,unsetTargets:g,pmRoot:o,settings:s,typeRegistry:u,parentReferencePolicy:_}),Ve=await KE(t.blockedBy,h.has("blocked_by"),o,s.id_prefix,s.item_format,u.type_to_folder),Mi=Ve.id,$i=[...wt.warnings,...fA(Ve)],Hn=Bo(t,a,t.runtimeFieldCommands),jt=cA(t,Hn);if(!Object.values(jt).some(Boolean))return lA({pmRoot:o,id:e,settings:s,typeRegistry:u});ce.push(...await _A({options:t,fieldFlags:jt,workflowEnforcement:p,typeWorkflows:f,statusRegistry:i,typeRegistry:u,pmRoot:o,id:e,settings:s}));let Re=await hA({options:t,fieldFlags:jt,statusRegistry:i,workflowTransitionWarnings:ce,global:n,id:e});if(Re)return Re;uA(t);let bt=Ft(),Di=jt.parent&&!h.has("parent")||T.additions.some($e=>bt.resolve($e.kind)?.hierarchy),P=await js({pmRoot:o,author:v,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Di});try{let $e=await dA({fieldFlags:jt,clearedMetadataKeys:h,pmRoot:o,settings:s,typeToFolder:u.type_to_folder}),rt,jr,kt=await yp({pmRoot:o,settings:s,typeToFolder:u.type_to_folder,id:e,op:qA(t,r),author:v,message:t.message,resolveHistoryContext:()=>jr,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(We){rt=KA({document:We,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),jr=rt?{recurrence:rt}:void 0,$e=$e?.map(qr=>qr.id===We.metadata.id?structuredClone(We.metadata):qr);let Gi=jA(We,{options:t,settings:s,typeRegistry:u,statusRegistry:i,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:h,dependencyUpdates:T,dependencyRemovals:D,commentUpdates:X,noteUpdates:K,learningUpdates:W,fileUpdates:Q,testUpdates:Ce,docUpdates:j,resolvedParentValue:wt.resolvedParentValue,resolvedBlockedByDependencyId:Mi,runtimeFieldUpdates:Hn,nowValue:b,nowIso:S,author:v,pmRoot:o});return mA({before:$e,document:We,statusRegistry:i}),Gi}});await P();let Ui=$e?Ss($e,$e.map(We=>We.id===kt.item.id?kt.item:We),kt.item.id):[];return{item:kt.item,changed_fields:kt.changedFields,warnings:[...ce,...$i,...I,...Ui,...kt.warnings],...rt===void 0?{}:{lifecycle_transition:rt}}}finally{await P()}}function qA(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function KA(e){if(e.recurrenceReason===void 0)return;let t=ee(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!ne(t,e.statusRegistry))throw new d(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,l.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=ee(n,e.statusRegistry)??n,o=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(i=>{let a=o[i];return typeof a=="string"?[[i,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:s}}async function _t(e,t,n){return yh(e,t,n)}async function vh(e,t,n,r){let o=await yh(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new d(`Item ${e} did not produce the required recurrence receipt.`,l.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ef785ae-bb1e-59dd-993c-3be56ddc26c2")}catch{}})();var bh=1,$c="update-many",zA=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),BA=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),HA={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},VA=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],WA={close_reason:"close_reason","close-reason":"close_reason",deadline:"deadline",estimate:"estimated_minutes",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",ac:"acceptance_criteria",definition_of_ready:"definition_of_ready","definition-of-ready":"definition_of_ready",order:"order",rank:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",why_now:"why_now","why-now":"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blocked_by:"blocked_by","blocked-by":"blocked_by",blocked_reason:"blocked_reason","blocked-reason":"blocked_reason",unblock_note:"unblock_note","unblock-note":"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",repro_steps:"repro_steps","repro-steps":"repro_steps",resolution:"resolution",expected_result:"expected_result","expected-result":"expected_result",actual_result:"actual_result","actual-result":"actual_result",affected_version:"affected_version","affected-version":"affected_version",fixed_version:"fixed_version","fixed-version":"fixed_version",component:"component",regression:"regression",customer_impact:"customer_impact","customer-impact":"customer_impact",type_options:"type_options","type-options":"type_options",tags:"tags"},kh=e=>{let t={};for(let[n,r]of Object.entries(e))zA.has(n)||r!==void 0&&(t[n]=r);return t},YA=e=>Object.keys(kh(e)).length>0,Sh=e=>typeof e=="string"?e.trim():e,JA=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Mc=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},XA=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Sh(e)},QA={priority:JA,estimatedMinutes:Mc,order:Mc,rank:Mc,regression:XA},ZA=(e,t)=>{if(t!==void 0)return(QA[e]??Sh)(t)},eT=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return WA[t]??t},ai=(e,t)=>at(e,t),tT=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],nT=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,rT=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",wh=(e,t)=>t===void 0?void 0:e[t],Un=e=>Array.isArray(e)?e.length:0,oT=(e,t,n)=>{let r=n[e.addKey],o=wh(n,e.removeKey),s=Un(r),i=Un(o),a=n[e.clearKey]===!0,c=wh(n,e.replaceKey)===!0;if(![a,c,s>0,i>0].includes(!0))return;let m=tT(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:rT({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:s,remove_count:i,before_count:nT(e.field,m)}}},sT=(e,t)=>{let n=[];for(let r of VA){let o=oT(r,e,t);o!==void 0&&n.push(o)}return n},iT=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],aT=(e,t)=>{if(![t.tags!==void 0,Un(t.addTags)>0,Un(t.removeTags)>0].includes(!0))return;let n=iT(e.tags),r=t.tags===void 0?n:Lt(t.tags),o=Tn(r,t.addTags),s=es(o,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!ai(i,s))return{field:"tags",before:n,after:s}},cT=(e,t)=>{let n=e.acceptance_criteria,r=Zo(An(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new d(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,l.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let o=r.criteria.join("; ");if(!ai(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},lT=(e,t,n)=>{for(let[r,o]of Object.entries(HA)){let s=n[r];if(s===void 0)continue;let i=t[o],a=ZA(r,s);ai(i,a)||e.push({field:o,before:i,after:a})}},dT=(e,t,n,r)=>{let o=Bo(n,r,["update_many"]);for(let[s,i]of Object.entries(o)){let a=t[s];ai(a,i)||e.push({field:s,before:a,after:i})}},mT=(e,t,n)=>{for(let r of n??[]){let o=eT(r),s=t[o];s!==void 0&&e.push({field:o,before:s,after:null})}},uT=(e,t,n={})=>{let r=e,o=[],s=aT(r,n);if(s&&o.push(s),lT(o,r,n),Un(n.addAc)>0||Un(n.removeAc)>0){let i=cT(r,n);i!==void 0&&o.push(i)}return o.push(...sT(r,n)),dT(o,r,n,t),mT(o,r,n.unset),{id:e.id,changes:o}},pT=(e,t)=>Op(e,t,{strict:!0,flagLabel:"--filter-status"}),fT=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new d("--ids requires at least one non-empty item ID",l.USAGE)},_T=[({update:e})=>{e.priority!==void 0&&Rn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,O());if(!ye(e.type,r))throw new d(Ct(e.type,r.types,Rt(n,t.schema)),l.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!ee(e.status,t)){let n=t.definitions.map(r=>r.id);throw new d(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,l.USAGE)}},({update:e})=>{e.deadline!==void 0&&oe(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&Cn(e.estimatedMinutes,"estimated-minutes")}],hT=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let s of _T)s(o)},gT=async e=>{let t=await Jo(e.pmRoot,$c,e.rollbackId,bh),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Xo(t.items,(o,s)=>Zt(o,s,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...Wt({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},yT=async e=>{let t={schema_version:bh,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Yo(e.pmRoot,$c,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},vT=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},Dc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},wT=async e=>{let t=E(process.cwd(),e.path);await R(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:$(n.schema),runtimeFieldRegistry:Je(n.schema)}},bT=e=>{if(e.options.dryRun===!0)throw new d("--dry-run cannot be combined with --rollback",l.USAGE);if(_r(e.options.list,e.options.status))throw new d("Rollback mode does not accept filter options",l.USAGE);if(Object.keys(e.updateSummary).length>0)throw new d("Rollback mode does not accept update mutation flags",l.USAGE);return gT({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},kT=async e=>{pT(e.options.status,e.runtime.statusRegistry);let t=await ut(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let s=uT(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?s:{...s,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await ut(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:vT(e.options.list?.ids,r)}},ST=e=>({outcome:"effect",exit_code:l.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...Dc(e)}),ET=e=>({...Wt({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...Dc(e)}),AT=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(s=>s.changes.length>0).map(s=>s.id));for(let s of e.items){if(!o.has(s.id)){t.push({id:s.id,status:"skipped"});continue}try{let i=Fa({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),a=await _t(s.id,i,e.global);t.push({id:s.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(s.id)}catch(i){t.push({id:s.id,status:"failed",error:gn(i)})}}return{rows:t,updatedIds:n}},TT=async e=>{if(e.plan.actionable.length===0)return ET(e.plan);let t=k(),n=Wo($c,t),r=new Set(e.plan.actionable.map(p=>p.id)),o=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),s=e.options.checkpoint===!1?void 0:await yT({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),i=await AT({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=p=>i.rows.filter(f=>f.status===p).length,c=a("updated"),m=a("skipped"),u=a("failed");return{...Wt({applied:c,skipped:m,failed:u,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...s?{checkpoint:s}:{},updated_count:c,skipped_count:m,failed_count:u,rows:i.rows,ids:i.updatedIds,...Dc(e.plan)}},Eh=async(e,t)=>{let n=await wT(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:Fa(await Nc(e.update))});let o=kh(e.update);if(fT(e.list),r!==void 0)return bT({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!YA(e.update)&&e.dryRun!==!0)throw new d(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${BA}), or pass --dry-run for a filter-only preview.`,l.USAGE);hT(e.update,n.settings,n.statusRegistry,n.pmRoot),Fc(e.update);let s=await en({pmRoot:n.pmRoot,dependencies:ii(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,O()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await kT({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:s});return await en({pmRoot:n.pmRoot,dependencies:ii(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,O()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:i.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:n.settings.schema}),e.dryRun===!0?ST(i):TT({runtime:n,options:e,global:t,plan:i})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="374c7cb8-9fd0-5a2d-8aaf-9d09b63abaf0")}catch{}})();var CT=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Ah=["brief","standard","deep"],Rh="plan-step-",zc="draft",Kc=["bug-investigation","feature-implementation","refactoring-sprint"],Th={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function RT(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(Th,t)?Th[t]:void 0;if(!n)throw new d(`Unknown plan template "${e}". Allowed: ${Kc.join(", ")}`,l.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Kc[0]}`]});return n.map(r=>({...r}))}function IT(e,t){return t>0?Math.round(e/t*100):0}function Ih(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function je(e){return Array.isArray(e)?e.flatMap(t=>In(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?In(e,{unique:!1}):[]}function Ae(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function Oh(e,t=zc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Yi.find(o=>o===n);if(!r)throw new d(`Invalid plan mode "${e}". Allowed: ${Yi.join(", ")}`,l.USAGE);return r}function Bc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ji.find(o=>o===n);if(!r)throw new d(`Invalid step status "${e}". Allowed: ${Ji.join(", ")}`,l.USAGE);return r}function xh(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Qi.find(o=>o===n);if(!r)throw new d(`Invalid step link kind "${e}". Allowed: ${Qi.join(", ")}`,l.USAGE);return r}function OT(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Xi.find(r=>r===t);if(!n)throw new d(`Invalid plan harness "${e}". Allowed: ${Xi.join(", ")}`,l.USAGE);return n}function xT(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=Ah.find(r=>r===t);if(!n)throw new d(`Invalid --depth "${e}". Allowed: ${Ah.join(", ")}`,l.USAGE);return n}function PT(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new d("Plan --fields requires a comma-separated list of plan field names",l.USAGE);return t}var Uc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function LT(e,t){let n=e,r={},o=[];for(let s of t){let i=s.startsWith("plan.")?s.slice(5):s;if(i.length!==0){if(!Uc.has(i)){o.push(s);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(o.length>0)throw new d(`Unknown Plan --fields value(s): ${o.join(", ")}`,l.USAGE,{nextSteps:[`Use --fields ${[...Uc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...Uc].join(",")}`}});return r}function Hc(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let s=o.indexOf("=");if(s<=0)throw new d(`Invalid ${t} entry "${o}"; expected key=value`,l.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[o.slice(0,s).trim().toLowerCase()]=o.slice(s+1).trim()}return n}function Vc(e){let t=Hc(e,"--file");if(!t.path)throw new d("--file requires path=<value>",l.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function Wc(e){let t=Hc(e,"--test");if(!t.command&&!t.path)throw new d("--test requires at least command=<value> or path=<value>",l.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function Yc(e){let t=Hc(e,"--doc");if(!t.path)throw new d("--doc requires path=<value>",l.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function NT(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=IT(t.completed,t.total),t}function FT(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${Rh}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new d("Could not allocate step id (limit reached)",l.GENERIC_FAILURE)}function Gn(e,t){let n=t.trim();if(n.length===0)throw new d("Step reference cannot be empty",l.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),s=e.find(i=>i.order===o);if(s)return s}throw new d(`Step "${t}" not found in plan`,l.NOT_FOUND)}function Ch(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function MT(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],o=[];if(n.length>0){if(t.length>n.length)throw new d("pm plan materialize --steps all cannot be combined with other step refs",l.USAGE);for(let i of e.slice().sort((a,c)=>a.order-c.order)){let a=Ch(i);if(a){o.push({from_step:i.id,...a});continue}r.push(i)}return{targets:r,skipped:o}}let s=new Set;for(let i of t){let a=Gn(e,i);if(s.has(a.id))continue;s.add(a.id);let c=Ch(a);if(c){o.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:o}}function $T(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function DT(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function UT(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function Le(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=NT(n),o=DT(n),s={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??zc,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:UT(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(s.steps=n),t==="deep"&&(s.decisions=e.plan_decisions??[],s.discoveries=e.plan_discoveries??[],s.validation=e.plan_validation??[]),s}function Ne(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!$a(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function Ph(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new d(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,l.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function GT(e){let t=E(process.cwd(),e.path);await R(t);let n=await A(t);return{pmRoot:t,settings:n}}async function Lh(e,t){let n=x(e.settings,O()),r=await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new d(`Plan ${t} not found`,l.NOT_FOUND);let o=await se(r,{schema:e.settings.schema});return Ph(o.document.metadata),{document:o.document,itemId:r.id}}function jT(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of je(e.related))t.push(`id=${n},kind=related`);for(let n of je(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of je(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function qT(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function KT(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||je(e.dependsOn).length>0||je(e.link).length>0}function zT(e){let t=e.stepTitle?.trim()||void 0,n=Ih(e.step),r=e.template?.trim()?RT(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function BT(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new d("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",l.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${Kc[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new d("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",l.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function HT(e,t){let n=Bc(e.stepStatus,"pending"),r=Jc(e,"depends_on"),o=Ae(e.file).map(Vc),s=Ae(e.test).map(Wc),i=Ae(e.doc).map(Yc),a=k();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:s.length>0?s:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function VT(e){let t=zT(e),n=KT(e);if(BT(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[HT(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((o,s)=>({id:`${Rh}${String(s+1).padStart(3,"0")}`,order:s+1,title:o,body:t.templateSteps[s]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function Nh(e,t,n=[]){be(e,t),n.length>0&&Cp(t,n)}async function WT(e,t,n){let r=e.title?.trim();if(!r)throw new d("pm plan create requires --title",l.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let o=Oh(e.mode,zc),s=OT(e.harness),i=e.fromSearch?.trim(),a=qT(e),{steps:c,hasPerStepDetailOptions:m}=VT(e);if(c.length===0&&m)throw new d("pm plan create step options require --step-title (or a single --step)",l.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:Ae(e.file),test:Ae(e.test),doc:Ae(e.doc),field:Ae(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:jT(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")};Nh(e,f);let _=await $t(f,t),g=await ie({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(h){let v=["plan_mode"];h.metadata.plan_mode=o,s&&(h.metadata.plan_harness=s,v.push("plan_harness"));let b=e.scope?.trim();b&&(h.metadata.plan_scope=b,v.push("plan_scope"));let S=e.resumeContext?.trim();return S&&(h.metadata.plan_resume_context=S,v.push("plan_resume_context")),h.metadata.plan_steps=c,v.push("plan_steps"),a&&(h.metadata.plan_validation=[...h.metadata.plan_validation??[],a],v.push("plan_validation")),p&&(h.metadata.assignee=p,v.push("assignee")),{changedFields:v}}}),y=Le(g.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Ne(_.item.id,y),warnings:[..._.warnings],generated_at:k()}}async function YT(e,t,n){let r=xT(t.depth),o=PT(t.fields),{document:s,itemId:i}=await Lh(n,e),a=Le(s.metadata,o===null?r:"deep");return{action:"show",plan:o===null?a:LT(a,o),next_actions:Ne(i,a),warnings:[],generated_at:k()}}function JT(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function et(e){let t=C(e.options.author,e.ctx.settings.author_default),n,r=await ie({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){Ph(o.metadata);let s=$(e.ctx.settings.schema);if(ne(o.metadata.status,s)||$a(o.metadata.plan_mode))throw new d(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.metadata.plan_mode??"unset"}) and cannot be mutated.`,l.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let i=(o.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(o.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,o);n=c.resultStep;let m=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));o.metadata.plan_steps=m;let u=JT(a,o.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function XT(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new d("pm plan add-step requires --step-title",l.USAGE);let o=Bc(t.stepStatus,"pending"),s=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await et({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;Fh(u,void 0,o,s);let f=QT(u,t,{order:p,title:r,status:o});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Le(i.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Ne(c,m),warnings:[],generated_at:k()}}function Fh(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(s=>s.id!==t&&s.status==="in_progress");if(o)throw new d(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,l.CONFLICT)}function QT(e,t,n){let r=Jc(t,"depends_on"),o=Ae(t.file).map(Vc),s=Ae(t.test).map(Wc),i=Ae(t.doc).map(Yc),a=k();return{id:FT(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:s.length>0?s:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function Jc(e,t){let n=je(e.dependsOn).map(u=>({id:u,kind:t})),r=je(e.related).map(u=>({id:u,kind:"related"})),o=je(e.blocks).map(u=>({id:u,kind:"blocks"})),s=je(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=je(e.link),a=xh(e.linkKind,t),c=e.linkNote?.trim(),m=i.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...o,...s,...m]}async function Gc(e,t,n,r){let{document:o,resultStep:s,itemId:i}=await et({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=Gn(c,r.stepRef),p=k(),f=r.finalStatus??Bc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return Fh(c,u.status==="in_progress"?u.id:void 0,f,_),ZT(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Le(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:s,next_actions:Ne(i,a),warnings:[],generated_at:k()}}function ZT(e,t,n,r){eC(e,t,n),tC(e,t),e.status=n,e.updated_at=r,nC(e,n,r)}function eC(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new d("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",l.USAGE)}function tC(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=t.stepOwner.trim()||void 0),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let r=Ae(t.file).map(Vc),o=Ae(t.test).map(Wc),s=Ae(t.doc).map(Yc);r.length>0&&(e.files=jc(e.files,r)),o.length>0&&(e.tests=jc(e.tests,o)),s.length>0&&(e.docs=jc(e.docs,s))}function jc(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let s=JSON.stringify(o);r.has(s)||(r.add(s),n.push(o))}return n}function nC(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function rC(e,t,n,r,o){let{document:s,itemId:i}=await et({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(c){let m=Gn(c,r),u=c.filter(f=>f.id!==m.id),p=Math.max(1,Math.min(o,u.length+1));return u.splice(p-1,0,m),u.forEach((f,_)=>{f.order=_+1,f.updated_at=k()}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=Le(s.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Ne(i,a),warnings:[],generated_at:k()}}async function oC(e,t,n,r){let{document:o,itemId:s}=await et({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=Gn(a,r),m=a.filter(u=>u.id!==c.id);return m.forEach((u,p)=>{u.order=p+1}),a.length=0,a.push(...m),{changedSteps:[c.id]}}}),i=Le(o.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Ne(s,i),warnings:[],generated_at:k()}}async function sC(e,t,n,r){let o=Jc(t,xh(t.linkKind,"related"));if(o.length===0)throw new d("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",l.USAGE);let s=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await et({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Gn(u,r),_=f.linked_items??[],g=h=>`${h.kind}:${h.id}`,y=new Set(_.map(g));for(let h of o){let v=g(h);y.has(v)||(_.push(h),y.add(v))}if(f.linked_items=_,f.updated_at=k(),s){let h=p.metadata.dependencies??[],v=S=>`${S.kind}:${S.id}`,b=new Set(h.map(v));for(let S of o){let T=S.kind==="depends_on"?"blocked_by":S.kind,I={id:S.id,kind:T,created_at:k(),author:C(t.author,n.settings.author_default)};b.has(v(I))||(h.push(I),b.add(v(I)))}p.metadata.dependencies=h}return{changedSteps:[f.id],resultStep:f}}}),m=Le(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ne(a,m),warnings:[],generated_at:k()}}async function iC(e,t,n,r){let o=je(t.link);if(o.length===0)throw new d("pm plan unlink requires --link <id> to remove",l.USAGE);let{document:s,itemId:i,resultStep:a}=await et({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=Gn(m,r),p=(u.linked_items??[]).filter(f=>!o.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=k(),{changedSteps:[u.id],resultStep:u}}}),c=Le(s.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Ne(i,c),warnings:[],generated_at:k()}}async function qc(e,t,n,r){let o=$T(r,t);if(!o){let m=`--${r}-text`,u=`--${r}`;throw new d(`pm plan ${r} requires ${m}`,l.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${m} "..."`,`pm plan ${r} <plan-id> ${u} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${m} <value>`}})}let s=C(t.author,n.settings.author_default),{document:i,itemId:a}=await et({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,u){let p=k();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:s,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:s,text:o}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Le(i.metadata,"deep");return{action:r,plan:c,next_actions:Ne(a,c),warnings:[],generated_at:k()}}async function aC(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new d("pm plan resume requires --resume-context <text>",l.USAGE);let{document:o,itemId:s}=await et({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Le(o.metadata,"brief");return{action:"resume",plan:i,next_actions:Ne(s,i),warnings:[],generated_at:k()}}async function cC(e,t,n){let r=Oh(t.mode??"approved","approved"),{document:o,itemId:s}=await et({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(a,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),i=Le(o.metadata,"brief");return{action:"approve",plan:i,next_actions:Ne(s,i),warnings:[],generated_at:k()}}function Mh(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function lC(e,t){let n=Le(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ne(e.itemId,n),warnings:Mh(t),generated_at:k()}}function dC(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let s=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${s}`)}return r}async function mC(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Ae(e.options.field)){let s=o.indexOf("=");if(s<=0)throw new d(`Invalid --field entry "${o}"; expected name=value`,l.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0)throw new d(`Invalid --field entry "${o}"; expected name=value`,l.USAGE);let c=i.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new d(`Invalid --field entry "${o}"; expected name=value`,l.USAGE);let[m,...u]=c,p=`${m}${u.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(p))throw new d(`Invalid --field entry "${o}"; "${p}" is reserved by materialize and cannot be overridden`,l.USAGE);n[p]=a}for(let o of e.targets){let s={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:dC(e.parent,e.planItemId,o)};Nh(e.options,s,["description",...Object.keys(n)]);let i=await $t(s,{path:e.pmRoot});t.push({id:i.item.id,title:i.item.title,type:e.resolvedTypeName,parent:i.item.parent,tags:i.item.tags??[],from_step:o.id})}return t}function uC(e,t,n){for(let r of t){let o=n.find(a=>a.from_step===r.id);if(!o)continue;let s=e.find(a=>a.id===r.id);if(!s)continue;let i=s.linked_items??[];i.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),s.linked_items=i,s.updated_at=k()}}async function pC(e,t,n){let r=je(t.steps);if(r.length===0)throw new d("pm plan materialize requires --steps <ids|orders|all>",l.USAGE);let o=t.materializeType?.trim()||"Task",s=x(n.settings,O()),i=ye(o,s);if(!i)throw new d(`Invalid --materialize-type "${o}"`,l.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await Lh(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=MT(u,r);if(p.length===0){if(f.length>0)return lC(m,f);throw new d("No matching plan steps found for --steps",l.NOT_FOUND)}let _=await mC({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:g,itemId:y}=await et({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(v){return uC(v,p,_),{changedSteps:p.map(b=>b.id)}}}),h=Le(g.metadata,"standard");return{action:"materialize",plan:h,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ne(y,h),warnings:Mh(f),generated_at:k()}}function fC(e){if(e.subcommand==="create")return e;let t=Ih(e.options.step);if(t.length>1)throw new d(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,l.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:be(e.options,{...e.options,stepTitle:t[0]})}:e}function ht(e,t){if(!e.id)throw new d(`pm plan ${t} requires a plan id`,l.USAGE);return e.id}function ln(e,t){let n=ht(e,t);if(!e.stepRef)throw new d(`pm plan ${t} requires <plan-id> <step>`,l.USAGE);return{id:n,stepRef:e.stepRef}}function _C(e){let t=ln(e,"reorder-step");if(e.reorderTo===void 0)throw new d("pm plan reorder-step requires <plan-id> <step> <new-order>",l.USAGE);return{...t,reorderTo:e.reorderTo}}var hC={create:(e,t)=>WT(e.options,e.global,t),show:(e,t)=>YT(ht(e,"show"),e.options,t),"add-step":(e,t)=>XT(ht(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=ln(e,"update-step");return Gc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=ln(e,"complete-step");return Gc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=ln(e,"block-step");return Gc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=_C(e);return rC(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=ln(e,"remove-step");return oC(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=ln(e,"link");return sC(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=ln(e,"unlink");return iC(n.id,e.options,t,n.stepRef)},decision:(e,t)=>qc(ht(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>qc(ht(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>qc(ht(e,"validation"),e.options,t,"validation"),resume:(e,t)=>aC(ht(e,"resume"),e.options,t),approve:(e,t)=>cC(ht(e,"approve"),e.options,t),materialize:(e,t)=>pC(ht(e,"materialize"),e.options,t)};function gC(e){let t=hC[e];if(!t)throw xe({command_path:"plan",token:e,allowed:CT});return t}async function $h(e){let t=await GT(e.global),n=fC(e);return gC(n.subcommand)(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64b269aa-d285-53bb-8949-b75bed767479")}catch{}})();function yC(e,t){return[...new Set([...Wr.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,o)=>r.localeCompare(o))}function vC(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Xc(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await A(r),s=x(o,O()),i=await q(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!i)throw await dt(r,e,o.id_prefix,s.type_to_folder);let a=await se(i,{schema:o.schema}),c=a.document.metadata,m=k(),u=C(t.author,o.author_default),p=await sr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:s.type_to_folder,probeExisting:!1}),f=$(o.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new d("Copy --title must not be empty",l.USAGE);let g={...c,id:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete g.closed_at,delete g.completed_at,delete g.close_reason,delete g.test_runs;let y=Et(O()),h=Xe({metadata:g,body:a.document.body},{schema:o.schema,extensionFieldNames:y}),v=await Nn({title:h.metadata.title,description:h.metadata.description,body:h.body,excludeIds:[i.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),b=yC(h.metadata,h.body),S=it(r,h.metadata.type,p,o.item_format,s.type_to_folder),T=Ye(r,p),I=await we(r,p,o.locks.ttl_seconds,u,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),D={metadata:{},body:""},N,X;try{let K=await xt(r,u,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await Nn({title:h.metadata.title,description:h.metadata.description,body:h.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let W=await q(r,p,o.id_prefix,o.item_format,s.type_to_folder);if(W)throw new d(`Cannot copy to ${p}: an item with that id already exists at ${W.itemPath}. Retry the copy to allocate a new id.`,l.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${W.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await te(S,qe(h,{format:o.item_format,schema:o.schema,extensionFieldNames:y}));try{let Q=Ie({nowIso:m,author:u,op:"create",before:D,after:h,message:vC(i.id,t.message)});await It(T,Q)}catch(Q){throw await _n(S),Q}X=await Pt({pmRoot:r,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:S,document:h})}finally{await K()}N=[...await V({path:S,scope:"project",op:"create",item_id:h.metadata.id,item_type:h.metadata.type,before:D,after:h,changed_fields:b}),...await V({path:T,scope:"project",op:"create:history",item_id:h.metadata.id,item_type:h.metadata.type,before:D,after:h,changed_fields:b})],yn({id:h.metadata.id,op:"create",item_type:h.metadata.type,status:h.metadata.status,current:Yt(h.metadata,b),changed_fields:b})}finally{await I()}return{source_id:i.id,item:structuredClone(h.metadata),changed_fields:b,warnings:[...Es(v),...X,...N],...v===void 0?{}:{similarity_advisory:v}}}import ci from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eef2ba25-bbdb-5c06-9f90-1cf485e98497")}catch{}})();async function Qc(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await A(r),s=C(t.author,o.author_default),i=await vp({pmRoot:r,settings:o,id:e,author:s,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?ci.relative(r,i.targetPath).split(ci.sep).join("/"):void 0;return{item:i.item,changed_fields:i.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:i.item.status,...a?{target_path:a}:{},history_retained:ci.relative(r,Ye(r,i.item.id)).split(ci.sep).join("/"),tombstone_retention:"retain_append_only",warnings:i.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8023e71b-f733-572c-bdc0-e9b8f481232c")}catch{}})();async function wC(e){await R(e)}async function Zc(e,t,n){let r=E(process.cwd(),n.path);if(await wC(r),t.clear===!0){if(e!==void 0)throw new d("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",l.USAGE);let p=await A(r),f=kn(C(void 0,p.author_default));return await qu(r),await ks({pmRoot:r,settings:p,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await Ko(r);if(p===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let f=await bC(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let s=await A(r),i=x(s,O()),a=await q(r,e,s.id_prefix,s.item_format,i.type_to_folder);if(!a)throw await dt(r,e,s.id_prefix,i.type_to_folder);let c=Ue(a.id,s.id_prefix),m=await se(a,{schema:s.schema}),u=Dh(m.document.metadata.title);return await ju(r,c),await ks({pmRoot:r,settings:s,principal:kn(C(void 0,s.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function bC(e,t){let n=await A(e),r=x(n,O()),o=await q(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let s=await se(o,{schema:n.schema});return Dh(s.document.metadata.title)}function Dh(e){return e.trim().length>0?e:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0f97e1d-37de-5512-806c-833ec249ff52")}catch{}})();var Uh=new Set(["item_format"]),Gh=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),kC=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),SC=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),EC={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function AC(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(Uh.has(t)||Gh.has(t)||kC.has(t)||t==="context")return t}function TC(e){let t=e.trim().toLowerCase();return EC[t]??e}function jh(e,t){let n=AC(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:Uh.has(n)?{routable:!0,flag:"format",value:t}:Gh.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:SC.has(n)?TC(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="326e677a-c427-55e0-aad9-5204ea59661b")}catch{}})();var CC=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,el=128,RC=1e4;function qh(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>el)throw new Error(`A legacy author must contain 1-${el} characters.`);return t}function IC(e){let t=e?.trim().toLowerCase();if(!t||!CC.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function OC(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function xC(e,t){let n=new Set;for(let r of(e??[]).slice(0,RC)){let o=r.trim().slice(0,el);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function PC(e,t){let n=qh(t.legacy_author),r=IC(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function LC(e,t){if(t.operation==="add")return PC(e,t);if(t.operation==="remove"){let r=qh(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function tl(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function Kh(e,t){let n=e?.version??1,r={...e?.aliases},o=LC(r,t),s={version:o?n+1:n,aliases:OC(r)};return{vocabulary:s,preview:{operation:t.operation,changed:o,version_before:n,version_after:s.version,alias_count:Object.keys(s.aliases).length,residual_author_count:xC(t.observed_authors,s.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6fdd2eb-5447-5b10-af5b-33765e341bd2")}catch{}})();var zh=["project","global"],gt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},NC=Object.keys(gt).map(e=>gt[e][0]),FC=Object.fromEntries(Object.keys(gt).flatMap(e=>gt[e].map(t=>[t,e]))),MC={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},$C=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],DC=new Set(["metadata_required_fields",...$C]),UC=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),GC=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),jC=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),qC=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),KC=new Set(["governance_preset","governance_create_default_type"]),Yh=e=>DC.has(e),zC=e=>jC.has(e),BC=e=>qC.has(e),HC=e=>KC.has(e);function nl(e){return e==="definition_of_done"||Yh(e)}function VC(e){if(zh.includes(e))return e;throw new d(`Invalid config scope "${e}". Allowed: ${zh.join(", ")}`,l.USAGE)}function WC(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw xe({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function YC(e){let t=FC[e];if(t)return t;let n=aa.map(r=>r.key).join(", ");throw new d(`Invalid config key "${e}". Supported: ${NC.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,l.USAGE)}function JC(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new d("Config set definition-of-done cannot combine --clear-criteria with --criterion values",l.USAGE);return[]}if(n.length===0)throw new d("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",l.USAGE);return n}function XC(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new d("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",l.USAGE):new d("Config set item-format requires --format toon",l.USAGE)}function Jh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new d("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",l.USAGE)}function QC(e){return ol(e,"test-result-tracking")}function ol(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new d(`Config set ${t} requires --policy with one of: enabled, disabled`,l.USAGE)}function Xh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new d("Config set telemetry-tracking requires --policy with one of: enabled, disabled",l.USAGE)}function sl(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new d("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",l.USAGE)}function Qh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new d("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",l.USAGE)}function Zh(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new d("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",l.USAGE)}function eg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new d("Config set governance-create-mode-default requires --policy with one of: progressive, strict",l.USAGE)}function tg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new d("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",l.USAGE)}function ng(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new d("Config set governance-workflow-enforcement requires one of: off, warn, strict",l.USAGE)}function rg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new d("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",l.USAGE)}function og(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new d("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",l.USAGE)}var ZC={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function Bh(e,t){let n=ZC[e];if(n)return ol(t,n);switch(e){case"history_missing_stream_policy":return Jh(t);case"sprint_release_format_policy":return Ma(t);case"parent_reference_policy":case"governance_parent_reference_policy":return ss(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return sl(t);case"governance_preset":return Qh(t);case"governance_ownership_enforcement":return Zh(t);case"governance_create_mode_default":return eg(t);case"governance_close_validation_default":return tg(t);case"governance_require_close_reason":return og(t);case"governance_workflow_enforcement":return ng(t);case"governance_force_required_for_stale_lock":return rg(t);case"telemetry_tracking":return Xh(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var Hh={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"},eR=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function tR(e,t){let n=[...new Set((e??[]).map(s=>s.trim()).filter(s=>s.length>0))];if(t){if(n.length>0)throw new d("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",l.USAGE);return[]}if(n.length===0)throw new d("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",l.USAGE);let r=n.map(s=>s.toLowerCase().replaceAll("-","_")),o=r.filter(s=>Hh[s]===void 0);if(o.length>0)throw new d(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${eR.join(", ")}`,l.USAGE);return[...new Set(r.map(s=>Hh[s]))].sort((s,i)=>s.localeCompare(i))}function nR(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,s)=>o.localeCompare(s));if(n){if(r.length>0)throw new d(`Config set ${gt[e][0]} cannot combine --clear-criteria with --criterion values`,l.USAGE);return[]}if(r.length===0)throw new d(`Config set ${gt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,l.USAGE);return r}function rR(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function oR(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new d(`Config action "${e}" does not accept <key>`,l.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new d(`Config action "${e}" requires <key>`,l.USAGE);return YC(t)}function sg(e){if(!e)throw new d("Config action requires <key>",l.USAGE)}var sR={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>tl(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function il(e,t){return sR[t](e)}function Te(e,t){return t.length===0?e:{...e,warnings:t}}async function iR(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):st(n),o=ue(r);return e==="project"&&await R(r),{pmRoot:r,settingsPath:o}}function aR(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new d(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,l.USAGE)}function Vh(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new d(`Context ${t} must be a positive integer`,l.USAGE)}async function cR(e,t,n,r,o){let s=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!Zi.includes(c))throw new d(`Context --default-depth must be one of ${Zi.join("|")}`,l.USAGE);i.default_depth!==c&&(i.default_depth=c,s=!0)}if(t.activityLimit!==void 0){let c=Vh(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,s=!0)}if(t.staleThresholdDays!==void 0){let c=Vh(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,s=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of a){let u=aR(m);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,s=!0)}}return s&&await Oe(n.pmRoot,e,"config:set:context"),Te({scope:r,key:"context",context_settings:{default_depth:i.default_depth,activity_limit:i.activity_limit,stale_threshold_days:i.stale_threshold_days,sections:{...i.sections}},settings_path:n.settingsPath,changed:s},o)}function lR(e,t,n){if(n.value!==void 0&&n.value!==t)throw new d(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,l.USAGE);return{...n,value:t}}function dR(e,t,n,r,o,s){if(o===void 0)return s;if(e!=="set")throw new d(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,l.USAGE);if(typeof t!="string"||t.trim().length===0)throw new d('Config action "set" requires <key> before a positional <value>.',l.USAGE);if(r)return lR(t,o,s);sg(n);let i=jh(n,o);if(!i.routable)throw new d(i.reason,l.USAGE);if(i.flag==="criterion"){if(s.criterion!==void 0&&s.criterion.length>0)throw new d(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,l.USAGE);return{...s,criterion:i.values}}if(i.flag==="format")return{...s,format:i.value};if(s.policy!==void 0&&Bh(n,s.policy)!==Bh(n,i.value))throw new d(`Config set ${t} received both positional value "${o}" and --policy "${s.policy}". Pass only one.`,l.USAGE);return{...s,policy:i.value}}function mR(e){let t=Object.keys(gt).map(r=>({key:r,aliases:gt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":nl(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:nl(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:MC[r],value:il(e.settings,r)})),n=aa.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:ca(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Te({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function uR(e){let t=Object.fromEntries(Object.keys(gt).map(n=>[n,il(e.settings,n)]));return Te({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function pR(e,t){let n=il(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Te({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Te({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Te({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Te({...r,criteria:n},e.warnings):Te({...r,policy:n},e.warnings)}async function fR(e,t,n,r){if(t==="get"){let a=ca(e.settings,n);return Te({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new d(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,l.USAGE);let s=eu(n,o);if(!s.ok)throw new d(s.error.message,l.USAGE);let i=Fo(e.settings,n,s.parsed.value);return i&&await Oe(e.target.pmRoot,e.settings,`config:set:${n.path}`),Te({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:s.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function Y(e,t,n){t&&await Oe(e.target.pmRoot,e.settings,n)}function Wh(e,t,n){return e!==n||t!==n}function de(e,t,n,r){return Te({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function rl(e,t,n,r){return Te({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function _R(e,t){let n=XC(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let s=x(e.settings,O()),i=await Pp(e.target.pmRoot,n,"config:set:item_format:migrate",s.type_to_folder,e.settings.schema);o={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await Oe(e.target.pmRoot,e.settings,"config:set:item_format")}return Te({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function hR(e,t,n){if(t==="history_missing_stream_policy"){let s=Jh(n.policy),i=e.settings.history.missing_stream!==s;return e.settings.history.missing_stream=s,await Y(e,i,"config:set:history_missing_stream_policy"),de(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let s=Ma(n.policy),i=e.settings.validation.sprint_release_format!==s;return e.settings.validation.sprint_release_format=s,await Y(e,i,"config:set:sprint_release_format_policy"),de(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let s=ss(n.policy),i=e.settings.validation.parent_reference!==s||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==s;return e.settings.validation.parent_reference=s,e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,await Y(e,i,"config:set:parent_reference_policy"),de(e,t,e.settings.validation.parent_reference,i)}let r=sl(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Y(e,o,"config:set:metadata_validation_profile"),de(e,t,e.settings.validation.metadata_profile,o)}async function gR(e,t,n){if(t==="metadata_required_fields"){let a=tR(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((m,u)=>m!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await Y(e,c,"config:set:metadata_required_fields"),rl(e,t,[...e.settings.validation.metadata_required_fields],c)}let o={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],s=nR(t,n.criterion,n.clearCriteria),i=s.length!==o.length||s.some((a,c)=>a!==o[c]);return o.splice(0,o.length,...s),await Y(e,i,`config:set:${t}`),rl(e,t,[...o],i)}async function yR(e,t,n){if(t==="governance_preset"){let c=Qh(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Y(e,m,"config:set:governance_preset"),de(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Y(e,c,"config:set:governance_create_default_type"),de(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new d('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',l.USAGE);let s=x(e.settings,O()),i=ye(o,s);if(!i)throw new d(Ct(o,s.types,Rt(e.target.pmRoot,e.settings.schema)),l.USAGE);let a=e.settings.governance.create_default_type!==i;return e.settings.governance.create_default_type=i,await Y(e,a,"config:set:governance_create_default_type"),de(e,t,e.settings.governance.create_default_type,a)}async function vR(e,t,n){if(t==="governance_ownership_enforcement"){let s=Zh(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==s;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=s,await Y(e,i,"config:set:governance_ownership_enforcement"),de(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let s=eg(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==s;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=s,await Y(e,i,"config:set:governance_create_mode_default"),de(e,t,e.settings.governance.create_mode_default,i)}let r=tg(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Y(e,o,"config:set:governance_close_validation_default"),de(e,t,e.settings.governance.close_validation_default,o)}async function wR(e,t,n){if(t==="governance_parent_reference_policy"){let s=ss(n.policy),i=e.settings.governance.preset!=="custom"||Wh(e.settings.governance.parent_reference,e.settings.validation.parent_reference,s);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,e.settings.validation.parent_reference=s,await Y(e,i,"config:set:governance_parent_reference_policy"),de(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let s=sl(n.policy),i=e.settings.governance.preset!=="custom"||Wh(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,s);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=s,e.settings.validation.metadata_profile=s,await Y(e,i,"config:set:governance_metadata_validation_profile"),de(e,t,e.settings.governance.metadata_profile,i)}let r=ng(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Y(e,o,"config:set:governance_workflow_enforcement"),de(e,t,e.settings.governance.workflow_enforcement,o)}async function bR(e,t,n){if(t==="governance_require_close_reason"){let a=og(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await Y(e,c,"config:set:governance_require_close_reason"),de(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let o=rg(n.policy)==="enabled",s=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==o;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=o,await Y(e,s,"config:set:governance_force_required_for_stale_lock"),de(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",s)}async function kR(e,t,n){if(t==="test_result_tracking"){let a=QC(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await Y(e,c,"config:set:test_result_tracking"),de(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}if(t==="untrusted_linked_test_execution"){let a=ol(n.policy,"untrusted-linked-test-execution")==="enabled",c=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await Y(e,c,"config:set:untrusted_linked_test_execution"),de(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",c)}let o=Xh(n.policy)==="enabled",s=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await Y(e,s,"config:set:telemetry_tracking"),de(e,t,e.settings.telemetry.enabled?"enabled":"disabled",s)}async function SR(e,t,n){let r=JC(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((s,i)=>s!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await Y(e,o,"config:set:definition_of_done"),rl(e,t,[...e.settings.workflow.definition_of_done],o)}function ER(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new d("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",l.USAGE)}function AR(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new d('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',l.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new d("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",l.USAGE);return{legacy_author:t}}if(t!==void 0)throw new d("Config set agent-identity-vocabulary --policy clear does not accept --value",l.USAGE);return{}}async function TR(e,t){let{operation:n,dryRun:r}=ER(t.policy),o=AR(n,t.value),s;try{s=Kh(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(i){throw new d(i.message,l.USAGE)}return s.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:s.vocabulary},await Y(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${s.preview.version_after}`)),Te({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:tl(r?e.settings.agent_identity?.identity_vocabulary:s.vocabulary),vocabulary_mutation:s.preview,settings_path:e.target.settingsPath,changed:s.preview.changed&&!r},e.warnings)}async function CR(e,t,n){if(n.clearCriteria===!0&&!nl(t))throw new d("--clear-criteria is only supported with config set criteria-list keys",l.USAGE);return t==="item_format"?_R(e,n):t==="context"?cR(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?TR(e,n):t==="definition_of_done"?SR(e,t,n):Yh(t)?gR(e,t,n):UC.has(t)?kR(e,t,n):GC.has(t)?bR(e,t,n):zC(t)?vR(e,t,n):BC(t)?wR(e,t,n):HC(t)?yR(e,t,n):hR(e,t,n)}async function ig(e,t,n,r,o,s){let i=VC(e),a=WC(t),c=a==="get"||a==="set"?No(n):void 0,m=c?void 0:oR(a,n),u=dR(a,n,m,c,s,r),p=await iR(i,o),{settings:f,metadata:_,warnings:g}=await up(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:rR(g)};return c?fR(y,a,c,u):a==="list"?mR(y):a==="export"?uR(y):(sg(m),a==="get"?pR(y,m):CR(y,m,u))}import oI from"node:fs/promises";import J from"node:path";import sI from"node:readline/promises";import{stdin as iI,stdout as Fe}from"node:process";import cl from"node:fs/promises";import me from"node:path";import RR from"node:readline/promises";import{stdin as IR,stdout as li}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5ae3e66-4a45-5c62-9144-46f8f5bff7cf")}catch{}})();var cg=["ask","add","skip","status"],OR=["AGENTS.md","CLAUDE.md"],xR=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],PR=8,ll=1,LR="<!-- pm-cli:agent-guidance:start:",NR=`<!-- pm-cli:agent-guidance:start:v${ll} -->`,al="<!-- pm-cli:agent-guidance:end -->",Rr="Add workflow guidance later: pm init --agent-guidance add";var FR=()=>RR.createInterface({input:IR,output:li});function Tr(e,t){let n=me.relative(e,t);return n.length===0?me.basename(t):n.split(me.sep).join("/")}function ag(e){return e.endsWith(`
|
|
4
|
+
`,{changedFields:["body"]}}});return{item:m.item,appended:c,changed_fields:m.changedFields}}import{readFile as tk}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a5fc27e-3f5a-59e0-998e-be5da72913dd")}catch{}})();function $i(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Se(e,t)}function k_(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new d(`Structured context events are append-only and cannot be ${t}.`,l.USAGE,{code:"structured_event_immutable"})}function yc(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function tn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Un(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let i=de(n,"--add");return Object.keys(i).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:i.text?.trim()||n}catch{return n}}function vc(e){return typeof e=="object"&&e!==null&&"code"in e}function Cr(e,t){if(!ht(e))throw new d(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,l.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function nk(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new d(`Specify ${t} text using only one input source: --add, --stdin, or --file`,l.USAGE);let r=$t(),o=ht(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",o)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return Cr(e,"--stdin"),{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let i=e.file.trim();if(!i)throw new d("--file path cannot be empty",l.USAGE);if(i==="-")return Cr(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await tk(i,"utf8"),emptyFlag:"--file"}}catch(s){if(vc(s)&&Vt(s))throw new d(`--file path not found: ${i}. Use --file - to read stdin.`,l.USAGE);let a=s instanceof Error?s.message:String(s);throw new d(`Failed to read --file path "${i}": ${a}. Use --file - to read stdin.`,l.USAGE)}}async function Di(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new d("Specify only one of --edit or --delete",l.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new d("--delete cannot be combined with replacement text",l.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new d("--delete must be a positive integer",l.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new d("--edit must be a positive integer",l.USAGE);let n=await nk(e,t);if(e.edit!==void 0){if(!n)throw new d("--edit requires replacement text from --add, --stdin, or --file",l.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function Tr(e,t){throw e instanceof d&&e.exitCode===l.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new d(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function E_(e){return e==="comments"?"--stdin":"--add -"}function rk(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let o=E_(t.collectionKey),i=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new d(`--add value "${r}" looks like an option, not annotation text. Use ${o} to read stdin, or use text=${r} for literal dash-leading text.`,l.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${i} ${o}`,`${i} --add text=${r}`]})}function ok(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new d(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,l.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new d(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,l.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_(e.collectionKey)}`]})}function ik(e,t,n,r,o,i){let s=tn(e.metadata,t),a=o?s.findIndex(c=>c.author===n&&c.text===r):-1;return a>=0?{changedFields:[],entryIndex:a+1}:(s.push(i({created_at:k(),author:n,text:r})),e.metadata[t]=s,{changedFields:[t],entryIndex:s.length})}async function Gn(e,t,n,r){ok(r,t);let o=E(process.cwd(),n.path);await R(o);let i=await A(o),s=x(i,O()),a=_r(t.limit);if(r.input.mode==="list"){let g=await q(o,e,i.id_prefix,i.item_format,s.type_to_folder);if(!g)throw new d(`Item ${e} not found`,l.NOT_FOUND);let y=await oe(g,{schema:i.schema}),h=tn(y.document.metadata,r.collectionKey);return Fi(g.id,r.collectionKey,h,a,t.includeMeta===!0)}let c=C(t.author,i.author_default);if(r.input.mode==="delete"){let g=r.deleteOp??r.op,y;try{y=await ie({pmRoot:o,settings:i,id:e,op:g,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(v){let b=tn(v.metadata,r.collectionKey),S=S_(r.input.index,b.length,r.collectionKey);return k_(b[S],"deleted"),b.splice(S,1),v.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(v){Tr(v,r.conflictGuidance)}let h=tn(y.item,r.collectionKey);return Fi(y.item.id,r.collectionKey,h,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";rk(m,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new d(`${r.input.emptyFlag??"--add"} text cannot be empty`,l.USAGE);if(r.input.mode==="edit"){let g=r.editOp??r.op,y;try{y=await ie({pmRoot:o,settings:i,id:e,op:g,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(v){let b=tn(v.metadata,r.collectionKey),S=S_(r.input.index,b.length,r.collectionKey),T=b[S];return k_(T,"edited"),b[S]={...T,text:u,edited_at:k()},v.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(v){Tr(v,r.conflictGuidance)}let h=tn(y.item,r.collectionKey);return Fi(y.item.id,r.collectionKey,h,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:h[r.input.index-1]},t.fullHistory===!0)}let p,f=0;try{p=await ie({pmRoot:o,settings:i,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(g){let y=ik(g,r.collectionKey,c,u,t.ifAbsent===!0,r.createEntry);return f=y.entryIndex,{changedFields:y.changedFields}}})}catch(g){Tr(g,r.conflictGuidance)}let _=tn(p.item,r.collectionKey);return Fi(p.item.id,r.collectionKey,_,a,t.includeMeta===!0,{action:"add",entryIndex:f,entry:_[f-1],changedCount:t.ifAbsent===!0?Math.min(p.changedFields.length,1):void 0},t.fullHistory===!0)}function S_(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,i=t===1?`1 ${r}`:`${t} ${n}`;throw new d(`${o} index ${e??"(missing)"} out of range (item has ${i})`,l.USAGE)}return e-1}function sk(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 Fi(e,t,n,r,o,i,s=!1){let a=i===void 0||s?yc(n,i!==void 0&&s?void 0:r):i.entry===void 0?[]:[i.entry],c=i!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...i?.changedCount===void 0?{}:{changed:i.changedCount===1},...[o,i!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...sk(t,i,c)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f366dd76-73b4-55c4-8c63-2913d0a0c380")}catch{}})();async function A_(e,t,n){return[...await Promise.resolve().then(()=>ip(Xe(e,t),t)).catch(()=>[])].reverse().find(i=>i.patch.some(s=>s.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9c1089b-b070-5a89-af49-f6be643c49e5")}catch{}})();var T_="no_available_next_item";function C_(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function Rr(e,t,n,r={}){let o=E(process.cwd(),n.path);await R(o);let i=await A(o),s=F(i.schema),a=C(r.author,i.author_default),c=Tn(a),m=null,u=!1,p=[],f=await ie({pmRoot:o,settings:i,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",h=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,ou(_.metadata.status,s)&&!t)throw new d(`Cannot claim terminal item ${_.metadata.id} without --force`,l.CONFLICT);if(m!==null&&h!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let T=await A_(o,_.metadata.id,y);throw new d(`Item ${_.metadata.id} is already ${T}. Use --force to take over, or --if-available to skip without failing.`,l.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}p.push(`claim_takeover:${m}->${a}`)}let b={assignee:a,claim_principal:c},S=["assignee","claim_principal"].filter(T=>_.metadata[T]!==b[T]);return Object.assign(_.metadata,b),{changedFields:S,warnings:p}}});return u||await ac({pmRoot:o,settings:i,principal:c,itemId:f.item.id}),{item:f.item,changed_fields:f.changedFields,claimed_by:u&&m!==null?m:a,previous_assignee:m,forced:t,...u?{skipped:!0}:{},...p.length>0?{warnings:p}:{}}}async function R_(e,t,n={},r={}){let o=ak(n.maxAttempts),i=await A(E(process.cwd(),t.path)),s={...n,author:C(n.author,i.author_default)},a=await Sr({...r,callerAuthor:s.author,limit:String(o)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return ck(c.slice(0,o),e,t,s)}function ak(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new d("--max-attempts must be an integer from 1 to 100",l.USAGE);return t}async function ck(e,t,n,r={},o=Rr){let i=0;for(let a of e){i+=1;try{let c=await o(a.id,t,n,r),m={...c,recommendation:a,attempts:i,available:!0};if(!c.skipped)return m}catch(c){if(!C_(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:C(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:i,warnings:[T_]};let s=i===0;throw new d(s?"No actionable items matched the selection filters":"No actionable item remained available to claim",s?l.NOT_FOUND:l.CONFLICT,{code:T_,why:s?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[s?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function Ir(e,t,n,r={}){let o=E(process.cwd(),n.path);await R(o);let i=await A(o),s=C(r.author,i.author_default),a=Tn(s),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await ie({pmRoot:o,settings:i,id:e,op:"release",author:s,message:r.message,force:t,bypassAssigneeConflict:c,mutate(_){return m=_.metadata.assignee??null,!m&&!_.metadata.claim_principal?{changedFields:[]}:(delete _.metadata.assignee,delete _.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(_){Tr(_,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await cc({pmRoot:o,principal:a,itemId:u.item.id});let p=F(i.schema),f=Pa(u.item.status,p)===Pa(p.in_progress_status,p);return{item:u.item,released_by:s,previous_assignee:m,forced:t,...f?{warnings:["released_unclaimed_in_progress"],suggestions:[`${u.item.id} remains ${u.item.status} and unclaimed. If work is paused, run pm release ${u.item.id} --pause to move it to ${p.open_status}.`]}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e63a8049-309b-57f2-ba48-cd0a550c11ab")}catch{}})();var lk=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function I_(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function wc(e,t){return bc(e,t,{operation:"close"})}function bc(e,t,n){let r=I_(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new d("Close reason text is required because governance.require_close_reason is enabled",l.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function kc(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],i=o.filter(m=>m.kind==="blocked_by"),s=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),s&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&i.length>0){let m=o.filter(u=>u.kind!=="blocked_by");m.length>0?e.dependencies=m:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...i.map(m=>m.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[t.orderingEdges==="preserve"?`closed_preserved_predecessors:${e.id}:${c.join(",")}`:`closed_removed_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="49e375b7-49a8-5b6f-89c8-be70d334b78f")}catch{}})();var dk=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function mk(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 d(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,l.USAGE)}function O_(e){let t=[];for(let n of dk){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function x_(e,t,n={}){let r=O_(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},i=r.map(a=>`--${a.key.replaceAll("_","-")}`),s=["--pm-path",t,"update",e.id,...r.flatMap((a,c)=>[i[c],o[a.key]?.trim()||"<value>"])];return{missing:i,suggested_retry:cr(s),suggested_retry_args:s}}async function uk(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let i=o.trim();if(i===n)return!0;if(r.has(i))return!1;r.add(i),o=(await e(i))?.duplicate_of}return!1}function pk(e){return typeof e!="string"||e.trim().length===0}async function fk(e,t,n,r){let o=n?.trim();if(!o)return;if(o===r)throw new d("An item cannot be closed as a duplicate of itself.",l.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let i=x(t,O()),s=new Map,a=async m=>{if(s.has(m))return s.get(m)??null;let u=await q(e,m,t.id_prefix,t.item_format,i.type_to_folder);if(!u)return s.set(m,null),null;let{document:p}=await oe(u,{schema:t.schema});return s.set(m,p.metadata),p.metadata},c=await a(o);if(!c)throw new d(`Duplicate target "${o}" was not found. Create or locate the canonical item first.`,l.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await uk(a,c.duplicate_of,r))throw new d(`Circular duplicate reference detected. Target "${o}" points back to "${r}".`,l.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 d(`Duplicate target "${o}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,l.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 _k(e,t,n){return e.filter(r=>r.parent===t&&!te(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function hk(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),o=i_(e),i=t.trim().toLowerCase(),s=n.blocked_statuses;return e.filter(a=>s.has(a.status)).map(a=>({item:a,blockerIds:o.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(i)).filter(({blockerIds:a})=>a.every(c=>{if(c===i)return!0;let m=r.get(c);return m!==void 0&&te(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function gk(e,t,n,r,o,i){let s=hk(n,r,i),a=[];for(let c of s)try{let m=await ie({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(g=>{let y=g.id.trim().toLowerCase();return g.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=i.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let u=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${u}`)}return a}function yk(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:i}of r){if(typeof o!="string")continue;let s=o.trim();s.length!==0&&(e[i]=s,n.push(i))}return n}function vk(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:i}of r)pk(e[o])&&(e[o]=i,n.push(o));return n}function wk(e,t,n,r){let o=[];if(t!=="off"){let i=O_(e);if(i.length>0){let s=i.map(a=>a.label);if(t==="strict"){let a=i.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(m=>[m,"<value>"])];throw new d(`Cannot close item ${e.id}: missing ${s.join(", ")}. Populate fields or use --validate-close warn.`,l.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:cr(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}o.push(`close_validation_missing_fields:${e.id}:${s.join(",")}`)}if(n.length>0){if(t==="strict")throw new d(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,l.USAGE);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function bk(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function kk(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function Sk(e,t){if(te(e.status,t.statusRegistry)&&!t.force)throw new d(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,l.CONFLICT,{recovery:x_(e,t.pmRoot,t.options)});let n=yk(e,t.options),r=vk(e,t.duplicateOf),o=wk(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let i=t.options.completedAt!==void 0||e.completed_at===void 0;i&&(e.completed_at=t.completedAt);let s=["status","closed_at",...i?["completed_at"]:[],...bk(e,t.closeReason),...n];if(jp(e)&&(e.plan_mode="completed",s.push("plan_mode")),t.duplicateOf!==void 0){s.push("duplicate_of");for(let c of r)s.includes(c)||s.push(c)}s.push(...kk(e));let a=kc(e,t.lifecyclePolicy);return s.push(...a.changedFields),o.push(...a.warnings),{changedFields:s,...o.length>0?{warnings:o}:{}}}async function P_(e,t,n,r){let o=E(process.cwd(),r.path);await R(o);let i=await A(o),s=F(i.schema),a=C(n.author,i.author_default),c=x(i,O()).type_to_folder,m=await q(o,e,i.id_prefix,i.item_format,c);if(!m)throw await _t(o,e,i.id_prefix,c);let u=await fk(o,i,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??i.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=wc({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=mk(n.validateClose)??i.governance.close_validation_default,g=await _e(o,i.item_format,c,void 0,i.schema),y=_k(g,m.id,s),h=k(),v=n.completedAt===void 0?h:re(n.completedAt,new Date(h),"completed-at"),b=await ie({pmRoot:o,settings:i,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(T){return Sk(T.metadata,{pmRoot:o,statusRegistry:s,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:h,completedAt:v,lifecyclePolicy:p})}}),S=_==="warn"?x_(b.item,o):void 0;return{item:b.item,changed_fields:b.changedFields,...S?{recovery:S}:{},warnings:[...b.warnings,...await gk(o,i,g,m.id,a,s)]}}function yt(e,t,n,r){return P_(e,t,n,r)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c45ead8e-c9ed-5b59-84e5-b8e077e84010")}catch{}})();function Ui(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Gi(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function ji(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(oo.includes(t))return t;let n=he(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new d("Confidence must be an integer 0..100 or one of low|med|medium|high",l.USAGE);return n}function qi(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new d("Regression must be one of true|false|1|0",l.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="add1928e-08d1-5ead-9a4e-0f1a9b6580fc")}catch{}})();var Ek=new Set(["none","null"]);function Ki(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function He(e){return e===void 0?!1:Ek.has(e.trim().toLowerCase())}function zi(e,t,n){if(!He(e))return;let r=n?` ${n}`:"";throw new d(`${t} no longer accepts "none" or "null".${r}`.trim(),l.USAGE)}function Ae(e,t,n){if(!e||e.length===0||!e.some(i=>He(i)))return;let o=n?` ${n}`:"";throw new d(`${t} no longer accepts "none" or "null".${o}`.trim(),l.USAGE)}function Bi(e,t){for(let n of t){let r=e[n.optionKey];if(!Array.isArray(r)||r.length===0)continue;if(!r.every(a=>typeof a=="string"))throw new d(`${n.valueFlag} entries must be strings.`,l.USAGE);let o=r;if(!o.some(a=>He(a)))continue;if(o.filter(a=>!He(a)).length>0)throw new d(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,l.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="49f970c3-e408-52d5-bb4d-8cea0c7f8ef4")}catch{}})();function N_(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 d(`${t} must be one of true|false|1|0|yes|no`,l.USAGE)}function Sc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Te(e,t,n,r=n){if(!t.includes(e))throw new d(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,l.USAGE,{field:r,required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var M_=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Ak(e,t){return t==="defined"?e!==void 0:!!e}function L_(e,t,n){if(!Ak(e,n))return;let r=he(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new d(`--event ${t} must be an integer >= 1`,l.USAGE);return r}function Tk(e,t,n){let r=e?re(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new d("--event recur_until must be at or after start",l.USAGE);return r}function Ck(e){return Array.from(new Set(Sc(e).map(t=>Te(t.toLowerCase(),Td,"event weekday")))).sort((t,n)=>ta(t)-ta(n))}function Rk(e){return Array.from(new Set(Sc(e).map(t=>{let n=he(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new d("--event recur_by_month_day values must be integers 1..31",l.USAGE);return n}))).sort((t,n)=>t-n)}function Ik(e,t){return Array.from(new Set(Sc(e).map(n=>re(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function F_(e,t,n,r){let o=e.recur_freq?.trim(),i=e.recur_interval?.trim(),s=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![o,i,s,a,c,m,u].some(S=>S!==void 0))return;if(!o)throw new d("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",l.USAGE);let f=Te(o.toLowerCase(),Ad,"event recurrence frequency"),_=L_(i,"recur_interval",r),g=L_(s,"recur_count",r),y=Tk(a,t,n),h=Ck(c),v=Rk(m),b=Ik(u,n);return{freq:f,interval:_,count:g,until:y,by_weekday:h.length>0?h:void 0,by_month_day:v.length>0?v:void 0,exdates:b.length>0?b:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ae7fdf9b-e2d5-511e-90db-cf0bc121628d")}catch{}})();var $_="--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.",Ok="--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).",xk=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,Pk=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,U_=1e3,Ec=60*U_,Lk=60*Ec;function D_(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new d(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,l.USAGE);return n.toISOString()}function Nk(e,t){let n=new Date(e),r=t.trim(),o=xk.exec(r);if(o){let a=o[1]==="-"?-1:1,c=Number.parseInt(o[2],10)*a;return D_(n.getTime()+c*Ec,r)}let i=Pk.exec(r);if(i){let[,a,c,m,u]=i;if(c||m||u){let f=a==="-"?-1:1,_=Number.parseInt(c??"0",10),g=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),h=_*Lk+g*Ec+y*U_;return D_(n.getTime()+f*h,r)}}let s=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return re(s,n,"event.duration")}function G_(e,t,n,r){if(t&&n)throw new d(Ok,l.USAGE);if(n){let i=Nk(e,n);if(i<e)throw new d($_,l.USAGE);return i===e?void 0:i}if(!t)return;let o=re(t,r,"event.end");if(o<e)throw new d($_,l.USAGE);if(o!==e)return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dfce9924-8453-5ded-a5df-47477caa9fe7")}catch{}})();var Mk=["at","date","text","title"],Fk=["start","date","end","duration","title","description","location","timezone","all_day",...M_],$k=["key","value"];function j_(e,t){return t==="trimmed"?e?.trim():e}function Dk(e,t){return t==="defined"?e!==void 0:!!e}function Hi(e,t,n){return e.map(r=>{let o=de(r,"--reminder");Be(o,"--reminder",Mk);let i=j_(o.at??o.date,n.valueMode),s=j_(o.text??o.title,n.valueMode);if(!i||!s)throw new d("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",l.USAGE);let a=s.trim();if(!a)throw new d("--reminder text must not be empty",l.USAGE);return{at:re(i,t,"reminder.at"),text:a}})}function Vi(e,t,n){return e.map(r=>{let o=de(r,"--event");Be(o,"--event",Fk);let i=(o.start??o.date)?.trim();if(!i)throw new d("--event requires start=<iso|relative> or date=<iso|relative>",l.USAGE);let s=re(i,t,"event.start"),a=o.end?.trim(),c=o.duration?.trim(),m=G_(s,a,c,t),u=o.title,p=o.description,f=o.location,_=o.timezone,g=u?.trim(),y=p?.trim(),h=f?.trim(),v=_?.trim(),b=[["title",u,g],["description",p,y],["location",f,h],["timezone",_,v]];for(let[D,M,Y]of b)if(M!==void 0&&!Y)throw new d(`--event ${D} must not be empty`,l.USAGE);let S=o.all_day?.trim(),T=F_(o,s,t,n.recurrenceEmptyNumericGuard),I=Dk(S,n.allDayEmptyGuard)?N_(S,"--event all_day"):void 0;return{start_at:s,end_at:m,title:g,description:y,location:h,all_day:I,timezone:v,recurrence:T}})}function Wi(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new d("--type-option values must not be empty",l.USAGE);let o,i;if(r.includes(",")||r.includes(`
|
|
5
|
+
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=de(r,"--type-option");Be(a,"--type-option",$k),o=a.key?.trim(),i=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),m=a;if(a<=0&&c>0&&(m=c),m<=0||m===r.length-1)throw new d("--type-option requires key=value or key=<name>,value=<value> entries",l.USAGE);o=r.slice(0,m).trim(),i=r.slice(m+1).trim()}if(!o||!i)throw new d("--type-option requires key and value",l.USAGE);t[o]=i}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e2e87672-508a-5aef-b728-42e40544cf3c")}catch{}})();function Or(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new d(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,l.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 xr(e,t,n=Dt()){for(let r of t??[])try{Ld(e,r.id,r.kind,n)}catch(o){throw new d(wn(o),l.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function q_(e,t){return(await oe(e,{schema:t})).document.metadata.created_at}async function Uk(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await q(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:q_(n,t.schema)}function Gk(e){let t=e.registry.require(e.dependency.kind);return new d(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,l.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 jk(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:i})=>i===null?[]:[[o,i]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await q_(n.get(o),e.context.schema)])));for(let o of e.holders){let i=await Uk(o,e.context);if(i!==void 0)for(let s of t){let a=r.get(s.id),c=Date.parse(i),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw Gk({holder:o,dependency:s,sourceCreatedAt:i,targetCreatedAt:a,registry:e.registry})}}}async function nn(e){let t=e.registry??Dt(),n=(e.dependencies??[]).filter(s=>!ku(s.source_kind)),r=[...new Set(n.map(s=>s.id))],o=await Promise.all(r.map(async s=>({target:s,located:await q(e.pmRoot,s,e.idPrefix,e.itemFormat,e.typeToFolder)}))),i=o.filter(({located:s})=>s===null).map(({target:s})=>s).sort((s,a)=>s<a?-1:1);if(i.length>0&&e.allowUnresolved!==!0)throw new d(`Dependency target${i.length===1?"":"s"} not found: ${i.join(", ")}`,l.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:i,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${i.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:i,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${i[0]}" --limit 10`}});return await jk({dependencies:n,missingTargets:i,resolutions:o,holders:e.holders??[],registry:t,context:e}),i.map(s=>`dependency_target_unresolved:${s}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4db3d1b3-68f3-5f74-b6f0-9847b3b00fc0")}catch{}})();var qk="hierarchy-integrity";async function Yi(e){let t=e.required?await ke(e.pmRoot,qk,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ca230957-d5a6-5f20-94b5-e1eeca8ca714")}catch{}})();var Kk=new Set(["event","meeting","reminder","milestone","decision","adr"]);function K_(e,t,n,r){if(Kk.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=qo("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm claim ${e} --start`,to_status:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="70971b2a-c025-50a8-918f-871fc8adfd2a")}catch{}})();var vt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],zk=new Set(vt);function z_(e){return ai(e,vt)}function Ji(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!zk.has(s)){r.push(o);continue}if(Object.hasOwn(n,s))throw new d(`${t} provides key "${o}" more than once after case normalization`,l.USAGE);n[s]=i}if(r.length>0)throw new d(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${vt.join(", ")}.`,l.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new d(`${t} command and cmd must match when both are provided`,l.USAGE);let{cmd:o,...i}=n;return{...i,command:i.command??o}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="800bdce7-d4d2-5702-9ceb-d83ac4a95fb0")}catch{}})();var sn=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",yr,lf,"FORCE_COLOR"]),Zi=/^[A-Za-z_][A-Za-z0-9_]*$/,on=["schema","tracker","auto"],B_=["source","isolated","snapshot"];function Pr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new d(`${t} env_set must include at least one KEY=VALUE assignment`,l.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,l.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1);if(!Zi.test(s))throw new d(`${t} env_set key "${s}" is invalid`,l.USAGE);if(sn.has(s.toUpperCase()))throw new d(`${t} env_set key "${s}" is reserved for sandbox safety`,l.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function Lr(e,t){if(!e)return;let n=Ln(e,{separators:/[;,\n]/});if(n.length===0)throw new d(`${t} env_clear must include at least one environment variable name`,l.USAGE);for(let r of n){if(!Zi.test(r))throw new d(`${t} env_clear key "${r}" is invalid`,l.USAGE);if(sn.has(r.toUpperCase()))throw new d(`${t} env_clear key "${r}" is reserved for sandbox safety`,l.USAGE)}return n}function es(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new d(`${t} ${n} must be one of true|false|1|0|yes|no`,l.USAGE)}function ts(e,t){if(!e)return;let n=e.trim().toLowerCase();if(on.includes(n))return n;throw new d(`${t} pm_context_mode must be one of: ${on.join(", ")}`,l.USAGE)}function an(e,t){if(!e)return;let n=e.trim().toLowerCase();if(B_.includes(n))return n;throw new d(`${t} workspace_context_mode must be one of: ${B_.join(", ")}`,l.USAGE)}function cn(e){if(!e)return;let t=Ln(e,{separators:/[;\n]/});return t.length>0?t:void 0}function jn(e,t,n){let r=cn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(i){throw new d(`${t} ${n} includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`,l.USAGE)}return r}}function ns(e,t){if(!e)return;let n=he(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new d(`${t} assert_stdout_min_lines must be an integer >= 0`,l.USAGE);return n}function rs(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new d(`${t} assert_json_field_equals must include at least one path=value assignment`,l.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,l.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0||a.length===0)throw new d(`${t} assert_json_field_equals entries must include non-empty path and value`,l.USAGE);r[s]=a}return Object.keys(r).length>0?r:void 0}function os(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new d(`${t} assert_json_field_gte must include at least one path=value assignment`,l.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,l.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0||a.length===0)throw new d(`${t} assert_json_field_gte entries must include non-empty path and value`,l.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new d(`${t} assert_json_field_gte value for "${s}" must be numeric`,l.USAGE);r[s]=c}return Object.keys(r).length>0?r:void 0}var Bk=new Set(vt);function is(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hk(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!Bk.has(s)){r.push(o);continue}if(Object.hasOwn(n,s))throw t(`provides key "${o}" more than once after case normalization`);n[s]=i}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${vt.join(", ")}.`);return n}function rn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function Xi(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(s=>typeof s!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=o.filter(s=>s.length>0);return i.length>0?i:void 0}function H_(e,t,n){let r=Xi(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(i){throw n(`field "${t}" includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`)}return r}}function Qi(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function Vk(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:Qi(n,"timeout_seconds",t),i=r===void 0?void 0:Qi(r,"timeout",t);if(o!==void 0&&i!==void 0&&o!==i)throw t("timeout and timeout_seconds must match when both are provided");let s=o??i;if(!Number.isInteger(s)||s<=0)throw t("timeout_seconds must be a positive integer");return s}function Wk(e,t){let n=rn(e,"scope",t);if(n===void 0)return"project";if(!ct.includes(n))throw t(`field "scope" must be one of: ${ct.join(", ")}`);return n}function Yk(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!is(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(typeof i!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Zi.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(sn.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=i}return Object.keys(r).length>0?r:void 0}function Jk(e,t){let n=Xi(e,"env_clear",t);if(n){for(let r of n){if(!Zi.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(sn.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function Xk(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function Qk(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=Qi(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function Zk(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!is(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof i!="string"&&typeof i!="number"&&typeof i!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(i)}return Object.keys(r).length>0?r:void 0}function eS(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!is(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=Qi(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function tS(e,t,n){let r=f=>new d(`${n} ${t} ${f}`,l.USAGE);if(!is(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${vt.join(", ")}.`);let o=Hk(e,r),i=rn(o,"command",r),s=rn(o,"cmd",r);if(i!==void 0&&s!==void 0&&i!==s)throw r("command and cmd must match when both are provided");let a=i??s;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=rn(o,"path",r),m=rn(o,"pm_context_mode",r);if(m!==void 0&&!on.includes(m))throw r(`field "pm_context_mode" must be one of: ${on.join(", ")}`);let u=an(rn(o,"workspace_context_mode",r),`${n} ${t}`),p=rn(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:Wk(o,r),timeout_seconds:Vk(o,r),pm_context_mode:m,workspace_context_mode:u,env_set:Yk(o,r),env_clear:Jk(o,r),shared_host_safe:Xk(o,"shared_host_safe",r),assert_stdout_contains:Xi(o,"assert_stdout_contains",r),assert_stdout_regex:H_(o,"assert_stdout_regex",r),assert_stderr_contains:Xi(o,"assert_stderr_contains",r),assert_stderr_regex:H_(o,"assert_stderr_regex",r),assert_stdout_min_lines:Qk(o,r),assert_json_field_equals:Zk(o,r),assert_json_field_gte:eS(o,r),note:p!==void 0&&p.trim().length>0?p.trim():void 0}}function V_(e,t){let n=e.trim();if(n.length===0)throw new d(`${t} requires a JSON object or array of objects describing linked-test entries`,l.USAGE);let r;try{r=JSON.parse(n)}catch(i){throw new d(`${t} value is not valid JSON: ${i instanceof Error?i.message:String(i)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,l.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new d(`${t} array must include at least one linked-test entry object`,l.USAGE);return o.map((i,s)=>tS(i,o.length>1?`entry ${s+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0562fd00-217b-5e1f-8004-df4574f8b796")}catch{}})();var Ac=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Tc=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],W_=[...Ac,...Tc],ss=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function as(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let o=r.trim().toLowerCase();if(!o)throw new d("--unset values must not be empty",l.USAGE);if(He(o))throw new d('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',l.USAGE);let i=e.resolveDefinition(o);if(!i)throw new d(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,l.USAGE);t.add(i.metadataKey),n.add(i.optionKey)}return{metadataKeys:t,optionKeys:n}}function cs(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let i of o){if(i.allow_unset===!1)continue;let s=new Set;if(typeof i.key=="string"&&i.key.length>0&&s.add(i.key.toLowerCase()),typeof i.metadata_key=="string"&&i.metadata_key.length>0&&s.add(i.metadata_key.toLowerCase()),typeof i.cli_flag=="string"&&i.cli_flag.length>0&&(s.add(i.cli_flag.replaceAll("-","_").toLowerCase()),s.add(i.cli_flag.toLowerCase())),Array.isArray(i.cli_aliases))for(let a of i.cli_aliases)typeof a!="string"||a.length===0||(s.add(a.replaceAll("-","_").toLowerCase()),s.add(a.toLowerCase()));if(s.has(r))return{optionKey:i.key,metadataKey:i.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var nS={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 rS(e){return nS[e]}function Cc(e){return rS(e)!==void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad3f992c-db2e-5276-a8ae-5d5d4ec8ae68")}catch{}})();var oS=["strict","progressive"],iS=["lightweight"],Q_=new Set(["Reminder","Meeting","Event"]),sS=new Set(["author","created_at","text"]),Ic=[...W_,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...ss],aS=(()=>{let e=new Map;for(let t of Ic)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),ls=new Map(Ic.map(e=>[e.optionKey,e.canonical])),cS=Ic.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function lS(e,t){let n=Z(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new d(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n}function dS(e,t){let n=e.default_status;if(n!==void 0){let r=Z(n,t);if(r)return r}return t.open_status}function Rc(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new d(`Invalid created_at timestamp "${e}"`,l.USAGE);return new Date(n).toISOString()}var mS=Ki();function Z_(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i};He(t.template)&&(t.template=void 0);let r=new Set([...ls.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!He(i))continue;let s=o==="rank"?"order":ls.get(o)??o;n(s),t[o]=void 0}return Se(e,Bi(t,mS))}function ye(e){if(e!==void 0)return e}function uS(e,t){return as({raw:e,supportedFields:cS,resolveDefinition:n=>aS.get(n)??cs(n,"create",t)})}var Y_=["id","kind","type","author","created_at","source_kind"],ds=["path","scope","note"];function pS(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(i=>{let s=i.trim(),a=ms(s,Y_);Or(s,a);let c=a?de(i,"--dep"):{id:s,kind:"related"};a&&Be(c,"--dep",Y_);let m=ye(c.id),u=fS(ye(c.kind??c.type));if(!m||!u)throw new d("--dep requires id and kind, or a bare item id to create a related dependency",l.USAGE);if(m.trim().toLowerCase()==="undefined")throw new d(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,l.USAGE);let p=hr(ye(c.source_kind)),f=ye(c.author);return{id:gr(m,n,p),kind:Te(u,Ht,"dependency kind","kind"),created_at:Rc(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function fS(e){return typeof e=="string"?mo(e)??e.trim():e}function ms(e,t){return ai(e,t)?!0:di(e)}function dn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Ae(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(s=>{let a=s.trim(),c=()=>{if(a.length===0)throw new d(`${e} requires text=<value>`,l.USAGE);return{created_at:n,author:r,text:a}},m;try{m=de(s,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!sS.has(f)).length>0)return{created_at:Rc(m.created_at,n),author:ye(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new d(`${e} requires text=<value>`,l.USAGE);return{created_at:Rc(m.created_at,n),author:ye(m.author)??r,text:p}}),explicitEmpty:!1})}function Oc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),o=ms(r,ds);ja(r,"--file","file path",o);let i=o?de(n,"--file"):{path:r};if(o&&Be(i,"--file",ds),!i.path)throw new d("--file requires path=<value> or a bare file path",l.USAGE);return{path:i.path,scope:Te(i.scope??"project",ct,"file scope"),note:ye(i.note)}}),explicitEmpty:!1})}function xc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),o=ms(r,vt);ja(r,"--test","test command",o);let i=o?Ji(de(n,"--test"),"--test"):{command:r},s=ye(i.command),a=ye(i.path);if(!s)throw new d("--test requires command=<value> or a bare command (path=<value> is optional metadata)",l.USAGE);let c=ye(i.timeout_seconds),m=ye(i.timeout);if(c&&m&&c!==m)throw new d("--test timeout and timeout_seconds must match when both are provided",l.USAGE);let u=c??m;return{command:s,path:a,scope:Te(i.scope??"project",ct,"test scope"),timeout_seconds:u?he(u,"timeout_seconds"):void 0,pm_context_mode:ts(i.pm_context_mode,"--test"),workspace_context_mode:an(i.workspace_context_mode,"--test"),env_set:Pr(i.env_set,"--test"),env_clear:Lr(i.env_clear,"--test"),shared_host_safe:es(i.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:cn(i.assert_stdout_contains),assert_stdout_regex:jn(i.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:cn(i.assert_stderr_contains),assert_stderr_regex:jn(i.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:ns(i.assert_stdout_min_lines,"--test"),assert_json_field_equals:rs(i.assert_json_field_equals,"--test"),assert_json_field_gte:os(i.assert_json_field_gte,"--test"),note:ye(i.note)}}),explicitEmpty:!1})}function Pc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),o=ms(r,ds),i=o?de(n,"--doc"):{path:r};if(o&&Be(i,"--doc",ds),!i.path)throw new d("--doc requires path=<value> or a bare doc path",l.USAGE);return{path:i.path,scope:Te(i.scope??"project",ct,"doc scope"),note:ye(i.note)}}),explicitEmpty:!1})}function _S(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Hi(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function hS(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--event","Use --clear-events to clear linked events."),{values:Vi(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function gS(e,t,n,r=[]){let o=[...io.filter(i=>e[i]!==void 0),...r.filter(i=>e[i]!==void 0),...t.length>0?["body"]:[],...n.map(i=>`unset:${i}`)];return Array.from(new Set(o))}function yS(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function J_(e,t,n){let r=Qn("create",e);if(!r)throw new d(`Unsupported ${n} entry "${e}" for type "${t}"`,l.CONFLICT);return r}function vS(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 eh(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 wS(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(J_(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(J_(r,e.name,"required_create_repeatables"));return n}function bS(e,t,n,r){for(let o of e)if(!(!eh(t,o)&&!n.has(o)))throw new d(`Option ${be("create",o)} is disabled for type "${r}" by command_option_policies`,l.USAGE)}function kS(e,t,n){if(t!=="strict")return;let r=e.filter(i=>n.has(i)&&!Cc(i));if(r.length===0)return;let o=[...new Set(r.map(i=>be("create",i)))].sort((i,s)=>i.localeCompare(s));throw new d(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,l.USAGE)}function SS(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Ae(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Wi(e),explicitEmpty:!1})}async function ES(e){return await mi(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 AS(e){return ht(e)?await ES(e):e}function TS(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 d(`Invalid --create-mode value "${e}". Allowed: ${oS.join(", ")}`,l.USAGE)}function CS(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new d("--schedule-preset must not be empty",l.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new d(`Invalid --schedule-preset value "${e}". Allowed: ${iS.join(", ")}`,l.USAGE)}function RS(e,t,n){let r=TS(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new d("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",l.USAGE);return"progressive"}function IS(e,t,n,r){let o=e.name,i=vS(t),s=wS(e,n),a=vn(e,"create",s);if(a.errors.length>0)throw new d(a.errors.join("; "),l.CONFLICT);bS(a.disabled,i,r,o),kS(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&Cc(u)?!0:eh(i,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>be("create",u)))].sort((u,p)=>u.localeCompare(p))}var th=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function OS(e,t){let n=[];for(let r of e){let o=r.match(th);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function xS(e,t){return e.filter(n=>{let r=n.match(th);return!r||r[2]!==t})}function PS(e,t,n,r){let o=xS(e,t);if(o.length===0)return;let i=nh(n,[],[],r.open_status);throw new d(o.join("; "),l.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[i],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function LS(e,t){let r=e.options.find(o=>o.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function NS(e,t,n){switch(e){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--dep":return["--dep",'"id=pm-xxxx,kind=related,author=maintainer,created_at=now"'];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];case"--note":return["--note",'"author=maintainer,created_at=now,text=Design note"'];case"--learning":return["--learning",'"author=maintainer,created_at=now,text=Durable lesson"'];case"--file":return["--file",'"path=src/example.ts,note=implementation file"'];case"--test":return["--test",'"command=node scripts/run-tests.mjs test,timeout_seconds=240"'];case"--doc":return["--doc",'"path=README.md,note=reference doc"'];default:return[e,'"<value>"']}}function nh(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],i=["--status","--priority","--message"],s=[...new Set([...i,...t])],a=new Set(["--title","--description","--type"]);for(let c of s)a.has(c)||(o.push(...NS(c,e.name,r)),a.add(c));for(let c of n){let m=LS(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function Lc(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new d("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",l.USAGE):new d('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.',l.USAGE):new d(`Missing required option ${t}`,l.USAGE);return n}function MS(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=Array.isArray(o)?[...o]:o;for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=Array.isArray(o)?[...o]:o);return n}function FS(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function $S(){let e=O();return e?e.commands.some(t=>t.action==="templates-show"||FS(t.command)==="templates show"):!1}function DS(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new d(`Templates package returned invalid payload for template "${t}". Expected an options object.`,l.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new d(`Templates package returned invalid options for template "${t}".`,l.GENERIC_FAILURE);let r={};for(let[o,i]of Object.entries(n)){if(typeof i=="string"||typeof i=="number"||typeof i=="boolean"){r[o]=i;continue}if(Array.isArray(i)&&i.every(s=>typeof s=="string")){r[o]=[...i];continue}throw new d(`Templates package returned unsupported option value for "${o}" in template "${t}".`,l.GENERIC_FAILURE)}return r}async function US(e,t,n){if(!$S())throw new d("--template requires the templates package. Install it first (for example: pm install templates --project).",l.USAGE);let r=await Yo({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let o=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new d(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${o}`,l.USAGE)}return DS(r.result,e)}function B(e,t,n){return e.has(t)||n===void 0?void 0:ye(n)}function ln(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var GS=new Set(["milestone","meeting","reminder","event"]);function rh(e,t,n,r){let o=t!==void 0,i=n!==void 0&&n.length>0,s=r!==void 0&&r.length>0;return GS.has(e.toLowerCase())&&!o&&!i&&!s}function jS(e,t,n,r,o){let i=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&i.push(`event_without_schedule:${t}:no_time_set`),rh(e,n,r,o)&&i.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),i}async function qS(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await Qo(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function KS(e,t,n,r,o,i){let s=vi(_i(o),t.id_prefix);if(Bo(s))return{parent:s,warnings:[]};if(gi(r,s,t.id_prefix),await q(e,s,t.id_prefix,t.item_format,n.type_to_folder))return{parent:s,warnings:[]};let c=Ge(s,t.id_prefix);return{parent:s,warnings:hi(c,i).warnings}}async function zS(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await KS(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function BS(e){if(e.explicitId===void 0)return pr(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new d("--id must be a string",l.USAGE);let t=e.explicitId.trim();if(t.length===0||$p(t))throw new d("--id must not be empty or use a placeholder token",l.USAGE);let n=Ge(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new d("--id must contain only letters, numbers, and dashes after normalization",l.USAGE);return n}function X_(e,t,n,r,o){let i=B(e,t,n);if(i===void 0)return{value:void 0,warnings:[]};let s=yi(r,i,o);return{value:s.value,warnings:s.warnings}}async function HS(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:i,status:s,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(i===void 0)return{dependencyValues:u,status:s};let p=Ge(i,n.id_prefix),f=await q(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:s};if((u??[]).some(y=>y.id===f.id&&y.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:s};let g=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((y,h)=>y.localeCompare(h))[0]??o.open_status;return{dependencyValues:u,status:g}}function VS(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let o=t.governance.create_default_type?.trim();if(o&&o.length>0&&we(o,n)){e.type=o;return}we("Task",n)&&(e.type="Task")}function WS(e,t){return e.options.filter(n=>Qn("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 d(`Template custom type option "${n.key}" must be a string, number, or boolean value`,l.USAGE)})}async function YS(e,t,n,r,o){let i=e,s=[];if(i.template!==void 0){let g=i.template.trim();if(g.length===0)throw new d("--template must not be empty. Omit --template to disable template usage.",l.USAGE);let y=await US(g,t,n);i=Z_(MS(y,i))}if(i.type===void 0&&VS(i,r,o),i.type===void 0)throw new d("Missing required option --type <value>",l.USAGE);let a=we(i.type,o);if(!a){let g=Up(i.type),y=g?we(g,o):void 0;if(y)s.push(`type_coercion:${i.type.trim()}:${y}`),i.type=y,a=y;else throw new d(Ot(i.type,o.types,xt(n,r.schema)),l.USAGE)}let c=co(a,o);if(!c)throw new d(`Invalid type value "${i.type}"`,l.USAGE);let m=c.name,u=WS(c,i),p=u.map(g=>`${g.key}=${String(i[g.key])}`);if(p.length>0){i.typeOption=[...p,...i.typeOption??[]];for(let g of u)delete i[g.key]}let f=CS(i.schedulePreset);if(f!==void 0&&!Q_.has(m))throw new d(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,l.USAGE);let _=RS(i.createMode,f,r.governance.create_mode_default);return{resolvedOptions:i,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:s}}function JS(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let i of o)if(i.enabled){if(i.values&&i.values.length>0)throw new d(`Cannot combine ${i.clearFlag} with ${i.valueFlag}`,l.USAGE);n.add(i.metadataKey),r.add(i.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function XS(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=ls.get(r)??r;throw new d(`Cannot combine --unset ${i} with ${be("create",r)}`,l.USAGE)}}function QS(e){let t=(n,r)=>{let o=ls.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;zi(n,be("create",r),i)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function ZS(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new d(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,l.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new d(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,l.USAGE)}var eE={"--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 tE(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:i,type:s,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(g=>{let y=g.type==="boolean"?"<true|false>":g.type==="array"?"<json-array>":g.type==="object"?"<json-object>":g.type==="number"?"<number>":g.type==="string_array"||g.repeatable?"<value>":"<string>";return{example:`--${g.cli_flag} ${y}`,description:`--${g.cli_flag} maps to ${g.metadata_key} (${g.type}${g.repeatable?", repeatable":""})`}}),u=[nh(n,r,o,i),...m.map(g=>g.example)].join(" "),p=[`Run "pm create --help --type ${s}" for type-aware required option guidance.`,...t.filter(g=>g==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+s+").")];a==="strict"&&(p.push('For staged onboarding, retry with "--create-mode progressive".'),Q_.has(s)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&p.push(`Required custom field formats: ${m.map(g=>g.description).join("; ")}.`);let f=[...new Set(t.flatMap(g=>{let y=g.split(" ",1)[0],h=eE[y];return h?[h]:[]}))];f.length>0&&p.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let _=t.length===1?`Missing required option ${t[0]} for type "${s}"`:`Missing required options ${t.join(", ")} for type "${s}"`;throw new d(_,l.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${s}" in one invocation.`,examples:[...f.map(g=>`pm create --type ${s} ${g} ...`),u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function nE(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new d("Cannot combine --unset tags with --add-tags",l.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Ft(t.tags):[];return On(n,t.addTags)}function rE(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new d("--order and --rank must match when both are provided",l.USAGE);let n=t.order??t.rank,r=ln(e,"order",n,o=>he(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new d("Order must be an integer",l.USAGE);return r}function oE(e,t,n,r,o,i){if(r.completedAt!==void 0&&e!==t.close_status)throw new d("--completed-at requires a terminal create status.",l.USAGE);let s=e!==t.close_status?void 0:r.completedAt===void 0?i:re(r.completedAt,new Date(i),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:s,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:bc(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:s,warnings:[]}}async function iE(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:i,author:s,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:g}=e,y=dt(t,n,r,o.item_format,i.type_to_folder),h=Xe(t,r),v=Dt(),b=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(D=>v.resolve(D.kind)?.hierarchy),S=await Yi({pmRoot:t,author:s,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:b}),T=b,I=[];try{let D=await ke(t,r,o.locks.ttl_seconds,s,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let M=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await _e(t,o.item_format,i.type_to_folder,void 0,o.schema):void 0;if(await q(t,r,o.id_prefix,o.item_format,i.type_to_folder))throw new d(`Item "${r}" already exists`,l.CONFLICT);if(M){let ae=F(o.schema);wi(M,[...M,c.metadata],r,j=>te(j,ae),v)}let z=await ur({pmRoot:t,settings:o,operation:"create",author:s,before:null,after:c});await Wo({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:ni({pmRoot:t,settings:o,typeToFolder:i.type_to_folder})});let K=await Nt(t,s,{required:o.governance.duplicate_detection_mode==="strict"&&g!==!0}),pe=[];try{o.governance.duplicate_detection_mode==="strict"&&g!==!0&&await Dn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await ee(y,ze(c,{format:o.item_format,schema:o.schema,extensionFieldNames:a}));try{let ae=Oe({nowIso:f,author:s,op:"create",before:m,after:c,message:u,context:z.decisions.length===0?void 0:{workflow_policies:z.decisions}});await Pt(h,ae)}catch(ae){throw await yn(y),ae}T&&(await S(),T=!1),pe=await Mt({pmRoot:t,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:y,document:c})}finally{await K()}I=[...z.warnings,...M?Pi(M,[...M,c.metadata],r):[],...pe,...await W({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await W({path:h,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],kn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Qt(c.metadata,p),changed_fields:p})}finally{await D()}}finally{T&&await S()}return I}async function Gt(e,t){let n=Z_(await AS(e)),r=E(process.cwd(),t.path);await R(r);let o=await A(r),i=F(o.schema),s=Qe(o.schema),a=x(o,O()),c=await YS(n,t,r,o,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=uS(n.unset,s),{explicitUnsets:_,clearOptionKeys:g}=JS(n,f);XS(n,f),QS(n);let y=IS(m,n,p,g),h=k(),v=C(ye(n.author),o.author_default),b=pS(n.dep,h,o.id_prefix,v),S=dn("--comment",n.comment,h,v),T=dn("--note",n.note,h,v),I=dn("--learning",n.learning,h,v),D=Oc(n.file),M=xc(n.test);M.values=await $n(M.values,v,h);let Y=Pc(n.doc),z=_S(n.reminder,h),K=hS(n.event,h),pe=SS(n.typeOption),ae=Zn(u,pe.values,a),j=O(),ce=Ct(j),st=so(n.field,j),Ye=Xu(n,s,u),Jn=new Set(Ye.missing_required_flags),zs=s.definitions.filter(V=>Jn.has(`--${V.cli_flag}`));ZS(st,Ye,f);let Xn=OS(ae.errors,u),zt=Xn.map(V=>`--type-option ${V}=<value>`),ad=[...new Set([...y,...zt,...Ye.missing_required_flags])].sort((V,Zs)=>V.localeCompare(Zs));tE({combinedMissingFlags:ad,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:Xn,openStatus:i.open_status,type:u,createMode:p,missingRequiredRuntimeFields:zs}),PS(ae.errors,u,m,i);let Ie=await BS({pmRoot:r,settings:o,typeRegistry:a,explicitId:n.id}),Et=n.status!==void 0?lS(n.status,i):dS(m,i),Bs=n.priority!==void 0?Pn(n.priority):2,P=f.metadataKeys,De=nE(P,n),at=ln(P,"deadline",n.deadline,V=>re(V,new Date(h),"deadline")),Qr=ln(P,"estimated_minutes",n.estimatedMinutes,V=>xn(V,"estimated-minutes")),At=B(P,"acceptance_criteria",n.acceptanceCriteria),Hs=B(P,"definition_of_ready",n.definitionOfReady),Je=rE(P,n),Vs=B(P,"goal",n.goal),Zr=B(P,"objective",n.objective),Iw=B(P,"value",n.value),Ow=B(P,"impact",n.impact),xw=B(P,"outcome",n.outcome),Pw=B(P,"why_now",n.whyNow),Lw=B(P,"assignee",n.assignee),Nw=P.has("author")?void 0:ye(n.author)??v,Mw=B(P,"parent",n.parent),cd=await qS(Mw,n,P,r),Ws=cd.parent,Fw=cd.parentSource,$w=B(P,"reviewer",n.reviewer),Dw=ln(P,"risk",n.risk,V=>Te(Ui(V),hn,"risk")),Uw=ln(P,"confidence",n.confidence,V=>ji(V)),Gw=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,ld=o.validation.sprint_release_format,Bt=[...c.warnings,...jS(u,Ie,at,z.values,K.values)],dd=await zS({itemId:Ie,parent:Ws,pmRoot:r,settings:o,typeRegistry:a,policy:Gw});Ws=dd.parent,Bt.push(...dd.warnings);let md=X_(P,"sprint",n.sprint,"sprint",ld),jw=md.value;Bt.push(...md.warnings);let ud=X_(P,"release",n.release,"release",ld),qw=ud.value;Bt.push(...ud.warnings);let pd=B(P,"blocked_by",n.blockedBy),fd=await HS({pmRoot:r,settings:o,typeRegistry:a,statusRegistry:i,blockedBy:pd,dependencyValues:b.values,status:Et,statusExplicit:n.status!==void 0,nowValue:h,author:v}),Ys=fd.dependencyValues;xr(Ie,Ys),Bt.push(...await nn({pmRoot:r,dependencies:Ys,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ie,createdAt:h}],schema:o.schema})),Et=fd.status;let Kw=B(P,"blocked_reason",n.blockedReason),zw=B(P,"unblock_note",n.unblockNote),Bw=B(P,"reporter",n.reporter),Hw=ln(P,"severity",n.severity,V=>Te(Gi(V),gn,"severity")),Vw=B(P,"environment",n.environment),Ww=B(P,"repro_steps",n.reproSteps),_d=B(P,"resolution",n.resolution),Yw=B(P,"expected_result",n.expectedResult),Jw=B(P,"actual_result",n.actualResult),Xw=B(P,"affected_version",n.affectedVersion),Qw=B(P,"fixed_version",n.fixedVersion),Zw=B(P,"component",n.component),eb=ln(P,"regression",n.regression,V=>qi(V)),tb=B(P,"customer_impact",n.customerImpact),Js=Lc(n.title,"--title"),Xs=n.description??"",eo=n.body??"",hd=await Dn({title:Js,description:Xs,body:eo},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Bt.push(...Li(hd));let Qs=oE(Et,i,o,n,_d,h),nb=Qs.closeReason,rb=Et===i.close_status?h:void 0,ob=Qs.completedAt;Bt.push(...Qs.warnings);let to=La({id:Ie,title:Js,description:Xs,type:u,type_options:ae.normalized,status:Et,closed_at:rb,completed_at:ob,close_reason:nb,priority:Bs,tags:De,created_at:h,updated_at:h,deadline:at,assignee:Lw,author:Nw,estimated_minutes:Qr,acceptance_criteria:At,definition_of_ready:Hs,order:Je,goal:Vs,objective:Zr,value:Iw,impact:Ow,outcome:xw,why_now:Pw,parent:Ws,reviewer:$w,risk:Dw,confidence:Uw,sprint:jw,release:qw,blocked_by:pd,blocked_reason:Kw,unblock_note:zw,reporter:Bw,severity:Hw,environment:Vw,repro_steps:Ww,resolution:_d,expected_result:Yw,actual_result:Jw,affected_version:Xw,fixed_version:Qw,component:Zw,regression:eb,customer_impact:tb,dependencies:Ys,comments:S.values,notes:T.values,learnings:I.values,files:D.values,tests:M.values,docs:Y.values,reminders:z.values,events:K.values,...st,...Ye.values});try{ao(to,j)}catch(V){throw new d(V instanceof Error?V.message:"Invalid extension item field values",l.USAGE)}let ib=Ze({metadata:to,body:eo},{schema:o.schema,extensionFieldNames:ce}),sb={metadata:{},body:""},gd=[..._].sort((V,Zs)=>V.localeCompare(Zs)),ab=yS(n.message,gd),yd=gS(to,eo,gd,[...Object.keys(st),...Object.keys(Ye.values??{})]),cb=await iE({pmRoot:r,type:u,id:Ie,settings:o,typeRegistry:a,author:v,extensionFieldNames:ce,afterDocument:ib,beforeDocument:sb,historyMessage:ab,changedFields:yd,nowValue:h,similarityCandidate:{title:Js,description:Xs,body:eo},allowDuplicate:n.allowDuplicate}),vd=structuredClone(to);p==="strict"&&_.has("dependencies")&&(vd.dependencies=[]);let lb=K_(Ie,u,Et,i);return rh(u,at,z.values,K.values)&&cp(`[pm] warning: ${u} '${Ie}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ie} --deadline <ISO>' or 'pm update ${Ie} --event "start=<ISO>,end=<ISO>"'.`),{item:vd,changed_fields:yd,warnings:[...Bt,...cb],...Object.fromEntries([["parent_source",Fw],["next_transition",lb],["similarity_advisory",hd]].filter(V=>V[1]!==void 0))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="80ec599f-7198-5b07-bca2-253f85c137b7")}catch{}})();var $c=[...Ac,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Tc,...ss],sE=(()=>{let e=new Map;for(let t of $c)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),us=new Map($c.map(e=>[e.optionKey,e.canonical])),aE=$c.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),cE=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),lE=Ki({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function mh(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i},r=new Set([...us.keys(),"rank"]);for(let o of r){let i=t[o];if(typeof i!="string"||!He(i))continue;let s=o==="rank"?"order":us.get(o)??o;n(s),t[o]=void 0}return Se(e,Bi(t,lE))}function uh(e,t,n=[]){return as({raw:e,supportedFields:aE,resolveDefinition:r=>{let o=n.find(s=>{let a=s.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return sE.get(r)??cs(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var oh=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 ih(e){let t=e.disallowedFlags.flatMap(r=>{let o=oh.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=oh.get(r);return o?[`Replace ${r} with: ${o(e.id)}`]:[]});return new d(e.message,l.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function dE(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new d("Choose only one package-provided ownership bypass mode.",l.USAGE);let i=(c,m,u)=>{c&&u.push(m)};if(o){let c=[];if(i(t.title!==void 0,"--title",c),i(t.description!==void 0,"--description",c),i(t.body!==void 0,"--body",c),i(t.status!==void 0,"--status",c),i(t.closeReason!==void 0,"--close-reason",c),i(t.priority!==void 0,"--priority",c),i(t.type!==void 0,"--type",c),i(t.tags!==void 0,"--tags",c),i(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),i(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),i(t.deadline!==void 0,"--deadline",c),i(t.estimatedMinutes!==void 0,"--estimate",c),i(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),i(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),i(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),i(t.definitionOfReady!==void 0,"--definition-of-ready",c),i(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),i(t.goal!==void 0,"--goal",c),i(t.objective!==void 0,"--objective",c),i(t.value!==void 0,"--value",c),i(t.impact!==void 0,"--impact",c),i(t.outcome!==void 0,"--outcome",c),i(t.whyNow!==void 0,"--why-now",c),i(t.assignee!==void 0,"--assignee",c),i(t.parent!==void 0,"--parent",c),i(t.reviewer!==void 0,"--reviewer",c),i(t.risk!==void 0,"--risk",c),i(t.confidence!==void 0,"--confidence",c),i(t.sprint!==void 0,"--sprint",c),i(t.release!==void 0,"--release",c),i(t.blockedBy!==void 0,"--blocked-by",c),i(t.blockedReason!==void 0,"--blocked-reason",c),i(t.unblockNote!==void 0,"--unblock-note",c),i(t.reporter!==void 0,"--reporter",c),i(t.severity!==void 0,"--severity",c),i(t.environment!==void 0,"--environment",c),i(t.reproSteps!==void 0,"--repro-steps",c),i(t.resolution!==void 0,"--resolution",c),i(t.expectedResult!==void 0,"--expected-result",c),i(t.actualResult!==void 0,"--actual-result",c),i(t.affectedVersion!==void 0,"--affected-version",c),i(t.fixedVersion!==void 0,"--fixed-version",c),i(t.component!==void 0,"--component",c),i(t.regression!==void 0,"--regression",c),i(t.customerImpact!==void 0,"--customer-impact",c),i(t.depRemove!==void 0,"--dep-remove",c),i(t.replaceDeps===!0,"--replace-deps",c),i(t.replaceTests===!0,"--replace-tests",c),i(t.replaceFiles===!0,"--replace-files",c),i(t.replaceDocs===!0,"--replace-docs",c),i(t.comment!==void 0,"--comment",c),i(t.note!==void 0,"--note",c),i(t.learning!==void 0,"--learning",c),i(t.file!==void 0,"--file",c),i(t.test!==void 0,"--test",c),i(t.doc!==void 0,"--doc",c),i(t.reminder!==void 0,"--reminder",c),i(t.event!==void 0,"--event",c),i(t.typeOption!==void 0,"--type-option",c),i(t.clearDeps===!0,"--clear-deps",c),i(t.clearComments===!0,"--clear-comments",c),i(t.clearNotes===!0,"--clear-notes",c),i(t.clearLearnings===!0,"--clear-learnings",c),i(t.clearFiles===!0,"--clear-files",c),i(t.clearTests===!0,"--clear-tests",c),i(t.clearDocs===!0,"--clear-docs",c),i(t.clearReminders===!0,"--clear-reminders",c),i(t.clearEvents===!0,"--clear-events",c),i(t.clearTypeOptions===!0,"--clear-type-options",c),i(t.force===!0,"--force",c),i(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new d("The dependency ownership bypass requires at least one --dep value",l.USAGE);if(c.length>0)throw ih({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let s=[];i(t.status!==void 0,"--status",s),i(t.closeReason!==void 0,"--close-reason",s),i(t.assignee!==void 0,"--assignee",s),i(t.parent!==void 0,"--parent",s),i(t.blockedBy!==void 0,"--blocked-by",s),i(t.blockedReason!==void 0,"--blocked-reason",s),i(t.unblockNote!==void 0,"--unblock-note",s),i(t.dep!==void 0,"--dep",s),i(t.depRemove!==void 0,"--dep-remove",s),i(t.replaceDeps===!0,"--replace-deps",s),i(t.replaceTests===!0,"--replace-tests",s),i(t.replaceFiles===!0,"--replace-files",s),i(t.replaceDocs===!0,"--replace-docs",s),i(t.note!==void 0,"--note",s),i(t.learning!==void 0,"--learning",s),i(t.test!==void 0,"--test",s),i(t.reminder!==void 0,"--reminder",s),i(t.event!==void 0,"--event",s),i(t.clearDeps===!0,"--clear-deps",s),i(t.clearComments===!0,"--clear-comments",s),i(t.clearNotes===!0,"--clear-notes",s),i(t.clearLearnings===!0,"--clear-learnings",s),i(t.clearFiles===!0,"--clear-files",s),i(t.clearTests===!0,"--clear-tests",s),i(t.clearDocs===!0,"--clear-docs",s),i(t.clearReminders===!0,"--clear-reminders",s),i(t.clearEvents===!0,"--clear-events",s);let a=[...n].filter(c=>cE.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(s.push(...a),s.length>0)throw ih({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${s.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:s})}function mE(e,t){let n=Z(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new d(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n}function uE(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=du({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Z(e.fromStatus,e.statusRegistry)??e.fromStatus,r=Z(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${mu(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new d(o,l.USAGE);return`workflow_transition_not_allowed: ${o}`}function pE(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:ph(e)}function ph(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new d(`Invalid dependency created_at timestamp "${e}"`,l.USAGE);return new Date(t).toISOString()}function qn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var fE=["id","kind","type","author","created_at","source_kind"],_E=["id","kind","type","author","created_at","source_kind"];function fh(e){return e.startsWith("```")||e.includes(`
|
|
6
|
+
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:di(e)}function _h(e){return typeof e=="string"?mo(e)??e.trim():e}function fs(e,t,n,r){return e?(Ae(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(i=>{let s=i.trim(),a=fh(s);Or(s,a);let c=a?de(i,"--dep"):{id:s,kind:"related"};a&&Be(c,"--dep",fE);let m=c.id?.trim(),u=_h((c.kind??c.type)?.trim());if(!m||!u)throw new d("--dep requires id and kind, or a bare item id to add a related dependency",l.USAGE);if(m.toLowerCase()==="undefined")throw new d(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,l.USAGE);let p=hr(qn(c.source_kind)),f=qn(c.author);return{id:gr(m,t,p),kind:Te(u,Ht,"dependency kind","kind"),created_at:pE(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function hE(e,t){return e?(Ae(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new d("--dep-remove requires id or key/value selectors",l.USAGE);let o=fh(r);if(Or(r,o,"--dep-remove"),o){let i=de(r,"--dep-remove");Be(i,"--dep-remove",_E);let s=i.id?.trim();if(!s)throw new d("--dep-remove key/value form requires id=<value>",l.USAGE);if(s.toLowerCase()==="undefined")throw new d(`--dep-remove id must not use placeholder token "${s}"`,l.USAGE);let a=_h(qn(i.kind??i.type)),c=hr(qn(i.source_kind)),m=qn(i.author),u=qn(i.created_at);return{id:gr(s,t,c),kind:a?Te(a,Ht,"dependency kind","kind"):void 0,source_kind:c,author:m,created_at:u?ph(u):void 0}}if(r.toLowerCase()==="undefined")throw new d(`--dep-remove id must not use placeholder token "${r}"`,l.USAGE);return{id:Ge(r,t)}})):[]}function ps(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function gE(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),i=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,i].join("\0")}function yE(e,t,n,r){let o=[...e??[]],i=!1;if(t===void 0){let s=o.filter(a=>a.kind!=="blocked_by");return s.length!==o.length&&(o=s,i=!0),i?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(s=>s.kind==="blocked_by"&&s.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),i=!0),i?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function vE(e,t,n,r,o,i){if(e===void 0||t)return{};let s=e.trim();if(s.length===0)return{};let a=await q(n,Ge(s,r),r,o,i);return a?{id:a.id}:{unresolved:s}}function wE(e,t,n,r,o){let i=yE(e.dependencies,t,n,r);i.changed&&(i.dependencies===void 0?delete e.dependencies:e.dependencies=i.dependencies,o.includes("dependencies")||o.push("dependencies"))}function bE(e){return`${e.path}::${e.scope}`}function kE(e){return`${e.path}::${e.scope}`}function SE(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function hh(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function sh(e,t){let n=Qn("update",e);if(!n)throw new d(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,l.CONFLICT);return n}function EE(e,t,n){let r=new Set,o=(i,s)=>{s&&r.add(i)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let i=uh(e.unset,t,n);for(let s of i.optionKeys)o(s,!0)}return r}function AE(e,t,n,r,o){let i=co(e,n);if(!i)throw new d(`Invalid type value "${e}"`,l.USAGE);let s=vn(i,"update",[]);if(s.errors.length>0)throw new d(s.errors.join("; "),l.CONFLICT);let a=EE(t,r,o);for(let c of s.disabled)if(a.has(sh(c,e)))throw new d(`Option ${be("update",c)} is disabled for type "${e}" by command_option_policies`,l.USAGE);for(let c of s.required)if(!a.has(sh(c,e)))throw new d(`Missing required option ${be("update",c)} for type "${e}"`,l.USAGE)}var TE=new Set(["order","rank"]),CE=ca.filter(e=>!TE.has(e)),gh=["tags","closeReason",...CE],RE=["title","description","body","status","closeReason","completedAt","priority","type",...ca,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],IE=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>re(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>xn(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"}],OE=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Te(Ui(e),hn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>ji(e)}],xE=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Te(Gi(e),gn,"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=>qi(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Fc(e,t,n){for(let r of e){let o=t[r.optionKey],i=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!i)){if(i){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new d(`${be("update",String(r.optionKey))} must be a string value`,l.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function PE(e){return mh(await mi(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 Dc(e){return ht(e)?await PE(e):mh(e)}function LE(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 Nc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new d(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,l.USAGE);if(e.enabled&&e.clearEnabled)throw new d(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,l.USAGE)}function Uc(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new d("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",l.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 d("--replace-deps requires at least one --dep entry",l.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new d("--replace-deps cannot be combined with --dep-remove",l.USAGE);Nc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Nc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Nc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function NE(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 d(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,l.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function ME(e){let t={};for(let n of gh)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function FE(e,t){let n=ME(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=us.get(r)??r;throw new d(`Cannot combine --unset ${i} with ${be("update",r)}`,l.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new d("Cannot combine --unset acceptance-criteria with --add-ac",l.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new d("Cannot combine --unset acceptance-criteria with --remove-ac",l.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new d("Cannot combine --unset tags with --add-tags",l.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new d("Cannot combine --unset tags with --remove-tags",l.USAGE)}}function $E(e){let t=(n,r)=>{let o=us.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;zi(n,be("update",r),i)};for(let n of gh)t(e[n],String(n));t(e.order??e.rank,"order"),Ae(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Ae(e.event,"--event","Use --clear-events to clear linked events.")}function DE(e,t){let n={};for(let r of RE)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.runtimeFields=Object.keys(t).length>0,n}async function UE(e){let t=await q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await oe(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function GE(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return _e(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function jE(e){e.before&&wi(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>te(t,e.statusRegistry),Dt())}function qE(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new d("--order and --rank must match when both are provided",l.USAGE)}async function KE(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=vi(_i(e.options.parent),e.settings.id_prefix);if(Bo(t))return{resolvedParentValue:t,warnings:[]};if(gi(e.id,t,e.settings.id_prefix),await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=Ge(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:hi(r,e.parentReferencePolicy).warnings}}function zE(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function BE(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await q(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await _t(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await oe(t,{schema:e.settings.schema}),r=e.options.type!==void 0?we(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=uE({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function HE(e){if(!e.fieldFlags.status||Z(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],o=[];if(n.length>0){let a=Se(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),c=await nt(e.id,a,e.global);o=c.changed_fields,r.push(...c.warnings)}let i=await yt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),s=[...e.workflowTransitionWarnings,...r,...i.warnings,"auto_routed_from_update_to_close"];return{item:i.item,changed_fields:[...o,...i.changed_fields],warnings:s}}function VE(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Lc(t.title,"--title"),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),Z(e.metadata.status,n)??e.metadata.status}var WE=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function YE(e,t){for(let n of WE)e[n]!==void 0&&(delete e[n],t.push(n))}function JE(e,t,n,r,o){let i=mE(n,t.statusRegistry);if(e.metadata.status=i,o.push("status"),i===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!te(i,t.statusRegistry)&&te(r,t.statusRegistry)&&YE(e.metadata,o)}function XE(e,t,n,r){if(t.options.status!==void 0&&JE(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!te(e.metadata.status,t.statusRegistry))throw new d("--completed-at can only be set on a terminal item",l.USAGE);e.metadata.completed_at=re(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function QE(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new d("--close-reason must not be empty",l.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&te(n,t.statusRegistry)&&!te(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function ZE(e,t,n,r){XE(e,t,n,r),QE(e,t,n,r)}function eA(e,t,n){let r=we(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=Pn(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=we(t.options.type,t.typeRegistry);if(!o)throw new d(Ot(t.options.type,t.typeRegistry.types,xt(t.pmRoot,t.settings.schema)),l.USAGE);e.metadata.type=o,r=o,n.push("type")}return AE(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),tA(e,t,r,n),r}function tA(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let i=Wi(t.options.typeOption??[]),s=Zn(n,i,t.typeRegistry);if(s.errors.length>0)throw new d(s.errors.join("; "),l.USAGE);e.metadata.type_options=s.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let o=Zn(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new d(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,l.USAGE);e.metadata.type_options=o.normalized}function nA(e,t){let n=new Set(t.map(o=>ps(o))),r=new Set;return e.filter(o=>{if(!n.has(ps(o)))return!0;let i=gE(o);return r.has(i)?!1:(r.add(i),!0)})}function rA(e,t,n){let r=t.filter(o=>!e.some(i=>hh(i,o)));if(r.length!==0)throw new d(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,l.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function oA(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=nA(r,t.dependencyUpdates.additions);let o=new Set(r.map(i=>ps(i)));for(let i of t.dependencyUpdates.additions){let s=ps(i);o.has(s)||(r.push(i),o.add(s))}}t.dependencyRemovals.length>0&&(rA(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(i=>hh(o,i)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function iA(e,t,n){Mc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Mc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Mc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Mc(e,t,n,r,o,i){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],i.push(t))}function sA(e,t,n){ah(e,"files",t.options.file,t.fileUpdates.values,bE,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),aA(e,t,n),ah(e,"docs",t.options.doc,t.docUpdates.values,kE,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function ah(e,t,n,r,o,i,s,a){if(!(n===void 0&&!s.has(t))){if(i)e.metadata[t]=r;else if(s.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(u=>o(u)));for(let u of r){let p=o(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function aA(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=ch(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=ch([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function ch(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=SE(r);n.has(o)||(t.push(r),n.add(o))}return t}function cA(e,t,n){let r=t.options.addTags,o=t.options.removeTags,i=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||i){let s=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Ft(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=li(On(s,r),o),n.changedFields.push("tags")}Fc(IE,t.options,n),dA(e,t,n.changedFields)}function lA(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let i=ci(In(e.metadata.acceptance_criteria),r,o);if(i.unmatchedRemovals.length>0)throw new d(`Acceptance criteria removal did not match: ${i.unmatchedRemovals.join(", ")}`,l.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:i.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let s=i.criteria.join("; ");e.metadata.acceptance_criteria!==s&&(s===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=s,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function dA(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=he(r??"","order");if(!Number.isInteger(o))throw new d("Order must be an integer",l.USAGE);e.metadata.order=o}n.push("order")}}function mA(e,t,n,r){uA(e,t,n.changedFields),pA(e,t,n.changedFields),Fc(OE,t.options,n),lh(e,t,"sprint",r,n.changedFields),lh(e,t,"release",r,n.changedFields),fA(e,t,n.changedFields),Fc(xE,t.options,n)}function uA(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 d("--assignee must not be empty. Use --unset assignee to clear it.",l.USAGE);e.metadata.assignee=r}n.push("assignee")}}function pA(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 lh(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let i=yi(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=i.value,r.push(...i.warnings)}o.push(n)}}function fA(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&wE(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function _A(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Hi(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=Vi(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function hA(e,t,n){dh(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),dh(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,i]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let s=o.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===o)?.cli_flag??s;throw new d(`Cannot combine --unset ${s} with --${c}`,l.USAGE)}mt(e[o],i)||(e[o]=i,n.push(o))}let r=so(t.options.field,t.extensionRegistrations);for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new d(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,l.USAGE);for(let[o,i]of Object.entries(r))mt(e[o],i)||(e[o]=i,n.push(o))}function dh(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function gA(e,t){let n=structuredClone(e.metadata),r=e.body,o=[],i=[],s=VE(e,t.options,t.statusRegistry,o),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};ZE(e,t,s,o),eA(e,t,o),oA(e,t,o),iA(e,t,o),sA(e,t,o),cA(e,t,c),lA(e,t,c),mA(e,t,c,i),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&xr(e.metadata.id,e.metadata.dependencies),Z(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),_A(e,t,o),hA(a,t,o);try{ao(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(p){throw new d(p instanceof Error?p.message:"Invalid extension item field values",l.USAGE)}let m=e.metadata,u=[...new Set(o)].filter(p=>p==="body"?e.body!==r:!mt(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&i.push(`acceptance_criteria_replaced:${In(n.acceptance_criteria).length}:${In(m.acceptance_criteria).length}`),{changedFields:u,warnings:i}}async function yh(e,t,n,r={}){t=await Dc(t);let o=E(process.cwd(),n.path);await R(o);let i=await A(o),s=F(i.schema),a=Qe(i.schema),c=O(),m=Ct(c),u=x(i,c),p=i.governance.workflow_enforcement??"off",f=p==="off"?[]:lu(i.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][i.validation.parent_reference],g=uh(t.unset,a,m),y=new Set(g.optionKeys),h=new Set(g.metadataKeys);Uc(t),NE({definitions:LE(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:h}),dE(e,t,h),FE(t,g),$E(t);let v=C(t.author,i.author_default),b=new Date,S=b.toISOString(),T=fs(t.dep,i.id_prefix,S,v);xr(e,T.additions);let I=await nn({pmRoot:o,dependencies:T.additions,idPrefix:i.id_prefix,itemFormat:i.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:i.schema}),D=hE(t.depRemove,i.id_prefix),M=dn("--comment",t.comment,S,v),Y=t.ownershipMetadataBypass===!0&&M.values?{...M,values:M.values.map(De=>({...De,author:v}))}:M,z=dn("--note",t.note,S,v),K=dn("--learning",t.learning,S,v),pe=Oc(t.file),ae=xc(t.test);ae.values=await $n(ae.values,v,S);let j=Pc(t.doc),ce=[],st=await KE({id:e,options:t,unsetTargets:g,pmRoot:o,settings:i,typeRegistry:u,parentReferencePolicy:_}),Ye=await vE(t.blockedBy,h.has("blocked_by"),o,i.id_prefix,i.item_format,u.type_to_folder),Jn=Ye.id,zs=[...st.warnings,...zE(Ye)],Xn=ei(t,a,t.runtimeFieldCommands),zt=DE(t,Xn);if(!Object.values(zt).some(Boolean))return UE({pmRoot:o,id:e,settings:i,typeRegistry:u});ce.push(...await BE({options:t,fieldFlags:zt,workflowEnforcement:p,typeWorkflows:f,statusRegistry:s,typeRegistry:u,pmRoot:o,id:e,settings:i}));let Ie=await HE({options:t,fieldFlags:zt,statusRegistry:s,workflowTransitionWarnings:ce,global:n,id:e});if(Ie)return Ie;qE(t);let Et=Dt(),Bs=zt.parent&&!h.has("parent")||T.additions.some(De=>Et.resolve(De.kind)?.hierarchy),P=await Yi({pmRoot:o,author:v,ttlSeconds:i.locks.ttl_seconds,waitMs:i.locks.wait_ms,required:Bs});try{let De=await GE({fieldFlags:zt,clearedMetadataKeys:h,pmRoot:o,settings:i,typeToFolder:u.type_to_folder}),at,Qr,At=await Tp({pmRoot:o,settings:i,typeToFolder:u.type_to_folder,id:e,op:yA(t,r),author:v,message:t.message,resolveHistoryContext:()=>Qr,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(Je){at=vA({document:Je,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:s}),Qr=at?{recurrence:at}:void 0,De=De?.map(Zr=>Zr.id===Je.metadata.id?structuredClone(Je.metadata):Zr);let Vs=gA(Je,{options:t,settings:i,typeRegistry:u,statusRegistry:s,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:h,dependencyUpdates:T,dependencyRemovals:D,commentUpdates:Y,noteUpdates:z,learningUpdates:K,fileUpdates:pe,testUpdates:ae,docUpdates:j,resolvedParentValue:st.resolvedParentValue,resolvedBlockedByDependencyId:Jn,runtimeFieldUpdates:Xn,nowValue:b,nowIso:S,author:v,pmRoot:o});return jE({before:De,document:Je,statusRegistry:s}),Vs}});await P();let Hs=De?Pi(De,De.map(Je=>Je.id===At.item.id?At.item:Je),At.item.id):[];return{item:At.item,changed_fields:At.changedFields,warnings:[...ce,...zs,...I,...Hs,...At.warnings],...at===void 0?{}:{lifecycle_transition:at}}}finally{await P()}}function yA(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function vA(e){if(e.recurrenceReason===void 0)return;let t=Z(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!te(t,e.statusRegistry))throw new d(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,l.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=Z(n,e.statusRegistry)??n,o=e.document.metadata,i=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(s=>{let a=o[s];return typeof a=="string"?[[s,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:i}}async function nt(e,t,n){return yh(e,t,n)}async function vh(e,t,n,r){let o=await yh(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new d(`Item ${e} did not produce the required recurrence receipt.`,l.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="961c1918-75f9-5e5d-bbae-b333ca29534f")}catch{}})();function _s(e){return qo("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ddc9a23d-28fe-54d4-a0a5-e9461ac47dd2")}catch{}})();async function Nr(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new d("--start requires an explicit item id and cannot be combined with --next or --if-available",l.USAGE);let r=await A(E(process.cwd(),n.path)),o=_s(F(r.schema)),i=await Rr(e,t.force===!0,n,t),s=await nt(e,je(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts"]),n);return{id:e,action:"start_task",claim:i,update:s}}async function Gc(e,t,n){let r=await A(E(process.cwd(),n.path)),o=F(r.schema).open_status,i=await nt(e,je(t,{status:o},["assignee","pause"]),n),s=await Ir(e,t.force===!0,n,t);return{id:e,action:"pause_task",update:i,release:s}}async function Mr(e,t,n,r){let o=await yt(e,t,n,r),i=await Ir(e,n.force===!0,r,n);return{id:e,action:"close_task",close:o,release:i}}import wA from"fast-json-patch";import jc from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="85aa928d-92b8-5f67-8482-0fe5715fef45")}catch{}})();async function wh(e,t,n){let r=await Ep(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:bh(n),recovered:!0}}function bA(e,t){return Rp(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function bh(e){let t=Ga(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Ze(et(t))}async function kA(e,t,n,r){let o=await Zt(e,t,n,r),i=o.located?await bp({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function SA(e,t){let n=mr(e),r=mr(t),o=wA.compare(n,r),i=new Set;for(let s of o){if(s.path==="/body"||s.path.startsWith("/body/")){i.add("body");continue}let a=s.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((s,a)=>s.localeCompare(a))}async function EA(e){let t=await Kf({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>wh(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function AA(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:bh(t),originalRaw:null}}function TA(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new d(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,l.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function CA(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await ee(e.existingItemPath,e.resolvedOriginalRaw),await jc.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await ee(e.existingItemPath,e.resolvedOriginalRaw);return}await jc.rm(e.restoredItemPath,{force:!0})}async function RA(e){return[...await W({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await W({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function mn(e,t,n,r){let o=E(process.cwd(),r.path);await R(o);let i=await A(o),s=x(i,O()),a=await kA(o,e,i,s.type_to_folder),c=a.id,{raw:m,entries:u}=await op(a.historyPath,c);if(u.length===0)throw new d(`No history exists for ${c}; restore is unavailable.`,l.NOT_FOUND);let p=bA(t,u),f=Ip(Ga(u,p.historyIndex),p),_=_p(f,{schema:i.schema});if(_.metadata.id!==c)throw new d(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,l.GENERIC_FAILURE);let y=(a.located?await wh(a.located,i,u):null)?.raw??null,h=C(n.author,i.author_default),v=await ke(o,c,i.locks.ttl_seconds,h,!!n.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let{loadedItemUnderLock:b,existingItemPath:S}=await EA({pmRoot:o,subject:a,settings:i,typeRegistry:s,historyRawBeforeLock:m,currentItemRawBeforeLock:y,history:u}),T="toon",I=AA(b,u),D=TA({document:I.document,author:h,force:n.force,enforcement:i.governance.ownership_enforcement,resolvedId:c}),M=SA(I.document,_),Y=await ur({pmRoot:o,settings:i,operation:"restore",author:h,before:I.document,after:_});await Wo({pm_root:o,operation:"restore",before:I.document,after:_,changed_fields:M,sdk:ni({pmRoot:o,settings:i,typeToFolder:s.type_to_folder})});let z=ze(_,{format:T,schema:i.schema}),K=dt(o,_.metadata.type,c,T,s.type_to_folder),pe=await Nt(o,h),ae=[];try{await ee(K,z),S&&K!==S&&await jc.rm(S);let Ye=Oe({nowIso:k(),author:h,op:"restore",before:I.document,after:_,message:n.message,context:Y.decisions.length===0?void 0:{workflow_policies:Y.decisions}});try{await Pt(a.historyPath,Ye)}catch(Jn){throw await CA({existingItemPath:S,resolvedOriginalRaw:I.originalRaw,restoredItemPath:K}),Jn}ae=await Mt({pmRoot:o,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:K,previousItemPath:S??void 0,document:_})}finally{await pe()}let j=await RA({restoredItemPath:K,historyPath:a.historyPath,before:I.document,after:_});kn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:I.document.metadata.status,status:_.metadata.status,previous:Qt(I.document.metadata,M),current:Qt(_.metadata,M),changed_fields:M});let ce=u[p.historyIndex],st=Cn(u,!0);return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,version:st===null?null:st+p.historyIndex+1,entry_ts:ce.ts,entry_op:ce.op},changed_fields:M,warnings:[...Y.warnings,...b?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...D,...ae,...j]}}finally{await v()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aec6f8e2-5fd0-53f3-8262-c6b49741ff96")}catch{}})();var Sh=1,qc="close-many",IA=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function OA(e,t){return kr(e,t,{includePagination:!1})}function xA(e,t){return kr(e,t)}function PA(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new d("--ids requires at least one non-empty item ID",l.USAGE)}function LA(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function NA(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new d("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",l.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function MA(e,t){let n=F(t.schema),r=x(t,O()),o=await _e(e,t.item_format,r.type_to_folder,void 0,t.schema),i=new Map,s=new Map;for(let a of o){if(typeof a.parent!="string"||a.parent.length===0||(s.set(a.id,a.parent),te(a.status,n)))continue;let c=i.get(a.parent);c?c.push(a.id):i.set(a.parent,[a.id])}for(let a of i.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:i,parentByChild:s}}function kh(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,i=t.get(e),s=[],a=new Set,c=!1;for(;i!==void 0&&!a.has(i);){let m=n?.get(i);if(m!==void 0){o+=m+1;break}a.add(i),s.push(i),o+=1,i=t.get(i)}if(i!==void 0&&a.has(i)&&(c=!0),!c){n?.set(e,o);for(let[m,u]of s.entries())n?.set(u,o-m-1)}return o}async function FA(e){let t=await ii(e.pmRoot,qc,e.rollbackId,Sh),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await si(t.items,(o,i)=>mn(o,i,{author:e.options.author,message:n,force:!0},e.global));return{...Xt({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function $A(e,t,n,r,o){return e.map(i=>{let s=(t.get(i.id)??[]).filter(c=>!n.has(c)),a=!Eh(i,r,o);return{id:i.id,title:typeof i.title=="string"?i.title:"",status:i.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...s.length>0?{active_child_ids:s}:{}}})}async function DA(e){let t=await oi(e.pmRoot,qc,e.checkpointId,{schema_version:Sh,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function UA(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await yt(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){t.push({id:r.id,status:"failed",error:wn(o)})}}return{rows:t,closedIds:n}}function GA(e){return typeof e.rollback=="string"?e.rollback:void 0}function jA(e,t){if(t.trim().length===0)throw new d("--rollback requires a checkpoint id",l.USAGE);if(e.dryRun===!0)throw new d("--dry-run cannot be combined with --rollback",l.USAGE);if(xA(e.list,e.status))throw new d("Rollback mode does not accept filter options",l.USAGE)}function qA(e){if(!OA(e.list,e.status))throw new d(`close-many requires at least one filter to scope the close (for example: ${IA}). Refusing to match every item.`,l.USAGE)}function KA(e,t){let n=new Map;return[...e].sort((r,o)=>{let i=kh(o.id,t,n)-kh(r.id,t,n);return i!==0?i:r.id.localeCompare(o.id)})}function Eh(e,t,n){return n||!te(e.status,t)}function zA(e,t,n){return new Set(e.filter(r=>Eh(r,t,n)).map(r=>r.id))}async function BA(e){qA(e.options);let t=F(e.settings.schema),n=NA(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await gt(e.options.status,LA(e.options.list),e.global),{childrenByParent:i,parentByChild:s}=await MA(e.pmRoot,e.settings),a=KA(o.items,s),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],m=c.length===0?[]:(await gt(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,u=new Set(m.map(f=>f.id)),p=zA(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!u.has(f)),planRows:$A(a,i,p,t,r)}}function HA(e){return{outcome:"effect",exit_code:l.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function VA(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return DA({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function Ah(e,t){let n=E(process.cwd(),t.path);await R(n);let r=await A(n),o=e.dryRun===!0,i=GA(e);if(PA(e.list),i!==void 0)return jA(e,i),FA({pmRoot:n,rollbackId:i,options:e,global:t});let s=await BA({pmRoot:n,settings:r,options:e,global:t});if(o)return HA(s);let a=new Set(s.planRows.filter(v=>v.action==="close").map(v=>v.id)),c=k(),m=ri(qc,c),u=await VA({context:s,options:e,closableIds:a,checkpointId:m,nowValue:c}),p={author:e.author,message:e.message??`close-many apply ${m}`,completedAt:e.completedAt,validateClose:s.validateCloseMode,force:s.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await UA({matched:s.matched,closableIds:a,reason:s.reason,closeOptions:p,global:t}),g=f.filter(v=>v.status==="closed").length,y=f.filter(v=>v.status==="skipped").length,h=f.filter(v=>v.status==="failed").length;return{...Xt({applied:g,skipped:y,failed:h,unmatched:s.unmatchedIds?.length??0}),mode:"apply",matched_count:s.matched.length,dry_run:!1,...s.reason!==void 0?{reason:s.reason}:{},filters:s.listed.filters,...s.validateCloseMode?{validate_close:s.validateCloseMode}:{},...u?{checkpoint:u}:{},closed_count:g,skipped_count:y,failed_count:h,rows:f,ids:_,...s.unmatchedIds!==void 0?{unmatched_ids:s.unmatchedIds,unmatched_count:s.unmatchedIds.length}:{}}}import{readFile as WA}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="29e1738e-026c-5714-b279-30e45951d256")}catch{}})();async function Kc(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",i=Number(n)+Number(r)+Number(o);if(i===0)return;if(i>1)throw new d("Specify comment text using only one input source: --add, --stdin, or --file",l.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",ht(e))??"",emptyFlag:"--add"};if(r)return Cr(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let s=e.file.trim();if(!s)throw new d("--file path cannot be empty",l.USAGE);if(s==="-")return Cr(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await WA(s,"utf8"),emptyFlag:"--file"}}catch(a){if(vc(a)&&Vt(a))throw new d(`--file path not found: ${s}. Use --file - to read stdin.`,l.USAGE);let c=a instanceof Error?a.message:String(a);throw new d(`Failed to read --file path "${s}": ${c}. Use --file - to read stdin.`,l.USAGE)}}async function YA(e,t){let n=e.edit,r=e.delete,o=n!==void 0,i=r!==void 0;if(o&&i)throw new d("Specify only one of --edit or --delete",l.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new d("--edit must be a positive integer",l.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new d("--delete must be a positive integer",l.USAGE);if(i){if(await Kc(e,t)!==void 0)throw new d("--delete does not take comment text",l.USAGE);return{mode:"delete",index:r}}if(o){let c=await Kc(e,t);if(c===void 0)throw new d("--edit requires replacement text via positional [text], --add, --stdin, or --file",l.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let s=await Kc(e,t);return s===void 0?{mode:"list"}:{mode:s.emptyFlag==="--add"?"add":s.emptyFlag==="--stdin"?"stdin":"file",value:s.value,emptyFlag:s.emptyFlag}}async function Th(e,t,n){let r=$t(),o=await YA(t,r),i=o.mode==="add"||o.mode==="edit",s=o.value??"";return Gn(e,t,n,{input:{...o,rawValue:t.add??s,value:i?Un(s,{stripPlainTextPrefix:!0}):s},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm comments pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="99f91321-fd91-5ec6-8d09-1493f40dacb1")}catch{}})();async function Ch(e,t,n){return Gn(e,t,n,{input:await Di(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Un(r),createEntry:r=>r,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm learnings pm-a1b2 --add "review learning" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eab6a65d-8f97-593e-8609-6ae452b1c5aa")}catch{}})();function JA(e){if(e===void 0)return;if(e.trim().length===0)throw new d("--add-json must contain a JSON value",l.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new d("--add-json must be valid JSON",l.USAGE,{code:"structured_event_json_invalid"})}return t}function XA(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function QA(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new d("--since must be a valid ISO timestamp",l.USAGE,{code:"structured_event_since_invalid"});return t}async function Rh(e,t,n){let r=JA(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new d("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",l.USAGE,{code:"structured_event_input_conflict"});let i=r===void 0?void 0:Wt(r),s=[t.since,t.eventType].some(g=>g!==void 0),a=QA(t.since),c=_r(t.limit),m=await Gn(e,{...t,...s?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,s].includes(!0)},n,{input:await Di(i===void 0?t:{add:i},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:g=>Un(g),createEntry:g=>r===void 0?g:{...g,format:"json",data:r,event_type:XA(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm notes pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}}),u=t.eventType?.trim(),p=m.notes.filter(g=>{let y=[g.format==="json",g.data!==void 0].every(Boolean),h=[a===void 0,Date.parse(g.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),v=[!u,g.event_type===u].includes(!0);return[!s,[y,h,v].every(Boolean)].includes(!0)}),f=s?yc(p,c):p,_=f.filter(g=>g.format==="json").length;return{...m,notes:f,count:f.length,...s?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ef785ae-bb1e-59dd-993c-3be56ddc26c2")}catch{}})();var Oh=1,Bc="update-many",ZA=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),eT=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),tT={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},nT=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],rT={close_reason:"close_reason","close-reason":"close_reason",deadline:"deadline",estimate:"estimated_minutes",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",ac:"acceptance_criteria",definition_of_ready:"definition_of_ready","definition-of-ready":"definition_of_ready",order:"order",rank:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",why_now:"why_now","why-now":"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blocked_by:"blocked_by","blocked-by":"blocked_by",blocked_reason:"blocked_reason","blocked-reason":"blocked_reason",unblock_note:"unblock_note","unblock-note":"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",repro_steps:"repro_steps","repro-steps":"repro_steps",resolution:"resolution",expected_result:"expected_result","expected-result":"expected_result",actual_result:"actual_result","actual-result":"actual_result",affected_version:"affected_version","affected-version":"affected_version",fixed_version:"fixed_version","fixed-version":"fixed_version",component:"component",regression:"regression",customer_impact:"customer_impact","customer-impact":"customer_impact",type_options:"type_options","type-options":"type_options",tags:"tags"},xh=e=>{let t={};for(let[n,r]of Object.entries(e))ZA.has(n)||r!==void 0&&(t[n]=r);return t},oT=e=>Object.keys(xh(e)).length>0,Ph=e=>typeof e=="string"?e.trim():e,iT=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},zc=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},sT=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Ph(e)},aT={priority:iT,estimatedMinutes:zc,order:zc,rank:zc,regression:sT},cT=(e,t)=>{if(t!==void 0)return(aT[e]??Ph)(t)},lT=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return rT[t]??t},hs=(e,t)=>mt(e,t),dT=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],mT=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,uT=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",Ih=(e,t)=>t===void 0?void 0:e[t],Kn=e=>Array.isArray(e)?e.length:0,pT=(e,t,n)=>{let r=n[e.addKey],o=Ih(n,e.removeKey),i=Kn(r),s=Kn(o),a=n[e.clearKey]===!0,c=Ih(n,e.replaceKey)===!0;if(![a,c,i>0,s>0].includes(!0))return;let m=dT(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:uT({replace:c,clear:a,removeCount:s}),clear:a,replace:c,add_count:i,remove_count:s,before_count:mT(e.field,m)}}},fT=(e,t)=>{let n=[];for(let r of nT){let o=pT(r,e,t);o!==void 0&&n.push(o)}return n},_T=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],hT=(e,t)=>{if(![t.tags!==void 0,Kn(t.addTags)>0,Kn(t.removeTags)>0].includes(!0))return;let n=_T(e.tags),r=t.tags===void 0?n:Ft(t.tags),o=On(r,t.addTags),i=li(o,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),s=n.slice().sort((a,c)=>a.localeCompare(c));if(!hs(s,i))return{field:"tags",before:n,after:i}},gT=(e,t)=>{let n=e.acceptance_criteria,r=ci(In(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new d(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,l.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let o=r.criteria.join("; ");if(!hs(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},yT=(e,t,n)=>{for(let[r,o]of Object.entries(tT)){let i=n[r];if(i===void 0)continue;let s=t[o],a=cT(r,i);hs(s,a)||e.push({field:o,before:s,after:a})}},vT=(e,t,n,r)=>{let o=ei(n,r,["update_many"]);for(let[i,s]of Object.entries(o)){let a=t[i];hs(a,s)||e.push({field:i,before:a,after:s})}},wT=(e,t,n)=>{for(let r of n??[]){let o=lT(r),i=t[o];i!==void 0&&e.push({field:o,before:i,after:null})}},bT=(e,t,n={})=>{let r=e,o=[],i=hT(r,n);if(i&&o.push(i),yT(o,r,n),Kn(n.addAc)>0||Kn(n.removeAc)>0){let s=gT(r,n);s!==void 0&&o.push(s)}return o.push(...fT(r,n)),vT(o,r,n,t),wT(o,r,n.unset),{id:e.id,changes:o}},kT=(e,t)=>Dp(e,t,{strict:!0,flagLabel:"--filter-status"}),ST=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new d("--ids requires at least one non-empty item ID",l.USAGE)},ET=[({update:e})=>{e.priority!==void 0&&Pn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,O());if(!we(e.type,r))throw new d(Ot(e.type,r.types,xt(n,t.schema)),l.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!Z(e.status,t)){let n=t.definitions.map(r=>r.id);throw new d(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,l.USAGE)}},({update:e})=>{e.deadline!==void 0&&re(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&xn(e.estimatedMinutes,"estimated-minutes")}],AT=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let i of ET)i(o)},TT=async e=>{let t=await ii(e.pmRoot,Bc,e.rollbackId,Oh),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await si(t.items,(o,i)=>mn(o,i,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...Xt({applied:r.restored_ids.length,skipped:0,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:r.restored_ids.length,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},CT=async e=>{let t={schema_version:Oh,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await oi(e.pmRoot,Bc,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},RT=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},Hc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},IT=async e=>{let t=E(process.cwd(),e.path);await R(t);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:F(n.schema),runtimeFieldRegistry:Qe(n.schema)}},OT=e=>{if(e.options.dryRun===!0)throw new d("--dry-run cannot be combined with --rollback",l.USAGE);if(kr(e.options.list,e.options.status))throw new d("Rollback mode does not accept filter options",l.USAGE);if(Object.keys(e.updateSummary).length>0)throw new d("Rollback mode does not accept update mutation flags",l.USAGE);return TT({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},xT=async e=>{kT(e.options.status,e.runtime.statusRegistry);let t=await gt(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let i=bT(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?i:{...i,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await gt(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:RT(e.options.list?.ids,r)}},PT=e=>({outcome:"effect",exit_code:l.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...Hc(e)}),LT=e=>({...Xt({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...Hc(e)}),NT=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(i=>i.changes.length>0).map(i=>i.id));for(let i of e.items){if(!o.has(i.id)){t.push({id:i.id,status:"skipped"});continue}try{let s=qa({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),a=await nt(i.id,s,e.global);t.push({id:i.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(i.id)}catch(s){t.push({id:i.id,status:"failed",error:wn(s)})}}return{rows:t,updatedIds:n}},MT=async e=>{if(e.plan.actionable.length===0)return LT(e.plan);let t=k(),n=ri(Bc,t),r=new Set(e.plan.actionable.map(p=>p.id)),o=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),i=e.options.checkpoint===!1?void 0:await CT({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),s=await NT({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=p=>s.rows.filter(f=>f.status===p).length,c=a("updated"),m=a("skipped"),u=a("failed");return{...Xt({applied:c,skipped:m,failed:u,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...i?{checkpoint:i}:{},updated_count:c,skipped_count:m,failed_count:u,rows:s.rows,ids:s.updatedIds,...Hc(e.plan)}},Lh=async(e,t)=>{let n=await IT(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:qa(await Dc(e.update))});let o=xh(e.update);if(ST(e.list),r!==void 0)return OT({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!oT(e.update)&&e.dryRun!==!0)throw new d(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${eT}), or pass --dry-run for a filter-only preview.`,l.USAGE);AT(e.update,n.settings,n.statusRegistry,n.pmRoot),Uc(e.update);let i=await nn({pmRoot:n.pmRoot,dependencies:fs(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,O()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),s=await xT({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:i});return await nn({pmRoot:n.pmRoot,dependencies:fs(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,O()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:s.listed.items.map(a=>({id:a.id,createdAt:a.created_at})),schema:n.settings.schema}),e.dryRun===!0?PT(s):MT({runtime:n,options:e,global:t,plan:s})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="374c7cb8-9fd0-5a2d-8aaf-9d09b63abaf0")}catch{}})();var FT=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Nh=["brief","standard","deep"],$h="plan-step-",Qc="draft",Xc=["bug-investigation","feature-implementation","refactoring-sprint"],Mh={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function $T(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(Mh,t)?Mh[t]:void 0;if(!n)throw new d(`Unknown plan template "${e}". Allowed: ${Xc.join(", ")}`,l.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Xc[0]}`]});return n.map(r=>({...r}))}function DT(e,t){return t>0?Math.round(e/t*100):0}function Dh(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function Ke(e){return Array.isArray(e)?e.flatMap(t=>Ln(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Ln(e,{unique:!1}):[]}function Ce(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function Uh(e,t=Qc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=na.find(o=>o===n);if(!r)throw new d(`Invalid plan mode "${e}". Allowed: ${na.join(", ")}`,l.USAGE);return r}function Zc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ra.find(o=>o===n);if(!r)throw new d(`Invalid step status "${e}". Allowed: ${ra.join(", ")}`,l.USAGE);return r}function Gh(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ia.find(o=>o===n);if(!r)throw new d(`Invalid step link kind "${e}". Allowed: ${ia.join(", ")}`,l.USAGE);return r}function UT(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=oa.find(r=>r===t);if(!n)throw new d(`Invalid plan harness "${e}". Allowed: ${oa.join(", ")}`,l.USAGE);return n}function GT(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=Nh.find(r=>r===t);if(!n)throw new d(`Invalid --depth "${e}". Allowed: ${Nh.join(", ")}`,l.USAGE);return n}function jT(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new d("Plan --fields requires a comma-separated list of plan field names",l.USAGE);return t}var Vc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function qT(e,t){let n=e,r={},o=[];for(let i of t){let s=i.startsWith("plan.")?i.slice(5):i;if(s.length!==0){if(!Vc.has(s)){o.push(i);continue}Object.prototype.hasOwnProperty.call(n,s)&&(r[s]=n[s])}}if(o.length>0)throw new d(`Unknown Plan --fields value(s): ${o.join(", ")}`,l.USAGE,{nextSteps:[`Use --fields ${[...Vc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...Vc].join(",")}`}});return r}function el(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let i=o.indexOf("=");if(i<=0)throw new d(`Invalid ${t} entry "${o}"; expected key=value`,l.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[o.slice(0,i).trim().toLowerCase()]=o.slice(i+1).trim()}return n}function tl(e){let t=el(e,"--file");if(!t.path)throw new d("--file requires path=<value>",l.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function nl(e){let t=el(e,"--test");if(!t.command&&!t.path)throw new d("--test requires at least command=<value> or path=<value>",l.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function rl(e){let t=el(e,"--doc");if(!t.path)throw new d("--doc requires path=<value>",l.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function KT(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=DT(t.completed,t.total),t}function zT(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${$h}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new d("Could not allocate step id (limit reached)",l.GENERIC_FAILURE)}function zn(e,t){let n=t.trim();if(n.length===0)throw new d("Step reference cannot be empty",l.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),i=e.find(s=>s.order===o);if(i)return i}throw new d(`Step "${t}" not found in plan`,l.NOT_FOUND)}function Fh(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function BT(e,t){let n=t.filter(s=>s.trim().toLowerCase()==="all"),r=[],o=[];if(n.length>0){if(t.length>n.length)throw new d("pm plan materialize --steps all cannot be combined with other step refs",l.USAGE);for(let s of e.slice().sort((a,c)=>a.order-c.order)){let a=Fh(s);if(a){o.push({from_step:s.id,...a});continue}r.push(s)}return{targets:r,skipped:o}}let i=new Set;for(let s of t){let a=zn(e,s);if(i.has(a.id))continue;i.add(a.id);let c=Fh(a);if(c){o.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:o}}function HT(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function VT(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function WT(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function Ne(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((s,a)=>s.order-a.order),r=KT(n),o=VT(n),i={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Qc,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:WT(n),linked_items:(e.dependencies??[]).map(s=>({id:s.id,kind:s.kind}))};return(t==="standard"||t==="deep")&&(i.steps=n),t==="deep"&&(i.decisions=e.plan_decisions??[],i.discoveries=e.plan_discoveries??[],i.validation=e.plan_validation??[]),i}function Me(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!za(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function jh(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new d(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,l.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function YT(e){let t=E(process.cwd(),e.path);await R(t);let n=await A(t);return{pmRoot:t,settings:n}}async function qh(e,t){let n=x(e.settings,O()),r=await q(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new d(`Plan ${t} not found`,l.NOT_FOUND);let o=await oe(r,{schema:e.settings.schema});return jh(o.document.metadata),{document:o.document,itemId:r.id}}function JT(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of Ke(e.related))t.push(`id=${n},kind=related`);for(let n of Ke(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of Ke(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function XT(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function QT(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||Ke(e.dependsOn).length>0||Ke(e.link).length>0}function ZT(e){let t=e.stepTitle?.trim()||void 0,n=Dh(e.step),r=e.template?.trim()?$T(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function eC(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new d("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",l.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${Xc[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new d("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",l.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function tC(e,t){let n=Zc(e.stepStatus,"pending"),r=ol(e,"depends_on"),o=Ce(e.file).map(tl),i=Ce(e.test).map(nl),s=Ce(e.doc).map(rl),a=k();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function nC(e){let t=ZT(e),n=QT(e);if(eC(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[tC(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=k();return{steps:t.stepTitles.map((o,i)=>({id:`${$h}${String(i+1).padStart(3,"0")}`,order:i+1,title:o,body:t.templateSteps[i]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function Kh(e,t,n=[]){Se(e,t),n.length>0&&Mp(t,n)}async function rC(e,t,n){let r=e.title?.trim();if(!r)throw new d("pm plan create requires --title",l.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let o=Uh(e.mode,Qc),i=UT(e.harness),s=e.fromSearch?.trim(),a=XT(e),{steps:c,hasPerStepDetailOptions:m}=nC(e);if(c.length===0&&m)throw new d("pm plan create step options require --step-title (or a single --step)",l.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:Ce(e.file),test:Ce(e.test),doc:Ce(e.doc),field:Ce(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:JT(e),message:e.message??(s?`plan create (search: ${s})`:"plan create")};Kh(e,f);let _=await Gt(f,t),g=await ie({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(h){let v=["plan_mode"];h.metadata.plan_mode=o,i&&(h.metadata.plan_harness=i,v.push("plan_harness"));let b=e.scope?.trim();b&&(h.metadata.plan_scope=b,v.push("plan_scope"));let S=e.resumeContext?.trim();return S&&(h.metadata.plan_resume_context=S,v.push("plan_resume_context")),h.metadata.plan_steps=c,v.push("plan_steps"),a&&(h.metadata.plan_validation=[...h.metadata.plan_validation??[],a],v.push("plan_validation")),p&&(h.metadata.assignee=p,v.push("assignee")),{changedFields:v}}}),y=Ne(g.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Me(_.item.id,y),warnings:[..._.warnings],generated_at:k()}}async function oC(e,t,n){let r=GT(t.depth),o=jT(t.fields),{document:i,itemId:s}=await qh(n,e),a=Ne(i.metadata,o===null?r:"deep");return{action:"show",plan:o===null?a:qT(a,o),next_actions:Me(s,a),warnings:[],generated_at:k()}}function iC(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function rt(e){let t=C(e.options.author,e.ctx.settings.author_default),n,r=await ie({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){jh(o.metadata);let i=F(e.ctx.settings.schema);if(te(o.metadata.status,i)||za(o.metadata.plan_mode))throw new d(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.metadata.plan_mode??"unset"}) and cannot be mutated.`,l.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let s=(o.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(o.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(s,o);n=c.resultStep;let m=s.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));o.metadata.plan_steps=m;let u=iC(a,o.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function sC(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new d("pm plan add-step requires --step-title",l.USAGE);let o=Zc(t.stepStatus,"pending"),i=t.allowMultipleActive===!0,{document:s,resultStep:a,itemId:c}=await rt({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;zh(u,void 0,o,i);let f=aC(u,t,{order:p,title:r,status:o});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Ne(s.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Me(c,m),warnings:[],generated_at:k()}}function zh(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(i=>i.id!==t&&i.status==="in_progress");if(o)throw new d(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,l.CONFLICT)}function aC(e,t,n){let r=ol(t,"depends_on"),o=Ce(t.file).map(tl),i=Ce(t.test).map(nl),s=Ce(t.doc).map(rl),a=k();return{id:zT(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:s.length>0?s:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function ol(e,t){let n=Ke(e.dependsOn).map(u=>({id:u,kind:t})),r=Ke(e.related).map(u=>({id:u,kind:"related"})),o=Ke(e.blocks).map(u=>({id:u,kind:"blocks"})),i=Ke(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),s=Ke(e.link),a=Gh(e.linkKind,t),c=e.linkNote?.trim(),m=s.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...o,...i,...m]}async function Wc(e,t,n,r){let{document:o,resultStep:i,itemId:s}=await rt({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=zn(c,r.stepRef),p=k(),f=r.finalStatus??Zc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return zh(c,u.status==="in_progress"?u.id:void 0,f,_),cC(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Ne(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:i,next_actions:Me(s,a),warnings:[],generated_at:k()}}function cC(e,t,n,r){lC(e,t,n),dC(e,t),e.status=n,e.updated_at=r,mC(e,n,r)}function lC(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new d("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",l.USAGE)}function dC(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=t.stepOwner.trim()||void 0),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let r=Ce(t.file).map(tl),o=Ce(t.test).map(nl),i=Ce(t.doc).map(rl);r.length>0&&(e.files=Yc(e.files,r)),o.length>0&&(e.tests=Yc(e.tests,o)),i.length>0&&(e.docs=Yc(e.docs,i))}function Yc(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let i=JSON.stringify(o);r.has(i)||(r.add(i),n.push(o))}return n}function mC(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function uC(e,t,n,r,o){let{document:i,itemId:s}=await rt({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(c){let m=zn(c,r),u=c.filter(f=>f.id!==m.id),p=Math.max(1,Math.min(o,u.length+1));return u.splice(p-1,0,m),u.forEach((f,_)=>{f.order=_+1,f.updated_at=k()}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=Ne(i.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Me(s,a),warnings:[],generated_at:k()}}async function pC(e,t,n,r){let{document:o,itemId:i}=await rt({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=zn(a,r),m=a.filter(u=>u.id!==c.id);return m.forEach((u,p)=>{u.order=p+1}),a.length=0,a.push(...m),{changedSteps:[c.id]}}}),s=Ne(o.metadata,"standard");return{action:"remove-step",plan:s,next_actions:Me(i,s),warnings:[],generated_at:k()}}async function fC(e,t,n,r){let o=ol(t,Gh(t.linkKind,"related"));if(o.length===0)throw new d("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",l.USAGE);let i=t.promoteToItemDep===!0,{document:s,itemId:a,resultStep:c}=await rt({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=zn(u,r),_=f.linked_items??[],g=h=>`${h.kind}:${h.id}`,y=new Set(_.map(g));for(let h of o){let v=g(h);y.has(v)||(_.push(h),y.add(v))}if(f.linked_items=_,f.updated_at=k(),i){let h=p.metadata.dependencies??[],v=S=>`${S.kind}:${S.id}`,b=new Set(h.map(v));for(let S of o){let T=S.kind==="depends_on"?"blocked_by":S.kind,I={id:S.id,kind:T,created_at:k(),author:C(t.author,n.settings.author_default)};b.has(v(I))||(h.push(I),b.add(v(I)))}p.metadata.dependencies=h}return{changedSteps:[f.id],resultStep:f}}}),m=Ne(s.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Me(a,m),warnings:[],generated_at:k()}}async function _C(e,t,n,r){let o=Ke(t.link);if(o.length===0)throw new d("pm plan unlink requires --link <id> to remove",l.USAGE);let{document:i,itemId:s,resultStep:a}=await rt({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=zn(m,r),p=(u.linked_items??[]).filter(f=>!o.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=k(),{changedSteps:[u.id],resultStep:u}}}),c=Ne(i.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Me(s,c),warnings:[],generated_at:k()}}async function Jc(e,t,n,r){let o=HT(r,t);if(!o){let m=`--${r}-text`,u=`--${r}`;throw new d(`pm plan ${r} requires ${m}`,l.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${m} "..."`,`pm plan ${r} <plan-id> ${u} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${m} <value>`}})}let i=C(t.author,n.settings.author_default),{document:s,itemId:a}=await rt({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,u){let p=k();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:i,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:i,text:o}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Ne(s.metadata,"deep");return{action:r,plan:c,next_actions:Me(a,c),warnings:[],generated_at:k()}}async function hC(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new d("pm plan resume requires --resume-context <text>",l.USAGE);let{document:o,itemId:i}=await rt({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),s=Ne(o.metadata,"brief");return{action:"resume",plan:s,next_actions:Me(i,s),warnings:[],generated_at:k()}}async function gC(e,t,n){let r=Uh(t.mode??"approved","approved"),{document:o,itemId:i}=await rt({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(a,c){c.metadata.plan_mode=r;let m=t.scope?.trim();return m&&(c.metadata.plan_scope=m),{changedSteps:[]}}}),s=Ne(o.metadata,"brief");return{action:"approve",plan:s,next_actions:Me(i,s),warnings:[],generated_at:k()}}function Bh(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function yC(e,t){let n=Ne(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Me(e.itemId,n),warnings:Bh(t),generated_at:k()}}function vC(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let i=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${i}`)}return r}async function wC(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Ce(e.options.field)){let i=o.indexOf("=");if(i<=0)throw new d(`Invalid --field entry "${o}"; expected name=value`,l.USAGE);let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();if(s.length===0)throw new d(`Invalid --field entry "${o}"; expected name=value`,l.USAGE);let c=s.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new d(`Invalid --field entry "${o}"; expected name=value`,l.USAGE);let[m,...u]=c,p=`${m}${u.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(p))throw new d(`Invalid --field entry "${o}"; "${p}" is reserved by materialize and cannot be overridden`,l.USAGE);n[p]=a}for(let o of e.targets){let i={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:vC(e.parent,e.planItemId,o)};Kh(e.options,i,["description",...Object.keys(n)]);let s=await Gt(i,{path:e.pmRoot});t.push({id:s.item.id,title:s.item.title,type:e.resolvedTypeName,parent:s.item.parent,tags:s.item.tags??[],from_step:o.id})}return t}function bC(e,t,n){for(let r of t){let o=n.find(a=>a.from_step===r.id);if(!o)continue;let i=e.find(a=>a.id===r.id);if(!i)continue;let s=i.linked_items??[];s.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),i.linked_items=s,i.updated_at=k()}}async function kC(e,t,n){let r=Ke(t.steps);if(r.length===0)throw new d("pm plan materialize requires --steps <ids|orders|all>",l.USAGE);let o=t.materializeType?.trim()||"Task",i=x(n.settings,O()),s=we(o,i);if(!s)throw new d(`Invalid --materialize-type "${o}"`,l.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await qh(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=BT(u,r);if(p.length===0){if(f.length>0)return yC(m,f);throw new d("No matching plan steps found for --steps",l.NOT_FOUND)}let _=await wC({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:s,tags:c,options:t,pmRoot:n.pmRoot}),{document:g,itemId:y}=await rt({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(v){return bC(v,p,_),{changedSteps:p.map(b=>b.id)}}}),h=Ne(g.metadata,"standard");return{action:"materialize",plan:h,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Me(y,h),warnings:Bh(f),generated_at:k()}}function SC(e){if(e.subcommand==="create")return e;let t=Dh(e.options.step);if(t.length>1)throw new d(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,l.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:Se(e.options,{...e.options,stepTitle:t[0]})}:e}function wt(e,t){if(!e.id)throw new d(`pm plan ${t} requires a plan id`,l.USAGE);return e.id}function un(e,t){let n=wt(e,t);if(!e.stepRef)throw new d(`pm plan ${t} requires <plan-id> <step>`,l.USAGE);return{id:n,stepRef:e.stepRef}}function EC(e){let t=un(e,"reorder-step");if(e.reorderTo===void 0)throw new d("pm plan reorder-step requires <plan-id> <step> <new-order>",l.USAGE);return{...t,reorderTo:e.reorderTo}}var AC={create:(e,t)=>rC(e.options,e.global,t),show:(e,t)=>oC(wt(e,"show"),e.options,t),"add-step":(e,t)=>sC(wt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=un(e,"update-step");return Wc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=un(e,"complete-step");return Wc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=un(e,"block-step");return Wc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=EC(e);return uC(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=un(e,"remove-step");return pC(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=un(e,"link");return fC(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=un(e,"unlink");return _C(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Jc(wt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Jc(wt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Jc(wt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>hC(wt(e,"resume"),e.options,t),approve:(e,t)=>gC(wt(e,"approve"),e.options,t),materialize:(e,t)=>kC(wt(e,"materialize"),e.options,t)};function TC(e){let t=AC[e];if(!t)throw Pe({command_path:"plan",token:e,allowed:FT});return t}async function Hh(e){let t=await YT(e.global),n=SC(e);return TC(n.subcommand)(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64b269aa-d285-53bb-8949-b75bed767479")}catch{}})();function CC(e,t){return[...new Set([...io.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,o)=>r.localeCompare(o))}function RC(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function il(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await A(r),i=x(o,O()),s=await q(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!s)throw await _t(r,e,o.id_prefix,i.type_to_folder);let a=await oe(s,{schema:o.schema}),c=a.document.metadata,m=k(),u=C(t.author,o.author_default),p=await pr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:i.type_to_folder,probeExisting:!1}),f=F(o.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new d("Copy --title must not be empty",l.USAGE);let g={...c,id:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete g.closed_at,delete g.completed_at,delete g.close_reason,delete g.test_runs;let y=Ct(O()),h=Ze({metadata:g,body:a.document.body},{schema:o.schema,extensionFieldNames:y}),v=await Dn({title:h.metadata.title,description:h.metadata.description,body:h.body,excludeIds:[s.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),b=CC(h.metadata,h.body),S=dt(r,h.metadata.type,p,o.item_format,i.type_to_folder),T=Xe(r,p),I=await ke(r,p,o.locks.ttl_seconds,u,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),D={metadata:{},body:""},M,Y;try{let z=await Nt(r,u,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await Dn({title:h.metadata.title,description:h.metadata.description,body:h.body,excludeIds:[s.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let K=await q(r,p,o.id_prefix,o.item_format,i.type_to_folder);if(K)throw new d(`Cannot copy to ${p}: an item with that id already exists at ${K.itemPath}. Retry the copy to allocate a new id.`,l.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${K.itemPath}.`,recovery:{suggested_retry:`pm copy ${s.id}`}});await ee(S,ze(h,{format:o.item_format,schema:o.schema,extensionFieldNames:y}));try{let pe=Oe({nowIso:m,author:u,op:"create",before:D,after:h,message:RC(s.id,t.message)});await Pt(T,pe)}catch(pe){throw await yn(S),pe}Y=await Mt({pmRoot:r,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:S,document:h})}finally{await z()}M=[...await W({path:S,scope:"project",op:"create",item_id:h.metadata.id,item_type:h.metadata.type,before:D,after:h,changed_fields:b}),...await W({path:T,scope:"project",op:"create:history",item_id:h.metadata.id,item_type:h.metadata.type,before:D,after:h,changed_fields:b})],kn({id:h.metadata.id,op:"create",item_type:h.metadata.type,status:h.metadata.status,current:Qt(h.metadata,b),changed_fields:b})}finally{await I()}return{source_id:s.id,item:structuredClone(h.metadata),changed_fields:b,warnings:[...Li(v),...Y,...M],...v===void 0?{}:{similarity_advisory:v}}}import gs from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eef2ba25-bbdb-5c06-9f90-1cf485e98497")}catch{}})();async function sl(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await A(r),i=C(t.author,o.author_default),s=await Cp({pmRoot:r,settings:o,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),a=s.targetPath?gs.relative(r,s.targetPath).split(gs.sep).join("/"):void 0;return{item:s.item,changed_fields:s.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:s.item.status,...a?{target_path:a}:{},history_retained:gs.relative(r,Xe(r,s.item.id)).split(gs.sep).join("/"),tombstone_retention:"retain_append_only",warnings:s.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8023e71b-f733-572c-bdc0-e9b8f481232c")}catch{}})();async function IC(e){await R(e)}async function al(e,t,n){let r=E(process.cwd(),n.path);if(await IC(r),t.clear===!0){if(e!==void 0)throw new d("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",l.USAGE);let p=await A(r),f=Tn(C(void 0,p.author_default));return await Ju(r),await xi({pmRoot:r,settings:p,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await Qo(r);if(p===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let f=await OC(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let i=await A(r),s=x(i,O()),a=await q(r,e,i.id_prefix,i.item_format,s.type_to_folder);if(!a)throw await _t(r,e,i.id_prefix,s.type_to_folder);let c=Ge(a.id,i.id_prefix),m=await oe(a,{schema:i.schema}),u=Vh(m.document.metadata.title);return await Yu(r,c),await xi({pmRoot:r,settings:i,principal:Tn(C(void 0,i.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function OC(e,t){let n=await A(e),r=x(n,O()),o=await q(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let i=await oe(o,{schema:n.schema});return Vh(i.document.metadata.title)}function Vh(e){return e.trim().length>0?e:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0f97e1d-37de-5512-806c-833ec249ff52")}catch{}})();var Wh=new Set(["item_format"]),Yh=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),xC=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),PC=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),LC={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function NC(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(Wh.has(t)||Yh.has(t)||xC.has(t)||t==="context")return t}function MC(e){let t=e.trim().toLowerCase();return LC[t]??e}function Jh(e,t){let n=NC(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:Wh.has(n)?{routable:!0,flag:"format",value:t}:Yh.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:PC.has(n)?MC(t):t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="326e677a-c427-55e0-aad9-5204ea59661b")}catch{}})();var FC=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,cl=128,$C=1e4;function Xh(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>cl)throw new Error(`A legacy author must contain 1-${cl} characters.`);return t}function DC(e){let t=e?.trim().toLowerCase();if(!t||!FC.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function UC(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function GC(e,t){let n=new Set;for(let r of(e??[]).slice(0,$C)){let o=r.trim().slice(0,cl);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function jC(e,t){let n=Xh(t.legacy_author),r=DC(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function qC(e,t){if(t.operation==="add")return jC(e,t);if(t.operation==="remove"){let r=Xh(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function ll(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function Qh(e,t){let n=e?.version??1,r={...e?.aliases},o=qC(r,t),i={version:o?n+1:n,aliases:UC(r)};return{vocabulary:i,preview:{operation:t.operation,changed:o,version_before:n,version_after:i.version,alias_count:Object.keys(i.aliases).length,residual_author_count:GC(t.observed_authors,i.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6fdd2eb-5447-5b10-af5b-33765e341bd2")}catch{}})();var Zh=["project","global"],bt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},KC=Object.keys(bt).map(e=>bt[e][0]),zC=Object.fromEntries(Object.keys(bt).flatMap(e=>bt[e].map(t=>[t,e]))),BC={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},HC=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],VC=new Set(["metadata_required_fields",...HC]),WC=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),YC=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),JC=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),XC=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),QC=new Set(["governance_preset","governance_create_default_type"]),og=e=>VC.has(e),ZC=e=>JC.has(e),eR=e=>XC.has(e),tR=e=>QC.has(e);function dl(e){return e==="definition_of_done"||og(e)}function nR(e){if(Zh.includes(e))return e;throw new d(`Invalid config scope "${e}". Allowed: ${Zh.join(", ")}`,l.USAGE)}function rR(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Pe({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function oR(e){let t=zC[e];if(t)return t;let n=fa.map(r=>r.key).join(", ");throw new d(`Invalid config key "${e}". Supported: ${KC.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,l.USAGE)}function iR(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new d("Config set definition-of-done cannot combine --clear-criteria with --criterion values",l.USAGE);return[]}if(n.length===0)throw new d("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",l.USAGE);return n}function sR(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new d("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",l.USAGE):new d("Config set item-format requires --format toon",l.USAGE)}function ig(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new d("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",l.USAGE)}function aR(e){return ul(e,"test-result-tracking")}function ul(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new d(`Config set ${t} requires --policy with one of: enabled, disabled`,l.USAGE)}function sg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new d("Config set telemetry-tracking requires --policy with one of: enabled, disabled",l.USAGE)}function pl(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new d("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",l.USAGE)}function ag(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new d("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",l.USAGE)}function cg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new d("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",l.USAGE)}function lg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new d("Config set governance-create-mode-default requires --policy with one of: progressive, strict",l.USAGE)}function dg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new d("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",l.USAGE)}function mg(e){let t=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new d("Config set governance-workflow-enforcement requires one of: off, warn, strict",l.USAGE)}function ug(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new d("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",l.USAGE)}function pg(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new d("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",l.USAGE)}var cR={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function eg(e,t){let n=cR[e];if(n)return ul(t,n);switch(e){case"history_missing_stream_policy":return ig(t);case"sprint_release_format_policy":return Ka(t);case"parent_reference_policy":case"governance_parent_reference_policy":return fi(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return pl(t);case"governance_preset":return ag(t);case"governance_ownership_enforcement":return cg(t);case"governance_create_mode_default":return lg(t);case"governance_close_validation_default":return dg(t);case"governance_require_close_reason":return pg(t);case"governance_workflow_enforcement":return mg(t);case"governance_force_required_for_stale_lock":return ug(t);case"telemetry_tracking":return sg(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var tg={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"},lR=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function dR(e,t){let n=[...new Set((e??[]).map(i=>i.trim()).filter(i=>i.length>0))];if(t){if(n.length>0)throw new d("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",l.USAGE);return[]}if(n.length===0)throw new d("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",l.USAGE);let r=n.map(i=>i.toLowerCase().replaceAll("-","_")),o=r.filter(i=>tg[i]===void 0);if(o.length>0)throw new d(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${lR.join(", ")}`,l.USAGE);return[...new Set(r.map(i=>tg[i]))].sort((i,s)=>i.localeCompare(s))}function mR(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));if(n){if(r.length>0)throw new d(`Config set ${bt[e][0]} cannot combine --clear-criteria with --criterion values`,l.USAGE);return[]}if(r.length===0)throw new d(`Config set ${bt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,l.USAGE);return r}function uR(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function pR(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new d(`Config action "${e}" does not accept <key>`,l.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new d(`Config action "${e}" requires <key>`,l.USAGE);return oR(t)}function fg(e){if(!e)throw new d("Config action requires <key>",l.USAGE)}var fR={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>ll(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function fl(e,t){return fR[t](e)}function Re(e,t){return t.length===0?e:{...e,warnings:t}}async function _R(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):lt(n),o=fe(r);return e==="project"&&await R(r),{pmRoot:r,settingsPath:o}}function hR(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new d(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,l.USAGE)}function ng(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new d(`Context ${t} must be a positive integer`,l.USAGE)}async function gR(e,t,n,r,o){let i=!1,s=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!sa.includes(c))throw new d(`Context --default-depth must be one of ${sa.join("|")}`,l.USAGE);s.default_depth!==c&&(s.default_depth=c,i=!0)}if(t.activityLimit!==void 0){let c=ng(t.activityLimit,"--activity-limit");s.activity_limit!==c&&(s.activity_limit=c,i=!0)}if(t.staleThresholdDays!==void 0){let c=ng(t.staleThresholdDays,"--stale-threshold-days");s.stale_threshold_days!==c&&(s.stale_threshold_days=c,i=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of a){let u=hR(m);if(u!==void 0){let p=c;s.sections[p]!==u&&(s.sections[p]=u,i=!0)}}return i&&await xe(n.pmRoot,e,"config:set:context"),Re({scope:r,key:"context",context_settings:{default_depth:s.default_depth,activity_limit:s.activity_limit,stale_threshold_days:s.stale_threshold_days,sections:{...s.sections}},settings_path:n.settingsPath,changed:i},o)}function yR(e,t,n){if(n.value!==void 0&&n.value!==t)throw new d(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,l.USAGE);return{...n,value:t}}function vR(e,t,n,r,o,i){if(o===void 0)return i;if(e!=="set")throw new d(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,l.USAGE);if(typeof t!="string"||t.trim().length===0)throw new d('Config action "set" requires <key> before a positional <value>.',l.USAGE);if(r)return yR(t,o,i);fg(n);let s=Jh(n,o);if(!s.routable)throw new d(s.reason,l.USAGE);if(s.flag==="criterion"){if(i.criterion!==void 0&&i.criterion.length>0)throw new d(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,l.USAGE);return{...i,criterion:s.values}}if(s.flag==="format")return{...i,format:s.value};if(i.policy!==void 0&&eg(n,i.policy)!==eg(n,s.value))throw new d(`Config set ${t} received both positional value "${o}" and --policy "${i.policy}". Pass only one.`,l.USAGE);return{...i,policy:s.value}}function wR(e){let t=Object.keys(bt).map(r=>({key:r,aliases:bt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":dl(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:dl(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:BC[r],value:fl(e.settings,r)})),n=fa.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:_a(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Re({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function bR(e){let t=Object.fromEntries(Object.keys(bt).map(n=>[n,fl(e.settings,n)]));return Re({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function kR(e,t){let n=fl(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Re({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Re({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Re({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Re({...r,criteria:n},e.warnings):Re({...r,policy:n},e.warnings)}async function SR(e,t,n,r){if(t==="get"){let a=_a(e.settings,n);return Re({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new d(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,l.USAGE);let i=cu(n,o);if(!i.ok)throw new d(i.error.message,l.USAGE);let s=zo(e.settings,n,i.parsed.value);return s&&await xe(e.target.pmRoot,e.settings,`config:set:${n.path}`),Re({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:i.parsed.value},settings_path:e.target.settingsPath,changed:s},e.warnings)}async function J(e,t,n){t&&await xe(e.target.pmRoot,e.settings,n)}function rg(e,t,n){return e!==n||t!==n}function me(e,t,n,r){return Re({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function ml(e,t,n,r){return Re({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function ER(e,t){let n=sR(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let i=x(e.settings,O()),s=await Gp(e.target.pmRoot,n,"config:set:item_format:migrate",i.type_to_folder,e.settings.schema);o={target_format:s.target_format,scanned:s.scanned,migrated:s.migrated,removed:s.removed,warnings:s.warnings},e.settings.item_format=n,await xe(e.target.pmRoot,e.settings,"config:set:item_format")}return Re({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function AR(e,t,n){if(t==="history_missing_stream_policy"){let i=ig(n.policy),s=e.settings.history.missing_stream!==i;return e.settings.history.missing_stream=i,await J(e,s,"config:set:history_missing_stream_policy"),me(e,t,e.settings.history.missing_stream,s)}if(t==="sprint_release_format_policy"){let i=Ka(n.policy),s=e.settings.validation.sprint_release_format!==i;return e.settings.validation.sprint_release_format=i,await J(e,s,"config:set:sprint_release_format_policy"),me(e,t,e.settings.validation.sprint_release_format,s)}if(t==="parent_reference_policy"){let i=fi(n.policy),s=e.settings.validation.parent_reference!==i||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==i;return e.settings.validation.parent_reference=i,e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,await J(e,s,"config:set:parent_reference_policy"),me(e,t,e.settings.validation.parent_reference,s)}let r=pl(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await J(e,o,"config:set:metadata_validation_profile"),me(e,t,e.settings.validation.metadata_profile,o)}async function TR(e,t,n){if(t==="metadata_required_fields"){let a=dR(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((m,u)=>m!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await J(e,c,"config:set:metadata_required_fields"),ml(e,t,[...e.settings.validation.metadata_required_fields],c)}let o={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],i=mR(t,n.criterion,n.clearCriteria),s=i.length!==o.length||i.some((a,c)=>a!==o[c]);return o.splice(0,o.length,...i),await J(e,s,`config:set:${t}`),ml(e,t,[...o],s)}async function CR(e,t,n){if(t==="governance_preset"){let c=ag(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await J(e,m,"config:set:governance_preset"),me(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await J(e,c,"config:set:governance_create_default_type"),me(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new d('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',l.USAGE);let i=x(e.settings,O()),s=we(o,i);if(!s)throw new d(Ot(o,i.types,xt(e.target.pmRoot,e.settings.schema)),l.USAGE);let a=e.settings.governance.create_default_type!==s;return e.settings.governance.create_default_type=s,await J(e,a,"config:set:governance_create_default_type"),me(e,t,e.settings.governance.create_default_type,a)}async function RR(e,t,n){if(t==="governance_ownership_enforcement"){let i=cg(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==i;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=i,await J(e,s,"config:set:governance_ownership_enforcement"),me(e,t,e.settings.governance.ownership_enforcement,s)}if(t==="governance_create_mode_default"){let i=lg(n.policy),s=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==i;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=i,await J(e,s,"config:set:governance_create_mode_default"),me(e,t,e.settings.governance.create_mode_default,s)}let r=dg(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await J(e,o,"config:set:governance_close_validation_default"),me(e,t,e.settings.governance.close_validation_default,o)}async function IR(e,t,n){if(t==="governance_parent_reference_policy"){let i=fi(n.policy),s=e.settings.governance.preset!=="custom"||rg(e.settings.governance.parent_reference,e.settings.validation.parent_reference,i);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,e.settings.validation.parent_reference=i,await J(e,s,"config:set:governance_parent_reference_policy"),me(e,t,e.settings.governance.parent_reference,s)}if(t==="governance_metadata_validation_profile"){let i=pl(n.policy),s=e.settings.governance.preset!=="custom"||rg(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,i);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=i,e.settings.validation.metadata_profile=i,await J(e,s,"config:set:governance_metadata_validation_profile"),me(e,t,e.settings.governance.metadata_profile,s)}let r=mg(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await J(e,o,"config:set:governance_workflow_enforcement"),me(e,t,e.settings.governance.workflow_enforcement,o)}async function OR(e,t,n){if(t==="governance_require_close_reason"){let a=pg(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await J(e,c,"config:set:governance_require_close_reason"),me(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let o=ug(n.policy)==="enabled",i=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==o;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=o,await J(e,i,"config:set:governance_force_required_for_stale_lock"),me(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",i)}async function xR(e,t,n){if(t==="test_result_tracking"){let a=aR(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await J(e,c,"config:set:test_result_tracking"),me(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}if(t==="untrusted_linked_test_execution"){let a=ul(n.policy,"untrusted-linked-test-execution")==="enabled",c=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await J(e,c,"config:set:untrusted_linked_test_execution"),me(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",c)}let o=sg(n.policy)==="enabled",i=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await J(e,i,"config:set:telemetry_tracking"),me(e,t,e.settings.telemetry.enabled?"enabled":"disabled",i)}async function PR(e,t,n){let r=iR(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((i,s)=>i!==e.settings.workflow.definition_of_done[s]);return e.settings.workflow.definition_of_done=r,await J(e,o,"config:set:definition_of_done"),ml(e,t,[...e.settings.workflow.definition_of_done],o)}function LR(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new d("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",l.USAGE)}function NR(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new d('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',l.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new d("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",l.USAGE);return{legacy_author:t}}if(t!==void 0)throw new d("Config set agent-identity-vocabulary --policy clear does not accept --value",l.USAGE);return{}}async function MR(e,t){let{operation:n,dryRun:r}=LR(t.policy),o=NR(n,t.value),i;try{i=Qh(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(s){throw new d(s.message,l.USAGE)}return i.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:i.vocabulary},await J(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${i.preview.version_after}`)),Re({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:ll(r?e.settings.agent_identity?.identity_vocabulary:i.vocabulary),vocabulary_mutation:i.preview,settings_path:e.target.settingsPath,changed:i.preview.changed&&!r},e.warnings)}async function FR(e,t,n){if(n.clearCriteria===!0&&!dl(t))throw new d("--clear-criteria is only supported with config set criteria-list keys",l.USAGE);return t==="item_format"?ER(e,n):t==="context"?gR(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?MR(e,n):t==="definition_of_done"?PR(e,t,n):og(t)?TR(e,t,n):WC.has(t)?xR(e,t,n):YC.has(t)?OR(e,t,n):ZC(t)?RR(e,t,n):eR(t)?IR(e,t,n):tR(t)?CR(e,t,n):AR(e,t,n)}async function _g(e,t,n,r,o,i){let s=nR(e),a=rR(t),c=a==="get"||a==="set"?Ko(n):void 0,m=c?void 0:pR(a,n),u=vR(a,n,m,c,i,r),p=await _R(s,o),{settings:f,metadata:_,warnings:g}=await wp(p.pmRoot),y={scope:s,target:p,settings:f,metadata:_,warnings:uR(g)};return c?SR(y,a,c,u):a==="list"?wR(y):a==="export"?bR(y):(fg(m),a==="get"?kR(y,m):FR(y,m,u))}import pI from"node:fs/promises";import X from"node:path";import fI from"node:readline/promises";import{stdin as _I,stdout as Fe}from"node:process";import hl from"node:fs/promises";import ue from"node:path";import $R from"node:readline/promises";import{stdin as DR,stdout as ys}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5ae3e66-4a45-5c62-9144-46f8f5bff7cf")}catch{}})();var gg=["ask","add","skip","status"],UR=["AGENTS.md","CLAUDE.md"],GR=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],jR=8,gl=1,qR="<!-- pm-cli:agent-guidance:start:",KR=`<!-- pm-cli:agent-guidance:start:v${gl} -->`,_l="<!-- pm-cli:agent-guidance:end -->",Dr="Add workflow guidance later: pm init --agent-guidance add";var zR=()=>$R.createInterface({input:DR,output:ys});function Fr(e,t){let n=ue.relative(e,t);return n.length===0?ue.basename(t):n.split(ue.sep).join("/")}function hg(e){return e.endsWith(`
|
|
7
7
|
`)?e:`${e}
|
|
8
|
-
`}function
|
|
8
|
+
`}function BR(e){return e.includes(`\r
|
|
9
9
|
`)?`\r
|
|
10
10
|
`:`
|
|
11
|
-
`}function
|
|
11
|
+
`}function yg(e){let t=e.indexOf(qR);if(t===-1)return null;let n=e.indexOf(_l,t);return n===-1?null:{start_index:t,end_index:n+_l.length}}function HR(e){return yg(e)!==null}function VR(e,t="<your project test command>"){return[KR,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",_l,""].join(e)}function WR(e,t="<your project test command>"){let n=BR(e),r=VR(n,t),o=yg(e);if(o){let a=e.slice(o.end_index),c=a.startsWith(`\r
|
|
12
12
|
`)?a.slice(2):a.startsWith(`
|
|
13
|
-
`)?a.slice(1):a,m=
|
|
13
|
+
`)?a.slice(1):a,m=hg(`${e.slice(0,o.start_index)}${r}${c}`);return{next_content:m,changed:m!==e}}let i=e.length===0?"":e.endsWith(`
|
|
14
14
|
`)?`
|
|
15
15
|
`:`
|
|
16
16
|
|
|
17
|
-
`,
|
|
17
|
+
`,s=hg(`${e}${i}${r}`);return{next_content:s,changed:s!==e}}async function YR(e){if(await L(ue.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await hl.readFile(ue.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=JR(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await L(ue.join(e,"pnpm-lock.yaml"))?"pnpm test":await L(ue.join(e,"bun.lock"))||await L(ue.join(e,"bun.lockb"))?"bun run test":await L(ue.join(e,"yarn.lock"))?"yarn test":"npm test"}function JR(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function XR(e,t){let n=ue.dirname(e);return ue.basename(e)==="pm"&&ue.basename(n)===".agents"?ue.dirname(n):ue.resolve(t,e)}function QR(e,t){let n=e.find(o=>ue.basename(o.file_path)==="AGENTS.md"&&o.exists);if(n)return n.file_path;let r=e.find(o=>o.exists);return r?r.file_path:ue.join(t,"AGENTS.md")}function ZR(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function eI(e){let t=zR();try{ys.write(`
|
|
18
18
|
Agent guidance check
|
|
19
|
-
`),
|
|
20
|
-
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return
|
|
21
|
-
`),
|
|
19
|
+
`),ys.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
20
|
+
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return ys.write(`
|
|
21
|
+
`),ZR(n,!0)}finally{t.close()}}function vg(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:gl,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function wg(e){let t=[];for(let n of UR){let r=ue.join(e,n),o=await L(r);if(!o){t.push({file_path:r,exists:o,has_guidance:!1,has_marker:!1});continue}let i=await hl.readFile(r,"utf8"),s=i.toLowerCase(),a=GR.filter(m=>s.includes(m)),c=HR(i);t.push({file_path:r,exists:o,has_guidance:c||a.length>=jR,has_marker:c})}return t}function Ur(e,t){e.includes(t)||e.push(t)}function tI(e,t){let n=vg(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function nI(e,t=ue.dirname(e)){let r=await L(e)?await hl.readFile(e,"utf8"):"",o=WR(r,await YR(t));return o.changed?(await ee(e,o.next_content),{changed:!0,warnings:await W({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function rI(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>Fr(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>Fr(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>Fr(e.projectRoot,t.file_path))}}async function oI(e,t,n){return e?await wg(n):t}function $r(e,t,n){e.state={...e.state,...n,template_version:gl,last_checked_files:t}}async function bg(e,t){if(t.presentBefore)return;let n=await nI(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function iI(e,t){t||(e.warnings.push("agent_guidance:missing"),Ur(e.nextSteps,Dr))}function sI(e,t){e.skipped=!0,$r(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Ur(e.nextSteps,Dr)}async function aI(e,t){await bg(e,t),$r(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function cI(e,t){e.state.declined&&$r(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function lI(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Ur(e.nextSteps,Dr)}async function dI(e,t){if(e.prompted=!0,await eI(t.targetRelativePath)){await bg(e,t),$r(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,$r(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Ur(e.nextSteps,Dr)}function mI(e){e.warnings.push("agent_guidance:missing_non_interactive"),Ur(e.nextSteps,Dr)}async function uI(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(iI(n,t.presentBefore),n):t.mode==="skip"?(sI(n,t.checkedFiles),n):t.mode==="add"?(await aI(n,t),n):t.presentBefore?(cI(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(lI(n),n):t.interactive?(await dI(n,t),n):(mI(n),n)}async function kg(e){let t=XR(e.pm_root,e.cwd),n=await wg(t),r=QR(n,t),o=Fr(t,r),i=n.map(u=>Fr(t,u.file_path)),s=n.some(u=>u.has_guidance),a=await uI(vg(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:o,checkedFiles:i,presentBefore:s,projectRoot:t}),c=tI(e.settings,a.state);return n=await oI(a.applied,n,t),{summary:rI({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:o,prompted:a.prompted,applied:a.applied,skipped:a.skipped,state:a.state}),warnings:a.warnings,next_steps:a.nextSteps,settings_changed:c.changed}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="55f7a34f-05d6-507f-a46c-1da0d957f2e3")}catch{}})();var vl=Symbol.for("pm.sdk.init-invocation-cwd");var hI=()=>fI.createInterface({input:_I,output:Fe});function gI(){return structuredClone(Tt)}var yI=["minimal","default","strict"];function Eg(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new d("--preset must not be empty",l.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new d(`Invalid --preset value "${e}". Allowed: ${yI.join(", ")}`,l.USAGE)}function vI(e){if(e!==void 0){if(e.trim().length===0)throw new d("--type-preset must not be empty",l.USAGE);try{return Zm(e)}catch{throw new d(`Invalid --type-preset value "${e}". Allowed: ${Qm.join(", ")}`,l.USAGE)}}}function wI(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new d("--author must not be empty",l.USAGE);return t}function yl(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:X.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function bI(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new d("--workspace must not be empty",l.USAGE);if(o!==void 0){if(t.path!==void 0||yl(n))throw new d("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",l.USAGE);let m=X.resolve(e,o),u=X.join(m,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:m}}}if(t.path===void 0&&yl(n)){let m=X.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let i=E(e,t.path),s=X.join(X.resolve(e),".agents","pm"),a=X.dirname(X.dirname(i)),c=X.resolve(i)===s?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:a,discovery:c,requested_cwd:X.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:s}:{}}:{mode:"tracker-path",tracker_root:i}}}function kI(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new d("--id-prefix must not be empty",l.USAGE);if(yl(t))throw new d(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,l.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&Lt(e)!==Lt(t))throw new d(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,l.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Lt(e)}`,`pm init --id-prefix ${Lt(t)}`]});return t}function SI(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new d("--agent-guidance must not be empty",l.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new d(`Invalid --agent-guidance value "${e}". Allowed: ${gg.join(", ")}`,l.USAGE)}function EI(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Ag(e,t){let n=Cd[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function AI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function TI(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(AI).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function CI(e,t,n){let r=jo(t.schema),o=ft(e,r.files.types,pt.types),s=Jm(await Q(o)),a=[],c=[];for(let m of eu(n)){let u=Xm(s,m);s=u.file,(u.replaced?c:a).push(u.definition.name)}return await tt({pmRoot:e,filePath:o,raw:Uo(s),op:"init:type-preset",author:C(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:o}}async function RI(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",X.join(".agents","pm")];for(let n of t)if(await L(X.join(e,n)))return!0;return!1}async function II(e,t,n){if(!t||n||await L(X.join(e,"settings.json"))||!await RI(e))return;let r=X.join(e,".agents","pm");throw new d(`Refusing to initialize tracker files directly in workspace root "${e}".`,l.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function Tg(e,t){let n=[],r=[];for(let o of t){let i=o?X.join(e,o):e,s=await L(i);await pI.mkdir(i,{recursive:!0}),s?r.push(`already_exists:${i}`):n.push(i),r.push(...await W({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function OI(e,t){let n=hI();try{Fe.write(`pm init setup wizard (agent-optimized)
|
|
22
22
|
`),Fe.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
23
23
|
|
|
24
24
|
`),Fe.write(`1/3 Item ID prefix
|
|
25
25
|
`),Fe.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
|
|
26
|
-
`);let r=await n.question(`Item ID prefix [${e}]: `),o=r.trim().length>0?
|
|
26
|
+
`);let r=await n.question(`Item ID prefix [${e}]: `),o=r.trim().length>0?Lt(r):e;Fe.write(`
|
|
27
27
|
2/3 Governance preset
|
|
28
28
|
`),Fe.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
29
29
|
`),Fe.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
30
30
|
`),Fe.write(`strict: ownership blocking, strict create defaults, close validation strict.
|
|
31
|
-
`);let
|
|
31
|
+
`);let i=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),s=i.trim().length>0?i.trim():"minimal",a="minimal";try{a=Eg(s)}catch{Fe.write(`Unrecognized governance preset "${s}"; using minimal.
|
|
32
32
|
`)}Fe.write(`
|
|
33
33
|
3/3 Project telemetry
|
|
34
34
|
`),Fe.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
|
|
35
|
-
`);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=
|
|
36
|
-
`),{prefix:o,preset:a,telemetry_enabled:u}}finally{n.close()}}function kI(e){return{presetFromOption:_g(e.preset),useDefaults:e.defaults===!0,authorFromOption:mI(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:fI(e.agentGuidance),typePreset:dI(e.typePreset)}}function SI(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function EI(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new d(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,l.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function AI(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(hg(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function TI(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=SI({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return EI(e.settingsPath,n,e.options.force===!0,e.target),AI({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Oe(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function CI(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await bI(t,St.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let s=n??"minimal",i=cI();i.id_prefix=t,hg(i,s);let a=zo()?.trim()||void 0;return i.author_default=e.normalizedOptions.authorFromOption??a??"",r!==void 0&&(i.telemetry.enabled=r,i.telemetry.first_run_prompt_completed=!0),await Oe(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function fg(e){return e.settingsExists?await TI(e):await CI({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function RI(e){let t=await pg({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await Oe(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function II(e,t){let n=[],r=[],o=await Ym(e,t.schema);for(let s of o.created_paths)n.push(s),r.push(...await V({path:s,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function OI(e){if(e.typePreset===void 0)return;let t=await yI(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await V({path:t.file,scope:"project",op:"init:type_preset"})),t}async function xI(e){let n=x(e.settings,O()).folders.filter(o=>!ea.includes(o)),r=await gg(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function PI(e){let t=J.resolve(e.tracker_root),n=J.dirname(t);return J.basename(t)==="pm"&&J.basename(n)===".agents"?J.dirname(n):e.workspace_root}async function LI(e,t,n,r){if(!e)return;let o=await xn("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let s=gI(o),i=s.packages.filter(a=>!a.ok).map(a=>a.alias);if(!s.installed_all||i.length>0)throw new d(`pm init --with-packages did not install all bundled packages successfully${i.length>0?`: ${i.join(", ")}`:"."}`,l.GENERIC_FAILURE);return s}function NI(e){let t=r=>tr([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function FI(e,t,n,r=nf){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof d))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function MI(e,t,n,r){if(e==null||n==="status")return;let o=await Ea(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Or(e,t,n={}){let r=t[ml],o=typeof r=="string"?r:process.cwd(),s=uI(o,t,e,n.workspace),i=s.pmRoot;e=pI(s.prefixArg,n.idPrefix);let a=kI(n);await wI(i,s.target.mode==="tracker-path",n.force===!0);let c=[],m=[],u=J.join(i,"settings.json"),p=await L(u),f;p&&(f=await fg({pmRoot:i,settingsPath:u,settingsExists:p,normalizedPrefix:Ot(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:s.target}));let _=await gg(i,ea);c.push(..._.createdDirs),m.push(..._.warnings),f??=await fg({pmRoot:i,settingsPath:u,settingsExists:p,normalizedPrefix:Ot(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:s.target});let{settings:g}=f,y=PI(s.target),h=await ps(y??J.dirname(i)),v=y??h,b=await RI({pmRoot:i,cwd:v??o,agentGuidanceMode:a.agentGuidanceMode,settings:g,warnings:m}),S=await II(i,g);c.push(...S.createdDirs),m.push(...S.warnings);let T=await OI({pmRoot:i,settings:g,typePreset:a.typePreset,warnings:m});T&&(g=await A(i)),await xI({pmRoot:i,settings:g,createdDirs:c,warnings:m}),await MI(v,i,a.agentGuidanceMode,m),!p&&n.mergeFence!==!1&&a.agentGuidanceMode!=="status"&&await FI(i,h,m);let I=await LI(a.installBundledPackages,t,i,m),D=NI({installBundledPackages:a.installBundledPackages,registeredTypePreset:T,agentGuidanceNextSteps:b.next_steps,target:s.target});return{ok:!0,path:i,target:s.target,settings:g,created_dirs:c,warnings:m,governance_preset:g.governance.preset,wizard_used:f.wizardUsed,...T?{registered_type_preset:T}:{},...I?{installed_packages:I}:{},next_steps:D,agent_guidance:b}}import KI from"node:fs/promises";import fl from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7b09736a-499b-57f6-b688-0458b487786b")}catch{}})();var vg=10,dn="https://schema.unbrained.dev/pm/eval-query-set/v1";var di={schema:dn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Be=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},$I=new Set(["keyword","semantic","hybrid"]);function yg(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function DI(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),o=yg(r,n),s=Array.from({length:t.size},()=>1),i=yg(s,n);return i===0?0:o/i}function UI(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function ul(e,t,n){let r=Math.min(n,e.length),o=0;for(let s=0;s<r;s+=1)t.has(e[s])&&(o+=1);return o}function GI(e,t,n){return n<=0?0:ul(e,t,n)/n}function jI(e,t,n){return t.size===0?0:ul(e,t,n)/t.size}function wg(e,t,n){return{ndcg:DI(e,t,n),mrr:UI(e,t,n),precision:GI(e,t,n),recall:jI(e,t,n),relevant_total:t.size,retrieved_relevant:ul(e,t,n)}}function bg(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function qI(e,t){if(typeof e!="object"||e===null)throw new Be(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new Be(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Be(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(s=>typeof s!="string"))throw new Be(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(s=>s.trim()).filter(s=>s.length>0))];if(o.length===0)throw new Be(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!$I.has(n.mode)))throw new Be(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function pl(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==dn)throw new Be(`Unsupported eval query set schema; expected "${dn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new Be('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Be("Eval query set must contain at least one query");return{schema:dn,queries:n.map((r,o)=>qI(r,o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7f6cfdef-5456-5716-9067-8ccadf077f5f")}catch{}})();var zI=fl.join("search","eval-queries.json"),_l={schema:dn,examples:[JSON.stringify(di)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},BI=new Set(["keyword","semantic","hybrid"]),HI=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!BI.has(t))throw new d("Eval --mode must be one of keyword|semantic|hybrid",l.USAGE);return t},VI=e=>{if(e===void 0||e==="")return vg;let t=bd(e);if(t===null)throw new d("Eval --k must be a positive integer",l.USAGE);return t},WI=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new d("Eval --fail-under must be a number in the range [0, 1]",l.USAGE);return n},Dt=e=>Math.round(e*1e4)/1e4,YI=async e=>{try{return await KI.readFile(e,"utf8")}catch{throw new d(`Eval query set not found at ${e}`,l.NOT_FOUND,{..._l,examples:[`echo '${JSON.stringify(di)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},JI=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new d(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,l.USAGE,_l)}},XI=e=>{try{return pl(e)}catch(t){throw new d(t instanceof Error?t.message:String(t),l.USAGE,_l)}},QI=async e=>XI(JI(await YI(e),e)),ZI=(e,t)=>t?fl.resolve(process.cwd(),t):fl.join(e,zI),e0=async(e,t,n,r)=>{let o=e.mode??t,i=(await gr(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=wg(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:Dt(a.ndcg),mrr:Dt(a.mrr),precision:Dt(a.precision),recall:Dt(a.recall)}}},t0=(e,t,n,r)=>{let o=bg(n);return{k:e,query_count:t.length,aggregate:{ndcg:Dt(o.ndcg),mrr:Dt(o.mrr),precision:Dt(o.precision),recall:Dt(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||o.ndcg>=r}},kg=async(e,t)=>{let n=E(process.cwd(),t.path);await R(n);let r=VI(e.k),o=HI(e.mode),s=WI(e.failUnder),i=ZI(n,e.queries),a=await QI(i),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await e0(u,o,r,t);m.push(f),c.push(p)}return t0(r,c,m,s)};import{readFile as n0,writeFile as r0}from"node:fs/promises";import o0 from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47487ad3-22a0-52ac-8a42-ebaca439cb6e")}catch{}})();var Sg=["item","history","relationship","json"];function s0(e){let t=e.trim().toLowerCase();if(Sg.includes(t))return t;throw new d(`Unknown merge artifact "${e}". Supported values: ${Sg.join(", ")}.`,l.USAGE)}function i0(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new d(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,l.USAGE)}async function hl(e,t){try{return await n0(e,"utf8")}catch{throw new d(`Cannot read merge ${t} file at ${e}.`,l.NOT_FOUND)}}async function a0(e){let t=E(process.cwd(),e.path);return await L(ue(t))?A(t):null}function c0(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Eg(e,t){let n=s0(e.artifact),r=i0(e.prefer),o=o0.resolve(e.outputPath??e.oursPath),[s,i,a]=await Promise.all([hl(e.basePath,"base"),hl(e.oursPath,"ours"),hl(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=kf(s,i,a);c=_.merged,p.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=Sf(s,i,a);c=_.merged,p.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await a0(t),g=c0(e.itemPath??o,_),y=Et(O()),h=Ef(s,i,a,{format:g,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"});if(c=h.merged,u.push(...h.conflict_fields),p.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let v=Yu(c,{format:g,schema:_?.schema,extensionFieldNames:y}),b=v.metadata,S=[...new Set([...h.fields_from_theirs,...h.union_fields,...h.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,bf(T==="body"?v.body:b[T])])),decisions:h.conflict_decisions,operation:await Tf(process.cwd(),e.itemPath)}}}else{let _=Af(s,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await r0(o,c,"utf8"),m!==void 0){let _=await Rf(m);_!==null&&(p.receipt=Xt(_))}let f=[];if(u.length>0){let _=p.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${p.receipt.receipt_id} with item ${p.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${u.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&p.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:u.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5fd3624a-d36b-58e6-8053-f2c0626e0c10")}catch{}})();async function Ag(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await Cf(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Mt(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Mt(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:r,message:e.message??"Settle rebase receipt after exact original Git state restoration",auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...Xt(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await fs(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as l0}from"node:fs/promises";import d0 from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="deef67cc-b902-5a4e-9c66-3839a1cdcc6f")}catch{}})();var m0=4;function Tg(e){let t=e.checks.find(a=>a.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,s=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,i=Array.isArray(o)?o.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:s,coordinates:i}}async function u0(e,t){let n=[];for(let r of t){let o;try{o=await l0(d0.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let s=o.split(/\r?\n/)[r.history_line-1];if(s===void 0||s.trim().length===0)continue;let i;try{i=JSON.parse(s)}catch{continue}let a=Lf(i,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!Pf(a)||a.eventTimestamp===void 0||jo(a.eventTimestamp,xf)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function p0(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;let t=new Map;for(let n of e.candidates){let r=t.get(n.item_id)??[];r.push(n),t.set(n.item_id,r)}for(let[n,r]of t)await Mt(n,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:r.map(o=>({receipt_id:o.receipt_id,original_history_line:o.history_line,original_event_ts:o.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function f0(e){try{return{status:"fulfilled",value:await Mt(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function _0(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function h0(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>fs(e.gitWorkspaceRoot??process.cwd(),r,{requireExisting:!0}))),n.length}async function Cg(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await ur(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),s=Tg(o),i=await u0(r,s.coordinates),a=await ps(r),c=await If(a??process.cwd(),{includeLossless:!0,pmRoot:r});if(c.invalid_evidence_count>0)throw new d(`Merge reconciliation refused ${c.invalid_evidence_count} invalid receipt evidence file(s).`,l.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let m=await p0({candidates:i,options:e,global:t}),u=c.receipts,p=await Ag({cwd:a,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),f=new Set(p),_=new Map;for(let j of u.filter(ce=>!f.has(ce.id))){let ce=_.get(j.item_id)??[];ce.push(j),_.set(j.item_id,ce)}let g=Object.fromEntries([..._].map(([j,ce])=>[j,{merge:{receipts:ce.map(Xt)}}])),y=Object.fromEntries([..._].map(([j,ce])=>[j,{gitWorkspaceRoot:a,receipts:ce}])),h=await hs({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:g,...u.length>0?{mergeReceiptProofById:y}:{}},t),v=new Set(h.streams.map(j=>j.id)),b=[..._.keys()].filter(j=>!v.has(j)),S=await wf(b,m0,j=>f0({id:j,dryRun:n,options:e,global:t,auditContext:g[j],mergeReceiptProof:y[j]}));_0({receiptOnlyIds:b,results:S,repair:h});let T=await h0({dryRun:n,pendingReceipts:u,repair:h,gitWorkspaceRoot:a}),I=await ws({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),D=m===0?o:await ur(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),N=Tg(D),X=I.checks.every(j=>j.status==="ok"),K=n?u.length===0:T+p.length===u.length,W=[h.totals.failed===0,X,K,N.count===0,!N.truncated].every(Boolean),Q=s.truncated||N.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,Ce=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",Q,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:W?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.",Q,...i.length>0&&m===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(j=>j!==void 0);return{ok:W,dry_run:n,repair:h,receipts:{pending_before:u.length,reconciled:T,abandoned:p.length,summaries:u.map(Xt),missing_history_references_before:s.count,legacy_disposition_eligible:i.length,legacy_disposition_recorded:m,missing_history_references_after:N.count},validation:I,guidance:Ce,generated_at:I.generated_at}}import{createHash as g0}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="117a463a-c0ab-569f-92e9-e85d14a1cf91")}catch{}})();var Og=1,xg=/^[A-Za-z0-9_-]+$/,y0=100,Rg=1e3;var qq=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function He(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function v0(e){return g0("sha256").update(Bt({type:He(e.type),author:He(e.author),item:He(e.item),harness:He(e.harness),agent_instance:He(e.agentInstance),provenance:He(e.provenanceFilter)})).digest("hex").slice(0,24)}function Ig(e,t){let n={version:Og,fingerprint:t,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function w0(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Og,n.fingerprint===t,typeof n.ts=="string",typeof n.stream_id=="string",typeof n.stream_offset=="number",Number.isSafeInteger(n.stream_offset),Number(n.stream_offset)>=0].every(Boolean)}function b0(e,t){let n=e.trim();if(n.length===0||n.length>4096||!xg.test(n))throw new d("Invalid mutation event cursor.",l.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new d("Invalid mutation event cursor.",l.USAGE,{code:"invalid_event_cursor"})}if(!w0(r,t))throw new d("Mutation event cursor does not match this query.",l.USAGE,{code:"event_cursor_query_mismatch"});return r}function k0(e){let t=e??y0;if(!Number.isSafeInteger(t)||t<0||t>Rg)throw new d(`Mutation event limit must be an integer from 0 to ${Rg}.`,l.USAGE,{code:"invalid_event_limit"});return t}function S0(e,t){let n=e?.trim();if(!n)return{};if(xg.test(n))return{cursor:b0(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new d("Mutation event --since must be an event cursor or ISO timestamp.",l.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function E0(e,t){let n=await Ca(e,t);if(n===null){if(!await Qu(e))return{...await Zu(e,t),source:"authoritative_history"};n=await Ca(e,t)}if(n===null)throw new d("Mutation event index could not be opened after rebuild.",l.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function A0(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new d("Mutation event cursor mode must be batch or row.",l.USAGE,{code:"invalid_event_cursor_mode"});return t}async function mi(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await R(t);let n=k0(e.limit),r=A0(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new d("Mutation event projections are mutually exclusive. Use --provenance or --full.",l.USAGE);let o=await A(t),s=o.agent_identity.identity_vocabulary,i=Fp(o.agent_identity.harness_signals),a=Mp({provenance:e.provenanceFilter},i),c=He(e.harness),m=v0(e),{cursor:u,sinceTimestamp:p}=S0(e.since,m),f={...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:He(e.type),authors:He(e.author),harnesses:c,harness_alias_authors:c?Object.entries(s.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:He(e.agentInstance),provenance:[...a].map(([y,h])=>({dimension:y,values:[...h]})),stream_ids:He(e.item),limit:n},_=await E0(t,f),g=_.events.map(y=>({...r==="row"?{cursor:Ig(y,m)}:{},item_id:y.stream_id,version:y.stream_offset+1,ts:y.entry.ts,author:y.entry.author,type:y.entry.op,...y.entry.message===void 0?{}:{message:y.entry.message},patch_count:y.entry.patch.length,...e.full===!0?{entry:y.entry}:{},...e.provenance===!0?{provenance:$p(y.entry,s,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:g,count:g.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:Ig(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Dp(_.events.map(y=>y.entry),s,i)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a196ae-61e1-528d-99a2-83eb9e11158b")}catch{}})();var T0="1h",C0="now",R0="+1d";function Ut(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Pg(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return be(n,r)}async function Lg(e,t,n,r){let o=Pg(e,t,n),s=[];return Ut(s,"start",n.start??C0),n.end!==void 0?Ut(s,"end",n.end):Ut(s,"duration",n.duration??T0),Ut(s,"location",n.location),Ut(s,"timezone",n.timezone),n.allDay===!0&&Ut(s,"all_day","true"),o.event=[s.join(",")],$t(o,r)}function Ng(e,t,n){return Lg("Meeting",e,t,n)}function Fg(e,t,n){return Lg("Event",e,t,n)}function Mg(e,t,n){let r=Pg("Reminder",e,t),o=[];return Ut(o,"at",t.at??R0),Ut(o,"text",t.text??e),r.reminder=[o.join(",")],$t(r,n)}import Pr from"node:crypto";import{cp as $g,lstat as I0,mkdir as mn,readFile as jn,readdir as yl,rename as Gg,rm as wl,writeFile as ui}from"node:fs/promises";import M from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="91604cb2-8afd-585e-9c18-26e223df25bc")}catch{}})();var jg="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var qg=M.join("runtime","workspace-snapshots"),O0=new Set(["checkpoints","locks","runtime","search","transactions"]),x0=/^[a-z0-9][a-z0-9._-]*$/,xr="sdk-workspace-transaction",gl={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Kg={renameEntry:Gg,removeEntry:async e=>{await wl(e,{recursive:!0,force:!0})}},vl=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await jn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==xr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await te(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
|
|
37
|
-
`)}};async function
|
|
38
|
-
`).filter(t=>t.trim().length>0).length}async function
|
|
39
|
-
`,"utf8"),await
|
|
40
|
-
`,"utf8"),await Gg(m,M.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function Lr(e,t){let n=await F0(e,t),r=await Wg(M.join(un(e),"objects",n,"manifest.json"),t);if(r.schema!==jg||r.fingerprint!==n)throw new d(`Snapshot manifest identity mismatch: ${t}`,l.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 Sl(e){let t=un(e),n=await yl(M.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&At(o))return[];throw o}),r=await yl(M.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&At(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Lr(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await jn(M.join(t,"refs",o),"utf8"))))}}async function El(e,t){let n=await Lr(e,t),{manifest:r,contents:o}=await Bg(e),s=new Map(r.files.map((p,f)=>[p,o[f]])),i=await P0(M.join(un(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),m=new Set([...a,...c]);for(let p of m){let f=s.get(p),_=i.get(p);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=Dg(s.get(p)),_=Dg(i.get(p));return{path:p,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(p=>p.removed_entries>0).sort((p,f)=>p.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:m.size,removed_file_count:[...a].filter(p=>!c.has(p)).length,added_file_count:[...c].filter(p=>!a.has(p)).length,removed_item_count:[...a].filter(p=>p.endsWith(".toon")&&!c.has(p)).length,affected_history_stream_count:u.length,removed_history_entry_count:u.reduce((p,f)=>p+f.removed_entries,0),affected_history_streams:u,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function Yg(e,t,n={}){if(n.force!==!0)throw new d("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",l.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",o=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,i=await we(e,xr,o,r,!1,!1,s),a=new vl(Qr(e,xr),r,o);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await El(e,t),f=await Lr(e,t),_=await kl(e),g=f.fingerprint,y=un(e),h=M.join(y,"objects",g,"files"),v=M.dirname(e),b=M.basename(e);c=M.join(v,`.${b}.restore-${Pr.randomUUID()}`);let S=M.join(v,`.${b}.backup-${Pr.randomUUID()}`);await Hg("restore_stage",async()=>{await mn(c,{recursive:!0}),await $g(h,c,{recursive:!0,force:!1}),await mn(M.join(c,"runtime"),{recursive:!0}),await $g(y,M.join(c,qg),{recursive:!0,force:!1})});let T=await lp({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:p.changed_file_count,removed_file_count:p.removed_file_count,removed_item_count:p.removed_item_count,affected_history_stream_count:p.affected_history_stream_count,removed_history_entry_count:p.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:s}),I=M.relative(c,T.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let D=Qr(c,xr);return await mn(M.dirname(D),{recursive:!0}),await ui(D,await jn(Qr(e,xr)),{flag:"wx"}),m=!0,await N0(c,e,S,Kg,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:I,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([wl(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function Jg(e,t){bl(t);let n=un(e);if(!/^[a-f0-9]{64}$/.test(t))return await Ug(M.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Sl(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Ug(M.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66cead7f-c3f3-5073-82a5-ad1535f3f611")}catch{}})();function Nr(e){let t={...e.args,...e.options};return be(e.options,t)}function yt(e,t){let n=w(e,t);if(n!==void 0)return n;throw new d(`Missing required parameter: ${t}`,l.USAGE)}function qn(e){return typeof e=="string"?[e]:ke(e)}function Xg(e){return kg(Nr(e),e.global)}function Qg(e){let t=Nr(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new d("Mutation event cursor mode must be batch or row.",l.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return mi({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:qn(t.type),author:qn(t.author),item:qn(t.item),limit:t.limit===void 0?void 0:Ge(t.limit,"limit"),full:t.full===!0,cursorMode:r,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:qn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:qn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:qn(t.provenanceFilter)}})}function Zg(e){let t=Nr(e),n=yt(t,"subcommand");if(n==="install")return tf({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return Cg({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return Of({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return Eg({artifact:yt(t,"artifact"),basePath:yt(t,"basePath"),oursPath:yt(t,"oursPath"),theirsPath:yt(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw xe({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function ey(e){let t=Nr(e),n=yt(t,"subcommand");if(n==="position")return r_(e.global);if(n!=="snapshot")throw xe({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??yt(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return kl(o,{name:w(t,"name")});if(r==="list")return Sl(o);let s=yt(t,"target");if(r==="inspect")return Lr(o,s);if(r==="delete")return Jg(o,s);if(r==="restore")return t.dryRun===!0?El(o,s):Yg(o,s,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Ge(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Ge(t.lockWaitMs,"lockWaitMs")});throw xe({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function pi(e){let t=Nr(e),n=yt(t,"title");return e.action==="meet"?Ng(n,t,e.global):e.action==="event"?Fg(n,t,e.global):Mg(n,t,e.global)}import W0 from"node:path";import M0 from"node:fs/promises";import ty from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ff76c0f3-d8cf-51de-a7e6-acb0a4942268")}catch{}})();var $0="templates",D0=".json",U0=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,G0=$o.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),j0=new Set(G0);function q0(e){let t=e.trim();if(!U0.test(t))throw new d(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,l.USAGE);return t}function ny(e){return ty.join(e,$0)}function ry(e,t){return ty.join(ny(e),`${t}${D0}`)}async function K0(e){await R(e)}function oy(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function z0(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(j0.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(s=>typeof s=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return oy(t)}function B0(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new d(`Template "${t}" has invalid options payload.`,l.GENERIC_FAILURE);let n=e,r={};for(let[o,s]of Object.entries(n)){let i=o.trim();if(i.length===0)throw new d(`Template "${t}" contains an empty option key.`,l.GENERIC_FAILURE);if(typeof s=="string"){r[i]=s;continue}if(Array.isArray(s)&&s.every(a=>typeof a=="string")){r[i]=[...s];continue}throw new d(`Template "${t}" contains invalid value for option "${i}".`,l.GENERIC_FAILURE)}return oy(r)}function H0(e,t){let n;try{n=JSON.parse(e)}catch{throw new d(`Template "${t}" contains invalid JSON.`,l.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new d(`Template "${t}" has invalid document shape.`,l.GENERIC_FAILURE);let r=n,o=B0(r.options,t),s=k();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:s,updated_at:typeof r.updated_at=="string"?r.updated_at:s,options:o}}async function V0(e,t){let n=await Z(ry(e,t));if(n===null)throw new d(`Template "${t}" not found`,l.NOT_FOUND);return H0(n,t)}async function Al(e,t,n){let r=E(process.cwd(),n.path);await K0(r);let o=q0(e),s=z0(t);if(Object.keys(s).length===0)throw new d("templates save requires at least one create option flag",l.USAGE);let i=k(),a=ry(r,o),c=i;await L(a)&&(c=(await V0(r,o)).created_at);let m={name:o,created_at:c,updated_at:i,options:s},u=await A(r);return await M0.mkdir(ny(r),{recursive:!0}),await Ze({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
|
|
41
|
-
`,op:"templates:save",author:C(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:a,options:m.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5529deea-21db-509b-9562-d5e08dfc004a")}catch{}})();var cy=["list","show","apply","lint"],Y0="schema-types",J0="schema-statuses",X0="schema-fields";function fi(){let e=O();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function ly(){let{profiles:e,warnings:t}=Vm(fi());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:Qm(n.definition)})),warnings:t,generated_at:k()}}function dy(e){let t;try{t=xo(e,fi())}catch(r){throw new d(r instanceof Error?r.message:String(r),l.USAGE)}let{resolved:n}=t;return{action:"show",...Zm(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function my(e){let t;try{t=xo(e,fi())}catch(o){throw new d(o instanceof Error?o.message:String(o),l.USAGE)}let{resolved:n}=t,r=wu(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:k()}}function Q0(e,t){return W0.join(e,"templates",`${t}.json`)}async function Z0(e,t){let n=await Z(Q0(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function sy(e,t,n,r){let o=new Map;for(let s of r.templates){let i=await Z0(e,s.name);i!==void 0&&o.set(s.name,i)}return{typesRaw:await Z(lt(e,t.files.types,ct.types)),statusesRaw:await Z(lt(e,t.files.statuses,ct.statuses)),fieldsRaw:await Z(lt(e,t.files.fields,ct.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Kn(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function iy(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Kn(t.types.changes),statuses:Kn(t.statuses.changes),fields:Kn(t.fields.changes),workflows:Kn(t.workflows.changes.map(s=>({key:s.type,status:s.status}))),config:Kn(t.config.changes),templates:Kn(t.templates.changes.map(s=>({key:s.name,status:s.status}))),packages:t.packages,warnings:[...new Set(o)].sort((s,i)=>s.localeCompare(i)),generated_at:k()}}async function eO(e){await R(e)}function tO(e){try{let t=xo(e,fi());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new d(t instanceof Error?t.message:String(t),l.USAGE)}}async function uy(e,t,n){let r=E(process.cwd(),n.path);await eO(r);let o=tO(e),s=o.profile,i=o.warnings,a=t.dryRun===!0,c=await A(r),m=Po(c.schema);if(a){let v=await sy(r,m,c,s),b=ay(s,v);return iy(s,b,!1,!0,[...i])}let u=C(t.author,c.author_default),p=mp(c),f=!!t.force,_=[...i],g=[],y=async v=>{g.push(await we(r,v,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},h;try{await y(Y0),await y(J0),await y(X0);let v=await sy(r,m,c,s);if(h=ay(s,v),h.types.changed){let b=lt(r,m.files.types,ct.types);await Ze({pmRoot:r,filePath:b,raw:Oo(h.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(s.types.map(I=>jm(I).name)),T=h.types.file.definitions.filter(I=>S.has(I.name));await cf(r,T,_,"profile:apply-type-folder"),_.push(...await V({path:b,scope:"project",op:"profile:apply-types"}))}if(h.statuses.changed){let b=lt(r,m.files.statuses,ct.statuses);await Ze({pmRoot:r,filePath:b,raw:Xm(h.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await V({path:b,scope:"project",op:"profile:apply-statuses"}))}if(h.fields.changed){let b=lt(r,m.files.fields,ct.fields);await Ze({pmRoot:r,filePath:b,raw:Wm(h.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await V({path:b,scope:"project",op:"profile:apply-fields"}))}if(h.config.changed||h.workflows.changed){for(let b of h.config.changes){if(b.status==="unchanged")continue;let S=No(b.key);S!==void 0&&Fo(c,S,b.value)}c.schema.type_workflows=h.workflows.result,await Oe(r,c,"profile:apply-config")}for(let b of h.templates.changes)b.status!=="unchanged"&&await Al(b.name,{...b.options},n)}finally{for(let v of g.reverse())try{await v()}catch{}}return iy(s,h,h.changed,!1,_)}function ay(e,t){try{return bu(e,t)}catch(n){throw new d(n instanceof Error?n.message:String(n),l.USAGE)}}import Tl from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d562ab68-1891-54cc-8256-57cc1121b9ce")}catch{}})();function py(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function nO(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function rO(e){let t=e.trim();if(t.length===0)throw new d("history-redact --regex requires a non-empty pattern.",l.USAGE);let n=t,r="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(n=t.slice(1,o),r=nO(t.slice(o+1)))}if(n.length===0)throw new d("history-redact --regex cannot use an empty pattern.",l.USAGE);try{new RegExp(n,r)}catch{throw new d("Invalid --regex value; provide a valid JavaScript regular expression.",l.USAGE)}return{kind:"regex",source:n,flags:r}}function oO(e,t){let n=[...new Set(py(e).map(s=>s.trim()))].filter(s=>s.length>0).map(s=>({kind:"literal",value:s})),r=[...new Set(py(t).map(s=>s.trim()))].filter(s=>s.length>0).map(rO),o=[...n,...r];if(o.length===0)throw new d("history-redact requires at least one matcher via --literal or --regex.",l.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return o}function sO(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){let s=e.indexOf(t,r);if(s===-1)break;o+=1,r=s+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function iO(e,t,n){let r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function _y(e,t,n){let r=e,o=0;for(let s of t){let i=s.kind==="literal"?sO(r,s.value,n):iO(r,s,n);r=i.value,o+=i.replacements}return{value:r,replacements:o}}function _i(e,t,n){if(typeof e=="string")return _y(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(s=>{let i=_i(s,t,n);return r+=i.replacements,i.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,o={};for(let[s,i]of Object.entries(e)){let a=_i(i,t,n);r+=a.replacements,o[s]=a.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function fy(e,t,n){let r=0;return{patch:e.map(s=>{if(!Object.prototype.hasOwnProperty.call(s,"value"))return s;let i=_i(s.value,t,n);return r+=i.replacements,i.replacements>0?{...s,value:i.value}:s}),replacements:r}}function aO(e){let t=structuredClone(Ia),n=0,r=0;for(let o=0;o<e.length;o+=1){let s=e[o];rr(t)!==s.before_hash&&(n+=1),t=En(t,s.patch,o+1,s.op),rr(t)!==s.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function cO(e,t,n){let r=0,o=!1,s=!1,i=e.message;if(typeof e.message=="string"){let m=_y(e.message,t,n);i=m.value,r+=m.replacements,m.replacements>0&&(o=!0)}let a=fy(e.patch,t,n);r+=a.replacements,o||=a.replacements>0;let c=e.reanchor_evidence?.map(m=>{let u=m.patch?fy(m.patch,t,n):{patch:void 0,replacements:0},p=m.record?_i(m.record,t,n):{value:void 0,replacements:0};r+=u.replacements,r+=p.replacements;let f=u.replacements>0||p.replacements>0;if(o||=f,!f)return m;s=!0;let{patch:_,record:g,record_hash:y,record_hash_version:h,...v}=m;return u.replacements>0?v:{...v,patch:m.patch}});return{entry:{...e,message:i,patch:a.patch,...c?{reanchor_evidence:c}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:s}}function lO(e,t,n){let r=structuredClone(Ia),o=0,s=0,i=[];for(let a=0;a<e.length;a+=1){let c=e[a],m=op(c);if(!m.ok)throw new d(`history-redact refuses invalid immutable record ${a+1} (${m.error}).`,l.GENERIC_FAILURE);let u=cO(c,t,n);s+=u.replacements,u.changed&&(o+=1);let p=rr(r);r=En(r,u.entry.patch,a+1,u.entry.op);let f=rr(r);i.push(sp(c,{...u.entry,before_hash:p,after_hash:f},{retainPriorRecord:u.changed,retainPriorRecordHash:!u.changed}))}return{entries:i,finalDocument:r,entriesChanged:o,replacements:s}}function dO(e){return Object.keys(e.metadata).length>0}function mO(e){if(!dO(e.finalDocument))return{raw:null,path:null,document:null};let t=Xe(Qe(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new d("history-redact would change the item id; narrow your patterns.",l.USAGE);return{document:t,path:it(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:qe(t,{format:"toon",schema:e.settings.schema})}}function uO(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function pO(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??Qe(e.rewritten.finalDocument);return t.push(Ie({nowIso:k(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function fO(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await xt(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let s=new Map;e.currentItem.path&&e.currentItem.raw!==null&&s.set(e.currentItem.path,e.currentItem.raw);let i=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await te(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await Tl.rm(e.currentItem.path,{force:!0}),await te(e.subject.historyPath,cp(e.rewrittenEntries))}catch(c){try{await _O(e.subject.historyPath,n,o,s)}finally{await Ra(e.subject.historyPath)}throw c}await Ra(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Pt({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(a=>{i=()=>{throw a}})}i()},afterWrite:async()=>[...t,...await hO(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function _O(e,t,n,r){t===null?await Tl.rm(e,{force:!0}):await te(e,t);for(let o of n){let s=r.get(o);s===void 0?await Tl.rm(o,{force:!0}):await te(o,s)}}async function hO(e,t){let n=[],r=new Set(t.filter(o=>o!==null));for(let o of r)n.push(...await V({path:o,scope:"project",op:"history_redact"}));return n.push(...await V({path:e,scope:"project",op:"history_redact:history"})),n}async function hy(e,t,n){let{pmRoot:r,settings:o,typeRegistry:s}=await ir(n.path),i=t.replacement??"",a=i.length===0,c=a?"[redacted]":i,m=oO(t.literal,t.regex),u=await Jt(r,e,o,s.type_to_folder);return _s({pmRoot:r,subject:u,settings:o,typeRegistry:s,operation:"history-redact",options:t,transform:p=>gO({pmRoot:r,subject:u,settings:o,typeRegistry:s,options:t,rules:m,replacement:c,replacementIsDefault:a},p)})}function gO(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:s,options:i,rules:a,replacement:c,replacementIsDefault:m}=e,u=t.entries,p=aO(u),f=lO(u,a,c),_=p.hashMismatchesBefore+p.hashMismatchesAfter,g=!!i.dryRun,y=f.replacements>0,h=[];_>0&&h.push(`history_redact_preexisting_hash_mismatches:${_}`),y||h.push("history_redact_no_matches");let v={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},b=mO({pmRoot:n,subject:r,settings:o,typeToFolder:s.type_to_folder,finalDocument:f.finalDocument}),S=(v.path??null)!==(b.path??null)||(v.raw??null)!==(b.raw??null),T=t.author,I=uO(i,f),{rewrittenEntries:D,auditEntryAdded:N}=pO({rewritten:f,dryRun:g,changed:y,nextItemDocument:b.document,author:T,message:I});return{changed:y,rewrittenEntries:D,...fO({pmRoot:n,subject:r,settings:o,typeRegistry:s,currentItem:v,nextItem:b,author:T,rewrittenEntries:D}),report:({verification:X,warnings:K})=>({id:r.id,dry_run:g,changed:y,patterns:{literal_count:a.filter(W=>W.kind==="literal").length,regex_count:a.filter(W=>W.kind==="regex").length,total_count:a.length,replacement_is_default:m},history:{path:r.historyPath,entries_scanned:u.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:p.hashMismatchesBefore,hash_mismatches_after:p.hashMismatchesAfter,preexisting_hash_mismatches:_,audit_entry_added:N,verify_ok:X.ok,verify_errors:X.errors},item:{existed_before:v.path!==null,exists_after:b.path!==null,path_before:v.path,path_after:b.path,changed:S},warnings:[...new Set([...h,...K])].sort((W,Q)=>W.localeCompare(Q)),generated_at:k()})}}import yy from"node:fs/promises";import vy from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d51da34a-9f37-5441-91f0-15a16b601709")}catch{}})();function yO(e,t,n){let r=new Set,o=[];for(let s of e){let i=s.trim();if(i.length===0||r.has(i))continue;r.add(i);let a=t.get(i);if(a===void 0){o.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){o.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return o}function vO(e,t){let n=[...e].sort((o,s)=>s.entries-o.entries||o.id.localeCompare(s.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function gy(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return yO(t.ids,n,t.minEntries)}return vO(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d6824edc-ca22-5900-b43b-645135e2562d")}catch{}})();function wO(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new d("history-compact --before requires a non-empty value.",l.USAGE);if(/^\d+$/.test(n)){let s=Number.parseInt(n,10),i=Sn(t);if(!Number.isSafeInteger(s)||s<i+1||s>i+t.length+1)throw new d(`history-compact --before version must be between ${i+1} and ${i+t.length+1}.`,l.USAGE);let a=s-i-1;return{kind:"version",raw:n,compactCount:a,retainedCount:t.length-a}}let r=Date.parse(n);if(!Number.isFinite(r))throw new d(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,l.USAGE);let o=0;for(let[s,i]of t.entries()){let a=Date.parse(i.ts);if(!Number.isFinite(a))throw new d(`History for this item contains invalid timestamp at entry ${s+1}.`,l.GENERIC_FAILURE);if(a>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function bO(e,t){let n=Ho(),r=Ho();for(let o=0;o<e.length;o+=1){let s=e[o];n=En(n,s.patch,o+1,s.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function kO(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:tp.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&ip(or(e.document),r).includes(n.after_hash))}}function SO(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function EO(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function AO(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=bO(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Sn(e.historyEntries,!0),s=Ie({nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:Qe(Ho()),after:Qe(t),message:EO(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:np(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),i=e.historyEntries[e.boundary.compactCount-1],a=[rp({...s,before_hash:e.historyEntries[0].before_hash,after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...r];return e.dryRun||a.push(Ie({nowIso:k(),author:e.author,op:"history_compact",before:Qe(n),after:Qe(n),message:SO(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Cl(e,t,n){let{pmRoot:r,settings:o,typeRegistry:s}=await ir(n.path),i=await Jt(r,e,o,s.type_to_folder);return _s({pmRoot:r,subject:i,settings:o,typeRegistry:s,operation:"history-compact",options:t,transform:a=>TO(i,t,a)})}function TO(e,t,n){let r=e.historyPath,o=n.entries,s=n.verification;if(!s.ok)throw new d(`history-compact requires a valid history chain (${s.errors.join(", ")}). Run pm history-repair ${e.id} first.`,l.CONFLICT);let i=wO(t.before,o),a=i.compactCount>0,c=!!t.dryRun,m=n.author,u=[];a||u.push("history_compact_noop_before_boundary");let p=kO(n.loadedItem,o);p.matchedChainBefore===!1&&u.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:_,auditEntryAdded:g}=AO({historyEntries:o,boundary:i,changed:a,dryRun:c,author:m,options:t}),y=Sn(o,!0),h=i.retainedCount>0&&y!==null?y+i.compactCount+1:null;return{changed:a,rewrittenEntries:f,report:({verification:v,warnings:b})=>({id:e.id,dry_run:c,changed:a,compact_boundary:{kind:i.kind,before:i.raw,entries_compacted:i.compactCount,entries_retained:i.retainedCount,first_retained_entry:h},history:{path:r,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:_,audit_entry_added:g,verify_ok:v.ok,verify_errors:v.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:p.matchedChainBefore},warnings:[...new Set([...u,...b])].sort((S,T)=>S.localeCompare(T)),generated_at:k()})}}var CO=3;function RO(e){for(let n of["allOver","minEntries"]){let r=e[n];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new d(`history-compact ${n} must be a non-negative safe integer.`,l.USAGE)}let t=os(e.ids);if(e.ids!==void 0&&t==="")throw new d("history-compact ids requires at least one valid item ID.",l.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:rs(t)}}function wy(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new d("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",l.USAGE);if(e!==void 0&&(n||r))throw new d("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",l.USAGE);if(n&&r)throw new d("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",l.USAGE)}function IO(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function OO(e){let t=$(e.settings.schema),n=bs(t),r=await pe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),s=vy.join(e.pmRoot,"history"),i=[],a=[];if(!await L(s))return{candidates:i,preselectionErrors:a};let c=(await yy.readdir(s)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=vy.join(s,m),p=m.slice(0,-6);try{let f=await yy.readFile(u,"utf8");await vn({path:u,scope:"project"}),i.push({id:p,entries:IO(f),bucket:o.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:i,preselectionErrors:a}}async function xO(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await Cl(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function by(e,t){let n=RO(e),{pmRoot:r,settings:o,typeRegistry:s}=await ir(t.path),{candidates:i,preselectionErrors:a}=await OO({pmRoot:r,settings:o,typeToFolder:s.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??CO,u=o.history.compact_policy,p=c==="scan"&&e.allOver===void 0&&u.enabled,f=e.allOver??(p?u.max_entries:void 0),_=gy(i,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),g=!!e.dryRun,y=[...a],h={streams_considered:i.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let v of _){let b=await xO({row:v,options:n,dryRun:g,global:t});if(y.push(b.result),!b.selected){h.items_skipped+=1;continue}h.selected+=1,b.compacted&&(h.items_compacted+=1),b.errored&&(h.items_errored+=1)}return{bulk:!0,dry_run:g,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:p},totals:h,results:y,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="41f0e5cd-5974-5451-9f34-2aec1d8df07c")}catch{}})();function ky(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return Ff(n,t),t?hs(e.options,e.global):Mt(n,e.options,e.global)}function Sy(e){let t=e.options.ids,n=os(t);if(t!==void 0&&n==="")throw new d("history-compact ids requires at least one valid item ID.",l.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:rs(n),o=Ge(e.options.allOver??e.options.all_over,"history-compact allOver"),s=Ge(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),i=w(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(i==="closed"||i==="all-streams")&&a.push(i);let c=[...new Set(a)];if(c.length>1)throw new d("history-compact: closed and all-streams scopes are mutually exclusive.",l.USAGE);let m=c[0];return wy(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?Cl(e.id,{before:w(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global):by({ids:r,scope:m,allOver:o,minEntries:s,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="961c1918-75f9-5e5d-bbae-b333ca29534f")}catch{}})();function hi(e){return Lo("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd0e532e-0f27-5786-8216-c17132f6e784")}catch{}})();async function Rl(e,t,n,r){let o=t.trim();if(o.length===0)throw new d("pm item reopen requires a non-empty recurrence reason.",l.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let s=E(process.cwd(),r.path),i=$((await A(s)).schema),a=i.open_status,c=hi(i),m=n.status??a,u=ee(m,i)??m;if(u!==a&&u!==c)throw new d(`Reopen target status must be ${a} or ${c}; received ${m}.`,l.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([a,c])],suggested_retry:`pm item reopen ${e} "${o}" --status ${a}`,suggested_retry_args:["item","reopen",e,o,"--status",a]}});let p=await vh(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:p.item,changed_fields:p.changed_fields,warnings:p.warnings,recurrence:p.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ddf427ce-aa09-5f14-be4d-d5e25c91eef0")}catch{}})();async function Ey(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Pe(e.args,e.options),o=e.force===!0||r.force===!0,s={...e.args,...r},i=e.args.next===!0||r.next===!0?await v_(o,e.global,s,s):await br(Il(e,r),o,e.global,s);return De(i,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Il(e,t){let n=e.id??w(t,"id");if(!n)throw new d("Missing required argument: id",64);return n}function Ay(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function Ty(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Pe(e.args,e.options);return De(await pt(Il(e,r),Ay(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Cy(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Pe(e.args,e.options);return De(await Rl(Il(e,r),Ay(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="419a061f-e181-5b18-9e3a-d22cc5aff416")}catch{}})();function Ry(e,t,n){let r;if(typeof e.lines=="string")r=gs(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");r=gs(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="afa4af56-0f0f-5603-b58c-7beff3d82004")}catch{}})();var PO=ha("list").properties.outputSession,LO={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:{...PO},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Iy={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},ae={type:"string",description:"pm item id, for example pm-abc1."},NO=`Operation name (one of): ${ma.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,FO={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."}},MO={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function U(e,t=[]){return{...Iy,properties:{...Iy.properties,...e},required:t}}var $O=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:U({action:{type:"string",enum:[...ma],description:NO},id:ae,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."},...LO},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:U({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:U({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:U({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid, options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:U({query:{type:"string"},options:{type:"object"},...MO},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:U({options:{type:"object"},...FO})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:U({id:ae,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:U({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:U({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:ae,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:ae,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:U({id:ae,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:U({id:ae,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:ae,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:U({id:ae,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:U({id:ae,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:ae,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:U({id:ae,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:U({id:ae,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:U({id:ae,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:U({id:ae,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:U({id:ae,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:U({id:ae,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:U({subcommand:{type:"string",enum:[...du]},id:ae,target:ae,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:U({id:ae,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:U({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:U({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:U({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Schema mutations write workspace config files, not item history.",inputSchema:U({subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset"],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or custom field key (show-field/add-field/remove-field). Required for those subcommands."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...Vi]},description:`Lifecycle roles for add-status: ${Vi.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys."}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:U({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:U({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:U({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],DO={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"},UO=$O.map(e=>{let t=DO[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:ha(t,{properties:n,required:r})}});function Oy(){return UO.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5fbd5bc2-6f35-5f7e-b357-7c16e6991787")}catch{}})();var xy=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),GO=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],jy=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),yi=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"]),Fr=new Set(["cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),qy=new Map([["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),Ky=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"]]),zy=new Map([...Ky.entries()].flatMap(([e,t])=>vt(t).map(n=>[n,e]))),By=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Hy=new Map(By.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),jO=10,qO=20,Py=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-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),Vy=[["init",em],["install",nm],["uninstall",rm],["explore",om],["manage",dm],["describe",sm],["reload",mm],["doctor",um],["catalog",pm],["adopt",fm],["adopt-all",im],["activate",am],["deactivate",cm],["migrate",lm]],KO=[...Vy.map(([e,t])=>e==="init"?[e,tm]:[e,t]),["upgrade",Qn]],zO=[...Vy.map(([e,t])=>[`extension ${e}`,t]),...KO.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",lo],["config",Zd],["extension",mo],["package",Xn],["packages",Xn],["install",_m],["create",go],["item mutate",Nm],["item complete",Fm],["item reopen",Mm],["copy",yo],["focus",vo],["update",wo],["update-many",bo],["upgrade",Qn],["calendar",Zn],["cal",Zn],["context",er],["ctx",er],["get",ko],["search",Co],["eval",Um],["workspace",Tt],["workspace position",[]],["workspace snapshot",Tt],["workspace snapshot create",Tt],["workspace snapshot list",Tt],["workspace snapshot inspect",Tt],["workspace snapshot restore",Tt],["workspace snapshot delete",Tt],["next",To],["aggregate",so],["deps",Eo],["graph",Ao],["guide",So],["reindex",hm],["history",io],["history-compact",Jd],["history-redact",Wd],["history-repair",Yd],["history-author-acknowledge",ao],["merge",Vd],["schema",Xd],["profile",Qd],["plan",co],["restore",vm],["delete",wm],["close",gm],["close-many",uo],["append",po],["claim",ym],["release",bm],["start-task",km],["pause-task",Sm],["close-task",Em],["comments",qd],["notes",Kd],["learnings",zd],["files",Bd],["docs",Hd],["test",Cm],["test-all",Rm],["telemetry",Im],["test-runs",Om],["gc",xm],["stats",fo],["duplicates",_o],["validate",Pm],["health",ho],["assurance",Lm],...Gm,["contracts",Ro],["completion",Io],["activity",$m],...[...jy].map(e=>[e,oo])],Mr=new Map(zO);for(let{alias:e,canonical:t}of Ht)Mr.set(t,Mr.get(e));function BO(e){let t=zy.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Ly(e){let t=Ht.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:la.includes(e)?ge(e):e.startsWith("extension-")?ge(`extension ${e.slice(10)}`):e.startsWith("package-")?ge(`package ${e.slice(8)}`):e.startsWith("item-")?ge(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ge(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ge(`templates ${e.slice(10)}`):yi.has(e)?Ky.get(e)??ge(e):null}function HO(e,t){let n=no(t);return n!==t?e.action===n:e.command_path===null?!1:vt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function vt(e){return e.split("|").map(t=>ge(t)).filter(t=>t.length>0)}function VO(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let s of vt(o.command_path)){let i=s.split(" ").filter(a=>a.length>0);if(i.length!==0)for(let a=i.length;a>0;a-=1){let c=i.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,s)=>o.localeCompare(s))}function gi(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 WO(e,t){if(!t)return{...e};let r=$r(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:r}}function Ol(e,t){let r=$r(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function ge(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Wy(e){return e.replace(/\s+/g,"-")}function tt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ny(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=tt(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function xl(e,t,n){n&&(e[t]=!0)}function Fy(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function YO(e){let t=Fy(e.long,"long"),n=Fy(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),xl(o,"required",e.required===!0),xl(o,"repeatable",e.repeatable===!0),xl(o,"list",e.list===!0);let s=tt(e.description);s&&(o.description=s);let i=tt(e.value_name);i&&(o.value_name=i);let a=[tt(e.value_type),tt(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(o.value_type=a),o}function Yy(e){let t=new Map;for(let r of e){let o=ge(r.target_command);if(o.length===0)continue;let s=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;s.sourceDedupe.has(i)||(s.sourceDedupe.add(i),s.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=YO(a);if(!c)continue;let m=`${c.flag}|${c.short??""}`;s.dedupe.has(m)||(s.dedupe.add(m),s.flags.push(c))}t.set(o,s)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((s,i)=>{let a=s.layer.localeCompare(i.layer);return a!==0?a:(s.name??"").localeCompare(i.name??"")})});return n}function JO(e){let t=Yy(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let i=ge(s.command);if(i.length===0)continue;let a=tt(s.action)??Wy(i),c=Array.isArray(s.arguments)?s.arguments.map(m=>{let u=tt(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:tt(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{command:i,action:a,source:{layer:s.layer,name:s.name},description:tt(s.description),intent:tt(s.intent),arguments:c,flags:t.get(i)?.flags??[],examples:Ny(s.examples),failure_hints:Ny(s.failure_hints)})}let r=new Set;for(let s of e.handlers)r.add(ge(s));for(let s of n.keys())r.add(s);for(let s of t.keys())r.add(s);let o=[];for(let s of[...r].sort((i,a)=>i.localeCompare(a))){let i=n.get(s);o.push(XO(s,i,t.get(s)?.flags??[]))}return o}function XO(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Wy(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function QO(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(o,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function ZO(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 ex(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function tx(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=ZO(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let s=QO(o);!s||n[s]!==void 0||(n[s]=ex(o,e.action),o.required===!0&&r.push(s))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function nx(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,i)=>s.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let i=`${s.flag}|${s.short??""}`;if(!o.has(i))o.add(i),r.flags.push(s);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);a&&nx(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 ox(e,t=A){let n={mode:St.extensions.policy.mode,trust_mode:St.extensions.policy.trust_mode,default_sandbox_profile:St.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await L(ue(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),s=await eo({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),i=await to({...s,loaded:s.loaded});return{handlers:new Set(i.commands.handlers.map(c=>ge(c.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function sx(e,t={}){let n=new Map;for(let r of da){let o=yi.has(r);if(o&&!t.includePackageOwnedActions)continue;let s=Ly(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:s})}if(t.includePackageOwnedActions)for(let r of yi)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Ly(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ge(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function ix(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null};let n=e.command_path?vt(e.command_path):[],r=n.some(i=>t.handlers.has(i)),o=n.map(i=>qy.get(i)).find(i=>typeof i=="string"),s=t.disabledReason===null&&r;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function Jy(e){return Mr.get(e)??ro}function ax(e){return Fr.has(e)?!1:Mr.has(e)}function cx(e){return jy.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function My(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 dx(e){let t=new Map;for(let r of e.definitions){let o=My(r.cli_flag);if(!o)continue;let s=r.cli_aliases.map(a=>lx(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>My(a)).filter(a=>a!==null&&a!==o);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=s?{flag:o,short:s}:{flag:o},u=`${m.flag}|${m.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(m));for(let p of i){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,sa(o.flags));return n}function $y(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let s=`${o.flag}|${o.short??""}`;r.has(s)||(r.add(s),n.push(o))}return sa(n)}function mx(e,t,n,r){return e.map(o=>{let s=ax(o),i=s?Jy(o):[],a=n.get(cx(o))??[],c=t.get(o),m=$y(i,a),u=$y(m,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:o,flags:u,...r?{canonical_command:Pl(o),visibility:Nu(Pl(o)),positionals:Ud(o)?.slots??[],flag_invocations:qo(o,u)}:{},provider:p,extension_sources:c?.sources}}).sort((o,s)=>o.command.localeCompare(s.command))}function ux(e,t=Jn){let n=new Set(e),r=new Map;for(let o of By){let s=o.aliases.filter(i=>n.has(i));r.set(o.canonical,{canonical:o.canonical,aliases:s,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let s=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};s.aliases.includes(o.alias)||s.aliases.push(o.alias),s.contracts.push(o),r.set(o.canonical,s)}return[...r.values()].map(({contracts:o,...s})=>o.length===0?s:{...s,contracts:o}).sort((o,s)=>o.canonical.localeCompare(s.canonical))}function px(){return{create_string_options:ku,create_repeatable_options:$o,update_string_options:Su,update_repeatable_options:Eu,list_string_options:Nd,search_string_options:Fd,calendar_string_options:Md,context_string_options:$d,activity_string_options:Dd}}function Dy(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=hn(e,"create",n),o=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(o.map(a=>ve("create",a)))].sort((a,c)=>a.localeCompare(c)),i=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:o,required_flags:s,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function fx(e){let t={},n={};for(let r of[...e.types].sort((o,s)=>o.localeCompare(s))){let o=e.by_type[r];t[r]=Dy(o,"strict"),n[r]=Dy(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function _x(e,t){let n=$r(e);if(n.length===0)return e;let r=!1,o=n.map(s=>{let i=s.properties;if(typeof i!="object"||i===null)return s;let a=i.action;return typeof a!="object"||a===null||a.const!=="create"?s:(r=!0,{...s,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function hx(e){let t=gi(e.action)!==void 0||gi(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,s=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=gi(e.action),u=gi(e.command),p=!r&&!c&&!o&&!s&&!i&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:o,flagsOnly:s,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function gx(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new d("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",l.USAGE)}async function yx(e,t=A){try{return await t(e)}catch{return structuredClone(St)}}async function vx(e,t){let n=await yx(t),r=await ox(e),o=x(n,r.registrations??O()),s=Je(n.schema),i=JO(r);return{settings:n,runtimeProbe:r,typeRegistry:o,statusRegistry:$(n.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:dx(s),createRequiredOptionContracts:fx(o),extensionContracts:i,mergedExtensionContracts:rx(i),extensionFlagMap:Yy(r.flagRegistrations)}}function Uy(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&yi.has(e.selectedAction)||e.selectedCommand!==void 0&&Fr.has(e.selectedCommand))}function wx(e,t){let n=sx(t,{includePackageOwnedActions:Uy(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(pu);return n.filter(o=>!r.has(o.action))}return Uy(e)&&e.selectedCommand!==void 0&&Fr.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:BO(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function bx(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new d(`Unknown action: "${e.selectedAction}".`,l.USAGE)}function kx(e,t){return[...new Set([...la.filter(n=>!Fr.has(n)),...[...Mr.keys()].filter(n=>!Fr.has(n)),...e.flatMap(n=>n.command_path?vt(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>ge(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function Sx(e,t){let n=t.slice(0,jO),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),s=t.slice(0,qO),i=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new d(`Command "${e}" is a command namespace. Choose a concrete child command: ${o}.`,l.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:i,nextSteps:[`Retry with a child command, for example: ${i[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function Ex(e,t){return new d(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,l.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function Ax(e){return new d(`Unknown command: "${e}".`,l.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 Tx(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 Sx(e.selectedCommand,r);let o=qy.get(e.selectedCommand);throw o?Ex(e.selectedCommand,o):Ax(e.selectedCommand)}function Cx(e,t){let n=wx(e,t.mergedExtensionContracts);bx(e,n);let r=kx(n,t.mergedExtensionContracts);Tx(e,r);let o=e.selectedCommand?zy.get(e.selectedCommand):void 0,s=e.selectedCommand?n.filter(m=>o?m.action===o:HO(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.some(m=>m.action===e.selectedAction))throw new d(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,l.USAGE);let i=e.selectedAction?s.filter(m=>m.action===e.selectedAction):s,a=[...new Map(i.map(m=>ix(m,t.runtimeProbe)).map(m=>[o?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(m=>m.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:s,scopedActionDescriptors:i,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function Rx(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 o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function Ix(e){let t=vu,n=$r(t),r=Rx(t),o=e.filter(s=>!r.has(s.action)).map(s=>tx(s));return o.length>0?{...t,oneOf:[...n,...o]}:t}function Gy(e,t,n){let r=new Set(t.actionDescriptors.map(s=>s.action)),o=e.selectedAction?WO(n,e.selectedAction):e.selectedCommand?Ol(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):Ol(n,r);return e.runtimeOnly&&!e.selectedAction?Ol(o,new Set(t.actions)):o}function Ox(e,t,n){let r=Ix(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?_x(Gy(e,n,r),t.createRequiredOptionContracts):Gy(e,n,r);return{mergedSchema:r,filteredSchema:s}}function xx(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?VO(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Px(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Jn.filter(r=>r.hidden&&(r.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(r=>r.alias));return t.filter(r=>!n.has(r))}function Pl(e){let t=Ht.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Hy.get(n)??n}var Lx=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"]]),Nx=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function Fx(e,t){let n=Py.get(no(e))??(e.includes(" ")?void 0:Py.get(Pl(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>vt(m.command).includes(e));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let o=e.split(" "),s=o.at(-1),i=o.slice(0,-1).join(" "),a=Lx.get(s),c=Nx.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function Mx(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(ge))].filter(s=>s.length>0).sort((s,i)=>s.localeCompare(i)).map(s=>{let i=ua(s,{generateFallback:!0}),a=s.split(" ")[0],c=Hy.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),m=new Set([...Jy(s).map(f=>f.flag),...t.filter(f=>vt(f.command).includes(s)).flatMap(f=>f.flags.map(_=>_.flag))]),u=(xy.get(no(s))??xy.get(c)??GO).filter(f=>m.has(f)),p=Fx(s,t);return{command:s,intent:p.intent,...o||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:i.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...i.default_max_estimated_tokens_by_format}}:{}}})}function $x(e){return e.map(t=>({budget:ua(t,{generateFallback:!0}),envelope:$u(t)}))}function Dx(e){let t=new Map;for(let n of e){let r=Tu(n),o=r===void 0?[l.SUCCESS,l.GENERIC_FAILURE,l.USAGE,l.NOT_FOUND,l.CONFLICT,l.DEPENDENCY_FAILED]:r.exit_codes,s=o.join(","),i=t.get(s)??{commands:[],exit_codes:o};i.commands.push(n),t.set(s,i)}return[...t.values()]}function Ux(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>vt(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>vt(o.command).some(s=>r.has(s)))}return t.extensionContracts}function Gx(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 jx(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,s])=>[o,[...new Set(s.map(i=>`--${i.cli_flag}`))].sort((i,a)=>i.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...ou],services:[...su],policy_modes:[...iu],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...lu],trust_modes:[...au],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...cu],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...ud],create_modes:[...pd],close_validation_modes:[...fd],workflow_enforcement_modes:[..._d]},e.relationship_kind_contracts=[...kd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,s)=>o.kind.localeCompare(s.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function qx(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 Kx(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=mx(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let s=new Set(r);e.list_projections=Object.entries(Gu).filter(([i])=>s.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...Uu],compact_fields:[...Du]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:s,aliases:i})=>({canonical:s,aliases:i})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function zx(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=px();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function Bx(e,t,n,r){e.command_summaries=Mx(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[..._u],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(ge))].filter(o=>fa(o)!==void 0).sort((o,s)=>o.localeCompare(s)).map(o=>({command:o,modes:[...gu(o).keys()]}))}:{}},e.grammar_contracts={nouns:Vt.nouns,shared_verbs:Vt.shared_verbs,scope_before_verb:Vt.scope_before_verb,visible_top_level_ceiling:Vt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Vt.ceiling_raise_requires_pm_item,positional_shape_budget:Vt.positional_shape_budget,positional_shape_count:new Set(oa.map(({slots:o})=>jd(o))).size,positional_action_count:ra.length,positional_action_parents:[...new Set(ra.map(({parent:o})=>o))].sort((o,s)=>o.localeCompare(s)),...r.includePositionalSignatures?{positional_signatures:oa}:{}}}async function Xy(e,t){let n=hx(e);gx(n);let r=E(process.cwd(),t.path),o=await vx(t,r),s=Cx(n,o),i=Ox(n,o,s),a=xx(n,s),c=Px(n,a),m=Gx(n,i,s,c),u=Ux(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&Bx(m,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return m;let f=ux(s.commandCatalog);return n.flagsOnly&&!n.fullOutput||jx(m,o,n),qx(m,n,i,u),Kx(m,n,o,c,f),zx(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...qp],gate_triggers:[...jp]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=Gd),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=Oy(),m.context_intents=Ou(),m.read_output_dimensions=pa,m.error_codes=Lu,m.command_output_contracts=$x(c),m.diagnostic_output_contracts=hu,m.command_exit_contracts={vocabulary:Au,command_sets:Dx(c)}),m}import RP from"node:fs/promises";import _v from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60090339-2f94-5f22-be47-518498838b92")}catch{}})();function vi(e,t,n,r,o,s="min"){let i=o==="min"?e-t:t-e,a=s==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&a<0}function Hx(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,s=null,i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let u;try{u=JSON.parse(m)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(vi(f,i,p,o,"min")&&(i=f,o=p),vi(f,a,p,s,"max","max")&&(a=f,s=p))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:s}}function Qy(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:g})=>Hx(_,g)),s=0,i=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of o){if(s+=_.lines,i+=_.bytes,_.oldest_ts!==null){let g=Date.parse(_.oldest_ts);vi(g,m,_.id,a?.id??null,"min")&&(m=g,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let g=Date.parse(_.newest_ts);vi(g,u,_.id,c?.id??null,"max")&&(u=g,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...o].sort((_,g)=>g.bytes-_.bytes||_.id.localeCompare(g.id)).slice(0,r),f=r===0?[]:[...o].sort((_,g)=>g.lines-_.lines||_.id.localeCompare(g.id)).slice(0,r);return{total_streams:e.length,total_lines:s,total_bytes:i,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as Wx}from"node:crypto";import{execFile as Yx}from"node:child_process";import tv from"node:path";import{promisify as Jx}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39d2b5aa-c6f3-57ac-adb4-e775bc838828")}catch{}})();var Zy=1;function Vx(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 Ll(e){if(e===null)return{format_version:Zy,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new d("Improvement ledger contains invalid JSON.",l.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Zy||!Array.isArray(t.observations))throw new d("Improvement ledger has an unsupported shape or format version.",l.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!Vx(r))throw new d("Improvement ledger contains an invalid observation.",l.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c800f76b-2867-51f5-80d6-fb7b1c61f9e4")}catch{}})();var Xx=Jx(Yx),Qx=50,ev=1e3,Zx=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function nv(e){let t=e.trim().toLowerCase();if(!Zx.test(t))throw new d(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,l.USAGE,{code:"invalid_improvement_metric"});return t}function eP(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new d("Improvement direction must be higher, lower, or target.",l.USAGE,{code:"invalid_improvement_observation"});return t}function Dr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new d(`${t} must not exceed 256 characters.`,l.USAGE,{code:"invalid_improvement_observation"});return n}}function tP(e){let t=e??Qx;if(!Number.isSafeInteger(t)||t<0||t>ev)throw new d(`Improvement observation limit must be an integer from 0 to ${ev}.`,l.USAGE,{code:"invalid_improvement_observation_limit"});return t}function rv(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new d(`${t} must be an ISO timestamp.`,l.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function nP(e,t,n){if(!Number.isFinite(n.value))throw new d("Improvement observation value must be finite.",l.USAGE,{code:"invalid_improvement_observation"});let r=nv(n.metric),o=eP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new d("Target-directed observations require a finite threshold.",l.USAGE,{code:"invalid_improvement_observation"});let s=await oP(e,n.revision),i=Dr(n.source,"source"),a=Dr(n.itemId,"itemId"),c=Dr(n.unit,"unit"),m=Dr(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,r,i??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:rv(n.observedAt??k(),"observedAt"),...s,author:C(n.author,t.author_default),...a===void 0?{}:{item_id:a},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:Wx("sha256").update(Bt(u)).digest("hex").slice(0,24),...u}}function rP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new d(`Improvement observation retry key already records a different value for ${t.metric}.`,l.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new d(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,l.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function oP(e,t){let n=Dr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await Xx("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:wd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function sP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function ov(e,t={}){let n=E(process.cwd(),t.path);await R(n);let r=await A(n),o=await nP(n,r,e),s=tv.join(n,"improvement-ledger.json"),i=await dp({pmRoot:n,filePath:s,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Ll(a),m=rP(c,o);return m?{raw:a,result:m}:(c.observations.push(o),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${Bt(c)}
|
|
42
|
-
`,result:o})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function sv(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await R(t);let n=e.metric===void 0?void 0:nv(e.metric),r=e.since===void 0?void 0:rv(e.since,"since"),o=tP(e.limit),i=Ll(await Z(tv.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of i){let m=a.get(c.metric)??[];m.push(c),a.set(c.metric,m)}return{observations:[...i].reverse().slice(0,o),total:i.length,truncated:i.length>o,trends:[...a].map(([,c])=>sP(c)).sort((c,m)=>c.metric.localeCompare(m.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2e7a7f40-523d-590f-8aea-90b65535506e")}catch{}})();function iv(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function iP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function aP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function Nl(e=nr,t=bn){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function cP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function Fl(e,t=bn,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let s of t){let i=`${o.agent_harness}\0${s}`,a=r.get(i)??{harness:o.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=o.agent_provenance?.[s];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(i,a)}return[...r.values()].map(o=>{let s=o.observed+o.unavailable;return{...o,coverage:s===0?null:o.observed/s,inert:s>=n&&o.observed===0}}).sort((o,s)=>o.harness.localeCompare(s.harness)||o.dimension.localeCompare(s.dimension))}function lP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let u=`${c.agent_harness}\0${m}`,p=o.get(u)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),o.set(u,p)}let s=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[u])=>m.localeCompare(u)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),i=s.filter(c=>c.entries>=r),a=i.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:i.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:s,failures:a}}function dP(e){let t=[...e].sort((s,i)=>s.ts.localeCompare(i.ts)||s.author.localeCompare(i.author)||s.op.localeCompare(i.op)||s.before_hash.localeCompare(i.before_hash)||s.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let s of t){let i=s.agent_episode,a=iv(s),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(s);continue}let u={id:a.id,...i?.label===void 0?{}:{label:i.label},...i?.parent_id===void 0?{}:{parent_id:i.parent_id},source:a.source,entries:[s],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let o=[];for(let s of n.values()){let i=s.parent_id?r.get(s.parent_id):void 0;i&&iP(s,i,r)?i.children.push(s):o.push(s)}return aP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0eeefcd-2202-55c6-94e9-0372fcfe0c87")}catch{}})();var mP=1e4,av=1e5,uP=1e3,pP=30,fP=["append","comment","docs","file","learning","note","test_run"];function _P(e){let t=e??mP;if(!Number.isSafeInteger(t)||t<1||t>av)throw new d(`History analytics event limit must be an integer from 1 to ${av}.`,l.USAGE,{code:"invalid_history_analytics_limit"});return t}function cv(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new d("History analytics minimum sample must be an integer from 1 to 10000.",l.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function hP(e){let t=e?.trim();if(!t)return new Date(Date.now()-pP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new d("History analytics --since duration must be positive.",l.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*s).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new d("History analytics --since must be an ISO timestamp or negative duration such as -30d.",l.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function lv(e,t){let n=_P(t.eventLimit),r=hP(t.since),o=[],s=r,i=!1;for(;o.length<n;){let a=await mi({pmRoot:e,since:s,limit:Math.min(uP,n-o.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),i=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:i,...i?{next_cursor:s}:{},source:"history_event_index"}}}function gP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function yP(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function vP(e){return fP.some(t=>e.startsWith(t))}function dv(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function wP(e,t,n){let r=new Map,o=new Map,s=new Map;for(let i of t){let a=gP(i.entry,e),c=yP(i.entry),m=o.get(i.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&o.set(i.item_id,u),!a)continue;let p=dv(r,a);p.events+=1,vP(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,s.set(i.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:s}}function bP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of o){let i=t.get(s);i&&(dv(e,i).defectEscapes+=1)}}}function kP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function SP(e,t,n,r,o,s){let{buckets:i,lastCloseValue:a}=wP(e,t,r);return bP(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>kP(c,m,o,s)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function EP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),s=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(s)?1:Math.max(1,(s-o)/864e5)}function AP(e,t,n){let r=Nl(t),o=Fl(e,bn,n),s=o.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),i=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:o,inert:s,undeclared:i,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...i.map(a=>`provenance_dimension_undeclared:${a}`)]}}function mv(e,t=nr,n={}){let r=cv(n.minimumSample);return{...AP(e.events.map(o=>o.entry),t,r),window:e.receipt}}function uv(e,t,n,r={}){let o=cv(r.minimumSample),s=EP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>SP(i,e.events,t,n,o,s)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c81415a5-81fa-57ed-936f-236841e5f066")}catch{}})();var TP=32;function CP(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let s=o.slice(0,o.indexOf("=")).trim();r.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Ur(e,t){let n=CP(e).map(o=>{let[s,...i]=o.split(","),a=s.indexOf("="),c=s.slice(0,a).trim(),m=s.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new d(`Invalid --measure "${o}"; expected name=value[,unit=...][,threshold=...]`,l.USAGE);let p,f;for(let _ of i){let g=_.indexOf("="),y=_.slice(0,g).trim(),h=_.slice(g+1).trim();if(y==="unit"&&h.length>0)p=h;else if(y==="threshold"&&h.length>0&&Number.isFinite(Number(h)))f=Number(h);else throw new d(`Invalid --measure attribute "${_}"`,l.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(o=>[o.name,o])).values()].sort((o,s)=>o.name.localeCompare(s.name)).slice(0,TP)}function pv(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function fv(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,i)=>i.recorded_at.localeCompare(s.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a567e72a-faff-580d-b9ae-e2ebfa492b89")}catch{}})();function IP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function OP(e,t,n,r,o){let s=fr(e,"type",r),i=new Set(s.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),m=(o?[...s.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=IP([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>o||f>0));return{byType:m,byStatus:p,omitted:o?0:a.length+Object.values(u).filter(f=>f===0).length}}function xP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function PP(e){let t=_v.join(e,"history");if(!await L(t))return[];await vn({path:t,scope:"project"});let n=(await RP.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,s)=>o.localeCompare(s)),r=[];for(let o of n){let s=_v.join(t,o),i=await Z(s);i!==null&&(await vn({path:s,scope:"project"}),r.push({id:o.slice(0,-6),raw:i}))}return r}async function LP(e,t){let n=[],r=k();for(let o of Ur(t.observe,r))n.push(await ov({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function NP(e,t,n){let r={};return t.byAssignee&&(r.assignee=fr(e,"assignee",n)),t.byTag&&(r.tag=fr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=fr(e,"priority",n)),r}async function FP(e,t,n,r,o){let s={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},i=o.provenanceCoverage||o.fleetAttribution?await lv(e,s):void 0;return{provenanceCoverage:o.provenanceCoverage&&i?mv(i,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:o.fleetAttribution&&i?uv(i,t,r,s):void 0}}function MP(e,t,n,r,o){let s=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...s?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:k()}}async function Ml(e,t={}){let n=E(process.cwd(),e.path);await R(n);let r=await A(n),o=await LP(e,t),s=x(r,O()),i=$(r.schema),a=t.fieldUtilization?await gp(n,r.item_format,s.type_to_folder,void 0,r.schema):await pe(n,r.item_format,s.type_to_folder,void 0,r.schema);await fp({pmRoot:n,settings:r,itemIds:a.map(S=>S.id),commandLabel:"stats"});let c=bs(i),m=OP(a,s.types,i.definitions.map(S=>S.id),c,t.includeEmpty===!0),u=await PP(n),p=0;for(let S of u)p+=xP(S.raw);let f=t.storage?Qy(u):void 0,_=t.metadataCoverage?Xf(a,c):void 0,g=NP(a,t,c),y=t.fieldUtilization?Qf(a):void 0,h=t.measurements===!0||o.length>0?await sv({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:v,fleetAttribution:b}=await FP(n,a,r,i.terminal_statuses,t);return MP({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:g,storage:f,fieldUtilization:y,improvementLedger:h,recordedObservations:o,provenanceCoverage:v,fleetAttribution:b})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="086d2640-2a64-554a-9e40-a8f6994ae3a8")}catch{}})();function hv(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:w(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ke(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:w(e,"measurementSource"),measurementItem:w(e,"measurementItem"),measurementRevision:w(e,"measurementRevision"),author:w(e,"author"),message:w(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:w(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import $P from"node:fs/promises";import Gt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32a15ab4-82a2-546f-8519-d4e565e7b578")}catch{}})();var bv=Gt.join("runtime","telemetry","events.jsonl"),kv=Gt.join("runtime","telemetry","state.json"),DP=Gt.join("runtime","telemetry"),UP=20,gv=["status","flush","stats","clear"],yv=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},$l=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,vv=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},GP=e=>({command:$l(e.event.command,"<unknown>"),eventType:$l(e.event.event_type,"unknown"),eventSchemaVersion:vv(e.event.schema_version),clientSchemaVersion:vv(e.client_schema_version)}),jP=()=>({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:{}}),qP=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},KP=e=>{let t=e?.command_resolution;return $l(t,"")||void 0},Sv=(e,t)=>{e[t]=(e[t]??0)+1},zP=(e,t)=>{let n=qP(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=KP(t);r!==void 0&&Sv(e.resolution_counts,r)},BP=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,wv=(e,t)=>{t!==void 0&&e.add(t)},HP=(e,t)=>{let n=GP(t),r=e.get(n.command)??jP();r.count+=1,r.max_attempts=Math.max(r.max_attempts,BP(t.attempts)),Sv(r.event_type_counts,n.eventType),wv(r.event_schema_versions,n.eventSchemaVersion),wv(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&zP(r,t.event.payload),e.set(n.command,r)},VP=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((s,i)=>s-i),o=Object.entries(t.resolution_counts).sort((s,i)=>s[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,i)=>s[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,i)=>s-i),client_schema_versions:[...t.client_schema_versions].sort((s,i)=>s-i),...r.length>0?{duration_p50_ms:yv(r,.5),duration_p95_ms:yv(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},WP=e=>{let t=(e??"status").trim().toLowerCase();if(gv.includes(t))return t;throw xe({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:gv,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Dl=()=>{throw new d("--limit must be a positive integer",l.USAGE)},Ev=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Dl():e,YP=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Dl():Ev(Number.parseInt(t,10))},JP=e=>e===void 0?UP:typeof e=="number"?Ev(e):typeof e=="string"?YP(e):Dl(),XP=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},QP=e=>{try{let t=JSON.parse(e);return XP(t)?t:void 0}catch{return}},ZP=e=>e===null?[]:e.split(`
|
|
43
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),Av=e=>{let t=ZP(e),n=[],r=0;for(let o of t){let s=QP(o);s===void 0?r+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},eL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tL=e=>{try{let t=JSON.parse(e);return eL(t)?t:{}}catch{return{}}},nL=async e=>{let t=await Z(e);return t===null||t.trim().length===0?{}:tL(t)},wi=e=>e??null,bi=async e=>{let t=await A(e),n=Gt.join(e,bv),r=Gt.join(e,kv),o=await Z(n),s=Av(o),i=await nL(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:wi(i.last_attempted_flush_at),last_successful_flush_at:wi(i.last_successful_flush_at),last_failed_flush_at:wi(i.last_failed_flush_at),last_failed_flush_error:wi(i.last_failed_flush_error)}},rL=e=>{let t=new Map;for(let n of e)HP(t,n);return[...t.entries()].map(([n,r])=>VP(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},oL=async(e,t)=>({action:"telemetry",subcommand:"status",status:await bi(t.globalPmRoot),generated_at:k()}),sL=async(e,t)=>{let n=await bi(t.globalPmRoot);await Np(t.globalPmRoot);let r=await bi(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),s=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:s,queue_drained:s,status:r,generated_at:k()}},iL=async(e,t)=>{let n=JP(e.limit),r=await Z(t.queuePath),o=Av(r),s=rL(o.entries),i=s.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:s.length>i.length,stats:i,generated_at:k()}},aL=async(e,t)=>{let n=await A(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await Oe(t.globalPmRoot,n,"telemetry:clear");let o=Gt.join(t.globalPmRoot,DP),s=await L(o);return await $P.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:s&&!await L(o),queue_exists_after:await L(t.queuePath),state_exists_after:await L(t.statePath),status:await bi(t.globalPmRoot),generated_at:k()}},cL={status:oL,flush:sL,stats:iL,clear:aL};async function Tv(e,t){let n=WP(e.subcommand),r=st(process.cwd());return cL[n](e,{globalPmRoot:r,queuePath:Gt.join(r,bv),statePath:Gt.join(r,kv)})}import{spawn as Hv}from"node:child_process";import{cp as ql,mkdir as Ti,mkdtemp as Vv,open as Kl,readdir as zl,rm as Gr,symlink as Wv}from"node:fs/promises";import{tmpdir as Yv}from"node:os";import B from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ffa50b5b-d99f-5ab4-a70d-cbf12911a0f2")}catch{}})();var Cv=20;function lL(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return Cv;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?Cv:t}function Ul(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let s=jo(r.recorded_at,o.recorded_at);if(s!==0)return s;let i=r.run_id.localeCompare(o.run_id);return i!==0?i:r.kind.localeCompare(o.kind)}),n=lL();return t.length>n?t.slice(t.length-n):t}async function ki(e){await ie({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=Ul([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="328c7577-364c-5869-aa92-199e56d2f6a7")}catch{}})();var Rv=100;function Gl(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new d(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,l.USAGE);return n}function dL(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Rv?n:`${n.slice(0,Rv-3)}...`}function Iv(e){return e.map((t,n)=>`${n+1}. ${dL(t)}`).join("; ")}function mL(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function uL(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Ov(e,t){let n=mL(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new d(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,l.USAGE);let r=n[0];if(e.length===0)throw new d(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,l.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new d("--match requires a non-empty substring to match against linked-test command/path values",l.USAGE);let s=[],i=[];for(let a=0;a<e.length;a+=1)uL(e[a],o)&&(i.push(e[a]),s.push(a+1));if(i.length===0)throw new d(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Iv(e)}`,l.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:s,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let o=Gl(t.onlyIndex);if(o>e.length)throw new d(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${Iv(e)}`,l.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2833cfc3-db98-5f7f-82e0-388e320ef740")}catch{}})();var Ai=20*1024*1024,pL=3e3,fL=1e4,_L=5e3,xv=120,hL=new Set(["locks","extensions","runtime"]),gL=new Set(["history","index","search","extensions","locks","runtime"]),yL=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],vL=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,wL=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,bL=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Vl(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function kL(){return Vl("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",pL)}function SL(){return Vl("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",fL)}function EL(){return Vl("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",_L)}function AL(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function TL(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function Wl(e){let t=0,n=0,r=0,o=0;for(let s of e){let i=s.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(r+=1),i.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function CL(e){let t=e??"project";if(!ot.includes(t))throw new d(`Invalid scope "${e}"`,l.USAGE);return t}function Ci(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(nn.includes(t))return t;throw new d(`Invalid --pm-context value "${e}". Expected one of: ${nn.join(", ")}`,l.USAGE)}function RL(e){return on(e??"source","--workspace-context")}function Jv(e,t,n){return n?t:on(e.workspace_context_mode,"linked test")??t}function Xv(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Ci(e.pm_context_mode)}function Qv(e,t){return e==="auto"?t?"tracker":"schema":e}function IL(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function OL(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function xL(e,t){let n={};if(!e)return n;for(let r of e){let o=Er(r,t);if(o)for(let[s,i]of Object.entries(o))n[s]=i}return n}function PL(e,t){if(!e)return[];let n=[];for(let r of e){let o=Ar(r,t);o&&n.push(...o)}return[...new Set(n)]}function LL(e){let t=Ri(e);return pr(t).some(n=>Ha(n)!==null)}function Zv(e){let t=Ri(e);return pr(t).some(n=>{let r=Ha(n);if(!r)return!1;let o=Hf(r);return o?bL.has(o.subcommand):!1})}function Si(e){if(e)return Kf.has(e.subcommand)?Pn(e.args,zf)?.subcommand:e.subcommand}function Pv(e,t){if(e==="npx"||e==="bunx")return vs(t)?.command;if(e==="pnpm")return Si(Pn(t,Uf));if(e==="npm")return Si(Pn(t,Gf));if(e==="yarn")return Si(Pn(t,jf));if(e==="bun")return Si(Pn(t,qf))}function Ei(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function jl(e){return!e||!Wa(e.command)&&!Bf(e.command)?!1:ys(e.args)==="test-all"}var ew=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),NL=new Set(["npx","bunx"]);function tw(e){let t=e.split(" ").filter(i=>i.length>0),n=Va(t);if(n.length===0)return!1;let[r,...o]=n,s=ew.get(r);if(s){let i=o.findIndex(a=>s.test(a));return i>=0?tw(o.slice(i+1).join(" ")):!1}return Wa(r)||Ya(r)?ys(o)==="test-all":r==="node"&&o.length>0&&Ya(o[0])?ys(o.slice(1))==="test-all":NL.has(r)?jl(vs(o)):r==="pnpm"?jl(Ja(o)):r==="npm"?jl(Xa(o)):!1}function nw(e){let t=Ri(e);return pr(t).some(n=>tw(n))}function rw(e){if(nw(e))throw new d('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',l.USAGE)}function Ri(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function ow(e){let t=e.split(" ").filter(i=>i.length>0),n=Va(t);if(n.length===0)return!1;let[r,...o]=n,s=ew.get(r);if(s){let i=o.findIndex(a=>s.test(a));return i>=0&&ow(o.slice(i+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?FL(o):ML(r,o)}function FL(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function ML(e,t){return e==="npx"||e==="bunx"?Ei(vs(t)?.command):e==="pnpm"||e==="npm"?Ei((e==="pnpm"?Ja(t):Xa(t))?.command)||Ei(Pv(e,t)):(e==="yarn"||e==="bun")&&Ei(Pv(e,t))}function $L(e){if(nw(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function DL(e){return e?e.map(UL):[]}function UL(e){let t=e.trim(),n=z_(t)?qs(le(e,"--add"),"--add"):{command:t},r=_e(n.command);if(!r)throw new d("--add requires command=<value> or a bare command (path=<value> is optional metadata)",l.USAGE);return rw(r),{command:r,path:_e(n.path),scope:CL(n.scope),timeout_seconds:GL(_e(n.timeout_seconds),_e(n.timeout)),pm_context_mode:Vs(_e(n.pm_context_mode),"--add"),workspace_context_mode:on(_e(n.workspace_context_mode),"--add"),env_set:Er(_e(n.env_set),"--add"),env_clear:Ar(_e(n.env_clear),"--add"),shared_host_safe:Hs(_e(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:sn(_e(n.assert_stdout_contains)),assert_stdout_regex:$n(_e(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:sn(_e(n.assert_stderr_contains)),assert_stderr_regex:$n(_e(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Ws(_e(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Ys(_e(n.assert_json_field_equals),"--add"),assert_json_field_gte:Js(_e(n.assert_json_field_gte),"--add"),note:_e(n.note)}}function _e(e){let t=e?.trim();return t&&t.length>0?t:void 0}function GL(e,t){if(e&&t&&e!==t)throw new d("--add timeout and timeout_seconds must match when both are provided",l.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(fe(n,"timeout_seconds"));if(r<=0)throw new d("--add timeout_seconds must be a positive integer",l.USAGE);return r}function jL(e){return e?e.flatMap(t=>{let n=V_(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new d("--add-json requires a non-empty command string",l.USAGE);rw(o)}return n}):[]}function qL(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new d("--remove requires command or path value",l.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let o=n.slice(r[0].length).trim();if(!o)throw new d("--remove requires a non-empty command=<value> or path=<value>",l.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new d("--remove structured selectors require command=<value> or path=<value>",l.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=le(n,"--remove"),s=o.path!==void 0?"path":"command",i=o.path??o.command;if(!i?.trim())throw new d("--remove requires command=<value> and/or path=<value>",l.USAGE);return{kind:s,value:i.trim()}}return{kind:"either",value:n}}):[]}function KL(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new d("--remove-index must be a positive integer",l.USAGE);return n}))]:[]}function zL(e){try{e.stdin?.end()}catch{}}function sw(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=xv?t:`${t.slice(0,xv-3)}...`}function iw(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Bl(e){try{process.stderr.write(`${e}
|
|
44
|
-
`)}catch{}}function
|
|
45
|
-
[pm linked-test output truncated at ${
|
|
46
|
-
`:"",
|
|
47
|
-
`);return
|
|
48
|
-
${t}`;for(let r of
|
|
49
|
-
${t}`;return uN.some(r=>r.test(n))}function qv(e){let t=Ri(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:pr(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&ow(n))}function _N(e){return{root:e,schemaProjectPmPath:B.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:B.join(e,"schema","global"),trackerProjectPmPath:B.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:B.join(e,"tracker","global"),workspaceSnapshotRoot:B.join(e,"workspace","project"),workspaceIsolatedRoot:B.join(e,"workspace","isolated")}}function hN(e,t,n){return e.some(r=>Jv(r,t,n)==="snapshot")}async function gN(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await Ti(B.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await ql(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(o){let s=B.relative(t,o);return s?!s.split(B.sep).some(i=>n.has(i)):!0}});let r=B.join(t,"node_modules");await L(r)&&await Wv(r,B.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function yN(e,t){let n=B.join(e,".agents"),r=B.join(n,"pm");await Ti(n,{recursive:!0}),await Gr(r,{recursive:!0,force:!0}),await Wv(t,r,process.platform==="win32"?"junction":"dir")}async function vN(e,t=Or,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function wN(e,t,n){t&&(await Mv(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await Mv(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await $v(t.projectPmRoot,e.trackerProjectPmPath),await $v(t.globalPmRoot,e.trackerGlobalPmPath),await Dv(t.projectPmRoot,e.trackerProjectPmPath),await Dv(t.globalPmRoot,e.trackerGlobalPmPath)))}function bN(e,t,n){return e.some(r=>{let o=r.command??"",s=o.length>0&&Zv(o),i=n?.autoPmContext===!0&&s?"auto":Xv(r,t,n?.overrideLinkedPmContext===!0);return Qv(i,s)==="tracker"})}async function kN(e,t){return{sourceProjectItemCount:t?await zn(t.projectPmRoot):0,sourceGlobalItemCount:t?await zn(t.globalPmRoot):0,schemaProjectItemCount:await zn(e.schemaProjectPmPath),schemaGlobalItemCount:await zn(e.schemaGlobalPmPath),trackerProjectItemCount:await zn(e.trackerProjectPmPath),trackerGlobalItemCount:await zn(e.trackerGlobalPmPath)}}function SN(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:a,trust:e.trust}}async function EN(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Ci(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?LL(n):!1,o=r&&n?Zv(n):!1,s=e.options?.autoPmContext===!0&&o,i=s?"auto":Xv(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Qv(i,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await yN(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await Qa(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Qa(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:SN({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function Kv(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Hl(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function AN(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function TN(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return AN(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function CN(e){if(!e.linkedTest.command)return Kv(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=$L(e.linkedTest.command);return t?Kv(e.linkedTest,e.executionContext,t):null}function RN(e){let t=CN(e);if(t)return t;let n=TN(e);if(n)return n;let r=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,o=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(r||o){let s=OL({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),i=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Hl(e.linkedTest,e.executionContext,`${i} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${s}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!IL(e.linkedTest)?Hl(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function IN(e){let t=rN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return Fv(n,e.runtimeDirectives),Fv(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&nN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[mr]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[mr]="read_only"),n}function ON(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function zv(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function xN(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:sN(e.execution),failure_category:eN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:QL(e.execution,e.timeoutMs)}}function PN(e){if(e.options?.failOnEmptyTestRun===!0||qv(e.linkedTest.command??"")){let n=pN(e.execution.stdout,e.execution.stderr);if(n)return zv({...e,emptyRunSignal:n});if(qv(e.linkedTest.command??"")&&!fN(e.execution.stdout,e.execution.stderr))return zv({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let t=lN(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Hl(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):ON(e.linkedTest,e.executionContext,e.execution)}async function LN(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await XL(t,n,IN(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?PN({...e,execution:r}):xN({...e,execution:r,timeoutMs:n})}async function Yl(e,t,n){let r=[],o=await Vv(B.join(Yv(),"pm-linked-test-")),s=_N(o),i=Ci(n?.pmContext),a=RL(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=oN(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,p=Wf(),f=bN(e,i,n),_=hN(e,a,n?.overrideLinkedWorkspaceContext===!0),g=await Vf(p);try{await vN(s,Or,f),await Ti(s.workspaceIsolatedRoot,{recursive:!0}),await wN(s,u,f),_&&await gN(s,p);let y=await kN(s,u);for(let h=0;h<e.length;h+=1){let v=e[h],b=Jv(v,a,n?.overrideLinkedWorkspaceContext===!0),S=await EN({linkedTest:v,layout:s,counts:y,sourceRoots:u,runLevelPmContextMode:i,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:b,currentSourceRef:g,sourceWorkspaceRoot:p}),T=RN({linkedTest:v,executionContext:S.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:S.linkedOverridePmContextMode,options:n});if(T){r.push(T);continue}r.push(await LN({linkedTest:v,index:h,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:S.executionContext,options:n}))}}finally{await Gr(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function NN(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,s=await q(n,t,r.id_prefix,r.item_format,o);if(!s)throw new d(`Item ${t} not found`,l.NOT_FOUND);let i=await se(s,{schema:r.schema});return{itemId:s.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function FN(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function MN(e,t){let n=[...e];for(let r of t)n.some(o=>FN(o,r))||n.push(r);return n}function $N(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((s,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:o,removed:e.length-o.length}}function DN(e,t,n,r){return $N(MN(e,t),n,r)}function UN(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function GN(e){if(UN(e)&&e.run!==!0)throw new d("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",l.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new d("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",l.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new d("--match, --only-index, and --only-last require --run",l.USAGE)}async function jN(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:s,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return NN({id:t,pmRoot:r,settings:o,typeToFolder:s});let m=0,u=await ie({pmRoot:r,settings:o,id:t,op:i.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=DN(f,i,a,c);if(m=_.removed,(a.length>0||c.length>0)&&m===0)throw new d("No linked tests matched the requested removal selector",l.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(g=>`${g.kind}=${g.value}`),...c.map(g=>`index=${g}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return p.metadata.tests=_.tests,{changedFields:at(f,_.tests)?[]:["tests"]}}});return{itemId:u.item.id,tests:u.item.tests??[],testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:m}}function qN(e,t){GN(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Gl(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?Ov(t,n):void 0,o=e.timeout===void 0?void 0:fe(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new d("Test timeout must be a positive number",l.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:Ci(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function KN(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Yl(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:st(process.cwd())}})}function zN(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=Wl(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function BN(e){let t=TL(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=k(),s=Ur(e.options.measure,o);return{run_id:AL("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function HN(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:s,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let m=BN({options:t,runStartedAt:s,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return m;try{return await ki({pmRoot:n,settings:r,itemId:o,author:C(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),m}catch(u){return c.push(`test_result_tracking_failed:${o}:${u instanceof Error?u.message:String(u)}`),m}}function Bv(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,o).trim(),i=e.metricBelow.slice(o+1).trim(),a=Number(i);if(o<=0||s.length===0||i.length===0||!Number.isFinite(a))throw new d("--metric-below must use name=value",l.USAGE);r=pv(t,s,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:fv(t,e.metricDiff)}}async function VN(e,t,n){if(e.acknowledgeLinkedTests===!0)return Yf(t,n,k())}async function Oi(e,t,n){let r=Nt(),o=E(process.cwd(),n.path);await R(o);let s=await A(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new d("--measure requires --run",l.USAGE);Ur(t.measure,"validation"),Bv(t,[],void 0);let i=x(s,O()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...DL(a),...jL(c)],p=await Ln(u,C(t.author,s.author_default),k())??[],f=qL(m),_=KL(t.removeIndex),g=await jN({id:e,options:t,pmRoot:o,settings:s,typeToFolder:i.type_to_folder,adds:p,removes:f,removeIndexes:_}),y=qN(t,g.tests),h=await VN(t,o,g.tests),v=t.run===!0?k():void 0,b=await KN({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests}),S=Ii(b),T=t.run===!0&&t.failOnSkipped===!0&&b.some(K=>K.status==="skipped"),I=zN(t,y.runSelection,b);h&&I.push(`linked_test_trust_acknowledged:${h.acknowledged}`);let D=await HN({options:t,pmRoot:o,settings:s,itemId:g.itemId,runStartedAt:v,runResults:b,failOnSkippedTriggered:T,warnings:I}),N=D?Ul([...g.testRuns,D]):g.testRuns,X=Bv(t,N,D);return{ok:b.every(K=>K.status!=="failed")&&T!==!0,id:g.itemId,tests:g.tests,run_results:b,failure_categories:S,selection:y.runSelection?{selector:y.runSelection.selector,requested:y.runSelection.requested,selected_indexes:y.runSelection.selected_indexes,selected_count:y.runSelection.selected_count,skipped_count:y.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:T?!0:void 0,warnings:I.length>0?I:void 0,changed:g.changed,count:g.tests.length,...g.removed>0?{removed:g.removed}:{},...X}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e3e3a1d4-4552-5f3c-9b02-c33ae72ea32b")}catch{}})();var WN=(e,t)=>{if(e===void 0)return;let n=ee(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new d(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n},YN=e=>{if(e===void 0)return;let t=fe(e,"timeout");if(t<=0)throw new d("timeout must be a positive number",l.USAGE);return t},aw=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new d(`${t} must be a non-negative integer`,l.USAGE);return n},JN=e=>e instanceof Error?e.message:String(e),XN=()=>{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)}`},QN=e=>e.trim().replaceAll(/\s+/g," "),ZN=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),eF=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),tF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},nF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},xi=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),cw=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),rF=e=>typeof e=="number"?e:void 0,oF=e=>{let t={assert_stdout_contains:xi(e.assert_stdout_contains),assert_stdout_regex:xi(e.assert_stdout_regex),assert_stderr_contains:xi(e.assert_stderr_contains),assert_stderr_regex:xi(e.assert_stderr_regex),assert_stdout_min_lines:rF(e.assert_stdout_min_lines),assert_json_field_equals:cw(e.assert_json_field_equals),assert_json_field_gte:cw(e.assert_json_field_gte)};return JSON.stringify(t)},sF=e=>{let t=Jl(e.command);return t!==void 0?`command:${e.scope}:${QN(t)}`:`path:${e.scope}:${Jl(e.path)??""}`},lw=e=>{let t=ZN(e.env_set),n=eF(e.env_clear),r=tF(e.pm_context_mode),o=nF(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",i=oF(e);return`${sF(e)}:${t}:${n}:${r}:${o}:${s}:${i}`},iF=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,aF=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},cF=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Pi=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
50
|
-
`)}catch{}},lF=async(e,t,n)=>{let r=[],o=0;for(let s of e){let i=await Oi(s.id,{run:!1},{...t,path:n});o+=i.tests.length,r.push({item:s,tests:i.tests})}return{itemTests:r,linkedTests:o}},dF=async e=>{let t=$(e.settings.schema),n=x(e.settings,O()),r=WN(e.options.status,t),o=aw(e.options.limit,"--limit"),s=aw(e.options.offset,"--offset")??0,a=(await pe(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(m=>r?m.status===r:!0).sort((m,u)=>m.id.localeCompare(u.id));return{filteredItems:o===void 0?a.slice(s):a.slice(s,s+o),statusFilter:r,limitFilter:o,offsetFilter:s}},mF=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=lw(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,iF(t.get(o),r.timeout_seconds))}return t},uF=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=lw(u),f=t.seenTestKeys.has(p);if(!f){t.seenTestKeys.add(p);let _=t.effectiveTimeoutByKey.get(p);n.push(_===void 0?u:{...u,timeout_seconds:_})}return{test:u,key:p,duplicate:f}}),o=n.length>0?await Yl(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],s=0,i=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=o[s];return s+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=aF(i),c=Ii(i),m=await _F(e,a,i,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:m,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:i,failure_categories:c}}},pF=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),fF=e=>e?!0:void 0,_F=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=pF(t,r.options);await ki({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:k(),recorded_at:k(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:fF(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${JN(o)}`]}return[]},hF=()=>{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},Jl=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},gF=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:st(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:mF(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:XN(),trackingAttempt:hF(),trackingResumedFrom:Jl(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),yF=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:Ii([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},vF=async(e,t,n)=>{for(let[r,o]of e.entries()){Pi(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let s=await uF(o,t);cF(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),Pi(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}},wF=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=Wl(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}`)},bF=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}),kF=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(" "),SF=async(e,t)=>{let n=E(process.cwd(),t.path);await R(n);let r=await A(n),o=await dF({pmRoot:n,settings:r,options:e}),s=YN(e.timeout),i=k(),a=await lF(o.filteredItems,t,n);return Pi(e,kF({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:s,runStartedAt:i}},EF=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}},dw=async(e,t)=>{let n=await SF(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=yF(e,n.linkedTests,n.filteredItems),s=gF({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await vF(n.itemTests,s,r),wF(e,r);let i=EF({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Pi(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),bF({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4277a72c-f012-55d2-9e18-c9a836d829d6")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f248824b-d56a-52ec-ac50-8b69b5ab1c99")}catch{}})();function mw(){return{metadata:{},body:""}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="780365af-6d4c-5313-865b-23b8c68f889f")}catch{}})();var pw=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:Mu().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm init","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm remind <title> --at <when> --parent <ID>","pm event <title> --start <when> --parent <ID>","pm meet <title> --start <when> --duration <span> --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Record the reminder or event under the item that owns the work, then confirm it appears in the agenda summary of a context read.",commands:["pm remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."}],related:["workflows","quickstart","extensions"]}],uw=new Map;for(let e of pw){uw.set(e.id,e);for(let t of e.aliases)uw.set(t,e)}function Xl(){return pw.map(e=>e.id)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3a7cf539-2663-5265-90e8-c2aa9926a62a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="56fd6790-568a-5c97-ab94-4b645aaa3718")}catch{}})();var T2=[...Br],C2=[...Hr],AF=new Set(Jn.filter(e=>e.hidden).map(e=>e.alias)),R2=Fu("full").filter(e=>!AF.has(e)),I2=F(oo),O2=F(so),x2=F(po),P2=F(yo),L2=qo("restore",ia("restore")),N2=F(vo),F2=F(Am),M2=F(Tm),$2=F(go),D2=F(ko),U2=F(wo),G2=F(bo),j2=F(uo),q2=Ht.map(e=>e.canonical_argv[1]).join(" "),K2=Ht.map(e=>({...e,flags:F(ia(e.alias))})),z2=F(io),B2=F(ao,!1),H2=F(Dm),V2=F(Zn),W2=F(er),Y2=F(To),J2=F(Eo),X2=F(_o),Q2=F(Ao),Z2=F(So),eV=F(Co),tV=F(fo),nV=F(ho),rV=F(lo),oV=F(Ro),sV=F(co);var TF=F(Io),iV=`${TF} bash zsh fish`,aV=IF(Xl()),CF="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",cV=`${CF} upgrade`,lV=F(mo),dV=F(Xn),mV=F(Qn);var RF=ro.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),uV=[...Do].join("|"),pV=[...Do].map(e=>`${e}=*`).join("|"),fV=[...RF.split(" ").filter(e=>!Do.has(e)),"-h","-V"].join("|");function IF(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c2a4576-a5d8-57c1-84e8-ca8b9019c84e")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7f8a7ea-3ec2-521b-ad52-45b655208f06")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="556364bc-5faa-5412-a327-e409564fbadf")}catch{}})();var gw=Symbol("pm.active-extension-host-context");function Me(e){return{fullChangedFields:!0,options:e}}var G=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[gw]=!0,n}run(t,n={}){return yw({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return s_(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Pa(await this.list(xa(t)))}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}append(t,n,r={}){return this.runTyped("append",{id:t,...Me(dr(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,s={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:s})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,s){return this.runTyped("plan",{...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...s===void 0?{}:{reorderTo:s},options:dr(r,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Me(t))}update(t,n={}){return this.runTyped("update",{id:t,...Me(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Me(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Me(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Me(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Me(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Me(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Me(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...Me(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Me(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Me(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Me(r)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function xF(e={},t={}){return new G(t).context(e)}function PF(e={},t={}){return new G(t).list(e)}function LF(e={},t={}){return new G(t).listAllComplete(e)}function NF(e,t={},n={}){return new G(n).search(e,t)}function FF(e,t={},n={}){return new G(n).get(e,t)}function MF(e={},t={}){return new G(t).next(e)}function $F(e={},t={}){return new G(t).aggregate(e)}function DF(e,t={},n={}){return new G(n).comments(e,t)}function UF(e,t={},n={}){return new G(n).notes(e,t)}function GF(e,t={},n={}){return new G(n).learnings(e,t)}function jF(e,t={},n={}){return new G(n).files(e,t)}function qF(e,t={},n={}){return new G(n).filesDiscover(e,t)}function KF(e,t={},n={}){return new G(n).docs(e,t)}function zF(e,t={},n={}){return new G(n).deps(e,t)}function BF(e,t={},n={},r={}){return new G(r).graph(e,t,n)}function HF(e,t,n={},r={}){return new G(r).append(e,t,n)}function VF(e={},t={}){return new G(t).create(e)}function WF(e,t={},n={}){return new G(n).update(e,t)}function YF(e,t,n={},r={}){return new G(r).reopen(e,t,n)}function JF(e,t,n={},r={}){return new G(r).close(e,t,n)}function XF(e,t={},n={}){return new G(n).claim(e,t)}function QF(e={},t={}){return new G(t).claimNext(e)}function ZF(e,t={},n={}){return new G(n).release(e,t)}function eM(e,t={},n={}){return new G(n).copy(e,t)}function tM(e,t={},n={}){return new G(n).delete(e,t)}function nM(e,t,n={},r={}){return new G(r).restore(e,t,n)}function rM(e,t={},n={}){return new G(n).focus(e,t)}function nt(e,t){let n=w(e,t);if(!n)throw new d(`Missing required argument: ${t}`,64);return n}var fw=Cu(),oM=new OF;function Li(){ga(Td()),ya(Cd()),va(Rd()),wa(Id()),ba(Od()),ka(xd()),Sa(Pd())}async function sM(e,t,n,r){return Ru(()=>t===void 0?fw.read(()=>_w(e,n,r)):fw.write(()=>aM(t,()=>_w(e,n,r))))}async function _w(e,t,n){let r=E(t,e.path);if(e.noExtensions)return Li(),dc({pmRoot:r},()=>n(null));if(!await L(ue(r)))return Li(),n(null);let o=null,s;try{let i=await A(r),a=await eo({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await to({...a,loaded:a.loaded});s={loadResult:a,activationResult:c},ga(c.hooks),ya(c.commands),va(c.parsers),wa(c.preflight),ba(c.services),ka(c.renderers),Sa(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){Li(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await dc({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Li(),s&&await Ld(s.loadResult,s.activationResult).catch(()=>{})}}async function iM(e,t,n,r,o){if(!o)throw new d(`Unsupported native pm action: ${e}`,l.USAGE);let s=On(e),a=o.registrations.commands.find(m=>On(m.action)===s)?.command??o.commands.handlers.find(m=>On(m.command)===s)?.command;if(!a)throw new d(`Unsupported native pm action: ${e}`,l.USAGE);let c=await Go({command:ja(a),args:ke(n.args??t.args),options:qa(t,n),global:r,pm_root:o.pmRoot,sdk:l_(o.pmRoot,G.forActiveExtensionHost({pmRoot:o.pmRoot,author:typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension"}))});if(!c.handled){let m=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new d(`Unsupported native pm action: ${e}${m}`,l.USAGE)}return c.result}async function aM(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function cM(e){let t=nt(e,"action"),n=On(t),r=Fi(a_,n),o=r?.action??n,s={...e,action:o};return r?.options!==void 0&&(s.options={...r.options,...na(e.options)}),o==="package"&&(s.options={...na(s.options),vocabulary:"package"}),{action:o,args:s}}async function yw(e){let t=cM(e),n=Da(t.args),r=Yp(t.action),o=w(t.args,"cwd"),s=o??process.cwd();t.action==="init"&&(n[ml]=s),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(s,n.path));try{return e[gw]===!0||oM.getStore()===!0?await hw(t.action,t.args,n,null):await sM(n,o,s,i=>hw(t.action,t.args,n,i))}finally{r&&ic()}}function Fi(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ni(e){return w(e.args,"target")??w(e.options,"target")}function re(e,t=e.options){return e.id??nt(t,"id")}async function lM(e){let t=wn("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),sc(await ut(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function dM(e){let t=nt(e.args,"query"),n=wn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),sc(await gr(t,n,e.global),n)}async function mM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Pe(e.args,e.options);return De(await $t(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function uM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Pe(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return De(await Xc(re(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function pM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Pe(e.args,e.options);return De(await _t(re(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function fM(e){let t=Rs(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),O_(re(e),t,e.global)}function vw(e,t){return Df(Ry(e.options,t,Ge),e.global)}function _M(e){let t=ke(e.options.lookupPath);if(t&&t.length>0)return vw(e,t);let n=re(e);return e.options.discover===!0?Ba(n,Ga(e.options),e.global):$f(n,us(e.options),e.global)}function hM(e){return Tv({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:Vp(e.args,e.options)},e.global)}function gM(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),ur(e.global,t)}function yM(e){let t=w(e.args,"configAction")??w(e.options,"configAction")??w(e.options,"action");if(t===void 0)throw new d("Missing required argument: configAction",64);let n=w(e.args,"value")??w(e.options,"value"),r=w(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return ig(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),r,e.global,w(e.options,"policy")===void 0?n:void 0)}function vM(e){let t=e.options;return Gp(Up(t),e.global)}function wM(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new d(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new d(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new d(`${t} must be a finite integer.`,64);return r}}function bM(e){let t=w(e.args,"subcommand")??nt(e.options,"subcommand"),n=e.options;return $h({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:kM(e),reorderTo:wM(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function kM(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function SM(e){let t=w(e.args,"subcommand")??nt(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:w(e.args,"name")??w(e.options,"name"),author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ke(n)}}function EM(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,a=Fi({list:()=>mf(t.global),show:()=>uf(r,t.global),"show-status":()=>pf(r,t.global),"list-fields":()=>hf(t.global),"show-field":()=>gf(r,t.global),"remove-type":()=>af(r,{author:o,force:s},t.global),"remove-field":()=>_f(r,{author:o,force:s},t.global),"remove-status":()=>df(r,{author:o,force:s},t.global),"apply-preset":()=>yf(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:o,force:s},t.global)},n);return a?a():null}function AM(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return ff(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:ke(i),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:s,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:ke(a),author:r,force:o},t.global)}function TM(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.role??t.options.role;return lf(n,{role:i===void 0?void 0:ke(i),alias:s,description:w(t.args,"description")??w(t.options,"description"),order:Ge(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function CM(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e;return sf(n,{description:w(t.args,"description")??w(t.options,"description"),defaultStatus:w(t.args,"defaultStatus")??w(t.args,"default_status")??w(t.options,"defaultStatus")??w(t.options,"default_status"),folder:w(t.args,"folder")??w(t.options,"folder"),alias:s,author:r,force:o},t.global)}function RM(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,i=w(t.args,"to")??nt(t.options,"to"),a=w(t.args,"migrationId")??w(t.args,"migration_id")??w(t.options,"migrationId")??w(t.options,"migration_id"),c=w(t.args,"fieldTypeScope")??w(t.options,"fieldTypeScope")??w(t.args,"type")??w(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:i}:n==="rename-field"?{kind:"rename-field",from:r??"",to:i,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:i};return rf(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:s},t.global)}function IM(e){let t=SM(e),n=EM(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return RM(t);if(t.subcommand==="add-field")return AM(t);if(t.subcommand==="add-status")return TM(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?vf({minCount:Ge(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):CM(t);throw xe({command_path:"schema",token:t.subcommand,allowed:of,exit_code:64})}function OM(e){let t=w(e.args,"subcommand")??nt(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),s=Fi({list:()=>ly(),show:()=>dy(r),lint:()=>my(r),apply:()=>uy(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!s)throw xe({command_path:"profile",token:t,allowed:cy,exit_code:64});return s()}async function xM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Pe(e.args,e.options);return De(await u_(re(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function PM(e){let{changedFields:t,runnerOptions:n}=Pe(e.args,e.options);return De(await Eh(za(n),e.global),{changedFields:t})}async function LM(e){let{changedFields:t,runnerOptions:n}=Pe(e.args,e.options),r=w(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),De(await I_(Ka(o),e.global),{changedFields:t})}async function NM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Pe(e.args,e.options),o=w(r,"target")??nt(e.args,"target");return De(await Zt(re(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function FM(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=hi($(n.schema)),o=re(e),s=await br(o,e.force,e.global,e.options),i=await _t(o,dr(e.options,{status:r,force:e.force},["assignee"]),e.global);return{id:o,action:"start_task",claim:s,update:i}}async function MM(e){let t=E(process.cwd(),e.global.path),n=await A(t),r=re(e),o=$(n.schema).open_status,s=await _t(r,dr(e.options,{status:o,force:e.force},["assignee"]),e.global),i=await Os(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:s,release:i}}async function $M(e){let t=re(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await pt(t,n,{...e.options,force:e.force},e.global),o=await Os(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:o}}function DM(e){let t={...e.args,...e.options};return zp(nt(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),Xp(t),e.global)}function UM(e){return Zp(E(process.cwd(),e.global.path),{...e.args,...e.options})}var GM={init:e=>Or(w(e.args,"prefix"),e.global,e.options),context:e=>nc(wn("context",e.options),e.global),next:e=>hr(wn("next",e.options),e.global),eval:Xg,events:Qg,merge:Zg,workspace:ey,meet:pi,event:pi,remind:pi,list:lM,get:e=>{let t=re(e);return rc(t,e.global,wn("get",e.options,[t]))},search:dM,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ke(e.options.status);return oc(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:w(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:Ge(e.options.limit,"limit")})},create:mM,copy:uM,focus:e=>Zc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:pM,"item-reopen":Cy,restore:NM,claim:Ey,release:e=>Os(re(e),e.force,e.global,e.options),"start-task":FM,"pause-task":MM,"close-task":$M,close:Ty,comments:fM,notes:e=>P_(re(e),Rs(e.options),e.global),learnings:e=>x_(re(e),Rs(e.options),e.global),files:_M,docs:e=>Mf(re(e),us(e.options),e.global),test:e=>Oi(re(e),e.options,e.global),"test-all":e=>dw(e.options,e.global),telemetry:hM,validate:e=>ws(e.options,e.global,{runUpdate:(t,n,r)=>_t(t,n,r)}),health:gM,assurance:e=>Zf(e.args,e.options,e.global),contracts:e=>Xy(e.options,e.global),config:yM,activity:vM,aggregate:e=>Za(e.options,e.global),extension:e=>xn(Ni(e),e.options,e.global),package:e=>xn(Ni(e),e.options,e.global),install:e=>xn(Ni(e),{...e.options,install:!0},e.global),upgrade:e=>t_(Ni(e),e.options,e.global),delete:e=>Qc(re(e),e.options,e.global),deps:e=>Kp(re(e),e.options,e.global),graph:DM,"files-discover":e=>Ba(re(e),e.options,e.global),"files-lookup":e=>vw(e,ke(e.options.paths)),history:e=>e_(re(e),e.options,e.global),"history-redact":e=>hy(re(e),e.options,e.global),"history-repair":ky,"history-compact":Sy,"history-author-acknowledge":UM,plan:bM,schema:IM,profile:OM,stats:e=>Ml(e.global,hv(e.options)),append:xM,"update-many":PM,"close-many":LM,gc:e=>n_(e.global,e.options)};async function hw(e,t,n,r){let o=Ua(t,e);_a(e,o),yu(e,o);let s={action:e,args:t,options:o,id:w(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},i=Fi(GM,e),a=i?await i(s):await iM(e,t,o,n,r);o.resolvedOutputFormat="json";let c=Pu(e,o,a);return await d_(E(process.cwd(),n.path),c),c}var jM={closeManyOptionsFromFlat:Ka,extensionOptionsFromArgs:qa,globalOptions:Da,mutationListOptions:Jp,normalizeActionName:On,normalizeCommandPath:ja,normalizeMcpUpdateOptions:Qp,normalizeMcpOptionsArrays:Wp,optionsWithAuthor:Ua,readRequiredString:nt,readScalarString:Bp,readScalarStringAllowBlank:Hp,readStringArray:ke,updateManyOptionsFromFlat:za,withAddNoteOption:us,withFilesDiscoveryOptions:Ga,withMutationCompaction:Pe};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=jM);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48d03e9b-14a4-545c-8e5d-5f5f2092a113")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38023567-8a5b-5e25-8d71-5112f74d1894")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3eaa41f7-77a1-5838-8a2f-2ab6a49c21ef")}catch{}})();export{bn as AGENT_PROVENANCE_DIMENSIONS,zu as BASELINE_ITEM_FORMAT_VERSION,vb as BUILTIN_AGENT_PROVENANCE_ADAPTERS,nr as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,Br as BUILTIN_ITEM_TYPE_VALUES,Vr as CONFIDENCE_TEXT_VALUES,Bu as CURRENT_ITEM_FORMAT_VERSION,Kt as DEPENDENCY_KIND_VALUES,l as EXIT_CODE,fn as ISSUE_SEVERITY_VALUES,md as ITEM_TYPE_VALUES,ac as PM_CLI_EXPECTED_ERROR_NAME,lb as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,ab as PM_READ_OUTPUT_DIMENSIONS,cb as PM_READ_OUTPUT_OPTION_FLAGS,pa as PM_READ_OUTPUT_SURFACE_CONTRACTS,d as PmCliError,G as PmClient,pn as RISK_VALUES,Lb as SEMANTIC_ATTRIBUTION_LIMITS,Hr as STATUS_VALUES,yb as agentSessionEnvironment,$F as aggregate,Nl as analyzeAgentProvenanceDescriptorCoverage,fb as analyzeSdkCliParameterCompleteness,HF as append,mb as applyReadOutputDimensions,nb as applyReadOutputSessionReferences,rb as attachReadOutputSessionReceipt,_b as boundAgentEpisodeIdentity,Xe as canonicalDocument,XF as claim,QF as claimNext,Wu as classifyItemFormatVersion,JF as close,DF as comments,xF as context,eM as copy,VF as create,c_ as createPmCliExpectedError,ib as decodeReadOutputContinuationCursor,tM as deleteItem,zF as deps,Tb as detectAgentIdentity,Ib as detectHarnessIdentity,Cb as diagnoseAgentIdentity,KF as docs,Hu as effectiveItemFormatVersion,mw as emptyImportedDocument,sb as encodeReadOutputContinuationCursor,lP as evaluateSemanticAttributionCoverage,xb as explainSourceTraceability,jF as files,qF as filesDiscover,rM as focus,FF as get,BF as graph,dP as groupHistoryByEpisode,y_ as isAlreadyClaimedError,As as isPmCliExpectedError,ub as isReadOutputBudgetExceeded,GF as learnings,PF as list,bb as listAgentProvenanceAdapters,LF as listAllComplete,MF as next,Sb as normalizeAgentProvenanceAdapterValue,Vu as normalizeItemFormatVersion,Ue as normalizeItemId,ee as normalizeStatusInput,UF as notes,k as nowIso,tb as parseReadOutputSession,gs as parseSourceLineRange,zo as readAuthorEnvironment,ob as readOutputSessionRemainingTokens,ec as recordClaimSemanticAttribution,ks as recordFocusSemanticAttribution,tc as recordReleaseSemanticAttribution,kb as registerAgentProvenanceAdapters,wb as registerHarnessSignalDescriptors,ZF as release,YF as reopen,hb as resolveAgentSessionContextFromSignals,Ob as resolveAuthorIdentity,iv as resolveHistoryEpisodeGroupIdentity,db as resolveReadOutputDimensions,pb as resolveReadOutputEncoding,fa as resolveReadOutputSurface,Pb as resolveSemanticLineageIds,nM as restore,yw as runAction,gb as runWithAgentSessionContext,Eb as runWithHarnessDetectionSignals,Ab as runWithWorkspaceHarnessSignalDescriptors,NF as search,Nb as semanticAttributionAffinity,qe as serializeItemDocument,cP as summarizeAgentModelProvenance,Fl as summarizeAgentProvenance,WF as update,_a as validateReadOutputOptions,Rb as writeAuthorEnvironment};
|
|
35
|
+
`);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=EI(m,t);return Fe.write(`
|
|
36
|
+
`),{prefix:o,preset:a,telemetry_enabled:u}}finally{n.close()}}function xI(e){return{presetFromOption:Eg(e.preset),useDefaults:e.defaults===!0,authorFromOption:wI(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:SI(e.agentGuidance),typePreset:vI(e.typePreset)}}function PI(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function LI(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new d(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,l.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function NI(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(Ag(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function MI(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=PI({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return LI(e.settingsPath,n,e.options.force===!0,e.target),NI({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await xe(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function FI(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await OI(t,Tt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let i=n??"minimal",s=gI();s.id_prefix=t,Ag(s,i);let a=Zo()?.trim()||void 0;return s.author_default=e.normalizedOptions.authorFromOption??a??"",r!==void 0&&(s.telemetry.enabled=r,s.telemetry.first_run_prompt_completed=!0),await xe(e.pmRoot,s),{settings:s,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function Sg(e){return e.settingsExists?await MI(e):await FI({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function $I(e){let t=await kg({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await xe(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function DI(e,t){let n=[],r=[],o=await ru(e,t.schema);for(let i of o.created_paths)n.push(i),r.push(...await W({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function UI(e){if(e.typePreset===void 0)return;let t=await CI(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await W({path:t.file,scope:"project",op:"init:type_preset"})),t}async function GI(e){let n=x(e.settings,O()).folders.filter(o=>!aa.includes(o)),r=await Tg(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function jI(e){let t=X.resolve(e.tracker_root),n=X.dirname(t);return X.basename(t)==="pm"&&X.basename(n)===".agents"?X.dirname(n):e.workspace_root}async function qI(e,t,n,r){if(!e)return;let o=await Mn("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let i=TI(o),s=i.packages.filter(a=>!a.ok).map(a=>a.alias);if(!i.installed_all||s.length>0)throw new d(`pm init --with-packages did not install all bundled packages successfully${s.length>0?`: ${s.join(", ")}`:"."}`,l.GENERIC_FAILURE);return i}function KI(e){let t=r=>cr([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function zI(e,t,n,r=mf){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof d))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function BI(e,t,n,r){if(e==null||n==="status")return;let o=await xa(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function Gr(e,t,n={}){let r=t[vl],o=typeof r=="string"?r:process.cwd(),i=bI(o,t,e,n.workspace),s=i.pmRoot;e=kI(i.prefixArg,n.idPrefix);let a=xI(n);await II(s,i.target.mode==="tracker-path",n.force===!0);let c=[],m=[],u=X.join(s,"settings.json"),p=await L(u),f;p&&(f=await Sg({pmRoot:s,settingsPath:u,settingsExists:p,normalizedPrefix:Lt(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:i.target}));let _=await Tg(s,aa);c.push(..._.createdDirs),m.push(..._.warnings),f??=await Sg({pmRoot:s,settingsPath:u,settingsExists:p,normalizedPrefix:Lt(e),prefixArg:e,options:n,normalizedOptions:a,warnings:m,target:i.target});let{settings:g}=f,y=jI(i.target),h=await ki(y??X.dirname(s)),v=y??h,b=await $I({pmRoot:s,cwd:v??o,agentGuidanceMode:a.agentGuidanceMode,settings:g,warnings:m}),S=await DI(s,g);c.push(...S.createdDirs),m.push(...S.warnings);let T=await UI({pmRoot:s,settings:g,typePreset:a.typePreset,warnings:m});T&&(g=await A(s)),await GI({pmRoot:s,settings:g,createdDirs:c,warnings:m}),await BI(v,s,a.agentGuidanceMode,m),!p&&n.mergeFence!==!1&&a.agentGuidanceMode!=="status"&&await zI(s,h,m);let I=await qI(a.installBundledPackages,t,s,m),D=KI({installBundledPackages:a.installBundledPackages,registeredTypePreset:T,agentGuidanceNextSteps:b.next_steps,target:i.target});return{ok:!0,path:s,target:i.target,settings:g,created_dirs:c,warnings:m,governance_preset:g.governance.preset,wizard_used:f.wizardUsed,...T?{registered_type_preset:T}:{},...I?{installed_packages:I}:{},next_steps:D,agent_guidance:b}}import QI from"node:fs/promises";import kl from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7b09736a-499b-57f6-b688-0458b487786b")}catch{}})();var Rg=10,pn="https://schema.unbrained.dev/pm/eval-query-set/v1";var vs={schema:pn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Ve=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},HI=new Set(["keyword","semantic","hybrid"]);function Cg(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function VI(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),o=Cg(r,n),i=Array.from({length:t.size},()=>1),s=Cg(i,n);return s===0?0:o/s}function WI(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function wl(e,t,n){let r=Math.min(n,e.length),o=0;for(let i=0;i<r;i+=1)t.has(e[i])&&(o+=1);return o}function YI(e,t,n){return n<=0?0:wl(e,t,n)/n}function JI(e,t,n){return t.size===0?0:wl(e,t,n)/t.size}function Ig(e,t,n){return{ndcg:VI(e,t,n),mrr:WI(e,t,n),precision:YI(e,t,n),recall:JI(e,t,n),relevant_total:t.size,retrieved_relevant:wl(e,t,n)}}function Og(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function XI(e,t){if(typeof e!="object"||e===null)throw new Ve(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new Ve(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Ve(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(i=>typeof i!="string"))throw new Ve(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new Ve(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!HI.has(n.mode)))throw new Ve(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function bl(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==pn)throw new Ve(`Unsupported eval query set schema; expected "${pn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new Ve('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Ve("Eval query set must contain at least one query");return{schema:pn,queries:n.map((r,o)=>XI(r,o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7f6cfdef-5456-5716-9067-8ccadf077f5f")}catch{}})();var ZI=kl.join("search","eval-queries.json"),Sl={schema:pn,examples:[JSON.stringify(vs)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},e0=new Set(["keyword","semantic","hybrid"]),t0=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!e0.has(t))throw new d("Eval --mode must be one of keyword|semantic|hybrid",l.USAGE);return t},n0=e=>{if(e===void 0||e==="")return Rg;let t=Od(e);if(t===null)throw new d("Eval --k must be a positive integer",l.USAGE);return t},r0=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new d("Eval --fail-under must be a number in the range [0, 1]",l.USAGE);return n},jt=e=>Math.round(e*1e4)/1e4,o0=async e=>{try{return await QI.readFile(e,"utf8")}catch{throw new d(`Eval query set not found at ${e}`,l.NOT_FOUND,{...Sl,examples:[`echo '${JSON.stringify(vs)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},i0=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new d(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,l.USAGE,Sl)}},s0=e=>{try{return bl(e)}catch(t){throw new d(t instanceof Error?t.message:String(t),l.USAGE,Sl)}},a0=async e=>s0(i0(await o0(e),e)),c0=(e,t)=>t?kl.resolve(process.cwd(),t):kl.join(e,ZI),l0=async(e,t,n,r)=>{let o=e.mode??t,s=(await Er(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=Ig(s,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:jt(a.ndcg),mrr:jt(a.mrr),precision:jt(a.precision),recall:jt(a.recall)}}},d0=(e,t,n,r)=>{let o=Og(n);return{k:e,query_count:t.length,aggregate:{ndcg:jt(o.ndcg),mrr:jt(o.mrr),precision:jt(o.precision),recall:jt(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||o.ndcg>=r}},xg=async(e,t)=>{let n=E(process.cwd(),t.path);await R(n);let r=n0(e.k),o=t0(e.mode),i=r0(e.failUnder),s=c0(n,e.queries),a=await a0(s),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await l0(u,o,r,t);m.push(f),c.push(p)}return d0(r,c,m,i)};import{readFile as m0,writeFile as u0}from"node:fs/promises";import p0 from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47487ad3-22a0-52ac-8a42-ebaca439cb6e")}catch{}})();var Pg=["item","history","relationship","json"];function f0(e){let t=e.trim().toLowerCase();if(Pg.includes(t))return t;throw new d(`Unknown merge artifact "${e}". Supported values: ${Pg.join(", ")}.`,l.USAGE)}function _0(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new d(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,l.USAGE)}async function El(e,t){try{return await m0(e,"utf8")}catch{throw new d(`Cannot read merge ${t} file at ${e}.`,l.NOT_FOUND)}}async function h0(e){let t=E(process.cwd(),e.path);return await L(fe(t))?A(t):null}function g0(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Lg(e,t){let n=f0(e.artifact),r=_0(e.prefer),o=p0.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([El(e.basePath,"base"),El(e.oursPath,"ours"),El(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=xf(i,s,a);c=_.merged,p.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=Pf(i,s,a);c=_.merged,p.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await h0(t),g=g0(e.itemPath??o,_),y=Ct(O()),h=Lf(i,s,a,{format:g,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"});if(c=h.merged,u.push(...h.conflict_fields),p.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let v=rp(c,{format:g,schema:_?.schema,extensionFieldNames:y}),b=v.metadata,S=[...new Set([...h.fields_from_theirs,...h.union_fields,...h.conflict_decisions.map(T=>T.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,mergedFieldHashes:Object.fromEntries(S.map(T=>[T,Of(T==="body"?v.body:b[T])])),decisions:h.conflict_decisions,operation:await Mf(process.cwd(),e.itemPath)}}}else{let _=Nf(i,s,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await u0(o,c,"utf8"),m!==void 0){let _=await $f(m);_!==null&&(p.receipt=en(_))}let f=[];if(u.length>0){let _=p.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${p.receipt.receipt_id} with item ${p.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${u.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&p.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:u.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5fd3624a-d36b-58e6-8053-f2c0626e0c10")}catch{}})();async function Ng(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await Ff(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Ut(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Ut(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:r,message:e.message??"Settle rebase receipt after exact original Git state restoration",auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...en(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await Si(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as y0}from"node:fs/promises";import v0 from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="deef67cc-b902-5a4e-9c66-3839a1cdcc6f")}catch{}})();var w0=4;function Mg(e){let t=e.checks.find(a=>a.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,s=Array.isArray(o)?o.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:i,coordinates:s}}async function b0(e,t){let n=[];for(let r of t){let o;try{o=await y0(v0.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let i=o.split(/\r?\n/)[r.history_line-1];if(i===void 0||i.trim().length===0)continue;let s;try{s=JSON.parse(i)}catch{continue}let a=qf(s,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!jf(a)||a.eventTimestamp===void 0||Jo(a.eventTimestamp,Gf)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function k0(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;let t=new Map;for(let n of e.candidates){let r=t.get(n.item_id)??[];r.push(n),t.set(n.item_id,r)}for(let[n,r]of t)await Ut(n,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:r.map(o=>({receipt_id:o.receipt_id,original_history_line:o.history_line,original_event_ts:o.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function S0(e){try{return{status:"fulfilled",value:await Ut(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function E0(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function A0(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>Si(e.gitWorkspaceRoot??process.cwd(),r,{requireExisting:!0}))),n.length}async function Fg(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await vr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=Mg(o),s=await b0(r,i.coordinates),a=await ki(r),c=await Df(a??process.cwd(),{includeLossless:!0,pmRoot:r});if(c.invalid_evidence_count>0)throw new d(`Merge reconciliation refused ${c.invalid_evidence_count} invalid receipt evidence file(s).`,l.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let m=await k0({candidates:s,options:e,global:t}),u=c.receipts,p=await Ng({cwd:a,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),f=new Set(p),_=new Map;for(let j of u.filter(ce=>!f.has(ce.id))){let ce=_.get(j.item_id)??[];ce.push(j),_.set(j.item_id,ce)}let g=Object.fromEntries([..._].map(([j,ce])=>[j,{merge:{receipts:ce.map(en)}}])),y=Object.fromEntries([..._].map(([j,ce])=>[j,{gitWorkspaceRoot:a,receipts:ce}])),h=await Ai({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:g,...u.length>0?{mergeReceiptProofById:y}:{}},t),v=new Set(h.streams.map(j=>j.id)),b=[..._.keys()].filter(j=>!v.has(j)),S=await If(b,w0,j=>S0({id:j,dryRun:n,options:e,global:t,auditContext:g[j],mergeReceiptProof:y[j]}));E0({receiptOnlyIds:b,results:S,repair:h});let T=await A0({dryRun:n,pendingReceipts:u,repair:h,gitWorkspaceRoot:a}),I=await Ii({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),D=m===0?o:await vr(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),M=Mg(D),Y=I.checks.every(j=>j.status==="ok"),z=n?u.length===0:T+p.length===u.length,K=[h.totals.failed===0,Y,z,M.count===0,!M.truncated].every(Boolean),pe=i.truncated||M.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,ae=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",pe,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:K?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.",pe,...s.length>0&&m===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(j=>j!==void 0);return{ok:K,dry_run:n,repair:h,receipts:{pending_before:u.length,reconciled:T,abandoned:p.length,summaries:u.map(en),missing_history_references_before:i.count,legacy_disposition_eligible:s.length,legacy_disposition_recorded:m,missing_history_references_after:M.count},validation:I,guidance:ae,generated_at:I.generated_at}}import{createHash as T0}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="117a463a-c0ab-569f-92e9-e85d14a1cf91")}catch{}})();var Ug=1,Gg=/^[A-Za-z0-9_-]+$/,C0=100,$g=1e3;var kK=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function We(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function R0(e){return T0("sha256").update(Wt({type:We(e.type),author:We(e.author),item:We(e.item),harness:We(e.harness),agent_instance:We(e.agentInstance),provenance:We(e.provenanceFilter)})).digest("hex").slice(0,24)}function Dg(e,t){let n={version:Ug,fingerprint:t,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function I0(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Ug,n.fingerprint===t,typeof n.ts=="string",typeof n.stream_id=="string",typeof n.stream_offset=="number",Number.isSafeInteger(n.stream_offset),Number(n.stream_offset)>=0].every(Boolean)}function O0(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Gg.test(n))throw new d("Invalid mutation event cursor.",l.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new d("Invalid mutation event cursor.",l.USAGE,{code:"invalid_event_cursor"})}if(!I0(r,t))throw new d("Mutation event cursor does not match this query.",l.USAGE,{code:"event_cursor_query_mismatch"});return r}function x0(e){let t=e??C0;if(!Number.isSafeInteger(t)||t<0||t>$g)throw new d(`Mutation event limit must be an integer from 0 to ${$g}.`,l.USAGE,{code:"invalid_event_limit"});return t}function P0(e,t){let n=e?.trim();if(!n)return{};if(Gg.test(n))return{cursor:O0(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new d("Mutation event --since must be an event cursor or ISO timestamp.",l.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function L0(e,t){let n=await Na(e,t);if(n===null){if(!await sp(e))return{...await ap(e,t),source:"authoritative_history"};n=await Na(e,t)}if(n===null)throw new d("Mutation event index could not be opened after rebuild.",l.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function N0(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new d("Mutation event cursor mode must be batch or row.",l.USAGE,{code:"invalid_event_cursor_mode"});return t}async function ws(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await R(t);let n=x0(e.limit),r=N0(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new d("Mutation event projections are mutually exclusive. Use --provenance or --full.",l.USAGE);let o=await A(t),i=o.agent_identity.identity_vocabulary,s=Kp(o.agent_identity.harness_signals),a=zp({provenance:e.provenanceFilter},s),c=We(e.harness),m=R0(e),{cursor:u,sinceTimestamp:p}=P0(e.since,m),f={...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:We(e.type),authors:We(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:We(e.agentInstance),provenance:[...a].map(([y,h])=>({dimension:y,values:[...h]})),stream_ids:We(e.item),limit:n},_=await L0(t,f),g=_.events.map(y=>({...r==="row"?{cursor:Dg(y,m)}:{},item_id:y.stream_id,version:y.stream_offset+1,ts:y.entry.ts,author:y.entry.author,type:y.entry.op,...y.entry.message===void 0?{}:{message:y.entry.message},patch_count:y.entry.patch.length,...e.full===!0?{entry:y.entry}:{},...e.provenance===!0?{provenance:Bp(y.entry,i,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:g,count:g.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:Dg(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Hp(_.events.map(y=>y.entry),i,s)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a196ae-61e1-528d-99a2-83eb9e11158b")}catch{}})();var M0="1h",F0="now",$0="+1d";function qt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function jg(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return Se(n,r)}async function qg(e,t,n,r){let o=jg(e,t,n),i=[];return qt(i,"start",n.start??F0),n.end!==void 0?qt(i,"end",n.end):qt(i,"duration",n.duration??M0),qt(i,"location",n.location),qt(i,"timezone",n.timezone),n.allDay===!0&&qt(i,"all_day","true"),o.event=[i.join(",")],Gt(o,r)}function Kg(e,t,n){return qg("Meeting",e,t,n)}function zg(e,t,n){return qg("Event",e,t,n)}function Bg(e,t,n){let r=jg("Reminder",e,t),o=[];return qt(o,"at",t.at??$0),qt(o,"text",t.text??e),r.reminder=[o.join(",")],Gt(r,n)}import qr from"node:crypto";import{cp as Hg,lstat as D0,mkdir as fn,readFile as Bn,readdir as Tl,rename as Yg,rm as Rl,writeFile as bs}from"node:fs/promises";import $ from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="91604cb2-8afd-585e-9c18-26e223df25bc")}catch{}})();var Jg="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var Xg=$.join("runtime","workspace-snapshots"),U0=new Set(["checkpoints","locks","runtime","search","transactions"]),G0=/^[a-z0-9][a-z0-9._-]*$/,jr="sdk-workspace-transaction",Al={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Qg={renameEntry:Yg,removeEntry:async e=>{await Rl(e,{recursive:!0,force:!0})}},Cl=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await Bn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==jr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await ee(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
|
|
37
|
+
`)}};async function Zg(e,t=""){let n=await Tl($.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((i,s)=>i.name.localeCompare(s.name))){if(t.length===0&&U0.has(o.name))continue;let i=$.posix.join(t.replaceAll($.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${i}`);if(o.isDirectory())r.push(...await Zg(e,i));else if(o.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function ey(e){let t=await Zg(e),n=qr.createHash("sha256"),r=[],o=0;for(let s of t){let a=await Bn($.join(e,s));r.push(a),o+=a.byteLength,n.update(s),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let i=n.digest("hex");return{manifest:{schema:Jg,fingerprint:i,files:t,bytes:o},contents:r}}function Vg(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
|
|
38
|
+
`).filter(t=>t.trim().length>0).length}async function j0(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),i=await Promise.all(o.map(async s=>[s,await Bn($.join(e,s))]));for(let[s,a]of i)n.set(s,a)}return n}function Il(e){if(!G0.test(e))throw new d("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",l.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 ty(e,t){return er(`workspace_snapshot_${e}`,t,{codes:{capacity:Al.capacity.code,permission:Al.permission.code,resource:Al.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 _n(e){return $.join(e,Xg)}function ny(e){return new d(`Unknown workspace snapshot: ${e}`,l.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 ry(e,t){try{return JSON.parse(await Bn(e,"utf8"))}catch(n){throw Rt(n)?ny(t):n}}async function Wg(e,t,n){try{await Rl(e,{recursive:n})}catch(r){throw Rt(r)?ny(t):r}}async function q0(e,t,n=Qg){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 K0(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(i){throw await r.renameEntry(n,t),await r.removeEntry(e),i}await r.removeEntry(n)}async function z0(e,t){return Il(t),/^[a-f0-9]{64}$/.test(t)?t:(await ry($.join(_n(e),"refs",`${t}.json`),t)).fingerprint}async function Ol(e,t={}){if(t.name!==void 0&&(Il(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new d("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",l.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 ey(e),o=_n(e),i=$.join(o,"objects",n.fingerprint),s=!1;try{s=(await D0(i)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&Rt(a)))throw a}if(!s){let a=$.join(o,"objects",`.create-${process.pid}-${qr.randomUUID()}`);await ty("create_object",async()=>{await fn($.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=$.join(a,"files",m);await fn($.dirname(u),{recursive:!0}),await bs(u,r[c])}await bs($.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
|
|
39
|
+
`,"utf8"),await fn($.dirname(i),{recursive:!0})}),s=await q0(a,i)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=$.join(o,"refs");await fn(c,{recursive:!0});let m=$.join(c,`.ref-${process.pid}-${qr.randomUUID()}`);await bs(m,`${JSON.stringify(a,null,2)}
|
|
40
|
+
`,"utf8"),await Yg(m,$.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:s}}async function Kr(e,t){let n=await z0(e,t),r=await ry($.join(_n(e),"objects",n,"manifest.json"),t);if(r.schema!==Jg||r.fingerprint!==n)throw new d(`Snapshot manifest identity mismatch: ${t}`,l.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 xl(e){let t=_n(e),n=await Tl($.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&Rt(o))return[];throw o}),r=await Tl($.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&Rt(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Kr(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await Bn($.join(t,"refs",o),"utf8"))))}}async function Pl(e,t){let n=await Kr(e,t),{manifest:r,contents:o}=await ey(e),i=new Map(r.files.map((p,f)=>[p,o[f]])),s=await j0($.join(_n(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),m=new Set([...a,...c]);for(let p of m){let f=i.get(p),_=s.get(p);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=Vg(i.get(p)),_=Vg(s.get(p));return{path:p,current_entries:f,target_entries:_,removed_entries:Math.max(0,f-_)}}).filter(p=>p.removed_entries>0).sort((p,f)=>p.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:m.size,removed_file_count:[...a].filter(p=>!c.has(p)).length,added_file_count:[...c].filter(p=>!a.has(p)).length,removed_item_count:[...a].filter(p=>p.endsWith(".toon")&&!c.has(p)).length,affected_history_stream_count:u.length,removed_history_entry_count:u.reduce((p,f)=>p+f.removed_entries,0),affected_history_streams:u,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function oy(e,t,n={}){if(n.force!==!0)throw new d("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",l.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",o=n.lockTtlSeconds??60,i=n.lockWaitMs??5e3,s=await ke(e,jr,o,r,!1,!1,i),a=new Cl(lo(e,jr),r,o);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await Pl(e,t),f=await Kr(e,t),_=await Ol(e),g=f.fingerprint,y=_n(e),h=$.join(y,"objects",g,"files"),v=$.dirname(e),b=$.basename(e);c=$.join(v,`.${b}.restore-${qr.randomUUID()}`);let S=$.join(v,`.${b}.backup-${qr.randomUUID()}`);await ty("restore_stage",async()=>{await fn(c,{recursive:!0}),await Hg(h,c,{recursive:!0,force:!1}),await fn($.join(c,"runtime"),{recursive:!0}),await Hg(y,$.join(c,Xg),{recursive:!0,force:!1})});let T=await gp({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:p.changed_file_count,removed_file_count:p.removed_file_count,removed_item_count:p.removed_item_count,affected_history_stream_count:p.affected_history_stream_count,removed_history_entry_count:p.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:i}),I=$.relative(c,T.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let D=lo(c,jr);return await fn($.dirname(D),{recursive:!0}),await bs(D,await Bn(lo(e,jr)),{flag:"wx"}),m=!0,await K0(c,e,S,Qg,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:I,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([Rl(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await s()}}}async function iy(e,t){Il(t);let n=_n(e);if(!/^[a-f0-9]{64}$/.test(t))return await Wg($.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await xl(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Wg($.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66cead7f-c3f3-5073-82a5-ad1535f3f611")}catch{}})();function zr(e){let t={...e.args,...e.options};return Se(e.options,t)}function kt(e,t){let n=w(e,t);if(n!==void 0)return n;throw new d(`Missing required parameter: ${t}`,l.USAGE)}function Hn(e){return typeof e=="string"?[e]:Ee(e)}function sy(e){return xg(zr(e),e.global)}function ay(e){let t=zr(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new d("Mutation event cursor mode must be batch or row.",l.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return ws({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Hn(t.type),author:Hn(t.author),item:Hn(t.item),limit:t.limit===void 0?void 0:qe(t.limit,"limit"),full:t.full===!0,cursorMode:r,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Hn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Hn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Hn(t.provenanceFilter)}})}function cy(e){let t=zr(e),n=kt(t,"subcommand");if(n==="install")return df({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return Fg({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return Uf({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return Lg({artifact:kt(t,"artifact"),basePath:kt(t,"basePath"),oursPath:kt(t,"oursPath"),theirsPath:kt(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw Pe({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function ly(e){let t=zr(e),n=kt(t,"subcommand");if(n==="position")return u_(e.global);if(n!=="snapshot")throw Pe({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??kt(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return Ol(o,{name:w(t,"name")});if(r==="list")return xl(o);let i=kt(t,"target");if(r==="inspect")return Kr(o,i);if(r==="delete")return iy(o,i);if(r==="restore")return t.dryRun===!0?Pl(o,i):oy(o,i,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:qe(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:qe(t.lockWaitMs,"lockWaitMs")});throw Pe({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function ks(e){let t=zr(e),n=kt(t,"title");return e.action==="meet"?Kg(n,t,e.global):e.action==="event"?zg(n,t,e.global):Bg(n,t,e.global)}import rO from"node:path";import B0 from"node:fs/promises";import dy from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ff76c0f3-d8cf-51de-a7e6-acb0a4942268")}catch{}})();var H0="templates",V0=".json",W0=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Y0=Ho.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),J0=new Set(Y0);function X0(e){let t=e.trim();if(!W0.test(t))throw new d(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,l.USAGE);return t}function my(e){return dy.join(e,H0)}function uy(e,t){return dy.join(my(e),`${t}${V0}`)}async function Q0(e){await R(e)}function py(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function Z0(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(J0.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(i=>typeof i=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return py(t)}function eO(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new d(`Template "${t}" has invalid options payload.`,l.GENERIC_FAILURE);let n=e,r={};for(let[o,i]of Object.entries(n)){let s=o.trim();if(s.length===0)throw new d(`Template "${t}" contains an empty option key.`,l.GENERIC_FAILURE);if(typeof i=="string"){r[s]=i;continue}if(Array.isArray(i)&&i.every(a=>typeof a=="string")){r[s]=[...i];continue}throw new d(`Template "${t}" contains invalid value for option "${s}".`,l.GENERIC_FAILURE)}return py(r)}function tO(e,t){let n;try{n=JSON.parse(e)}catch{throw new d(`Template "${t}" contains invalid JSON.`,l.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new d(`Template "${t}" has invalid document shape.`,l.GENERIC_FAILURE);let r=n,o=eO(r.options,t),i=k();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:i,updated_at:typeof r.updated_at=="string"?r.updated_at:i,options:o}}async function nO(e,t){let n=await Q(uy(e,t));if(n===null)throw new d(`Template "${t}" not found`,l.NOT_FOUND);return tO(n,t)}async function Ll(e,t,n){let r=E(process.cwd(),n.path);await Q0(r);let o=X0(e),i=Z0(t);if(Object.keys(i).length===0)throw new d("templates save requires at least one create option flag",l.USAGE);let s=k(),a=uy(r,o),c=s;await L(a)&&(c=(await nO(r,o)).created_at);let m={name:o,created_at:c,updated_at:s,options:i},u=await A(r);return await B0.mkdir(my(r),{recursive:!0}),await tt({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
|
|
41
|
+
`,op:"templates:save",author:C(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:a,options:m.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5529deea-21db-509b-9562-d5e08dfc004a")}catch{}})();var gy=["list","show","apply","lint"],oO="schema-types",iO="schema-statuses",sO="schema-fields";function Ss(){let e=O();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function yy(){let{profiles:e,warnings:t}=tu(Ss());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:su(n.definition)})),warnings:t,generated_at:k()}}function vy(e){let t;try{t=Go(e,Ss())}catch(r){throw new d(r instanceof Error?r.message:String(r),l.USAGE)}let{resolved:n}=t;return{action:"show",...au(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function wy(e){let t;try{t=Go(e,Ss())}catch(o){throw new d(o instanceof Error?o.message:String(o),l.USAGE)}let{resolved:n}=t,r=Ru(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:k()}}function aO(e,t){return rO.join(e,"templates",`${t}.json`)}async function cO(e,t){let n=await Q(aO(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function fy(e,t,n,r){let o=new Map;for(let i of r.templates){let s=await cO(e,i.name);s!==void 0&&o.set(i.name,s)}return{typesRaw:await Q(ft(e,t.files.types,pt.types)),statusesRaw:await Q(ft(e,t.files.statuses,pt.statuses)),fieldsRaw:await Q(ft(e,t.files.fields,pt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Vn(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function _y(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Vn(t.types.changes),statuses:Vn(t.statuses.changes),fields:Vn(t.fields.changes),workflows:Vn(t.workflows.changes.map(i=>({key:i.type,status:i.status}))),config:Vn(t.config.changes),templates:Vn(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(o)].sort((i,s)=>i.localeCompare(s)),generated_at:k()}}async function lO(e){await R(e)}function dO(e){try{let t=Go(e,Ss());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new d(t instanceof Error?t.message:String(t),l.USAGE)}}async function by(e,t,n){let r=E(process.cwd(),n.path);await lO(r);let o=dO(e),i=o.profile,s=o.warnings,a=t.dryRun===!0,c=await A(r),m=jo(c.schema);if(a){let v=await fy(r,m,c,i),b=hy(i,v);return _y(i,b,!1,!0,[...s])}let u=C(t.author,c.author_default),p=vp(c),f=!!t.force,_=[...s],g=[],y=async v=>{g.push(await ke(r,v,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},h;try{await y(oO),await y(iO),await y(sO);let v=await fy(r,m,c,i);if(h=hy(i,v),h.types.changed){let b=ft(r,m.files.types,pt.types);await tt({pmRoot:r,filePath:b,raw:Uo(h.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let S=new Set(i.types.map(I=>Ym(I).name)),T=h.types.file.definitions.filter(I=>S.has(I.name));await gf(r,T,_,"profile:apply-type-folder"),_.push(...await W({path:b,scope:"project",op:"profile:apply-types"}))}if(h.statuses.changed){let b=ft(r,m.files.statuses,pt.statuses);await tt({pmRoot:r,filePath:b,raw:iu(h.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await W({path:b,scope:"project",op:"profile:apply-statuses"}))}if(h.fields.changed){let b=ft(r,m.files.fields,pt.fields);await tt({pmRoot:r,filePath:b,raw:nu(h.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await W({path:b,scope:"project",op:"profile:apply-fields"}))}if(h.config.changed||h.workflows.changed){for(let b of h.config.changes){if(b.status==="unchanged")continue;let S=Ko(b.key);S!==void 0&&zo(c,S,b.value)}c.schema.type_workflows=h.workflows.result,await xe(r,c,"profile:apply-config")}for(let b of h.templates.changes)b.status!=="unchanged"&&await Ll(b.name,{...b.options},n)}finally{for(let v of g.reverse())try{await v()}catch{}}return _y(i,h,h.changed,!1,_)}function hy(e,t){try{return Iu(e,t)}catch(n){throw new d(n instanceof Error?n.message:String(n),l.USAGE)}}import Nl from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d562ab68-1891-54cc-8256-57cc1121b9ce")}catch{}})();function ky(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function mO(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function uO(e){let t=e.trim();if(t.length===0)throw new d("history-redact --regex requires a non-empty pattern.",l.USAGE);let n=t,r="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(n=t.slice(1,o),r=mO(t.slice(o+1)))}if(n.length===0)throw new d("history-redact --regex cannot use an empty pattern.",l.USAGE);try{new RegExp(n,r)}catch{throw new d("Invalid --regex value; provide a valid JavaScript regular expression.",l.USAGE)}return{kind:"regex",source:n,flags:r}}function pO(e,t){let n=[...new Set(ky(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),r=[...new Set(ky(t).map(i=>i.trim()))].filter(i=>i.length>0).map(uO),o=[...n,...r];if(o.length===0)throw new d("history-redact requires at least one matcher via --literal or --regex.",l.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return o}function fO(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){let i=e.indexOf(t,r);if(i===-1)break;o+=1,r=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function _O(e,t,n){let r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function Ey(e,t,n){let r=e,o=0;for(let i of t){let s=i.kind==="literal"?fO(r,i.value,n):_O(r,i,n);r=s.value,o+=s.replacements}return{value:r,replacements:o}}function Es(e,t,n){if(typeof e=="string")return Ey(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(i=>{let s=Es(i,t,n);return r+=s.replacements,s.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,o={};for(let[i,s]of Object.entries(e)){let a=Es(s,t,n);r+=a.replacements,o[i]=a.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function Sy(e,t,n){let r=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=Es(i.value,t,n);return r+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:r}}function hO(e){let t=structuredClone(Fa),n=0,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];dr(t)!==i.before_hash&&(n+=1),t=Rn(t,i.patch,o+1,i.op),dr(t)!==i.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function gO(e,t,n){let r=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let m=Ey(e.message,t,n);s=m.value,r+=m.replacements,m.replacements>0&&(o=!0)}let a=Sy(e.patch,t,n);r+=a.replacements,o||=a.replacements>0;let c=e.reanchor_evidence?.map(m=>{let u=m.patch?Sy(m.patch,t,n):{patch:void 0,replacements:0},p=m.record?Es(m.record,t,n):{value:void 0,replacements:0};r+=u.replacements,r+=p.replacements;let f=u.replacements>0||p.replacements>0;if(o||=f,!f)return m;i=!0;let{patch:_,record:g,record_hash:y,record_hash_version:h,...v}=m;return u.replacements>0?v:{...v,patch:m.patch}});return{entry:{...e,message:s,patch:a.patch,...c?{reanchor_evidence:c}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:i}}function yO(e,t,n){let r=structuredClone(Fa),o=0,i=0,s=[];for(let a=0;a<e.length;a+=1){let c=e[a],m=up(c);if(!m.ok)throw new d(`history-redact refuses invalid immutable record ${a+1} (${m.error}).`,l.GENERIC_FAILURE);let u=gO(c,t,n);i+=u.replacements,u.changed&&(o+=1);let p=dr(r);r=Rn(r,u.entry.patch,a+1,u.entry.op);let f=dr(r);s.push(pp(c,{...u.entry,before_hash:p,after_hash:f},{retainPriorRecord:u.changed,retainPriorRecordHash:!u.changed}))}return{entries:s,finalDocument:r,entriesChanged:o,replacements:i}}function vO(e){return Object.keys(e.metadata).length>0}function wO(e){if(!vO(e.finalDocument))return{raw:null,path:null,document:null};let t=Ze(et(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new d("history-redact would change the item id; narrow your patterns.",l.USAGE);return{document:t,path:dt(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:ze(t,{format:"toon",schema:e.settings.schema})}}function bO(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function kO(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??et(e.rewritten.finalDocument);return t.push(Oe({nowIso:k(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function SO(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await Nt(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await ee(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await Nl.rm(e.currentItem.path,{force:!0}),await ee(e.subject.historyPath,hp(e.rewrittenEntries))}catch(c){try{await EO(e.subject.historyPath,n,o,i)}finally{await Ma(e.subject.historyPath)}throw c}await Ma(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Mt({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(a=>{s=()=>{throw a}})}s()},afterWrite:async()=>[...t,...await AO(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function EO(e,t,n,r){t===null?await Nl.rm(e,{force:!0}):await ee(e,t);for(let o of n){let i=r.get(o);i===void 0?await Nl.rm(o,{force:!0}):await ee(o,i)}}async function AO(e,t){let n=[],r=new Set(t.filter(o=>o!==null));for(let o of r)n.push(...await W({path:o,scope:"project",op:"history_redact"}));return n.push(...await W({path:e,scope:"project",op:"history_redact:history"})),n}async function Ay(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await fr(n.path),s=t.replacement??"",a=s.length===0,c=a?"[redacted]":s,m=pO(t.literal,t.regex),u=await Zt(r,e,o,i.type_to_folder);return Ei({pmRoot:r,subject:u,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:p=>TO({pmRoot:r,subject:u,settings:o,typeRegistry:i,options:t,rules:m,replacement:c,replacementIsDefault:a},p)})}function TO(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:i,options:s,rules:a,replacement:c,replacementIsDefault:m}=e,u=t.entries,p=hO(u),f=yO(u,a,c),_=p.hashMismatchesBefore+p.hashMismatchesAfter,g=!!s.dryRun,y=f.replacements>0,h=[];_>0&&h.push(`history_redact_preexisting_hash_mismatches:${_}`),y||h.push("history_redact_no_matches");let v={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},b=wO({pmRoot:n,subject:r,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),S=(v.path??null)!==(b.path??null)||(v.raw??null)!==(b.raw??null),T=t.author,I=bO(s,f),{rewrittenEntries:D,auditEntryAdded:M}=kO({rewritten:f,dryRun:g,changed:y,nextItemDocument:b.document,author:T,message:I});return{changed:y,rewrittenEntries:D,...SO({pmRoot:n,subject:r,settings:o,typeRegistry:i,currentItem:v,nextItem:b,author:T,rewrittenEntries:D}),report:({verification:Y,warnings:z})=>({id:r.id,dry_run:g,changed:y,patterns:{literal_count:a.filter(K=>K.kind==="literal").length,regex_count:a.filter(K=>K.kind==="regex").length,total_count:a.length,replacement_is_default:m},history:{path:r.historyPath,entries_scanned:u.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:p.hashMismatchesBefore,hash_mismatches_after:p.hashMismatchesAfter,preexisting_hash_mismatches:_,audit_entry_added:M,verify_ok:Y.ok,verify_errors:Y.errors},item:{existed_before:v.path!==null,exists_after:b.path!==null,path_before:v.path,path_after:b.path,changed:S},warnings:[...new Set([...h,...z])].sort((K,pe)=>K.localeCompare(pe)),generated_at:k()})}}import Cy from"node:fs/promises";import Ry from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d51da34a-9f37-5441-91f0-15a16b601709")}catch{}})();function CO(e,t,n){let r=new Set,o=[];for(let i of e){let s=i.trim();if(s.length===0||r.has(s))continue;r.add(s);let a=t.get(s);if(a===void 0){o.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){o.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return o}function RO(e,t){let n=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function Ty(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return CO(t.ids,n,t.minEntries)}return RO(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d6824edc-ca22-5900-b43b-645135e2562d")}catch{}})();function IO(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new d("history-compact --before requires a non-empty value.",l.USAGE);if(/^\d+$/.test(n)){let i=Number.parseInt(n,10),s=Cn(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new d(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,l.USAGE);let a=i-s-1;return{kind:"version",raw:n,compactCount:a,retainedCount:t.length-a}}let r=Date.parse(n);if(!Number.isFinite(r))throw new d(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,l.USAGE);let o=0;for(let[i,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new d(`History for this item contains invalid timestamp at entry ${i+1}.`,l.GENERIC_FAILURE);if(a>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function OO(e,t){let n=ti(),r=ti();for(let o=0;o<e.length;o+=1){let i=e[o];n=Rn(n,i.patch,o+1,i.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function xO(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:lp.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&fp(mr(e.document),r).includes(n.after_hash))}}function PO(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function LO(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function NO(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=OO(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Cn(e.historyEntries,!0),i=Oe({nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:et(ti()),after:et(t),message:LO(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:dp(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),s=e.historyEntries[e.boundary.compactCount-1],a=[mp({...i,before_hash:e.historyEntries[0].before_hash,after_hash:s.after_hash,item_hash_version:s.item_hash_version}),...r];return e.dryRun||a.push(Oe({nowIso:k(),author:e.author,op:"history_compact",before:et(n),after:et(n),message:PO(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Ml(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await fr(n.path),s=await Zt(r,e,o,i.type_to_folder);return Ei({pmRoot:r,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>MO(s,t,a)})}function MO(e,t,n){let r=e.historyPath,o=n.entries,i=n.verification;if(!i.ok)throw new d(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,l.CONFLICT);let s=IO(t.before,o),a=s.compactCount>0,c=!!t.dryRun,m=n.author,u=[];a||u.push("history_compact_noop_before_boundary");let p=xO(n.loadedItem,o);p.matchedChainBefore===!1&&u.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:_,auditEntryAdded:g}=NO({historyEntries:o,boundary:s,changed:a,dryRun:c,author:m,options:t}),y=Cn(o,!0),h=s.retainedCount>0&&y!==null?y+s.compactCount+1:null;return{changed:a,rewrittenEntries:f,report:({verification:v,warnings:b})=>({id:e.id,dry_run:c,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:h},history:{path:r,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:_,audit_entry_added:g,verify_ok:v.ok,verify_errors:v.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:p.matchedChainBefore},warnings:[...new Set([...u,...b])].sort((S,T)=>S.localeCompare(T)),generated_at:k()})}}var FO=3;function $O(e){for(let n of["allOver","minEntries"]){let r=e[n];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new d(`history-compact ${n} must be a non-negative safe integer.`,l.USAGE)}let t=pi(e.ids);if(e.ids!==void 0&&t==="")throw new d("history-compact ids requires at least one valid item ID.",l.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:ui(t)}}function Iy(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new d("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",l.USAGE);if(e!==void 0&&(n||r))throw new d("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",l.USAGE);if(n&&r)throw new d("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",l.USAGE)}function DO(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function UO(e){let t=F(e.settings.schema),n=Oi(t),r=await _e(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),i=Ry.join(e.pmRoot,"history"),s=[],a=[];if(!await L(i))return{candidates:s,preselectionErrors:a};let c=(await Cy.readdir(i)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=Ry.join(i,m),p=m.slice(0,-6);try{let f=await Cy.readFile(u,"utf8");await Sn({path:u,scope:"project"}),s.push({id:p,entries:DO(f),bucket:o.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:s,preselectionErrors:a}}async function GO(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await Ml(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function Oy(e,t){let n=$O(e),{pmRoot:r,settings:o,typeRegistry:i}=await fr(t.path),{candidates:s,preselectionErrors:a}=await UO({pmRoot:r,settings:o,typeToFolder:i.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??FO,u=o.history.compact_policy,p=c==="scan"&&e.allOver===void 0&&u.enabled,f=e.allOver??(p?u.max_entries:void 0),_=Ty(s,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),g=!!e.dryRun,y=[...a],h={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let v of _){let b=await GO({row:v,options:n,dryRun:g,global:t});if(y.push(b.result),!b.selected){h.items_skipped+=1;continue}h.selected+=1,b.compacted&&(h.items_compacted+=1),b.errored&&(h.items_errored+=1)}return{bulk:!0,dry_run:g,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:p},totals:h,results:y,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="41f0e5cd-5974-5451-9f34-2aec1d8df07c")}catch{}})();function xy(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return zf(n,t),t?Ai(e.options,e.global):Ut(n,e.options,e.global)}function Py(e){let t=e.options.ids,n=pi(t);if(t!==void 0&&n==="")throw new d("history-compact ids requires at least one valid item ID.",l.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:ui(n),o=qe(e.options.allOver??e.options.all_over,"history-compact allOver"),i=qe(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),s=w(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(s==="closed"||s==="all-streams")&&a.push(s);let c=[...new Set(a)];if(c.length>1)throw new d("history-compact: closed and all-streams scopes are mutually exclusive.",l.USAGE);let m=c[0];return Iy(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?Ml(e.id,{before:w(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global):Oy({ids:r,scope:m,allOver:o,minEntries:i,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd0e532e-0f27-5786-8216-c17132f6e784")}catch{}})();async function Fl(e,t,n,r){let o=t.trim();if(o.length===0)throw new d("pm item reopen requires a non-empty recurrence reason.",l.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let i=E(process.cwd(),r.path),s=F((await A(i)).schema),a=s.open_status,c=_s(s),m=n.status??a,u=Z(m,s)??m;if(u!==a&&u!==c)throw new d(`Reopen target status must be ${a} or ${c}; received ${m}.`,l.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([a,c])],suggested_retry:`pm item reopen ${e} "${o}" --status ${a}`,suggested_retry_args:["item","reopen",e,o,"--status",a]}});let p=await vh(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:p.item,changed_fields:p.changed_fields,warnings:p.warnings,recurrence:p.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="343f871b-e160-5841-87db-cb6c5902c713")}catch{}})();async function Ly(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Le(e.args,e.options),o=e.force===!0||r.force===!0,i={...e.args,...r};if(i.start===!0)return Nr(Br(e,r),je(r,{force:o}),e.global);let s=e.args.next===!0||r.next===!0?await R_(o,e.global,i,i):await Rr(Br(e,r),o,e.global,i);return Ue(s,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Br(e,t){let n=e.id??w(t,"id");if(!n)throw new d("Missing required argument: id",64);return n}function $l(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function Ny(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Le(e.args,e.options);return r.releaseAssignment===!0?Mr(Br(e,r),$l(e,r),je(r,{force:e.force===!0||r.force===!0}),e.global):Ue(await yt(Br(e,r),$l(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function My(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Le(e.args,e.options);return Ue(await Fl(Br(e,r),$l(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="419a061f-e181-5b18-9e3a-d22cc5aff416")}catch{}})();function Fy(e,t,n){let r;if(typeof e.lines=="string")r=Ti(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");r=Ti(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1979adcd-4a7f-5dc7-b5dd-6bfc15eed1af")}catch{}})();var jO=Sa("list").properties.outputSession,qO={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:{...jO},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},$y={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."}},Dy={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},se={type:"string",description:"pm item id, for example pm-abc1."},KO=`Operation name (one of): ${ya.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,zO={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."}},BO={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function U(e,t=[]){return{...Dy,properties:{...Dy.properties,...e},required:t}}var HO=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:U({action:{type:"string",enum:[...ya],description:KO},id:se,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...qO},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:U({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:U({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:U({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (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:U({query:{type:"string"},options:{type:"object"},...BO},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:U({options:{type:"object"},...zO})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:U({id:se,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:U({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:U({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"]},id:se,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"}},required:["op"],additionalProperties:!1}},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["transactionId","mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:se,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:U({id:se,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:U({id:se,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:se,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:U({id:se,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:U({id:se,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:U({id:se,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:U({id:se,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:U({id:se,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:U({id:se,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:U({id:se,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:U({id:se,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:U({id:se,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:U({subcommand:{type:"string",enum:[...yu]},id:se,target:se,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:U({id:se,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:U({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:U({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:U({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:U({...$y,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",...bn],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:[...ea]},description:`Lifecycle roles for add-status: ${ea.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:$y}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:U({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:U({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:U({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],VO={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"},WO=HO.map(e=>{let t=VO[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Sa(t,{properties:n,required:r})}});function Uy(){return WO.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b11154f9-a48f-5986-bb0f-200f07e6b787")}catch{}})();var Gy=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),YO=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Jy=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Ts=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"]),Hr=new Set(["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"]),Xy=new Map([["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["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"]]),Qy=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"]]),Zy=new Map([...Qy.entries()].flatMap(([e,t])=>St(t).map(n=>[n,e]))),ev=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],jl=new Map(ev.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),JO=10,XO=20,jy=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-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),tv=[["init",lm],["install",mm],["uninstall",um],["explore",pm],["manage",vm],["describe",fm],["reload",wm],["doctor",bm],["catalog",km],["adopt",Sm],["adopt-all",_m],["activate",hm],["deactivate",gm],["migrate",ym]],QO=[...tv.map(([e,t])=>e==="init"?[e,dm]:[e,t]),["upgrade",ir]],ZO=[...tv.map(([e,t])=>[`extension ${e}`,t]),...QO.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",yo],["config",cm],["extension",vo],["package",or],["packages",or],["install",Em],["create",Ao],["item mutate",Km],["item complete",zm],["item reopen",Bm],["copy",To],["focus",Co],["update",Ro],["update-many",Io],["upgrade",ir],["calendar",sr],["cal",sr],["context",ar],["ctx",ar],["get",xo],["search",Fo],["eval",Vm],["events",Oo],["workspace",It],["workspace position",[]],["workspace snapshot",It],["workspace snapshot create",It],["workspace snapshot list",It],["workspace snapshot inspect",It],["workspace snapshot restore",It],["workspace snapshot delete",It],["next",Mo],["aggregate",fo],["deps",Lo],["graph",No],["guide",Po],["reindex",Am],["history",_o],["history-compact",im],["history-redact",rm],["history-repair",om],["history-author-acknowledge",ho],["merge",nm],["schema",sm],["profile",am],["plan",go],["restore",Rm],["delete",Im],["close",Tm],["close-many",wo],["append",bo],["claim",Cm],["release",Om],["start-task",xm],["pause-task",Pm],["close-task",Lm],["comments",Xd],["notes",Qd],["learnings",Zd],["files",em],["docs",tm],["test",Fm],["test-all",$m],["telemetry",Dm],["test-runs",Um],["gc",Gm],["stats",ko],["ops",[]],["duplicates",So],["validate",jm],["health",Eo],["assurance",qm],...Wm,["contracts",$o],["completion",Do],["activity",Hm],...[...Jy].map(e=>[e,po])],Vr=new Map(ZO);for(let{alias:e,canonical:t}of ut){let n=Vr.get(e);n!==void 0&&Vr.set(t,n)}function ex(e){let t=Zy.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function qy(e){let t=ut.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:ha.includes(e)?ve(e):e.startsWith("extension-")?ve(`extension ${e.slice(10)}`):e.startsWith("package-")?ve(`package ${e.slice(8)}`):e.startsWith("item-")?ve(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ve(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ve(`templates ${e.slice(10)}`):Ts.has(e)?Qy.get(e)??ve(e):null}function tx(e,t){let n=le(t);return n!==t?e.action===n:e.command_path===null?!1:St(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function St(e){return e.split("|").map(t=>ve(t)).filter(t=>t.length>0)}function nx(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let i of St(o.command_path)){let s=i.split(" ").filter(a=>a.length>0);if(s.length!==0)for(let a=s.length;a>0;a-=1){let c=s.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function As(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Wr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function rx(e,t){if(!t)return{...e};let r=Wr(e).filter(o=>{let i=o.properties;if(typeof i!="object"||i===null)return!1;let s=i.action;return typeof s!="object"||s===null?!1:s.const===t});return{...e,oneOf:r}}function Dl(e,t){let r=Wr(e).filter(o=>{let i=o.properties;if(typeof i!="object"||i===null)return!1;let s=i.action;if(typeof s!="object"||s===null)return!1;let a=s.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function ve(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function nv(e){return e.replace(/\s+/g,"-")}function ot(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ky(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=ot(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function Ul(e,t,n){n&&(e[t]=!0)}function zy(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?n:null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function ox(e){let t=zy(e.long,"long"),n=zy(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),Ul(o,"required",e.required===!0),Ul(o,"repeatable",e.repeatable===!0),Ul(o,"list",e.list===!0);let i=ot(e.description);i&&(o.description=i);let s=ot(e.value_name);s&&(o.value_name=s);let a=[ot(e.value_type),ot(e.type),s?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(o.value_type=a),o}function rv(e){let t=new Map;for(let r of e){let o=ve(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},s=`${r.layer}:${r.name}`;i.sourceDedupe.has(s)||(i.sourceDedupe.add(s),i.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=ox(a);if(!c)continue;let m=`${c.flag}|${c.short??""}`;i.dedupe.has(m)||(i.dedupe.add(m),i.flags.push(c))}t.set(o,i)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((i,s)=>{let a=i.layer.localeCompare(s.layer);return a!==0?a:(i.name??"").localeCompare(s.name??"")})});return n}function ix(e){let t=rv(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let s=ve(i.command);if(s.length===0)continue;let a=ot(i.action)??nv(s),c=Array.isArray(i.arguments)?i.arguments.map(m=>{let u=ot(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:ot(m.description)}:null}).filter(m=>m!==null):[];n.set(s,{command:s,action:a,source:{layer:i.layer,name:i.name},description:ot(i.description),intent:ot(i.intent),arguments:c,flags:t.get(s)?.flags??[],examples:Ky(i.examples),failure_hints:Ky(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(ve(i));for(let i of n.keys())r.add(i);for(let i of t.keys())r.add(i);let o=[];for(let i of[...r].sort((s,a)=>s.localeCompare(a))){let s=n.get(i);o.push(sx(i,s,t.get(i)?.flags??[]))}return o}function sx(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:nv(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function ax(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(o,i)=>i.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function cx(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 lx(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function dx(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=cx(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=ax(o);!i||n[i]!==void 0||(n[i]=lx(o,e.action),o.required===!0&&r.push(i))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function mx(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 ux(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((i,s)=>i.localeCompare(s)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(i=>`${i.flag}|${i.short??""}`));for(let i of n.flags){let s=`${i.flag}|${i.short??""}`;if(!o.has(s))o.add(s),r.flags.push(i);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===s);a&&mx(a,i)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function px(e,t=A){let n={mode:Tt.extensions.policy.mode,trust_mode:Tt.extensions.policy.trust_mode,default_sandbox_profile:Tt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await L(fe(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await tr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),s=await nr({...i,loaded:i.loaded});return{handlers:new Set(s.commands.handlers.map(c=>ve(c.command))),disabledReason:null,commandDefinitions:s.registrations.commands,flagRegistrations:s.registrations.flags,registrations:s.registrations,policyState:{mode:i.policy.mode,trust_mode:i.policy.trust_mode,default_sandbox_profile:i.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function fx(e,t={}){let n=new Map;for(let r of ga){let o=Ts.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=qy(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of Ts)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:qy(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ut.find(o=>o.alias===r.command)?.canonical??ve(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function _x(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null};let n=e.command_path?St(e.command_path):[],r=n.some(s=>t.handlers.has(le(s))),o=n.map(s=>Xy.get(le(s))).find(s=>typeof s=="string"),i=t.disabledReason===null&&r;return{action:e.action,invocable:i,available:i,requires_extension:!0,provider:"extension",disabled_reason:i?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function ov(e){return Vr.get(e)??uo}function hx(e){return Hr.has(le(e))?!1:Vr.has(e)}function gx(e){return Jy.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function By(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function yx(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function vx(e){let t=new Map;for(let r of e.definitions){let o=By(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(a=>yx(a)).find(a=>a!==null),s=r.cli_aliases.map(a=>By(a)).filter(a=>a!==null&&a!==o);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=i?{flag:o,short:i}:{flag:o},u=`${m.flag}|${m.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(m));for(let p of s){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,pa(o.flags));return n}function Hy(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let i=`${o.flag}|${o.short??""}`;r.has(i)||(r.add(i),n.push(o))}return pa(n)}function wx(e,t,n,r){return e.map(o=>{let i=hx(o),s=i?ov(o):[],a=n.get(gx(o))??[],c=t.get(le(o)),m=Hy(s,a),u=Hy(m,c?.flags??[]),p=s.length>0&&(c?.flags.length??0)>0?"mixed":i?"core":"extension";return{command:o,flags:u,...r?{canonical_command:Gl(o),visibility:qu(Gl(o)),positionals:Wd(o)?.slots??[],flag_invocations:Xo(o,u)}:{},provider:p,extension_sources:c?.sources}}).sort((o,i)=>o.command.localeCompare(i.command))}function bx(e,t=rr){let n=new Set(e),r=new Map;for(let o of ev){let i=o.aliases.filter(s=>n.has(s));r.set(o.canonical,{canonical:o.canonical,aliases:i,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let i=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};i.aliases.includes(o.alias)||i.aliases.push(o.alias),i.contracts.push(o),r.set(o.canonical,i)}return[...r.values()].map(({contracts:o,...i})=>o.length===0?i:{...i,contracts:o}).sort((o,i)=>o.canonical.localeCompare(i.canonical))}function kx(){return{create_string_options:Ou,create_repeatable_options:Ho,update_string_options:xu,update_repeatable_options:Pu,list_string_options:qd,search_string_options:Kd,calendar_string_options:zd,context_string_options:Bd,activity_string_options:Hd}}function Vy(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=vn(e,"create",n),o=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),i=[...new Set(o.map(a=>be("create",a)))].sort((a,c)=>a.localeCompare(c)),s=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:o,required_flags:i,required_type_options:s,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function Sx(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){let o=e.by_type[r];t[r]=Vy(o,"strict"),n[r]=Vy(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Ex(e,t){let n=Wr(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let s=i.properties;if(typeof s!="object"||s===null)return i;let a=s.action;return typeof a!="object"||a===null||a.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function Ax(e){let t=As(e.action)!==void 0||As(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,i=e.flagsOnly===!0,s=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=As(e.action),u=As(e.command),p=!r&&!c&&!o&&!i&&!s&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:s,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function Tx(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new d("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",l.USAGE)}async function Cx(e,t=A){try{return await t(e)}catch{return structuredClone(Tt)}}async function Rx(e,t){let n=await Cx(t),r=await px(e),o=x(n,r.registrations??O()),i=Qe(n.schema),s=ix(r);return{settings:n,runtimeProbe:r,typeRegistry:o,statusRegistry:F(n.schema),runtimeFieldRegistry:i,runtimeFieldFlagMap:vx(i),createRequiredOptionContracts:Sx(o),extensionContracts:s,mergedExtensionContracts:ux(s),extensionFlagMap:rv(r.flagRegistrations)}}function Wy(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Ts.has(e.selectedAction)||e.selectedCommand!==void 0&&Hr.has(le(e.selectedCommand)))}function Ix(e,t){let n=fx(t,{includePackageOwnedActions:Wy(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(bu);return n.filter(o=>!r.has(o.action))}return Wy(e)&&e.selectedCommand!==void 0&&Hr.has(le(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:ex(le(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function Ox(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new d(`Unknown action: "${e.selectedAction}".`,l.USAGE)}function xx(e,t){return[...new Set([...ha.filter(n=>!Hr.has(le(n))),...[...Vr.keys()].filter(n=>!Hr.has(le(n))),...e.flatMap(n=>n.command_path?St(n.command_path):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let o=ut.find(i=>i.alias===r)?.canonical;return o===void 0?[r]:[r,o]}))])].map(n=>ve(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function Px(e,t){let n=t.slice(0,JO),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,XO),s=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new d(`Command "${e}" is a command namespace. Choose a concrete child command: ${o}.`,l.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:s,nextSteps:[`Retry with a child command, for example: ${s[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:i.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function Lx(e,t){return new d(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,l.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function Nx(e){return new d(`Unknown command: "${e}".`,l.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 Mx(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(i=>i.startsWith(`${e.selectedCommand} `));if(r.length>0)throw Px(e.selectedCommand,r);let o=Xy.get(le(e.selectedCommand));throw o?Lx(e.selectedCommand,o):Nx(e.selectedCommand)}function Fx(e,t){let n=Ix(e,t.mergedExtensionContracts);Ox(e,n);let r=xx(n,t.mergedExtensionContracts);Mx(e,r);let o=e.selectedCommand?Zy.get(le(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(m=>o?m.action===o:tx(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.some(m=>m.action===e.selectedAction))throw new d(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,l.USAGE);let s=e.selectedAction?i.filter(m=>m.action===e.selectedAction):i,a=[...new Map(s.map(m=>_x(m,t.runtimeProbe)).map(m=>[o?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(m=>m.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:i,scopedActionDescriptors:s,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function $x(e){return new Set(Wr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function Dx(e){let t=Cu,n=Wr(t),r=$x(t),o=e.filter(i=>!r.has(i.action)).map(i=>dx(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function Yy(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?rx(n,e.selectedAction):e.selectedCommand?Dl(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):Dl(n,r);return e.runtimeOnly&&!e.selectedAction?Dl(o,new Set(t.actions)):o}function Ux(e,t,n){let r=Dx(t.mergedExtensionContracts),i=!e.flagsOnly&&!e.availabilityOnly?Ex(Yy(e,n,r),t.createRequiredOptionContracts):Yy(e,n,r);return{mergedSchema:r,filteredSchema:i}}function Gx(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?nx(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function jx(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(rr.filter(r=>r.hidden&&(r.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(r=>r.alias));if(e.summary&&!e.fullOutput)for(let r of jl.keys())n.add(r);return t.filter(r=>!n.has(r))}function Gl(e){let t=ut.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":jl.get(n)??n}var qx=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"]]),Kx=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function zx(e,t){let n=jy.get(le(e))??(e.includes(" ")?void 0:jy.get(Gl(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>St(m.command).includes(le(e)));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let o=e.split(" "),i=o.at(-1),s=o.slice(0,-1).join(" "),a=qx.get(i),c=Kx.get(e)??s;return{intent:a===void 0||s.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function Bx(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(ve))].filter(i=>i.length>0).sort((i,s)=>i.localeCompare(s)).map(i=>{let s=va(i,{generateFallback:!0}),a=i.split(" ")[0],c=jl.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),m=new Set([...ov(i).map(f=>f.flag),...t.filter(f=>St(f.command).includes(le(i))).flatMap(f=>f.flags.map(_=>_.flag))]),u=(Gy.get(le(i))??Gy.get(c)??YO).filter(f=>m.has(f)),p=zx(i,t);return{command:i,intent:p.intent,...o||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:s.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...s.default_max_estimated_tokens_by_format}}:{}}})}function Hx(e){return e.map(t=>({budget:va(t,{generateFallback:!0}),envelope:Bu(t)}))}function Vx(e){let t=new Map;for(let n of e){let r=Nu(n),o=r===void 0?[l.SUCCESS,l.GENERIC_FAILURE,l.USAGE,l.NOT_FOUND,l.CONFLICT,l.DEPENDENCY_FAILED]:r.exit_codes,i=o.join(","),s=t.get(i)??{commands:[],exit_codes:o};s.commands.push(n),t.set(i,s)}return[...t.values()]}function Wx(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>St(r.command).includes(le(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>St(o.command).some(i=>r.has(i)))}return t.extensionContracts}function Yx(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 Jx(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,i])=>[o,[...new Set(i.map(s=>`--${s.cli_flag}`))].sort((s,a)=>s.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...uu],services:[...pu],policy_modes:[...fu],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...gu],trust_modes:[..._u],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...hu],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...bd],create_modes:[...kd],close_validation_modes:[...Sd],workflow_enforcement_modes:[...Ed]},e.relationship_kind_contracts=[...xd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,i)=>o.kind.localeCompare(i.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function Xx(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 Qx(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=wx(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let i=new Set(r);e.list_projections=Object.entries(Wu).filter(([s])=>i.has(s)).map(([s,a])=>({command:s,default:a,brief_fields:[...Vu],compact_fields:[...Hu]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:s})=>({canonical:i,aliases:s})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function Zx(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 eP(e,t,n,r){e.command_summaries=Bx(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Su],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(ve))].filter(o=>ba(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...Au(o).keys()]}))}:{}},e.grammar_contracts={nouns:Yt.nouns,shared_verbs:Yt.shared_verbs,scope_before_verb:Yt.scope_before_verb,visible_top_level_ceiling:Yt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Yt.ceiling_raise_requires_pm_item,positional_shape_budget:Yt.positional_shape_budget,positional_shape_count:new Set(ua.map(({slots:o})=>Jd(o))).size,positional_action_count:ma.length,positional_action_parents:[...new Set(ma.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:ua}:{}}}async function iv(e,t){let n=Ax(e);Tx(n);let r=E(process.cwd(),t.path),o=await Rx(t,r),i=Fx(n,o),s=Ux(n,o,i),a=Gx(n,i),c=jx(n,a),m=Yx(n,s,i,c),u=Wx(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&eP(m,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return m;let f=bx(i.commandCatalog);return n.flagsOnly&&!n.fullOutput||Jx(m,o,n),Xx(m,n,s,u),Qx(m,n,o,c,f),Zx(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...Jp],gate_triggers:[...Yp]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=Yd),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=Uy(),m.context_intents=Du(),m.read_output_dimensions=wa,m.error_codes=ju,m.command_output_contracts=Hx(c),m.diagnostic_output_contracts=Eu,m.command_exit_contracts={vocabulary:Lu,command_sets:Vx(c)}),m}import $P from"node:fs/promises";import Sv from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60090339-2f94-5f22-be47-518498838b92")}catch{}})();function Cs(e,t,n,r,o,i="min"){let s=o==="min"?e-t:t-e,a=i==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return s<0||s===0&&r!==null&&a<0}function tP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,i=null,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let u;try{u=JSON.parse(m)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(Cs(f,s,p,o,"min")&&(s=f,o=p),Cs(f,a,p,i,"max","max")&&(a=f,i=p))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:i}}function sv(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:g})=>tP(_,g)),i=0,s=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of o){if(i+=_.lines,s+=_.bytes,_.oldest_ts!==null){let g=Date.parse(_.oldest_ts);Cs(g,m,_.id,a?.id??null,"min")&&(m=g,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let g=Date.parse(_.newest_ts);Cs(g,u,_.id,c?.id??null,"max")&&(u=g,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...o].sort((_,g)=>g.bytes-_.bytes||_.id.localeCompare(g.id)).slice(0,r),f=r===0?[]:[...o].sort((_,g)=>g.lines-_.lines||_.id.localeCompare(g.id)).slice(0,r);return{total_streams:e.length,total_lines:i,total_bytes:s,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as rP}from"node:crypto";import{execFile as oP}from"node:child_process";import lv from"node:path";import{promisify as iP}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39d2b5aa-c6f3-57ac-adb4-e775bc838828")}catch{}})();var av=1;function nP(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 ql(e){if(e===null)return{format_version:av,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new d("Improvement ledger contains invalid JSON.",l.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==av||!Array.isArray(t.observations))throw new d("Improvement ledger has an unsupported shape or format version.",l.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!nP(r))throw new d("Improvement ledger contains an invalid observation.",l.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c800f76b-2867-51f5-80d6-fb7b1c61f9e4")}catch{}})();var sP=iP(oP),aP=50,cv=1e3,cP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function dv(e){let t=e.trim().toLowerCase();if(!cP.test(t))throw new d(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,l.USAGE,{code:"invalid_improvement_metric"});return t}function lP(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new d("Improvement direction must be higher, lower, or target.",l.USAGE,{code:"invalid_improvement_observation"});return t}function Yr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new d(`${t} must not exceed 256 characters.`,l.USAGE,{code:"invalid_improvement_observation"});return n}}function dP(e){let t=e??aP;if(!Number.isSafeInteger(t)||t<0||t>cv)throw new d(`Improvement observation limit must be an integer from 0 to ${cv}.`,l.USAGE,{code:"invalid_improvement_observation_limit"});return t}function mv(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new d(`${t} must be an ISO timestamp.`,l.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function mP(e,t,n){if(!Number.isFinite(n.value))throw new d("Improvement observation value must be finite.",l.USAGE,{code:"invalid_improvement_observation"});let r=dv(n.metric),o=lP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new d("Target-directed observations require a finite threshold.",l.USAGE,{code:"invalid_improvement_observation"});let i=await pP(e,n.revision),s=Yr(n.source,"source"),a=Yr(n.itemId,"itemId"),c=Yr(n.unit,"unit"),m=Yr(n.idempotencyKey,"idempotencyKey")??(i.revision_source==="unversioned"?void 0:[i.revision,r,s??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:mv(n.observedAt??k(),"observedAt"),...i,author:C(n.author,t.author_default),...a===void 0?{}:{item_id:a},...s===void 0?{}:{source:s},...m===void 0?{}:{idempotency_key:m}};return{id:rP("sha256").update(Wt(u)).digest("hex").slice(0,24),...u}}function uP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new d(`Improvement observation retry key already records a different value for ${t.metric}.`,l.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new d(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,l.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function pP(e,t){let n=Yr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await sP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Id(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function fP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function uv(e,t={}){let n=E(process.cwd(),t.path);await R(n);let r=await A(n),o=await mP(n,r,e),i=lv.join(n,"improvement-ledger.json"),s=await yp({pmRoot:n,filePath:i,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=ql(a),m=uP(c,o);return m?{raw:a,result:m}:(c.observations.push(o),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${Wt(c)}
|
|
42
|
+
`,result:o})}});return{changed:s.changed,observation:s.result,ledger_path:"improvement-ledger.json"}}async function pv(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await R(t);let n=e.metric===void 0?void 0:dv(e.metric),r=e.since===void 0?void 0:mv(e.since,"since"),o=dP(e.limit),s=ql(await Q(lv.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of s){let m=a.get(c.metric)??[];m.push(c),a.set(c.metric,m)}return{observations:[...s].reverse().slice(0,o),total:s.length,truncated:s.length>o,trends:[...a].map(([,c])=>fP(c)).sort((c,m)=>c.metric.localeCompare(m.metric)),source:"audited_workspace_singleton"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2e7a7f40-523d-590f-8aea-90b65535506e")}catch{}})();function fv(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 _P(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function hP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function Kl(e=lr,t=An){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function gP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function zl(e,t=An,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let i of t){let s=`${o.agent_harness}\0${i}`,a=r.get(s)??{harness:o.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=o.agent_provenance?.[i];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(s,a)}return[...r.values()].map(o=>{let i=o.observed+o.unavailable;return{...o,coverage:i===0?null:o.observed/i,inert:i>=n&&o.observed===0}}).sort((o,i)=>o.harness.localeCompare(i.harness)||o.dimension.localeCompare(i.dimension))}function yP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let u=`${c.agent_harness}\0${m}`,p=o.get(u)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),o.set(u,p)}let i=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[u])=>m.localeCompare(u)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),s=i.filter(c=>c.entries>=r),a=s.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:s.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:i,failures:a}}function vP(e){let t=[...e].sort((i,s)=>i.ts.localeCompare(s.ts)||i.author.localeCompare(s.author)||i.op.localeCompare(s.op)||i.before_hash.localeCompare(s.before_hash)||i.after_hash.localeCompare(s.after_hash)),n=new Map,r=new Map;for(let i of t){let s=i.agent_episode,a=fv(i),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(i);continue}let u={id:a.id,...s?.label===void 0?{}:{label:s.label},...s?.parent_id===void 0?{}:{parent_id:s.parent_id},source:a.source,entries:[i],children:[]};n.set(c,u),s!==void 0&&r.set(a.id,u)}let o=[];for(let i of n.values()){let s=i.parent_id?r.get(i.parent_id):void 0;s&&_P(i,s,r)?s.children.push(i):o.push(i)}return hP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0eeefcd-2202-55c6-94e9-0372fcfe0c87")}catch{}})();var wP=1e4,_v=1e5,bP=1e3,kP=30,SP=["append","comment","docs","file","learning","note","test_run"];function EP(e){let t=e??wP;if(!Number.isSafeInteger(t)||t<1||t>_v)throw new d(`History analytics event limit must be an integer from 1 to ${_v}.`,l.USAGE,{code:"invalid_history_analytics_limit"});return t}function hv(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new d("History analytics minimum sample must be an integer from 1 to 10000.",l.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function AP(e){let t=e?.trim();if(!t)return new Date(Date.now()-kP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),i=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new d("History analytics --since duration must be positive.",l.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*i).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new d("History analytics --since must be an ISO timestamp or negative duration such as -30d.",l.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function gv(e,t){let n=EP(t.eventLimit),r=AP(t.since),o=[],i=r,s=!1;for(;o.length<n;){let a=await ws({pmRoot:e,since:i,limit:Math.min(bP,n-o.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),s=a.has_more,i=a.next_cursor,!a.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:s,...s?{next_cursor:i}:{},source:"history_event_index"}}}function TP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function CP(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 RP(e){return SP.some(t=>e.startsWith(t))}function yv(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 IP(e,t,n){let r=new Map,o=new Map,i=new Map;for(let s of t){let a=TP(s.entry,e),c=CP(s.entry),m=o.get(s.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&o.set(s.item_id,u),!a)continue;let p=yv(r,a);p.events+=1,RP(s.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,i.set(s.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:i}}function OP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(i=>i.kind==="discovered_from").map(i=>i.id));for(let i of o){let s=t.get(i);s&&(yv(e,s).defectEscapes+=1)}}}function xP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function PP(e,t,n,r,o,i){let{buckets:s,lastCloseValue:a}=IP(e,t,r);return OP(s,a,n),{dimension:e,status:s.size===0?"unavailable":"available",rows:[...s].map(([c,m])=>xP(c,m,o,i)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function LP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),i=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(i)?1:Math.max(1,(i-o)/864e5)}function NP(e,t,n){let r=Kl(t),o=zl(e,An,n),i=o.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),s=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:o,inert:i,undeclared:s,warnings:[...i.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...s.map(a=>`provenance_dimension_undeclared:${a}`)]}}function vv(e,t=lr,n={}){let r=hv(n.minimumSample);return{...NP(e.events.map(o=>o.entry),t,r),window:e.receipt}}function wv(e,t,n,r={}){let o=hv(r.minimumSample),i=LP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(s=>PP(s,e.events,t,n,o,i)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c81415a5-81fa-57ed-936f-236841e5f066")}catch{}})();var MP=32;function FP(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let i=o.slice(0,o.indexOf("=")).trim();r.length>0&&i!=="unit"&&i!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Jr(e,t){let n=FP(e).map(o=>{let[i,...s]=o.split(","),a=i.indexOf("="),c=i.slice(0,a).trim(),m=i.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new d(`Invalid --measure "${o}"; expected name=value[,unit=...][,threshold=...]`,l.USAGE);let p,f;for(let _ of s){let g=_.indexOf("="),y=_.slice(0,g).trim(),h=_.slice(g+1).trim();if(y==="unit"&&h.length>0)p=h;else if(y==="threshold"&&h.length>0&&Number.isFinite(Number(h)))f=Number(h);else throw new d(`Invalid --measure attribute "${_}"`,l.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(o=>[o.name,o])).values()].sort((o,i)=>o.name.localeCompare(i.name)).slice(0,MP)}function bv(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function kv(e,t){let n=e.flatMap(i=>i.measurements??[]).filter(i=>i.name===t).sort((i,s)=>s.recorded_at.localeCompare(i.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a567e72a-faff-580d-b9ae-e2ebfa492b89")}catch{}})();function DP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function UP(e,t,n,r,o){let i=br(e,"type",r),s=new Set(i.rows.map(f=>f.key)),a=t.filter(f=>!s.has(f)),m=(o?[...i.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:i.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=DP([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>o||f>0));return{byType:m,byStatus:p,omitted:o?0:a.length+Object.values(u).filter(f=>f===0).length}}function GP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function jP(e){let t=Sv.join(e,"history");if(!await L(t))return[];await Sn({path:t,scope:"project"});let n=(await $P.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,i)=>o.localeCompare(i)),r=[];for(let o of n){let i=Sv.join(t,o),s=await Q(i);s!==null&&(await Sn({path:i,scope:"project"}),r.push({id:o.slice(0,-6),raw:s}))}return r}async function qP(e,t){let n=[],r=k();for(let o of Jr(t.observe,r))n.push(await uv({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function KP(e,t,n){let r={};return t.byAssignee&&(r.assignee=br(e,"assignee",n)),t.byTag&&(r.tag=br(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=br(e,"priority",n)),r}async function zP(e,t,n,r,o){let i={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},s=o.provenanceCoverage||o.fleetAttribution?await gv(e,i):void 0;return{provenanceCoverage:o.provenanceCoverage&&s?vv(s,n.agent_identity?.harness_signals,i):void 0,fleetAttribution:o.fleetAttribution&&s?wv(s,t,r,i):void 0}}function BP(e,t,n,r,o){let i=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...i?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:k()}}async function Bl(e,t={}){let n=E(process.cwd(),e.path);await R(n);let r=await A(n),o=await qP(e,t),i=x(r,O()),s=F(r.schema),a=t.fieldUtilization?await Ap(n,r.item_format,i.type_to_folder,void 0,r.schema):await _e(n,r.item_format,i.type_to_folder,void 0,r.schema);await kp({pmRoot:n,settings:r,itemIds:a.map(S=>S.id),commandLabel:"stats"});let c=Oi(s),m=UP(a,i.types,s.definitions.map(S=>S.id),c,t.includeEmpty===!0),u=await jP(n),p=0;for(let S of u)p+=GP(S.raw);let f=t.storage?sv(u):void 0,_=t.metadataCoverage?s_(a,c):void 0,g=KP(a,t,c),y=t.fieldUtilization?a_(a):void 0,h=t.measurements===!0||o.length>0?await pv({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:v,fleetAttribution:b}=await zP(n,a,r,s.terminal_statuses,t);return BP({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:g,storage:f,fieldUtilization:y,improvementLedger:h,recordedObservations:o,provenanceCoverage:v,fleetAttribution:b})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="086d2640-2a64-554a-9e40-a8f6994ae3a8")}catch{}})();function Ev(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:w(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:Ee(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:w(e,"measurementSource"),measurementItem:w(e,"measurementItem"),measurementRevision:w(e,"measurementRevision"),author:w(e,"author"),message:w(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:w(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import HP from"node:fs/promises";import Kt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32a15ab4-82a2-546f-8519-d4e565e7b578")}catch{}})();var Iv=Kt.join("runtime","telemetry","events.jsonl"),Ov=Kt.join("runtime","telemetry","state.json"),VP=Kt.join("runtime","telemetry"),WP=20,Av=["status","flush","stats","clear"],Tv=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Hl=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Cv=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},YP=e=>({command:Hl(e.event.command,"<unknown>"),eventType:Hl(e.event.event_type,"unknown"),eventSchemaVersion:Cv(e.event.schema_version),clientSchemaVersion:Cv(e.client_schema_version)}),JP=()=>({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:{}}),XP=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},QP=e=>{let t=e?.command_resolution;return Hl(t,"")||void 0},xv=(e,t)=>{e[t]=(e[t]??0)+1},ZP=(e,t)=>{let n=XP(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=QP(t);r!==void 0&&xv(e.resolution_counts,r)},eL=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Rv=(e,t)=>{t!==void 0&&e.add(t)},tL=(e,t)=>{let n=YP(t),r=e.get(n.command)??JP();r.count+=1,r.max_attempts=Math.max(r.max_attempts,eL(t.attempts)),xv(r.event_type_counts,n.eventType),Rv(r.event_schema_versions,n.eventSchemaVersion),Rv(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&ZP(r,t.event.payload),e.set(n.command,r)},nL=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((i,s)=>i-s),o=Object.entries(t.resolution_counts).sort((i,s)=>i[0].localeCompare(s[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((i,s)=>i[0].localeCompare(s[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((i,s)=>i-s),client_schema_versions:[...t.client_schema_versions].sort((i,s)=>i-s),...r.length>0?{duration_p50_ms:Tv(r,.5),duration_p95_ms:Tv(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},rL=e=>{let t=(e??"status").trim().toLowerCase();if(Av.includes(t))return t;throw Pe({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Av,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Vl=()=>{throw new d("--limit must be a positive integer",l.USAGE)},Pv=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Vl():e,oL=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Vl():Pv(Number.parseInt(t,10))},iL=e=>e===void 0?WP:typeof e=="number"?Pv(e):typeof e=="string"?oL(e):Vl(),sL=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},aL=e=>{try{let t=JSON.parse(e);return sL(t)?t:void 0}catch{return}},cL=e=>e===null?[]:e.split(`
|
|
43
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),Lv=e=>{let t=cL(e),n=[],r=0;for(let o of t){let i=aL(o);i===void 0?r+=1:n.push(i)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},lL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dL=e=>{try{let t=JSON.parse(e);return lL(t)?t:{}}catch{return{}}},mL=async e=>{let t=await Q(e);return t===null||t.trim().length===0?{}:dL(t)},Rs=e=>e??null,Is=async e=>{let t=await A(e),n=Kt.join(e,Iv),r=Kt.join(e,Ov),o=await Q(n),i=Lv(o),s=await mL(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:i.rows_total,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:Rs(s.last_attempted_flush_at),last_successful_flush_at:Rs(s.last_successful_flush_at),last_failed_flush_at:Rs(s.last_failed_flush_at),last_failed_flush_error:Rs(s.last_failed_flush_error)}},uL=e=>{let t=new Map;for(let n of e)tL(t,n);return[...t.entries()].map(([n,r])=>nL(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},pL=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Is(t.globalPmRoot),generated_at:k()}),fL=async(e,t)=>{let n=await Is(t.globalPmRoot);await qp(t.globalPmRoot);let r=await Is(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),i=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:i,queue_drained:i,status:r,generated_at:k()}},_L=async(e,t)=>{let n=iL(e.limit),r=await Q(t.queuePath),o=Lv(r),i=uL(o.entries),s=i.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:i.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:i.length>s.length,stats:s,generated_at:k()}},hL=async(e,t)=>{let n=await A(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await xe(t.globalPmRoot,n,"telemetry:clear");let o=Kt.join(t.globalPmRoot,VP),i=await L(o);return await HP.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:i&&!await L(o),queue_exists_after:await L(t.queuePath),state_exists_after:await L(t.statePath),status:await Is(t.globalPmRoot),generated_at:k()}},gL={status:pL,flush:fL,stats:_L,clear:hL};async function Nv(e,t){let n=rL(e.subcommand),r=lt(process.cwd());return gL[n](e,{globalPmRoot:r,queuePath:Kt.join(r,Iv),statePath:Kt.join(r,Ov)})}import{spawn as ew}from"node:child_process";import{cp as Xl,mkdir as Ns,mkdtemp as tw,open as Ql,readdir as Zl,rm as Xr,symlink as nw}from"node:fs/promises";import{tmpdir as rw}from"node:os";import H from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ffa50b5b-d99f-5ab4-a70d-cbf12911a0f2")}catch{}})();var Mv=20;function yL(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return Mv;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?Mv:t}function Wl(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let i=Jo(r.recorded_at,o.recorded_at);if(i!==0)return i;let s=r.run_id.localeCompare(o.run_id);return s!==0?s:r.kind.localeCompare(o.kind)}),n=yL();return t.length>n?t.slice(t.length-n):t}async function Os(e){await ie({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=Wl([...n,e.entry]),{changedFields:["test_runs"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="328c7577-364c-5869-aa92-199e56d2f6a7")}catch{}})();var Fv=100;function Yl(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new d(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,l.USAGE);return n}function vL(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Fv?n:`${n.slice(0,Fv-3)}...`}function $v(e){return e.map((t,n)=>`${n+1}. ${vL(t)}`).join("; ")}function wL(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function bL(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Dv(e,t){let n=wL(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,i)=>i+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new d(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,l.USAGE);let r=n[0];if(e.length===0)throw new d(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,l.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new d("--match requires a non-empty substring to match against linked-test command/path values",l.USAGE);let i=[],s=[];for(let a=0;a<e.length;a+=1)bL(e[a],o)&&(s.push(e[a]),i.push(a+1));if(s.length===0)throw new d(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${$v(e)}`,l.USAGE);return{selector:"match",requested:t.match,selected:s,selected_indexes:i,selected_count:s.length,skipped_count:e.length-s.length}}if(r==="only-index"){let o=Yl(t.onlyIndex);if(o>e.length)throw new d(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${$v(e)}`,l.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2833cfc3-db98-5f7f-82e0-388e320ef740")}catch{}})();var Ls=20*1024*1024,kL=3e3,SL=1e4,EL=5e3,Uv=120,AL=new Set(["locks","extensions","runtime"]),TL=new Set(["history","index","search","extensions","locks","runtime"]),CL=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],RL=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,IL=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,OL=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function nd(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function xL(){return nd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",kL)}function PL(){return nd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",SL)}function LL(){return nd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",EL)}function NL(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function ML(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function rd(e){let t=0,n=0,r=0,o=0;for(let i of e){let s=i.execution_context;!s||s.is_pm_command!==!0||(t+=1,s.is_pm_tracker_read_command===!0&&(n+=1),s.mismatch_detected===!0&&(r+=1),s.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function FL(e){let t=e??"project";if(!ct.includes(t))throw new d(`Invalid scope "${e}"`,l.USAGE);return t}function Ms(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(on.includes(t))return t;throw new d(`Invalid --pm-context value "${e}". Expected one of: ${on.join(", ")}`,l.USAGE)}function $L(e){return an(e??"source","--workspace-context")}function ow(e,t,n){return n?t:an(e.workspace_context_mode,"linked test")??t}function iw(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Ms(e.pm_context_mode)}function sw(e,t){return e==="auto"?t?"tracker":"schema":e}function DL(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function UL(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function GL(e,t){let n={};if(!e)return n;for(let r of e){let o=Pr(r,t);if(o)for(let[i,s]of Object.entries(o))n[i]=s}return n}function jL(e,t){if(!e)return[];let n=[];for(let r of e){let o=Lr(r,t);o&&n.push(...o)}return[...new Set(n)]}function qL(e){let t=Fs(e);return wr(t).some(n=>Za(n)!==null)}function aw(e){let t=Fs(e);return wr(t).some(n=>{let r=Za(n);if(!r)return!1;let o=t_(r);return o?OL.has(o.subcommand):!1})}function xs(e){if(e)return Qf.has(e.subcommand)?Fn(e.args,Zf)?.subcommand:e.subcommand}function Gv(e,t){if(e==="npx"||e==="bunx")return Ri(t)?.command;if(e==="pnpm")return xs(Fn(t,Wf));if(e==="npm")return xs(Fn(t,Yf));if(e==="yarn")return xs(Fn(t,Jf));if(e==="bun")return xs(Fn(t,Xf))}function Ps(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function Jl(e){return!e||!tc(e.command)&&!e_(e.command)?!1:Ci(e.args)==="test-all"}var cw=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),KL=new Set(["npx","bunx"]);function lw(e){let t=e.split(" ").filter(s=>s.length>0),n=ec(t);if(n.length===0)return!1;let[r,...o]=n,i=cw.get(r);if(i){let s=o.findIndex(a=>i.test(a));return s>=0?lw(o.slice(s+1).join(" ")):!1}return tc(r)||nc(r)?Ci(o)==="test-all":r==="node"&&o.length>0&&nc(o[0])?Ci(o.slice(1))==="test-all":KL.has(r)?Jl(Ri(o)):r==="pnpm"?Jl(rc(o)):r==="npm"?Jl(oc(o)):!1}function dw(e){let t=Fs(e);return wr(t).some(n=>lw(n))}function mw(e){if(dw(e))throw new d('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',l.USAGE)}function Fs(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function uw(e){let t=e.split(" ").filter(s=>s.length>0),n=ec(t);if(n.length===0)return!1;let[r,...o]=n,i=cw.get(r);if(i){let s=o.findIndex(a=>i.test(a));return s>=0&&uw(o.slice(s+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?zL(o):BL(r,o)}function zL(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function BL(e,t){return e==="npx"||e==="bunx"?Ps(Ri(t)?.command):e==="pnpm"||e==="npm"?Ps((e==="pnpm"?rc(t):oc(t))?.command)||Ps(Gv(e,t)):(e==="yarn"||e==="bun")&&Ps(Gv(e,t))}function HL(e){if(dw(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function VL(e){return e?e.map(WL):[]}function WL(e){let t=e.trim(),n=z_(t)?Ji(de(e,"--add"),"--add"):{command:t},r=ge(n.command);if(!r)throw new d("--add requires command=<value> or a bare command (path=<value> is optional metadata)",l.USAGE);return mw(r),{command:r,path:ge(n.path),scope:FL(n.scope),timeout_seconds:YL(ge(n.timeout_seconds),ge(n.timeout)),pm_context_mode:ts(ge(n.pm_context_mode),"--add"),workspace_context_mode:an(ge(n.workspace_context_mode),"--add"),env_set:Pr(ge(n.env_set),"--add"),env_clear:Lr(ge(n.env_clear),"--add"),shared_host_safe:es(ge(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:cn(ge(n.assert_stdout_contains)),assert_stdout_regex:jn(ge(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:cn(ge(n.assert_stderr_contains)),assert_stderr_regex:jn(ge(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:ns(ge(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:rs(ge(n.assert_json_field_equals),"--add"),assert_json_field_gte:os(ge(n.assert_json_field_gte),"--add"),note:ge(n.note)}}function ge(e){let t=e?.trim();return t&&t.length>0?t:void 0}function YL(e,t){if(e&&t&&e!==t)throw new d("--add timeout and timeout_seconds must match when both are provided",l.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(he(n,"timeout_seconds"));if(r<=0)throw new d("--add timeout_seconds must be a positive integer",l.USAGE);return r}function JL(e){return e?e.flatMap(t=>{let n=V_(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new d("--add-json requires a non-empty command string",l.USAGE);mw(o)}return n}):[]}function XL(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new d("--remove requires command or path value",l.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let o=n.slice(r[0].length).trim();if(!o)throw new d("--remove requires a non-empty command=<value> or path=<value>",l.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new d("--remove structured selectors require command=<value> or path=<value>",l.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=de(n,"--remove"),i=o.path!==void 0?"path":"command",s=o.path??o.command;if(!s?.trim())throw new d("--remove requires command=<value> and/or path=<value>",l.USAGE);return{kind:i,value:s.trim()}}return{kind:"either",value:n}}):[]}function QL(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new d("--remove-index must be a positive integer",l.USAGE);return n}))]:[]}function ZL(e){try{e.stdin?.end()}catch{}}function pw(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=Uv?t:`${t.slice(0,Uv-3)}...`}function fw(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function ed(e){try{process.stderr.write(`${e}
|
|
44
|
+
`)}catch{}}function eN(e,t){if(!fw(t))return null;let n=pw(e.command),r=Date.now();ed(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let i=Date.now()-r;ed(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${i} command="${n}"`)},PL());return o.unref?.(),o}function tN(e,t,n,r){if(!fw(r))return;let o=pw(e.command),i=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",c=[];t.timedOut&&c.push("reason=timeout"),t.maxBufferExceeded&&c.push("reason=max_buffer"),t.outputTruncated&&c.push("output=truncated"),t.signal&&c.push(`signal=${t.signal}`);let m=t.exitCode===null?"null":String(t.exitCode),u=c.length>0?` ${c.join(" ")}`:"";ed(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${i}${u} command="${o}"`)}async function jv(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=ew("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function nN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function rN(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await jv(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{jv(r)},xL()),t.forceKillTimer.unref?.()}}function oN(e){return new Promise(t=>{let n=!1,r=null,o=(i,s=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),s&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(i))};e.on("exit",(i,s)=>{n||(r=setTimeout(()=>{o({code:i,signal:s},!0)},LL()),r.unref?.())}),e.on("close",(i,s)=>{o({code:i,signal:s})})})}function iN(e,t,n,r,o){return ew(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function qv(e){let t=await Ql(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,Ls),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>Ls}}finally{await t.close()}}async function sN(e,t,n,r,o,i=process.cwd()){let s=Date.now(),a=await tw(H.join(rw(),"pm-linked-test-output-"));try{let c=H.join(a,"stdout.log"),m=H.join(a,"stderr.log"),[u,p]=await Promise.all([Ql(c,"w"),Ql(m,"w")]),f;try{f=iN(e,n,u.fd,p.fd,i)}catch(z){throw await Promise.all([u.close(),p.close()]),z}let _=oN(f),g;f.on("error",z=>{g=z.message}),await Promise.all([u.close(),p.close()]),ZL(f);let y={heartbeat:eN(r,o),forceKillTimer:null,timedOutTimer:null},h=rN(f,y),v=!1;y.timedOutTimer=setTimeout(()=>{v=!0,h()},t),y.timedOutTimer.unref?.();let{code:b,signal:S}=await _;nN(y);let[T,I]=await Promise.all([qv(c),qv(m)]),D=T.truncated||I.truncated,M=D?`
|
|
45
|
+
[pm linked-test output truncated at ${Ls} bytes per stream; the child process continued to completion]
|
|
46
|
+
`:"",Y={stdout:`${T.text}${M}`,stderr:I.text,exitCode:b,signal:S,timedOut:v,maxBufferExceeded:!1,outputTruncated:D,spawnError:g};return tN(r,Y,s,o),Y}finally{await Xr(a,{recursive:!0,force:!0})}}function aN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Ls} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function cN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
47
|
+
`);return CL.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>RL.test(n)&&IL.test(n))}function lN(e){return cN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function dN(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function $s(e){let t=dN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function Kv(e,t){for(let[n,r]of Object.entries(t.env_set))sn.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)sn.has(n.toUpperCase())||delete e[n]}function mN(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function uN(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function pN(e,t,n){return{env_set:GL(e,"--env-set"),env_clear:jL(t,"--env-clear"),shared_host_safe:n===!0}}async function Yn(e,t,n=!1,r=Ns){if(await L(e))try{await er("seed_linked_test",async()=>{if(await r(H.dirname(t),{recursive:!0}),n){await Xl(e,t,{recursive:!0,force:!0});return}await Xl(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&Rt(o))return;throw o}}async function zv(e,t,n){await Yn(fe(n.projectPmRoot),fe(e)),await Yn(H.join(n.projectPmRoot,"extensions"),H.join(e,"extensions"),!0),await Yn(fe(n.globalPmRoot),fe(t)),await Yn(H.join(n.globalPmRoot,"extensions"),H.join(t,"extensions"),!0)}async function Bv(e,t){if(!await L(e))return;let n=await Zl(e,{withFileTypes:!0});for(let r of n){if(AL.has(r.name))continue;let o=H.join(e,r.name),i=H.join(t,r.name);if(r.isDirectory()){await Yn(o,i,!0);continue}r.isFile()&&await Yn(o,i)}}async function Hv(e,t){let n=await Q(fe(e));if(n===null||await L($a(e)))return;let r=await A(t);await Xr($a(t),{force:!0}),await Xr(fe(t),{force:!0}),await tt({pmRoot:t,filePath:fe(t),raw:n,op:"settings:write",author:C(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function Wn(e){if(!await L(e))return 0;let t=0,n=await Zl(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||TL.has(r.name))continue;let o=H.join(e,r.name),i;try{i=await Zl(o,{withFileTypes:!0})}catch{continue}for(let s of i)s.isFile()&&Rd.some(a=>s.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function fN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function _N(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let r of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isInteger(o)||o<0)return[];t.push(o);continue}t.push(r)}return t}function Vv(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=_N(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let i of r){if(typeof i=="number"){if(!Array.isArray(o)||i>=o.length)return{found:!1,value:void 0};o=o[i];continue}if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,i))return{found:!1,value:void 0};o=o[i]}return{found:!0,value:o}}function hN(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function gN(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?mt(e,t):Object.is(e,t)}function yN(e,t,n){let r=[];r.push(...Wv("stdout",t,e.assert_stdout_contains)),r.push(...Yv("stdout",t,e.assert_stdout_regex)),r.push(...Wv("stderr",n,e.assert_stderr_contains)),r.push(...Yv("stderr",n,e.assert_stderr_regex)),r.push(...vN(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},i=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(i).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,m]of Object.entries(o)){let u=Vv(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=hN(m);gN(u.value,p)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(u.value)})`)}for(let[c,m]of Object.entries(i)){let u=Vv(a,c);if(!u.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof u.value!="number"||!Number.isFinite(u.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}u.value<m&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${m}, actual ${u.value})`)}return r}function Wv(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function Yv(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(i){r.push(`${e} regex assertion is invalid: /${o}/ (${i instanceof Error?i.message:String(i)})`)}return r}function vN(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var wN=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],bN=[/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu,/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu,/\bTests?\s+[1-9]\d*\s+passed\b/iu,/\b[1-9]\d*\s+passed\b/iu,/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu];function kN(e,t){let n=`${e}
|
|
48
|
+
${t}`;for(let r of wN)if(r.regex.test(n))return{code:r.code};return null}function SN(e,t){let n=`${e}
|
|
49
|
+
${t}`;return bN.some(r=>r.test(n))}function Jv(e){let t=Fs(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:wr(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&uw(n))}function EN(e){return{root:e,schemaProjectPmPath:H.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:H.join(e,"schema","global"),trackerProjectPmPath:H.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:H.join(e,"tracker","global"),workspaceSnapshotRoot:H.join(e,"workspace","project"),workspaceIsolatedRoot:H.join(e,"workspace","isolated")}}function AN(e,t,n){return e.some(r=>ow(r,t,n)==="snapshot")}async function TN(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await Ns(H.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await Xl(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(o){let i=H.relative(t,o);return i?!i.split(H.sep).some(s=>n.has(s)):!0}});let r=H.join(t,"node_modules");await L(r)&&await nw(r,H.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function CN(e,t){let n=H.join(e,".agents"),r=H.join(n,"pm");await Ns(n,{recursive:!0}),await Xr(r,{recursive:!0,force:!0}),await nw(t,r,process.platform==="win32"?"junction":"dir")}async function RN(e,t=Gr,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function IN(e,t,n){t&&(await zv(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await zv(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Bv(t.projectPmRoot,e.trackerProjectPmPath),await Bv(t.globalPmRoot,e.trackerGlobalPmPath),await Hv(t.projectPmRoot,e.trackerProjectPmPath),await Hv(t.globalPmRoot,e.trackerGlobalPmPath)))}function ON(e,t,n){return e.some(r=>{let o=r.command??"",i=o.length>0&&aw(o),s=n?.autoPmContext===!0&&i?"auto":iw(r,t,n?.overrideLinkedPmContext===!0);return sw(s,i)==="tracker"})}async function xN(e,t){return{sourceProjectItemCount:t?await Wn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Wn(t.globalPmRoot):0,schemaProjectItemCount:await Wn(e.schemaProjectPmPath),schemaGlobalItemCount:await Wn(e.schemaGlobalPmPath),trackerProjectItemCount:await Wn(e.trackerProjectPmPath),trackerGlobalItemCount:await Wn(e.trackerGlobalPmPath)}}function PN(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,i=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,s=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":s;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:i,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==i),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:s,source_workspace_root:a,trust:e.trust}}async function LN(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Ms(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?qL(n):!1,o=r&&n?aw(n):!1,i=e.options?.autoPmContext===!0&&o,s=i?"auto":iw(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=sw(s,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await CN(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await ic(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await ic(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:PN({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:s,effectivePmContextMode:a,autoPmContextApplied:i,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function Xv(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function td(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function NN(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function MN(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return NN(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function FN(e){if(!e.linkedTest.command)return Xv(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=HL(e.linkedTest.command);return t?Xv(e.linkedTest,e.executionContext,t):null}function $N(e){let t=FN(e);if(t)return t;let n=MN(e);if(n)return n;let r=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,o=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(r||o){let i=UL({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),s=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return td(e.linkedTest,e.executionContext,`${s} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${i}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!DL(e.linkedTest)?td(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function DN(e){let t=uN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return Kv(n,e.runtimeDirectives),Kv(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&mN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[yr]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[yr]="read_only"),n}function UN(e,t,n){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr}}function Qv(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function GN(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:fN(e.execution),failure_category:lN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:aN(e.execution,e.timeoutMs)}}function jN(e){if(e.options?.failOnEmptyTestRun===!0||Jv(e.linkedTest.command??"")){let n=kN(e.execution.stdout,e.execution.stderr);if(n)return Qv({...e,emptyRunSignal:n});if(Jv(e.linkedTest.command??"")&&!SN(e.execution.stdout,e.execution.stderr))return Qv({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let t=yN(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?td(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):UN(e.linkedTest,e.executionContext,e.execution)}async function qN(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await sN(t,n,DN(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?jN({...e,execution:r}):GN({...e,execution:r,timeoutMs:n})}async function od(e,t,n){let r=[],o=await tw(H.join(rw(),"pm-linked-test-")),i=EN(o),s=Ms(n?.pmContext),a=$L(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=pN(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,p=r_(),f=ON(e,s,n),_=AN(e,a,n?.overrideLinkedWorkspaceContext===!0),g=await n_(p);try{await RN(i,Gr,f),await Ns(i.workspaceIsolatedRoot,{recursive:!0}),await IN(i,u,f),_&&await TN(i,p);let y=await xN(i,u);for(let h=0;h<e.length;h+=1){let v=e[h],b=ow(v,a,n?.overrideLinkedWorkspaceContext===!0),S=await LN({linkedTest:v,layout:i,counts:y,sourceRoots:u,runLevelPmContextMode:s,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:b,currentSourceRef:g,sourceWorkspaceRoot:p}),T=$N({linkedTest:v,executionContext:S.executionContext,runLevelPmContextMode:s,linkedOverridePmContextMode:S.linkedOverridePmContextMode,options:n});if(T){r.push(T);continue}r.push(await qN({linkedTest:v,index:h,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:S.executionContext,options:n}))}}finally{await Xr(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function KN(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,i=await q(n,t,r.id_prefix,r.item_format,o);if(!i)throw new d(`Item ${t} not found`,l.NOT_FOUND);let s=await oe(i,{schema:r.schema});return{itemId:i.id,tests:s.document.metadata.tests??[],testRuns:s.document.metadata.test_runs??[],changed:!1,removed:0}}function zN(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function BN(e,t){let n=[...e];for(let r of t)n.some(o=>zN(o,r))||n.push(r);return n}function HN(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((i,s)=>r.has(s+1)?!1:!t.some(a=>a.kind==="command"?i.command===a.value:a.kind==="path"?i.path===a.value:i.command===a.value||i.path===a.value));return{tests:o,removed:e.length-o.length}}function VN(e,t,n,r){return HN(BN(e,t),n,r)}function WN(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function YN(e){if(WN(e)&&e.run!==!0)throw new d("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",l.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new d("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",l.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new d("--match, --only-index, and --only-last require --run",l.USAGE)}async function JN(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:i,adds:s,removes:a,removeIndexes:c}=e;if(s.length===0&&a.length===0&&c.length===0)return KN({id:t,pmRoot:r,settings:o,typeToFolder:i});let m=0,u=await ie({pmRoot:r,settings:o,id:t,op:s.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=VN(f,s,a,c);if(m=_.removed,(a.length>0||c.length>0)&&m===0)throw new d("No linked tests matched the requested removal selector",l.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(g=>`${g.kind}=${g.value}`),...c.map(g=>`index=${g}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return p.metadata.tests=_.tests,{changedFields:mt(f,_.tests)?[]:["tests"]}}});return{itemId:u.item.id,tests:u.item.tests??[],testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:m}}function XN(e,t){YN(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Yl(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?Dv(t,n):void 0,o=e.timeout===void 0?void 0:he(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new d("Test timeout must be a positive number",l.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:Ms(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function QN(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await od(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:lt(process.cwd())}})}function ZN(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=rd(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function eM(e){let t=ML(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=k(),i=Jr(e.options.measure,o);return{run_id:NL("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:i.length>0?i:void 0,executions:e.runResults.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}}async function tM(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:i,runResults:s,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!i)return;let m=eM({options:t,runStartedAt:i,runResults:s,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return m;try{return await Os({pmRoot:n,settings:r,itemId:o,author:C(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),m}catch(u){return c.push(`test_result_tracking_failed:${o}:${u instanceof Error?u.message:String(u)}`),m}}function Zv(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),i=e.metricBelow.slice(0,o).trim(),s=e.metricBelow.slice(o+1).trim(),a=Number(s);if(o<=0||i.length===0||s.length===0||!Number.isFinite(a))throw new d("--metric-below must use name=value",l.USAGE);r=bv(t,i,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:kv(t,e.metricDiff)}}async function nM(e,t,n){if(e.acknowledgeLinkedTests===!0)return o_(t,n,k())}async function Ds(e,t,n){let r=$t(),o=E(process.cwd(),n.path);await R(o);let i=await A(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new d("--measure requires --run",l.USAGE);Jr(t.measure,"validation"),Zv(t,[],void 0);let s=x(i,O()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...VL(a),...JL(c)],p=await $n(u,C(t.author,i.author_default),k())??[],f=XL(m),_=QL(t.removeIndex),g=await JN({id:e,options:t,pmRoot:o,settings:i,typeToFolder:s.type_to_folder,adds:p,removes:f,removeIndexes:_}),y=XN(t,g.tests),h=await nM(t,o,g.tests),v=t.run===!0?k():void 0,b=await QN({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:i.testing.allow_untrusted_linked_tests}),S=$s(b),T=t.run===!0&&t.failOnSkipped===!0&&b.some(z=>z.status==="skipped"),I=ZN(t,y.runSelection,b);h&&I.push(`linked_test_trust_acknowledged:${h.acknowledged}`);let D=await tM({options:t,pmRoot:o,settings:i,itemId:g.itemId,runStartedAt:v,runResults:b,failOnSkippedTriggered:T,warnings:I}),M=D?Wl([...g.testRuns,D]):g.testRuns,Y=Zv(t,M,D);return{ok:b.every(z=>z.status!=="failed")&&T!==!0,id:g.itemId,tests:g.tests,run_results:b,failure_categories:S,selection:y.runSelection?{selector:y.runSelection.selector,requested:y.runSelection.requested,selected_indexes:y.runSelection.selected_indexes,selected_count:y.runSelection.selected_count,skipped_count:y.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:T?!0:void 0,warnings:I.length>0?I:void 0,changed:g.changed,count:g.tests.length,...g.removed>0?{removed:g.removed}:{},...Y}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e3e3a1d4-4552-5f3c-9b02-c33ae72ea32b")}catch{}})();var rM=(e,t)=>{if(e===void 0)return;let n=Z(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new d(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,l.USAGE)}return n},oM=e=>{if(e===void 0)return;let t=he(e,"timeout");if(t<=0)throw new d("timeout must be a positive number",l.USAGE);return t},_w=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new d(`${t} must be a non-negative integer`,l.USAGE);return n},iM=e=>e instanceof Error?e.message:String(e),sM=()=>{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)}`},aM=e=>e.trim().replaceAll(/\s+/g," "),cM=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),lM=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),dM=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},mM=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Us=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),hw=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),uM=e=>typeof e=="number"?e:void 0,pM=e=>{let t={assert_stdout_contains:Us(e.assert_stdout_contains),assert_stdout_regex:Us(e.assert_stdout_regex),assert_stderr_contains:Us(e.assert_stderr_contains),assert_stderr_regex:Us(e.assert_stderr_regex),assert_stdout_min_lines:uM(e.assert_stdout_min_lines),assert_json_field_equals:hw(e.assert_json_field_equals),assert_json_field_gte:hw(e.assert_json_field_gte)};return JSON.stringify(t)},fM=e=>{let t=id(e.command);return t!==void 0?`command:${e.scope}:${aM(t)}`:`path:${e.scope}:${id(e.path)??""}`},gw=e=>{let t=cM(e.env_set),n=lM(e.env_clear),r=dM(e.pm_context_mode),o=mM(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",s=pM(e);return`${fM(e)}:${t}:${n}:${r}:${o}:${i}:${s}`},_M=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,hM=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},gM=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Gs=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
50
|
+
`)}catch{}},yM=async(e,t,n)=>{let r=[],o=0;for(let i of e){let s=await Ds(i.id,{run:!1},{...t,path:n});o+=s.tests.length,r.push({item:i,tests:s.tests})}return{itemTests:r,linkedTests:o}},vM=async e=>{let t=F(e.settings.schema),n=x(e.settings,O()),r=rM(e.options.status,t),o=_w(e.options.limit,"--limit"),i=_w(e.options.offset,"--offset")??0,a=(await _e(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(m=>r?m.status===r:!0).sort((m,u)=>m.id.localeCompare(u.id));return{filteredItems:o===void 0?a.slice(i):a.slice(i,i+o),statusFilter:r,limitFilter:o,offsetFilter:i}},wM=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=gw(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,_M(t.get(o),r.timeout_seconds))}return t},bM=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=gw(u),f=t.seenTestKeys.has(p);if(!f){t.seenTestKeys.add(p);let _=t.effectiveTimeoutByKey.get(p);n.push(_===void 0?u:{...u,timeout_seconds:_})}return{test:u,key:p,duplicate:f}}),o=n.length>0?await od(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],i=0,s=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=o[i];return i+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=hM(s),c=$s(s),m=await EM(e,a,s,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:m,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:s,failure_categories:c}}},kM=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),SM=e=>e?!0:void 0,EM=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=kM(t,r.options);await Os({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:k(),recorded_at:k(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:SM(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${iM(o)}`]}return[]},AM=()=>{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},id=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},TM=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:lt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:wM(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:sM(),trackingAttempt:AM(),trackingResumedFrom:id(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),CM=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:$s([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},RM=async(e,t,n)=>{for(let[r,o]of e.entries()){Gs(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let i=await bM(o,t);gM(n.failureCategories,i.failureCategories),n.passed+=i.passed,n.failed+=i.failed,n.skipped+=i.skipped,n.trackingWarnings.push(...i.trackingWarnings),n.results.push(i.result),Gs(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${i.failed===0?"passed":"failed"} passed=${i.passed} failed=${i.failed} skipped=${i.skipped}`)}},IM=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=rd(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}`)},OM=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(" "),PM=async(e,t)=>{let n=E(process.cwd(),t.path);await R(n);let r=await A(n),o=await vM({pmRoot:n,settings:r,options:e}),i=oM(e.timeout),s=k(),a=await yM(o.filteredItems,t,n);return Gs(e,xM({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:i,runStartedAt:s}},LM=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}},yw=async(e,t)=>{let n=await PM(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=CM(e,n.linkedTests,n.filteredItems),i=TM({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await RM(n.itemTests,i,r),IM(e,r);let s=LM({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Gs(e,`end status=${s.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),OM({ok:s.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:s.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4277a72c-f012-55d2-9e18-c9a836d829d6")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aba4af26-98d3-53aa-8b23-1be7c90a38d1")}catch{}})();function vw(){return{metadata:{},body:""}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="780365af-6d4c-5313-865b-23b8c68f889f")}catch{}})();var bw=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:zu().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm init","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm remind <title> --at <when> --parent <ID>","pm event <title> --start <when> --parent <ID>","pm meet <title> --start <when> --duration <span> --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Record the reminder or event under the item that owns the work, then confirm it appears in the agenda summary of a context read.",commands:["pm remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."}],related:["workflows","quickstart","extensions"]}],ww=new Map;for(let e of bw){ww.set(e.id,e);for(let t of e.aliases)ww.set(t,e)}function sd(){return bw.map(e=>e.id)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3a7cf539-2663-5265-90e8-c2aa9926a62a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="961951cf-e644-50ae-becc-205bea47225d")}catch{}})();var aV=[...no],cV=[...ro],NM=new Set(rr.filter(e=>e.hidden).map(e=>e.alias)),lV=Ku("full").filter(e=>!e.includes(" ")&&!NM.has(e)),dV=N(po),mV=N(fo),uV=N(bo),pV=N(To),fV=Xo("restore",Jt("restore")),_V=N(Co),hV=N(Nm),gV=N(Mm),yV=N(Ao),vV=N(xo),wV=N(Ro),bV=N(Io),kV=N(wo),MM=[...new Set(ut.map(e=>e.canonical_argv[0]))],FM=Object.fromEntries(MM.map(e=>[e,ut.filter(t=>t.canonical_argv[0]===e).map(t=>t.canonical_argv[1]).join(" ")])),SV=FM.history,EV=Vd.map(e=>({...e,flags:N(Jt(e.alias))})),AV=N(_o),TV=N(ho,!1),CV=N(Oo),RV=N(sr),IV=N(ar),OV=N(Mo),xV=N(Lo),PV=N(So),LV=N(No),NV=N(Po),MV=N(Fo),FV=N(ko),$V=N(Eo),DV=N(yo),UV=N($o),GV=N(go),jV=`${bn.join(" ")} list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status`;var $M=N(Do),qV=`${$M} bash zsh fish`,KV=GM(sd()),DM="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",zV=`${DM} upgrade`,BV=N(vo),HV=N(or),VV=N(ir);var WV=N(Jt("close")),YV=N(Jt("close-task")),JV=N(Jt("release")),XV=N(Jt("claim"));var UM=uo.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),QV=[...Vo].join("|"),ZV=[...Vo].map(e=>`${e}=*`).join("|"),eW=[...UM.split(" ").filter(e=>!Vo.has(e)),"-h","-V"].join("|");function GM(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c2a4576-a5d8-57c1-84e8-ca8b9019c84e")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7f8a7ea-3ec2-521b-ad52-45b655208f06")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d35e9a61-b8d8-5dc0-b242-586b2086cc95")}catch{}})();var Tw=Symbol("pm.active-extension-host-context");function $e(e){return{fullChangedFields:!0,options:e}}var G=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[Tw]=!0,n}run(t,n={}){return Cw({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return f_(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Ua(await this.list(Da(t)))}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}append(t,n,r={}){return this.runTyped("append",{id:t,...$e(je(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,i={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,r={}){return this.runTyped("schema",{name:n,options:{...r,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,i){return this.runTyped("plan",{...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...i===void 0?{}:{reorderTo:i},options:je(r,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",$e(t))}update(t,n={}){return this.runTyped("update",{id:t,...$e(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...$e(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...$e(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...$e(t)})}release(t,n={}){return this.runTyped("release",{id:t,...$e(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...$e(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...$e(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...$e(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...$e(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...$e(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...$e(r)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function qM(e={},t={}){return new G(t).context(e)}function KM(e={},t={}){return new G(t).list(e)}function zM(e={},t={}){return new G(t).listAllComplete(e)}function BM(e,t={},n={}){return new G(n).search(e,t)}function HM(e,t={},n={}){return new G(n).get(e,t)}function VM(e={},t={}){return new G(t).next(e)}function WM(e={},t={}){return new G(t).aggregate(e)}function YM(e,t={},n={}){return new G(n).comments(e,t)}function JM(e,t={},n={}){return new G(n).notes(e,t)}function XM(e,t={},n={}){return new G(n).learnings(e,t)}function QM(e,t={},n={}){return new G(n).files(e,t)}function ZM(e,t={},n={}){return new G(n).filesDiscover(e,t)}function eF(e,t={},n={}){return new G(n).docs(e,t)}function tF(e,t={},n={}){return new G(n).deps(e,t)}function nF(e,t={},n={},r={}){return new G(r).graph(e,t,n)}function rF(e,t,n={},r={}){return new G(r).append(e,t,n)}function oF(e={},t={}){return new G(t).create(e)}function iF(e,t={},n={}){return new G(n).update(e,t)}function sF(e,t,n={},r={}){return new G(r).reopen(e,t,n)}function aF(e,t,n={},r={}){return new G(r).close(e,t,n)}function cF(e,t={},n={}){return new G(n).claim(e,t)}function lF(e={},t={}){return new G(t).claimNext(e)}function dF(e,t={},n={}){return new G(n).release(e,t)}function mF(e,t={},n={}){return new G(n).copy(e,t)}function uF(e,t={},n={}){return new G(n).delete(e,t)}function pF(e,t,n={},r={}){return new G(r).restore(e,t,n)}function fF(e,t={},n={}){return new G(n).focus(e,t)}function it(e,t){let n=w(e,t);if(!n)throw new d(`Missing required argument: ${t}`,64);return n}var kw=Mu(),_F=new jM;function js(){Ea(Md()),Aa(Fd()),Ta($d()),Ca(Dd()),Ra(Ud()),Ia(Gd()),Oa(jd())}async function hF(e,t,n,r){return Fu(()=>t===void 0?kw.read(()=>Sw(e,n,r)):kw.write(()=>yF(t,()=>Sw(e,n,r))))}async function Sw(e,t,n){let r=E(t,e.path);if(e.noExtensions)return js(),gc({pmRoot:r},()=>n(null));if(!await L(fe(r)))return js(),n(null);let o=null,i;try{let s=await A(r),a=await tr({pmRoot:r,settings:s,cwd:t,noExtensions:!1}),c=await nr({...a,loaded:a.loaded});i={loadResult:a,activationResult:c},Ea(c.hooks),Aa(c.commands),Ta(c.parsers),Ca(c.preflight),Ra(c.services),Ia(c.renderers),Oa(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(s){js(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",s)}try{return await gc({pmRoot:r,packages:o?.packages},()=>n(o))}finally{js(),i&&await da(i.loadResult,i.activationResult).catch(()=>{})}}async function gF(e,t,n,r,o){if(!o)throw new d(`Unsupported native pm action: ${e}`,l.USAGE);let i=Nn(e),a=o.registrations.commands.find(m=>Nn(m.action)===i)?.command??o.commands.handlers.find(m=>Nn(m.command)===i)?.command;if(!a)throw new d(`Unsupported native pm action: ${e}`,l.USAGE);let c=await Yo({command:Wa(a),args:Ee(n.args??t.args),options:Ya(t,n),global:r,pm_root:o.pmRoot,sdk:y_(o.pmRoot,G.forActiveExtensionHost({pmRoot:o.pmRoot,author:typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension"}))});if(!c.handled){let m=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new d(`Unsupported native pm action: ${e}${m}`,l.USAGE)}return c.result}async function yF(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function vF(e){let t=it(e,"action"),n=Nn(t),r=Ks(h_,n),o=r?.action??n,i={...e,action:o};return r?.options!==void 0&&(i.options={...r.options,...la(e.options)}),o==="package"&&(i.options={...la(i.options),vocabulary:"package"}),{action:o,args:i}}async function Cw(e){let t=vF(e),n=Ba(t.args),r=rf(t.action),o=w(t.args,"cwd"),i=o??process.cwd();t.action==="init"&&(n[vl]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=E(i,n.path));try{return e[Tw]===!0||_F.getStore()===!0?await Aw(t.action,t.args,n,null):await hF(n,o,i,s=>Aw(t.action,t.args,n,s))}finally{r&&pc()}}function Ks(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function qs(e){return w(e.args,"target")??w(e.options,"target")}function ne(e,t=e.options){return e.id??it(t,"id")}async function wF(e){let t=En("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),uc(await gt(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function bF(e){let t=it(e.args,"query"),n=En("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),uc(await Er(t,n,e.global),n)}async function kF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Le(e.args,e.options);return Ue(await Gt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function SF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Le(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Ue(await il(ne(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function EF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Le(e.args,e.options);return Ue(await nt(ne(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function AF(e){let t=$i(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),Th(ne(e),t,e.global)}function Rw(e,t){return Vf(Fy(e.options,t,qe),e.global)}function TF(e){let t=Ee(e.options.lookupPath);if(t&&t.length>0)return Rw(e,t);let n=ne(e);return e.options.discover===!0?Qa(n,Va(e.options),e.global):Hf(n,bi(e.options),e.global)}function CF(e){return Nv({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:tf(e.args,e.options)},e.global)}function RF(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),vr(e.global,t)}function IF(e){let t=w(e.args,"configAction")??w(e.options,"configAction")??w(e.options,"action");if(t===void 0)throw new d("Missing required argument: configAction",64);let n=w(e.args,"value")??w(e.options,"value"),r=w(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return _g(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),r,e.global,w(e.options,"policy")===void 0?n:void 0)}function OF(e){let t=e.options;return Wp(Vp(t),e.global)}function xF(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new d(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new d(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new d(`${t} must be a finite integer.`,64);return r}}function PF(e){let t=w(e.args,"subcommand")??it(e.options,"subcommand"),n=e.options;return Hh({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:LF(e),reorderTo:xF(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function LF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function NF(e){let t=w(e.args,"subcommand")??it(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:w(e.args,"name")??w(e.options,"name"),author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:Ee(n)}}function MF(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=Ks({list:()=>wf(t.global),show:()=>bf(r,t.global),"show-status":()=>kf(r,t.global),"list-fields":()=>Af(t.global),"show-field":()=>Tf(r,t.global),"remove-type":()=>hf(r,{author:o,force:i},t.global),"remove-field":()=>Ef(r,{author:o,force:i},t.global),"remove-status":()=>vf(r,{author:o,force:i},t.global),"apply-preset":()=>Cf(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function FF(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return Sf(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:s===void 0?void 0:Ee(s),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:i,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:Ee(a),author:r,force:o},t.global)}function $F(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,s=t.args.role??t.options.role;return yf(n,{role:s===void 0?void 0:Ee(s),alias:i,description:w(t.args,"description")??w(t.options,"description"),order:qe(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function DF(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return _f(n,{description:w(t.args,"description")??w(t.options,"description"),defaultStatus:w(t.args,"defaultStatus")??w(t.args,"default_status")??w(t.options,"defaultStatus")??w(t.options,"default_status"),folder:w(t.args,"folder")??w(t.options,"folder"),alias:i,author:r,force:o},t.global)}function UF(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,s=w(t.args,"to")??it(t.options,"to"),a=w(t.args,"migrationId")??w(t.args,"migration_id")??w(t.options,"migrationId")??w(t.options,"migration_id"),c=w(t.args,"fieldTypeScope")??w(t.options,"fieldTypeScope")??w(t.args,"type")??w(t.options,"type"),m=n==="rename-type"?{kind:"rename-type",from:r??"",to:s}:n==="rename-field"?{kind:"rename-field",from:r??"",to:s,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:s};return pf(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function GF(e){let t=NF(e),n=bn.find(o=>o===t.subcommand);if(n)return uf(n,t.name,{definition:e.args.definition??e.options.definition,policy:w(e.args,"policy")??w(e.options,"policy"),message:w(e.args,"message")??w(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=MF(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return UF(t);if(t.subcommand==="add-field")return FF(t);if(t.subcommand==="add-status")return $F(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Rf({minCount:qe(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):DF(t);throw Pe({command_path:"schema",token:t.subcommand,allowed:ff,exit_code:64})}function jF(e){let t=w(e.args,"subcommand")??it(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),i=Ks({list:()=>yy(),show:()=>vy(r),lint:()=>wy(r),apply:()=>by(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!i)throw Pe({command_path:"profile",token:t,allowed:gy,exit_code:64});return i()}async function qF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Le(e.args,e.options);return Ue(await b_(ne(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function KF(e){let{changedFields:t,runnerOptions:n}=Le(e.args,e.options);return Ue(await Lh(Xa(n),e.global),{changedFields:t})}async function zF(e){let{changedFields:t,runnerOptions:n}=Le(e.args,e.options),r=w(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Ue(await Ah(Ja(o),e.global),{changedFields:t})}async function BF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Le(e.args,e.options),o=w(r,"target")??it(e.args,"target");return Ue(await mn(ne(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Ew(e){return Gc(ne(e),je(e.options,{force:e.force}),e.global)}async function HF(e){let t=ne(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text");return Mr(t,n,je(e.options,{force:e.force}),e.global)}function VF(e){let t={...e.args,...e.options};return Qp(it(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),sf(t),e.global)}function WF(e){return cf(E(process.cwd(),e.global.path),{...e.args,...e.options})}var YF={init:e=>Gr(w(e.args,"prefix"),e.global,e.options),context:e=>lc(En("context",e.options),e.global),next:e=>Sr(En("next",e.options),e.global),eval:sy,events:ay,merge:cy,workspace:ly,meet:ks,event:ks,remind:ks,list:wF,get:e=>{let t=ne(e);return dc(t,e.global,En("get",e.options,[t]))},search:bF,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:Ee(e.options.status);return mc(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:w(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:qe(e.options.limit,"limit")})},create:kF,copy:SF,focus:e=>al(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:EF,"item-reopen":My,restore:BF,claim:Ly,release:e=>e.options.pause===!0?Ew(e):Ir(ne(e),e.force,e.global,e.options),"start-task":e=>Nr(ne(e),je(e.options,{force:e.force}),e.global),"pause-task":Ew,"close-task":HF,close:Ny,comments:AF,notes:e=>Rh(ne(e),$i(e.options),e.global),learnings:e=>Ch(ne(e),$i(e.options),e.global),files:TF,docs:e=>Bf(ne(e),bi(e.options),e.global),test:e=>Ds(ne(e),e.options,e.global),"test-all":e=>yw(e.options,e.global),telemetry:CF,validate:e=>Ii(e.options,e.global,{runUpdate:(t,n,r)=>nt(t,n,r)}),health:RF,assurance:e=>c_(e.args,e.options,e.global),contracts:e=>iv(e.options,e.global),config:IF,activity:OF,aggregate:e=>sc(e.options,e.global),extension:e=>Mn(qs(e),e.options,e.global),package:e=>Mn(qs(e),e.options,e.global),install:e=>Mn(qs(e),{...e.options,install:!0},e.global),upgrade:e=>d_(qs(e),e.options,e.global),delete:e=>sl(ne(e),e.options,e.global),deps:e=>Xp(ne(e),e.options,e.global),graph:VF,"files-discover":e=>Qa(ne(e),e.options,e.global),"files-lookup":e=>Rw(e,Ee(e.options.paths)),history:e=>l_(ne(e),e.options,e.global),"history-redact":e=>Ay(ne(e),e.options,e.global),"history-repair":xy,"history-compact":Py,"history-author-acknowledge":WF,plan:PF,schema:GF,profile:jF,stats:e=>Bl(e.global,Ev(e.options)),append:qF,"update-many":KF,"close-many":zF,gc:e=>m_(e.global,e.options)};async function Aw(e,t,n,r){let o=Ha(t,e);ka(e,o),Tu(e,o);let i={action:e,args:t,options:o,id:w(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},s=Ks(YF,e),a=s?await s(i):await gF(e,t,o,n,r);o.resolvedOutputFormat="json";let c=Gu(e,o,a);return await v_(E(process.cwd(),n.path),c),c}var JF={closeManyOptionsFromFlat:Ja,extensionOptionsFromArgs:Ya,globalOptions:Ba,mutationListOptions:of,normalizeActionName:Nn,normalizeCommandPath:Wa,normalizeMcpUpdateOptions:af,normalizeMcpOptionsArrays:nf,optionsWithAuthor:Ha,readRequiredString:it,readScalarString:Zp,readScalarStringAllowBlank:ef,readStringArray:Ee,updateManyOptionsFromFlat:Xa,withAddNoteOption:bi,withFilesDiscoveryOptions:Va,withMutationCompaction:Le};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=JF);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48d03e9b-14a4-545c-8e5d-5f5f2092a113")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38023567-8a5b-5e25-8d71-5112f74d1894")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3eaa41f7-77a1-5838-8a2f-2ab6a49c21ef")}catch{}})();export{An as AGENT_PROVENANCE_DIMENSIONS,Qu as BASELINE_ITEM_FORMAT_VERSION,Rb as BUILTIN_AGENT_PROVENANCE_ADAPTERS,lr as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,no as BUILTIN_ITEM_TYPE_VALUES,oo as CONFIDENCE_TEXT_VALUES,Zu as CURRENT_ITEM_FORMAT_VERSION,Ht as DEPENDENCY_KIND_VALUES,l as EXIT_CODE,gn as ISSUE_SEVERITY_VALUES,wd as ITEM_TYPE_VALUES,fc as PM_CLI_EXPECTED_ERROR_NAME,yb as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,hb as PM_READ_OUTPUT_DIMENSIONS,gb as PM_READ_OUTPUT_OPTION_FLAGS,wa as PM_READ_OUTPUT_SURFACE_CONTRACTS,d as PmCliError,G as PmClient,hn as RISK_VALUES,qb as SEMANTIC_ATTRIBUTION_LIMITS,ro as STATUS_VALUES,Cb as agentSessionEnvironment,WM as aggregate,Kl as analyzeAgentProvenanceDescriptorCoverage,Sb as analyzeSdkCliParameterCompleteness,rF as append,wb as applyReadOutputDimensions,mb as applyReadOutputSessionReferences,ub as attachReadOutputSessionReceipt,Eb as boundAgentEpisodeIdentity,Ze as canonicalDocument,cF as claim,lF as claimNext,np as classifyItemFormatVersion,aF as close,YM as comments,qM as context,mF as copy,oF as create,g_ as createPmCliExpectedError,_b as decodeReadOutputContinuationCursor,uF as deleteItem,tF as deps,Mb as detectAgentIdentity,Db as detectHarnessIdentity,Fb as diagnoseAgentIdentity,eF as docs,ep as effectiveItemFormatVersion,vw as emptyImportedDocument,fb as encodeReadOutputContinuationCursor,yP as evaluateSemanticAttributionCoverage,Gb as explainSourceTraceability,QM as files,ZM as filesDiscover,fF as focus,HM as get,nF as graph,vP as groupHistoryByEpisode,C_ as isAlreadyClaimedError,Ni as isPmCliExpectedError,bb as isReadOutputBudgetExceeded,XM as learnings,KM as list,Ob as listAgentProvenanceAdapters,zM as listAllComplete,VM as next,Pb as normalizeAgentProvenanceAdapterValue,tp as normalizeItemFormatVersion,Ge as normalizeItemId,Z as normalizeStatusInput,JM as notes,k as nowIso,db as parseReadOutputSession,Ti as parseSourceLineRange,Zo as readAuthorEnvironment,pb as readOutputSessionRemainingTokens,ac as recordClaimSemanticAttribution,xi as recordFocusSemanticAttribution,cc as recordReleaseSemanticAttribution,xb as registerAgentProvenanceAdapters,Ib as registerHarnessSignalDescriptors,dF as release,sF as reopen,Ab as resolveAgentSessionContextFromSignals,Ub as resolveAuthorIdentity,fv as resolveHistoryEpisodeGroupIdentity,vb as resolveReadOutputDimensions,kb as resolveReadOutputEncoding,ba as resolveReadOutputSurface,jb as resolveSemanticLineageIds,pF as restore,Cw as runAction,Tb as runWithAgentSessionContext,Lb as runWithHarnessDetectionSignals,Nb as runWithWorkspaceHarnessSignalDescriptors,BM as search,Kb as semanticAttributionAffinity,ze as serializeItemDocument,gP as summarizeAgentModelProvenance,zl as summarizeAgentProvenance,iF as update,ka as validateReadOutputOptions,$b as writeAuthorEnvironment};
|
|
51
51
|
//# sourceMappingURL=sdk-core.js.map
|