@unbrained/pm-cli 2026.8.19 → 2026.8.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +19 -0
- package/dist/cli/register-list-query.js +12 -10
- package/dist/cli/register-structured-mutation.d.ts +2 -0
- package/dist/cli/register-structured-mutation.js +29 -6
- package/dist/cli-bundle/bundle-manifest.json +151 -143
- package/dist/cli-bundle/chunks/{chunk-4THEB6PD.js → chunk-2RDVGYWE.js} +12 -12
- package/dist/cli-bundle/chunks/{chunk-BHYMXLAE.js → chunk-4GB2LTOQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TOXJM4WA.js → chunk-7BRF2BX2.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-BLVQHFSY.js +35 -0
- package/dist/cli-bundle/chunks/chunk-CU25EQVV.js +5 -0
- package/dist/cli-bundle/chunks/{chunk-4NRRH7AM.js → chunk-K3EN3LK2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OIOKV6NO.js → chunk-L4LGPBJU.js} +49 -49
- package/dist/cli-bundle/chunks/chunk-RS3IV2R6.js +197 -0
- package/dist/cli-bundle/chunks/chunk-TSMWLCHS.js +3 -0
- package/dist/cli-bundle/chunks/chunk-US2ZQW2M.js +77 -0
- package/dist/cli-bundle/chunks/{chunk-QXSH7BLM.js → chunk-XYDDWBZN.js} +2 -2
- package/dist/cli-bundle/chunks/register-list-query-JSAQCVOC.js +11 -0
- package/dist/cli-bundle/chunks/{register-mutation-AUWVCW4M.js → register-mutation-XJPAW63D.js} +20 -20
- package/dist/cli-bundle/chunks/{register-operations-PZQPHXW5.js → register-operations-DSOSB2XQ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-I4LUHGVW.js → register-setup-QUR6QL2C.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-DKPLYW3L.js → chunk-325UXIO7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5L7M4AI7.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-EF6ZS5GH.js → chunk-6AHG2YW7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MCZXYZAF.js → chunk-AZBACT5T.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-VXDSU5MC.js → chunk-BLJCGGID.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-FUREQLQN.js +18 -0
- package/dist/cli-bundle/focused-chunks/{chunk-US7VEYZG.js → chunk-G3C5ERXG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZBIQQYMI.js → chunk-GXWQBE3T.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JDOMQ7VQ.js → chunk-JWKEDZJI.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-KYZ6JGPL.js +155 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ESISGDAY.js → chunk-M32HFIQB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EXBCLIBU.js → chunk-OM65KHGF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-Q47EX4DI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BJRYFVSH.js → chunk-RIHDMCUM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-T4ZFY7ZJ.js +16 -0
- package/dist/cli-bundle/focused-chunks/chunk-TDR5OGG3.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ODHQEECS.js → chunk-UGSS4F5X.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-Z3PLWSGM.js +2 -0
- package/dist/cli-bundle/main.js +2 -2
- 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 +41 -41
- 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 +31 -31
- 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 +5 -5
- package/dist/core/output/mutation-projection.js +26 -2
- package/dist/core/shared/constants.d.ts +1 -5
- package/dist/core/shared/constants.js +3 -81
- package/dist/core/shared/item-metadata-contract.d.ts +14 -0
- package/dist/core/shared/item-metadata-contract.js +90 -0
- package/dist/core/store/item-store.d.ts +60 -0
- package/dist/core/store/item-store.js +22 -5
- package/dist/sdk/agent/closed-domain-contracts.d.ts +25 -0
- package/dist/sdk/agent/closed-domain-contracts.js +140 -0
- package/dist/sdk/agent/refusal-closure.d.ts +13 -1
- package/dist/sdk/agent/refusal-closure.js +45 -3
- package/dist/sdk/agent/refusal-reachability.d.ts +26 -0
- package/dist/sdk/agent/refusal-reachability.js +26 -2
- package/dist/sdk/agent-capability-contracts.js +6 -11
- package/dist/sdk/cli-contracts/completeness.js +8 -2
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +4 -2
- package/dist/sdk/cli-contracts/enum-contracts.js +16 -6
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +11 -2
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.d.ts +19 -2
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +105 -5
- package/dist/sdk/cli-contracts/grammar-contracts.d.ts +2 -2
- package/dist/sdk/cli-contracts/grammar-contracts.js +5 -2
- package/dist/sdk/cli-contracts/runtime-contracts.js +7 -3
- package/dist/sdk/cli-contracts/tool-schema.js +7 -2
- package/dist/sdk/cli-contracts.d.ts +2 -2
- package/dist/sdk/cli-contracts.js +4 -4
- package/dist/sdk/contracts.d.ts +1 -0
- package/dist/sdk/contracts.js +3 -2
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +3 -3
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +74 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +112 -40
- package/dist/sdk/index.d.ts +5 -3
- package/dist/sdk/index.js +6 -4
- package/dist/sdk/init-agent-guidance.d.ts +5 -3
- package/dist/sdk/init-agent-guidance.js +69 -9
- package/dist/sdk/lifecycle/mcp-actions.d.ts +18 -0
- package/dist/sdk/lifecycle/mcp-actions.js +52 -0
- package/dist/sdk/lifecycle/reopen.d.ts +44 -0
- package/dist/sdk/lifecycle/reopen.js +69 -0
- package/dist/sdk/lifecycle/update.d.ts +31 -0
- package/dist/sdk/lifecycle/update.js +95 -13
- package/dist/sdk/query/get.d.ts +1 -1
- package/dist/sdk/query/get.js +18 -52
- package/dist/sdk/query/list.d.ts +7 -21
- package/dist/sdk/query/list.js +35 -49
- package/dist/sdk/query/projection-contracts.d.ts +33 -0
- package/dist/sdk/query/projection-contracts.js +185 -0
- package/dist/sdk/query/search-contracts.d.ts +2 -1
- package/dist/sdk/query/search-contracts.js +18 -87
- package/dist/sdk/query/search.d.ts +15 -0
- package/dist/sdk/query/search.js +31 -5
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +3 -3
- package/dist/sdk/runtime.d.ts +6 -0
- package/dist/sdk/runtime.js +18 -14
- package/dist/sdk/similarity.d.ts +13 -0
- package/dist/sdk/similarity.js +32 -6
- package/docs/COMMANDS.md +13 -1
- package/docs/README.md +1 -0
- package/docs/RECURRENCE_RECOVERY_CONTRACTS.md +114 -0
- package/docs/SDK.md +10 -2
- package/docs/SDK_CONTEXT_INTEGRITY.md +45 -0
- package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -1
- package/docs/performance/sdk-entrypoint-import-costs.md +14 -21
- 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/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/sdk/public-surface.json +387 -25
- package/dist/cli-bundle/chunks/chunk-GWMXAQOD.js +0 -197
- package/dist/cli-bundle/chunks/chunk-HVFQTLYM.js +0 -35
- package/dist/cli-bundle/chunks/chunk-OI4XI562.js +0 -5
- package/dist/cli-bundle/chunks/chunk-SARFF5H5.js +0 -3
- package/dist/cli-bundle/chunks/chunk-YBMRWW4E.js +0 -77
- package/dist/cli-bundle/chunks/register-list-query-Y56KINDU.js +0 -11
- package/dist/cli-bundle/focused-chunks/chunk-34QBIYZI.js +0 -155
- package/dist/cli-bundle/focused-chunks/chunk-L623ZPNK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PRHY2IMX.js +0 -18
- package/dist/cli-bundle/focused-chunks/chunk-RZU5U6Q7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-YBMGXBFV.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-YLVBJ6GF.js +0 -2
|
@@ -1,55 +1,55 @@
|
|
|
1
|
-
import{n as um,o as ls,p as gm,q as ym,r as Li,s as ps,t as bm,u as Fi,v as fs,y as Fm,z as $m}from"./focused-chunks/chunk-VXDSU5MC.js";import{a as Gm,f as jm,h as Ut,m as Bm,o as Hm,r as Vm,s as Wm,w as Ym}from"./focused-chunks/chunk-YLVBJ6GF.js";import{$ as ua,$a as Mp,Aa as yp,Ba as bp,Bb as jp,Ca as wp,Cb as Yp,Da as vp,Db as Jp,Ea as En,Fa as kp,G as Vu,Ga as Sp,I as w,Ia as Yn,J as Wu,Ja as Ep,K as Yu,Ka as Tp,L as Le,La as Ap,M as Ju,Ma as Cp,N as ia,Na as Rp,O as Xu,Oa as Ip,P as aa,Q as zs,R as ca,Ra as xp,S as Kt,Sa as Hs,T as da,Ta as hw,U as he,Ua as Op,V as la,Va as Pp,W as Ve,Wa as pa,X as Qu,Xa as Np,Y as Zu,Ya as Lp,Z as ma,Za as Fp,_ as ep,_a as $p,a as Ki,ab as Dp,b as Iu,bb as Jn,cb as fa,db as _a,eb as Vs,fb as ha,gb as Up,ha as tp,hb as ga,i as qu,ib as Ws,j as Ku,ja as Bs,jb as Tn,ka as np,kb as ya,la as rp,lb as ba,ma as sp,mb as Gp,na as op,oa as ip,pa as ap,pb as Ys,qa as cp,ra as dp,sa as lp,ta as mp,ua as up,va as pp,wa as fp,xa as _p,ya as hp,za as gp}from"./focused-chunks/chunk-EF6ZS5GH.js";import{e as dm,g as lm,h as mm,k as pm,q as hm}from"./focused-chunks/chunk-EXBCLIBU.js";import{b as Mm,c as _s,e as Dm,f as Um,g as rw}from"./focused-chunks/chunk-DKPLYW3L.js";import{H as qi,L as Lm,a as el,b as tl,c as nl,d as rl,f as sl}from"./focused-chunks/chunk-MCZXYZAF.js";import{a as Au,b as Cu,c as Qs}from"./focused-chunks/chunk-ZBIQQYMI.js";import{Z as Hu,b as Ru,e as zu,f as Vn,g as Wn,i as oa,t as Bu}from"./focused-chunks/chunk-BJRYFVSH.js";import{$a as Sa,D as Js,E as Kp,Ea as gw,F as Qn,Fa as va,G as zp,Ga as ka,Ha as Xs,Ia as yw,Ja as bw,L as Bp,M as Hp,N as Vp,R as Et,T as wa,c as ea,e as ta,eb as Zn,g as ku,gb as Wp,h as Cs,i as na,j as Su,k as Rs,kb as Ea,l as Is,m as xs,n as Eu,o as Tu,s as $u,t as Mu,u as Du,v as Uu,w as Gu,x as ju,xb as er,y as Xn,yb as Ta}from"./focused-chunks/chunk-YBMGXBFV.js";import{A as ra,B as Ks,Ca as Fu,D as Ou,E as Pu,Ea as Zs,F as Hn,Ia as An,a as Os,b as Ps,c as Ns,d as Ls,h as Fs,j as $s,k as Ms,l as xu,m as Ds,n as Us,o as St,p as bn,q as Gs,r as wn,s as js,t as te,u as qs,v as Ue,va as Sn,w as Ne,wa as Nu,x as se,xa as sa,y as vn,ya as Lu,z as kn}from"./focused-chunks/chunk-PRHY2IMX.js";import{c as im,f as am,g as cm,i as ds,j as gt,k as wm,l as vm,m as km}from"./focused-chunks/chunk-ESISGDAY.js";import{$ as Nl,$a as F,A as Ur,Aa as em,B as pl,Ba as Yr,C as fl,Ca as tm,D as _l,Da as nm,E as Gr,Ea as Jr,F as hl,Fa as Xr,G as gl,Ga as Qr,H as yl,Ha as Zr,I as jr,Ia as jn,J as qr,Ja as es,K as bl,Ka as rm,L as Kr,La as qn,Ma as ts,N as wl,Na as ns,O as Gn,Oa as rs,P as vl,Pa as ss,Q as kl,Qa as sm,R as Sl,Ra as ht,S as El,Sa as os,T as Tl,Ta as is,U as Al,Ua as as,V as Cl,Va as cs,W as Rl,X as Il,Y as xl,Ya as om,Z as Ol,_ as Pl,aa as Ll,ba as Fl,ca as $l,d as Oi,da as Ml,e as ol,ea as Dl,fa as zr,ga as Br,h as il,ha as Ul,i as Pi,ia as Gl,j as Dt,ja as jl,ka as ql,l as al,la as Kl,ma as zl,na as Bl,oa as Hl,q as Ni,qa as Vl,ra as Wl,s as $r,sa as Yl,t as Mr,ta as Jl,u as Dr,ua as Xl,v as cl,va as Ql,w as dl,wa as Hr,x as ll,xa as Vr,y as ml,ya as Wr,z as ul,za as Zl}from"./focused-chunks/chunk-L623ZPNK.js";import{c as qp}from"./focused-chunks/chunk-US7VEYZG.js";import{$a as yu,Ab as Ee,Da as De,Ea as wt,F as bs,G as Qm,Ga as Ss,H as Zm,Ha as Pe,I as pn,Ia as jt,J as zn,Ja as mu,K as cw,Ka as qt,L as dw,La as uu,M as lw,N as mw,Na as pu,O as uw,Oa as hn,P as ws,Pa as fu,Q as pw,Qa as Es,R as fw,Ra as ot,S as _w,T as fn,U as R,V as S,Wa as _u,X as _n,Xa as hu,Ya as vt,Z as Q,_ as xe,_a as gu,a as Jm,ab as A,ba as eu,bb as Se,c as Xm,ca as vs,cb as bu,da as tu,db as wu,e as zi,ea as nu,eb as kt,f as Bi,fa as ru,fb as Zi,g as Hi,ga as su,gb as _e,h as Vi,ha as ou,hb as Bn,i as Wi,j as Yi,ja as ne,k as Ji,l as I,la as Oe,m as mn,ma as ks,n as Gt,na as Xi,nb as gn,o as z,oa as iu,p as gs,pa as Me,pb as yn,q as un,qa as He,ra as bt,rb as M,sa as au,sb as K,t as ys,ta as cu,ua as Qi,ub as re,v as st,vb as Ts,w as sw,wa as du,wb as As,x as ow,xa as lu,xb as it,y as iw,yb as Y,z as aw,zb as vu}from"./focused-chunks/chunk-34QBIYZI.js";import{$ as jd,B as Ii,C as Dn,D as fe,G as x,Ga as Lr,H as ue,Ha as Zd,I as Or,Ia as Fr,J as cn,K as Un,L as Ud,La as nt,M as T,N as Gd,Na as ms,O as et,Oa as rt,P as C,Pa as yt,Q as Mt,Qa as fm,S as ke,Sa as j,T as Pr,Ta as us,Ua as Be,Wa as _m,Z as dn,ba as xi,ca as qd,ea as Kd,ga as Nr,h as ft,i as Ir,ia as zd,j as xr,ja as Bd,la as Hd,ma as Vd,na as Wd,oa as Yd,pa as Jd,q as k,qa as Xd,r as $t,ra as Qd,s as _t,t as q,u as me,w as an}from"./focused-chunks/chunk-JDOMQ7VQ.js";import{b as hs,h as qm,i as Km,l as ln,p as zm}from"./focused-chunks/chunk-ODHQEECS.js";import{$a as Jb,A as Ld,B as Fd,C as $d,Ca as Kb,D as Md,Da as zb,E as ki,Ea as Bb,F as Si,Fa as Hb,G as Ei,Ga as Pm,H as Ti,I as Ai,J as Ci,Ma as Ui,Oa as Vb,Pa as Wb,Q as Ri,S as Rr,T as Dd,W as pt,Y as d,Z as l,Za as Yb,aa as J,ab as Xb,ba as tt,bb as Gi,cb as Qb,db as ji,ea as Kn,gb as Nm,hb as Zb,ia as Sm,ja as Em,jb as ew,ka as Tm,kb as tw,l as Tr,la as Am,lb as nw,m as Od,ma as Cm,n as Ar,na as Rm,o as vi,oa as $i,pa as Im,qa as xm,s as Ft,sa as Mi,t as Ze,ta as Om,u as sn,ua as Di,v as on,w as Cr,y as Pd,z as Nd}from"./focused-chunks/chunk-RZU5U6Q7.js";import{AsyncLocalStorage as jL}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]="27dd77f6-e53d-55b7-be15-db0e60eaec4e")}catch{}})();function Xp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ww(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 Aa(e,t){let n=ww(t),r=n==="brief"?n:Xp(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:Xp(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]="6ede8efb-54ec-5b13-a1bf-216b525acc12")}catch{}})();async function Qp(e,t){let n=T(t??process.cwd(),e),r=await A(n);return re(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]="b9eae1a3-3eb6-5415-86c3-a8e8e1fedd1f")}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]="7c898a52-eba4-5626-8207-5ffefd4990ba")}catch{}})();var vw=new Map;function Ca(){vw.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]="6f62939a-7b99-5687-93ae-834e0032f1d5")}catch{}})();var kw={"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 Zp(e){return Object.fromEntries(xm.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var ef={ctx:{action:"context"},...kw,...Zp("extension"),...Zp("package")};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="41012e87-ed61-56b2-8505-8f786b3952b2")}catch{}})();var Ra="PmCliError";function Sw(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=d.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function tf(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new l(e,Sw(t.exitCode??d.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function eo(e){if(!(e instanceof Error)||e.name!==Ra)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]="ff13ec2a-64a8-5512-973f-5447be945978")}catch{}})();function Ia(e){let t=Kd();for(let n of e)t.register(n);return t}function nf(e,t){return{client:t,isItemNotFoundError:n=>eo(n)&&n.exitCode===d.NOT_FOUND,getItemAt:(n,r)=>Tu(n,r,{pmRoot:e}),openRelationshipEventStore:n=>Cu.open({pmRoot:e,nodes:n.nodes,registry:Ia(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new Bd(n.nodes,n.edges,Ia(n.definitions)),analyzeRelationshipImpact:(n,r,s)=>Ru(n,r,s),validateRelationshipEvents:n=>{let r=new Au(n.nodes,{registry:Ia(n.definitions)});return n.events.map(s=>r.append({...s,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>Iu({...n,pmRoot:e})}}import{readFile as Ew}from"node:fs/promises";import Tw 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]="7ba0243e-98d1-5aef-bd47-54f0b630be58")}catch{}})();var xa="context-intents.json";function to(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Aw(e,t,n){if(!to(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(s=>typeof s=="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 rf(e,t){let n=Array.isArray(e)?e:to(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,s)=>Aw(r,t,s))}async function Cw(e){let t=Tw.join(e,xa),n;try{n=await Ew(t,"utf8")}catch(s){if($t(s))return[];throw s}let r;try{r=JSON.parse(n)}catch(s){let o=s instanceof Error?s.message:String(s);throw new TypeError(`Invalid ${xa}: ${o}`,{cause:s})}return rf(r,xa)}function Rw(e){if(!to(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return to(n)?n.contextIntents??n.context_intents:void 0}function Iw(e){return e.flatMap(t=>{let n=Rw(t.module);return n===void 0?[]:rf(n,`package ${t.name}`)})}async function xw(e){let t=await Cw(e.pmRoot),n=Iw(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Oa(e,t){let n=await xw(e);return await Km(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]="9e3ba7e9-8822-53ba-981e-e177be5219f3")}catch{}})();async function sf(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=Ne(),s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=R(t.author,o.author_default),c=(await r.resolveValue(t.body,"--body")).trim();if(c.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",d.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 Y({pmRoot:s,settings:o,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 ym,o as ps,p as Sm,q as Em,r as Mi,s as hs,t as Tm,u as Di,v as gs,y as jm,z as qm}from"./focused-chunks/chunk-BLJCGGID.js";import{a as Hm,f as Vm,h as qt,m as Xm,o as Qm,r as Zm,s as eu,w as tu}from"./focused-chunks/chunk-Z3PLWSGM.js";import{$ as _a,$a as Vp,Aa as Rp,Ba as Ip,Bb as Xp,Ca as xp,Cb as nf,Da as Op,Db as rf,Ea as Cn,Fa as Pp,G as rp,Ga as Np,I as w,Ia as er,J as sp,Ja as Lp,K as op,Ka as Fp,L as Fe,La as $p,M as ip,Ma as Mp,N as da,Na as Dp,O as ap,Oa as Up,P as la,Q as Vs,R as ma,Ra as Gp,S as Ht,Sa as Ys,T as ua,Ta as Tw,U as ye,Ua as jp,V as pa,Va as qp,W as $e,Wa as ha,X as cp,Xa as Kp,Y as dp,Ya as zp,Z as fa,Za as Bp,_ as lp,_a as Hp,a as Hi,ab as Wp,b as Uu,bb as tr,cb as ga,db as ya,eb as Js,fb as ba,gb as Yp,ha as mp,hb as wa,i as Qu,ib as Xs,j as Zu,ja as Ws,jb as Rn,ka as up,kb as va,la as pp,lb as ka,ma as fp,mb as Jp,na as _p,oa as hp,pa as gp,pb as Qs,qa as yp,ra as bp,sa as wp,ta as vp,ua as kp,va as Sp,wa as Ep,xa as Tp,ya as Ap,za as Cp}from"./focused-chunks/chunk-6AHG2YW7.js";import{e as _m,g as hm,h as gm,k as bm,q as km}from"./focused-chunks/chunk-OM65KHGF.js";import{b as Km,c as ys,e as zm,f as Bm,g as uw}from"./focused-chunks/chunk-325UXIO7.js";import{H as Bi,L as Gm,a as ol,b as il,c as al,d as cl,f as dl}from"./focused-chunks/chunk-AZBACT5T.js";import{a as $u,b as Mu,c as to}from"./focused-chunks/chunk-GXWQBE3T.js";import{Z as np,b as Du,e as ep,f as Qn,g as Zn,i as ca,t as tp}from"./focused-chunks/chunk-RIHDMCUM.js";import{Ba as Aw,Ca as Ea,D as Zs,Da as Ta,E as Zp,Ea as eo,F as rr,Fa as Cw,G as ef,Ga as Rw,O as It,Q as Sa,Ya as Aa,bb as sr,c as ra,db as tf,e as sa,g as Pu,h as xs,hb as Ca,i as oa,j as Nu,k as Os,l as Ps,m as Ns,n as Lu,o as Fu,s as Hu,t as Vu,u as Wu,v as Yu,w as Ju,wb as or,x as Xu,xb as Ra,y as nr}from"./focused-chunks/chunk-T4ZFY7ZJ.js";import{a as nu,b as ru,c as su}from"./focused-chunks/chunk-5L7M4AI7.js";import{A as ia,B as Hs,Ca as Bu,D as ju,E as qu,Ea as no,F as Xn,Ia as In,a as Ls,b as Fs,c as $s,d as Ms,h as Ds,j as Us,k as Gs,l as Gu,m as js,n as qs,o as Rt,p as kn,q as Ks,r as Sn,s as zs,t as ne,u as Bs,v as Ke,va as An,w as Le,wa as Ku,x as ie,xa as aa,y as En,ya as zu,z as Tn}from"./focused-chunks/chunk-FUREQLQN.js";import{c as um,f as pm,g as fm,i as us,j as kt,k as Am,l as Cm,m as Rm}from"./focused-chunks/chunk-M32HFIQB.js";import{$ as Dl,A as qr,Aa as om,B as yl,Ba as Qr,C as bl,Ca as im,D as wl,Da as am,E as Kr,Ea as cm,F as vl,Fa as Zr,G as kl,Ga as es,H as Sl,Ha as ts,I as zr,Ia as ns,J as Br,Ja as Hn,K as El,Ka as rs,L as Hr,La as dm,Ma as Vn,N as Tl,Na as ss,O as Bn,Oa as os,P as Al,Pa as is,Q as Cl,Qa as as,R as Rl,Ra as lm,S as Il,Sa as vt,T as xl,Ta as cs,U as Ol,Ua as ds,V as Pl,Va as ls,W as Nl,Wa as ms,X as Ll,Y as Fl,Z as $l,Za as mm,_ as Ml,aa as Ul,ab as F,ba as Gl,ca as jl,d as Li,da as ql,e as ll,ea as Kl,fa as Vr,ga as Wr,h as ml,ha as zl,i as Fi,ia as Bl,j as jt,ja as Hl,ka as Vl,l as ul,la as Wl,ma as Yl,na as Jl,oa as Xl,q as $i,qa as Ql,ra as Zl,s as Ur,sa as em,t as Gr,ta as tm,u as jr,ua as nm,v as pl,va as rm,w as fl,wa as Yr,x as _l,xa as Jr,y as hl,ya as Xr,z as gl,za as sm}from"./focused-chunks/chunk-TDR5OGG3.js";import{c as Qp}from"./focused-chunks/chunk-G3C5ERXG.js";import{$a as Cu,Ab as Ou,Bb as Te,Da as qe,Ea as Tt,F as ks,G as au,Ga as As,H as cu,Ha as Ne,I as hn,Ia as zt,J as Yn,Ja as wu,K as gw,Ka as Bt,L as yw,La as vu,M as bw,N as ww,Na as ku,O as vw,Oa as bn,P as Ss,Pa as Su,Q as kw,Qa as Cs,R as Sw,Ra as st,S as Ew,T as gn,U as R,V as S,Wa as Eu,X as yn,Xa as Tu,Ya as At,Z as Q,_ as Pe,_a as Au,a as ou,ab as A,ba as du,bb as Ee,c as iu,ca as Es,cb as Ru,da as lu,db as Iu,e as Vi,ea as mu,eb as Ct,f as Wi,fa as uu,fb as na,g as Yi,ga as pu,gb as ge,h as Ji,ha as fu,hb as Jn,i as Xi,j as Qi,ja as W,k as Zi,l as I,la as se,m as fn,ma as Ts,n as Kt,na as ea,nb as wn,o as z,oa as _u,p as ws,pa as je,pb as vn,q as _n,qa as We,ra as Et,rb as D,sa as hu,sb as K,t as vs,ta as gu,ua as ta,ub as oe,v as Ge,vb as Rs,w as pw,wa as yu,wb as Is,x as fw,xa as bu,xb as ot,y as _w,yb as xu,z as hw,zb as Z}from"./focused-chunks/chunk-KYZ6JGPL.js";import{$ as Hd,B as Pi,C as Kn,D as he,G as x,Ga as Mr,H as pe,Ha as sl,I as Lr,Ia as Dr,J as mn,K as zn,L as zd,La as nt,M as T,N as Bd,Na as fs,O as et,Oa as rt,P as C,Pa as St,Q as Gt,Qa as wm,S as Se,Sa as M,T as Fr,Ta as _s,Ua as Ve,Wa as vm,Z as un,ba as Ni,ca as Vd,ea as Wd,ga as $r,h as bt,i as Pr,ia as Yd,j as Nr,ja as Jd,la as Xd,ma as Qd,na as Zd,oa as el,pa as tl,q as k,qa as nl,r as Ut,ra as rl,s as wt,t as q,u as ue,w as ln}from"./focused-chunks/chunk-JWKEDZJI.js";import{b as bs,h as Wm,i as Ym,l as pn,p as Jm}from"./focused-chunks/chunk-UGSS4F5X.js";import{A as Ud,B as Gd,C as jd,D as qd,Da as Qb,E as Ti,Ea as Zb,F as Ai,Fa as ew,G as Ci,Ga as tw,H as Ri,Ha as Dm,I as Ii,J as xi,L as Or,Na as qi,Pa as nw,Qa as rw,R as Oi,T as Kd,W as yt,Y as d,Z as l,_a as sw,aa as J,ab as ow,ba as tt,bb as iw,cb as Ki,db as aw,ea as Wn,eb as zi,hb as Um,ia as Im,ib as cw,ja as xm,ka as Om,kb as dw,l as Rr,la as Pm,lb as lw,m as $d,ma as Nm,mb as mw,n as Ir,na as Lm,o as Ei,oa as Ui,pa as Fm,qa as $m,s as Dt,t as Ze,ta as Gi,u as cn,ua as Mm,v as dn,va as ji,w as xr,y as Md,z as Dd}from"./focused-chunks/chunk-Q47EX4DI.js";import{AsyncLocalStorage as eF}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]="27dd77f6-e53d-55b7-be15-db0e60eaec4e")}catch{}})();function sf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Iw(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 Ia(e,t){let n=Iw(t),r=n==="brief"?n:sf(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:sf(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]="6ede8efb-54ec-5b13-a1bf-216b525acc12")}catch{}})();async function of(e,t){let n=T(t??process.cwd(),e),r=await A(n);return oe(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]="b9eae1a3-3eb6-5415-86c3-a8e8e1fedd1f")}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]="7c898a52-eba4-5626-8207-5ffefd4990ba")}catch{}})();var xw=new Map;function xa(){xw.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]="6f62939a-7b99-5687-93ae-834e0032f1d5")}catch{}})();var Ow={"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 af(e){return Object.fromEntries($m.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var cf={ctx:{action:"context"},...Ow,...af("extension"),...af("package")};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="41012e87-ed61-56b2-8505-8f786b3952b2")}catch{}})();var Oa="PmCliError";function Pw(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=d.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function df(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new l(e,Pw(t.exitCode??d.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function ro(e){if(!(e instanceof Error)||e.name!==Oa)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]="ff13ec2a-64a8-5512-973f-5447be945978")}catch{}})();function Pa(e){let t=Wd();for(let n of e)t.register(n);return t}function lf(e,t){return{client:t,isItemNotFoundError:n=>ro(n)&&n.exitCode===d.NOT_FOUND,getItemAt:(n,r)=>Fu(n,r,{pmRoot:e}),openRelationshipEventStore:n=>Mu.open({pmRoot:e,nodes:n.nodes,registry:Pa(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new Jd(n.nodes,n.edges,Pa(n.definitions)),analyzeRelationshipImpact:(n,r,s)=>Du(n,r,s),validateRelationshipEvents:n=>{let r=new $u(n.nodes,{registry:Pa(n.definitions)});return n.events.map(s=>r.append({...s,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>Uu({...n,pmRoot:e})}}import{readFile as Nw}from"node:fs/promises";import Lw 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]="7ba0243e-98d1-5aef-bd47-54f0b630be58")}catch{}})();var Na="context-intents.json";function so(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fw(e,t,n){if(!so(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(s=>typeof s=="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 mf(e,t){let n=Array.isArray(e)?e:so(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,s)=>Fw(r,t,s))}async function $w(e){let t=Lw.join(e,Na),n;try{n=await Nw(t,"utf8")}catch(s){if(Ut(s))return[];throw s}let r;try{r=JSON.parse(n)}catch(s){let o=s instanceof Error?s.message:String(s);throw new TypeError(`Invalid ${Na}: ${o}`,{cause:s})}return mf(r,Na)}function Mw(e){if(!so(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return so(n)?n.contextIntents??n.context_intents:void 0}function Dw(e){return e.flatMap(t=>{let n=Mw(t.module);return n===void 0?[]:mf(n,`package ${t.name}`)})}async function Uw(e){let t=await $w(e.pmRoot),n=Dw(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function La(e,t){let n=await Uw(e);return await Ym(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]="9e3ba7e9-8822-53ba-981e-e177be5219f3")}catch{}})();async function uf(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=Le(),s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=R(t.author,o.author_default),c=(await r.resolveValue(t.body,"--body")).trim();if(c.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",d.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 Z({pmRoot:s,settings:o,id:e,op:"append",author:i,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 Ow}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]="0af9967c-ca72-563a-9518-2e68da0c0fe0")}catch{}})();function ro(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,t}function of(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,d.USAGE,{code:"structured_event_immutable"})}function Pa(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function zt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Cn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let o=te(n,"--add");return Object.keys(o).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:o.text?.trim()||n}catch{return n}}function Na(e){return typeof e=="object"&&e!==null&&"code"in e}async function Pw(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,d.USAGE);let r=Ne();if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add")??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new l("--file path cannot be empty",d.USAGE);try{return{value:await Ow(s,"utf8"),emptyFlag:"--file"}}catch(o){if(Na(o)&&$t(o))throw new l(`--file path not found: ${s}`,d.USAGE);let i=o instanceof Error?o.message:String(o);throw new l(`Failed to read --file path "${s}": ${i}`,d.USAGE)}}async function so(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",d.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",d.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",d.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",d.USAGE);let n=await Pw(e,t);if(e.edit!==void 0){if(!n)throw new l("--edit requires replacement text from --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function nr(e,t){throw e instanceof l&&e.exitCode===d.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function cf(e){return e==="comments"?"--stdin":"--add -"}function Nw(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let s=cf(t.collectionKey),o=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new l(`--add value "${r}" looks like an option, not annotation text. Use ${s} to read stdin, or use text=${r} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${s} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${o} ${s}`,`${o} --add text=${r}`]})}function Lw(e,t){if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,d.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> ${cf(e.collectionKey)}`]})}async function Rn(e,t,n,r){Lw(r,t);let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=x(o,I()),a=Hn(t.limit);if(r.input.mode==="list"){let _=await M(s,e,o.id_prefix,o.item_format,i.type_to_folder);if(!_)throw new l(`Item ${e} not found`,d.NOT_FOUND);let h=await K(_,{schema:o.schema}),y=zt(h.document.metadata,r.collectionKey);return no(_.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=R(t.author,o.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,h;try{h=await Y({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=zt(g.metadata,r.collectionKey),v=af(r.input.index,b.length,r.collectionKey);return of(b[v],"deleted"),b.splice(v,1),g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){nr(g,r.conflictGuidance)}let y=zt(h.item,r.collectionKey);return no(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";Nw(m,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,d.USAGE);if(r.input.mode==="edit"){let _=r.editOp??r.op,h;try{h=await Y({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=zt(g.metadata,r.collectionKey),v=af(r.input.index,b.length,r.collectionKey),E=b[v];return of(E,"edited"),b[v]={...E,text:u,edited_at:S()},g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){nr(g,r.conflictGuidance)}let y=zt(h.item,r.collectionKey);return no(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:y[r.input.index-1]},t.fullHistory===!0)}let p;try{p=await Y({pmRoot:s,settings:o,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(_){let h=zt(_.metadata,r.collectionKey),y={created_at:S(),author:c,text:u};return h.push(r.createEntry(y)),_.metadata[r.collectionKey]=h,{changedFields:[r.collectionKey]}}})}catch(_){nr(_,r.conflictGuidance)}let f=zt(p.item,r.collectionKey);return no(p.item.id,r.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:f.length,entry:f.at(-1)},t.fullHistory===!0)}function af(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),s=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,o=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${s} index ${e??"(missing)"} out of range (item has ${o})`,d.USAGE)}return e-1}function no(e,t,n,r,s,o,i=!1){let a=o===void 0||i?Pa(n,o!==void 0&&i?void 0:r):o.entry===void 0?[]:[o.entry],c=o!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...[s,o!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...o===void 0?{}:{mutation_receipt:{action:o.action,entry_index:o.entryIndex,changed_count:1,full_history_included:!c},omission_receipt:{has_omissions:c,omitted_field_group_count:c?1:0,omitted_field_groups:c?[{name:`${t}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0579277-f123-5f96-8664-dfe05ade1b24")}catch{}})();async function df(e,t,n){return[...await bt(ke(e,t),t).catch(()=>[])].reverse().find(o=>o.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]="f70f1329-4dfb-5625-ae0a-66c858d88f7b")}catch{}})();var lf="no_available_next_item";function mf(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 oo(e,t,n,r={}){let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=j(o.schema),a=R(r.author,o.author_default),c=fn(a),m=null,u=!1,p=[],f=await Y({pmRoot:s,settings:o,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,_m(_.metadata.status,i)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&g!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let v=await df(s,_.metadata.id,y);throw new l(`Item ${_.metadata.id} is already ${v}. Use --force to take over, or --if-available to skip without failing.`,d.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}`)}return _.metadata.assignee=a,_.metadata.claim_principal=c,{changedFields:["assignee","claim_principal"],warnings:p}}});return u||await va({pmRoot:s,settings:o,principal:c,itemId:f.item.id}),{item:f.item,claimed_by:u&&m!==null?m:a,previous_assignee:m,forced:t,...u?{skipped:!0}:{},...p.length>0?{warnings:p}:{}}}async function uf(e,t,n={},r={}){let s=Fw(n.maxAttempts),o=await A(T(process.cwd(),t.path)),i={...n,author:R(n.author,o.author_default)},a=await Zn({...r,callerAuthor:i.author,limit:String(s)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return $w(c.slice(0,s),e,t,i)}function Fw(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new l("--max-attempts must be an integer from 1 to 100",d.USAGE);return t}async function $w(e,t,n,r={},s=oo){let o=0;for(let a of e){o+=1;try{let c=await s(a.id,t,n,r),m={...c,recommendation:a,attempts:o,available:!0};if(!c.skipped)return m}catch(c){if(!mf(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:R(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:o,warnings:[lf]};let i=o===0;throw new l(i?"No actionable items matched the selection filters":"No actionable item remained available to claim",i?d.NOT_FOUND:d.CONFLICT,{code:lf,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 io(e,t,n,r={}){let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=R(r.author,o.author_default),a=fn(i),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await Y({pmRoot:s,settings:o,id:e,op:"release",author:i,message:r.message,force:t,bypassAssigneeConflict:c,mutate(p){return m=p.metadata.assignee??null,!m&&!p.metadata.claim_principal?{changedFields:[]}:(delete p.metadata.assignee,delete p.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(p){nr(p,{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."]})}return await ka({pmRoot:s,principal:a,itemId:u.item.id}),{item:u.item,released_by:i,previous_assignee:m,forced: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]="a7ae3c89-b50b-5e4f-8273-8318bc976d84")}catch{}})();var Mw=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function pf(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 La(e,t){return Fa(e,t,{operation:"close"})}function Fa(e,t,n){let r=pf(e);if(!t||r.closeReason!==void 0)return r;let s=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",d.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:s,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 $a(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,s=e.dependencies??[],o=s.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"&&o.length>0){let m=s.filter(u=>u.kind!=="blocked_by");m.length>0?e.dependencies=m:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...o.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]="83affe54-a56c-5d84-b6b0-9634d4238ff5")}catch{}})();var Dw=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function Uw(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new l(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,d.USAGE)}function Gw(e){let t=[];for(let n of Dw){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function jw(e,t,n){let r=new Set,s=t;for(;typeof s=="string"&&s.trim().length>0;){let o=s.trim();if(o===n)return!0;if(r.has(o))return!1;r.add(o),s=(await e(o))?.duplicate_of}return!1}function qw(e){return typeof e!="string"||e.trim().length===0}async function Kw(e,t,n,r){let s=n?.trim();if(!s)return;if(s===r)throw new l("An item cannot be closed as a duplicate of itself.",d.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let o=x(t,I()),i=new Map,a=async m=>{if(i.has(m))return i.get(m)??null;let u=await M(e,m,t.id_prefix,t.item_format,o.type_to_folder);if(!u)return i.set(m,null),null;let{document:p}=await K(u,{schema:t.schema});return i.set(m,p.metadata),p.metadata},c=await a(s);if(!c)throw new l(`Duplicate target "${s}" was not found. Create or locate the canonical item first.`,d.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 ${s}" --duplicate-of ${s}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await jw(a,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${s}" points back to "${r}".`,d.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new l(`Duplicate target "${s}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,d.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 zw(e,t,n){return e.filter(r=>r.parent===t&&!Oe(r.status,n)).map(r=>r.id).sort((r,s)=>r.localeCompare(s))}function Bw(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),s=qp(e),o=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:s.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(o)).filter(({blockerIds:a})=>a.every(c=>{if(c===o)return!0;let m=r.get(c);return m!==void 0&&Oe(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function Hw(e,t,n,r,s,o){let i=Bw(n,r,o),a=[];for(let c of i)try{let m=await Y({pmRoot:e,settings:t,id:c.id,op:"update",author:s,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(h=>{let y=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=o.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 Vw(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:s,key:o}of r){if(typeof s!="string")continue;let i=s.trim();i.length!==0&&(e[o]=i,n.push(o))}return n}function Ww(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:s,value:o}of r)qw(e[s])&&(e[s]=o,n.push(s));return n}function Yw(e,t,n,r){let s=[];if(t!=="off"){let o=Gw(e);if(o.length>0){let i=o.map(a=>a.label);if(t==="strict"){let a=o.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(m=>[m,"<value>"])];throw new l(`Cannot close item ${e.id}: missing ${i.join(", ")}. Populate fields or use --validate-close warn.`,d.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:hs(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."]})}s.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new l(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,d.USAGE);s.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return s}return n.length>0&&s.push(`closed_with_active_children:${e.id}:${n.join(",")}`),s}function Jw(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function Xw(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function Qw(e,t){if(Oe(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use --force to close again.`,d.CONFLICT);let n=Vw(e,t.options),r=Ww(e,t.duplicateOf),s=Yw(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let o=t.options.completedAt!==void 0||e.completed_at===void 0;o&&(e.completed_at=t.completedAt);let i=["status","closed_at",...o?["completed_at"]:[],...Jw(e,t.closeReason),...n];if(Lu(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(...Xw(e));let a=$a(e,t.lifecyclePolicy);return i.push(...a.changedFields),s.push(...a.warnings),{changedFields:i,...s.length>0?{warnings:s}:{}}}async function ff(e,t,n,r){let s=T(process.cwd(),r.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=j(o.schema),a=R(n.author,o.author_default),c=x(o,I()).type_to_folder,m=await M(s,e,o.id_prefix,o.item_format,c);if(!m)throw await it(s,e,o.id_prefix,c);let u=await Kw(s,o,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=La({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=Uw(n.validateClose)??o.governance.close_validation_default,h=await re(s,o.item_format,c,void 0,o.schema),y=zw(h,m.id,i),g=new Date().toISOString(),b=n.completedAt===void 0?g:Q(n.completedAt,new Date(g),"completed-at"),v=await Y({pmRoot:s,settings:o,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(E){return Qw(E.metadata,{pmRoot:s,statusRegistry:i,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:g,completedAt:b,lifecyclePolicy:p})}});return{item:v.item,changed_fields:v.changedFields,warnings:[...v.warnings,...await Hw(s,o,h,m.id,a,i)]}}function Tt(e,t,n,r){return ff(e,t,n,r)}import Zw from"fast-json-patch";import Ma 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]="353be665-9f67-5d0e-99c9-6bbb7e927e0b")}catch{}})();function ev(e,t){return ku(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function tv(e){let t=na(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:He(jt(t))}async function nv(e,t,n,r){let s=await M(e,t,n.id_prefix,n.item_format,r);if(s){let c=ke(e,s.id),m=await bu({pmRoot:e,settings:n,itemId:s.id,commandLabel:"restore"});return{id:s.id,historyPath:c,located:s,historyPolicyWarnings:m.warnings}}let o=_e(t,n.id_prefix),i=Zi(t),a=o===i?[o]:[o,i];for(let c of a){let m=ke(e,c);if(await k(m))return{id:c,historyPath:m,located:null,historyPolicyWarnings:[]}}throw new l(`Item ${t} not found`,d.NOT_FOUND)}function rv(e,t){let n=qt(e),r=qt(t),s=Zw.compare(n,r),o=new Set;for(let i of s){if(i.path==="/body"||i.path.startsWith("/body/")){o.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];o.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(o).sort((i,a)=>i.localeCompare(a))}async function sv(e){if(await q(e.subject.historyPath)!==e.historyRawBeforeLock)throw new l(`History for ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);let n=await M(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),r=n?await K(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==e.currentItemRawBeforeLock)throw new l(`Item ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);return{loadedItemUnderLock:r,existingItemPath:n?.itemPath??null}}function ov(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:tv(t),originalRaw:null}}function iv(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new l(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,d.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function av(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await me(e.existingItemPath,e.resolvedOriginalRaw),await Ma.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await me(e.existingItemPath,e.resolvedOriginalRaw);return}await Ma.rm(e.restoredItemPath,{force:!0})}async function cv(e){return[...await z({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 z({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 Bt(e,t,n,r){let s=T(process.cwd(),r.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=x(o,I()),a=await nv(s,e,o,i.type_to_folder),c=a.id,m=await q(a.historyPath),u=await bt(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let p=ev(t,u),f=Su(na(u,p.historyIndex),p),_=mu(f,{schema:o.schema});if(_.metadata.id!==c)throw new l(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let y=(a.located?await K(a.located,{schema:o.schema}):null)?.raw??null,g=R(n.author,o.author_default),b=await xe(s,c,o.locks.ttl_seconds,g,!!n.force,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let{loadedItemUnderLock:v,existingItemPath:E}=await sv({pmRoot:s,resolvedId:c,subject:a,settings:o,typeToFolder:i.type_to_folder,historyRawBeforeLock:m,currentItemRawBeforeLock:y}),N="toon",P=ov(v,u),$=iv({document:P.document,author:g,force:n.force,enforcement:o.governance.ownership_enforcement,resolvedId:c}),G=rv(P.document,_);await gs({pm_root:s,operation:"restore",before:P.document,after:_,changed_fields:G,sdk:As({pmRoot:s,settings:o,typeToFolder:i.type_to_folder})});let Ie=Me(_,{format:N,schema:o.schema}),ee=Mt(s,_.metadata.type,c,N,i.type_to_folder),pe=await gn(s,g),ie=[];try{await me(ee,Ie),E&&ee!==E&&await Ma.rm(E);let Pt=De({nowIso:S(),author:g,op:"restore",before:P.document,after:_,message:n.message});try{await wt(a.historyPath,Pt)}catch(ut){throw await av({existingItemPath:E,resolvedOriginalRaw:P.originalRaw,restoredItemPath:ee}),ut}ie=await yn({pmRoot:s,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:ee,previousItemPath:E??void 0,document:_})}finally{await pe()}let Xe=await cv({restoredItemPath:ee,historyPath:a.historyPath,before:P.document,after:_});mn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:P.document.metadata.status,status:_.metadata.status,previous:Gt(P.document.metadata,G),current:Gt(_.metadata,G),changed_fields:G});let ze=u[p.historyIndex];return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,entry_ts:ze.ts,entry_op:ze.op},changed_fields:G,warnings:[...a.historyPolicyWarnings,...$,...ie,...Xe]}}finally{await 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]="4da07a98-855e-59cf-a6a4-2f59a8b3c0bd")}catch{}})();var hf=1,Da="close-many",dv=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function lv(e,t){return Xn(e,t,{includePagination:!1})}function mv(e,t){return Xn(e,t)}function uv(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)}function pv(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(s=>s.trim().length>0)||(t[n]=r);return t}function fv(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new l("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",d.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 _v(e,t){let n=j(t.schema),r=x(t,I()),s=await re(e,t.item_format,r.type_to_folder,void 0,t.schema),o=new Map,i=new Map;for(let a of s){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),Oe(a.status,n)))continue;let c=o.get(a.parent);c?c.push(a.id):o.set(a.parent,[a.id])}for(let a of o.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:o,parentByChild:i}}function _f(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let s=0,o=t.get(e),i=[],a=new Set,c=!1;for(;o!==void 0&&!a.has(o);){let m=n?.get(o);if(m!==void 0){s+=m+1;break}a.add(o),i.push(o),s+=1,o=t.get(o)}if(o!==void 0&&a.has(o)&&(c=!0),!c){n?.set(e,s);for(let[m,u]of i.entries())n?.set(u,s-m-1)}return s}async function hv(e){let t=await Ns(e.pmRoot,Da,e.rollbackId,hf),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Ls(t.items,(s,o)=>Bt(s,o,{author:e.options.author,message:n,force:!0},e.global));return{...Ut({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 gv(e,t,n,r,s){return e.map(o=>{let i=(t.get(o.id)??[]).filter(c=>!n.has(c)),a=!gf(o,r,s);return{id:o.id,title:typeof o.title=="string"?o.title:"",status:o.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function yv(e){let t=await Ps(e.pmRoot,Da,e.checkpointId,{schema_version:hf,id:e.checkpointId,created_at:e.nowValue,author:R(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function bv(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 s=await Tt(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:s.changed_fields,...s.warnings&&s.warnings.length>0?{warnings:s.warnings}:{}}),n.push(r.id)}catch(s){t.push({id:r.id,status:"failed",error:dn(s)})}}return{rows:t,closedIds:n}}function wv(e){return typeof e.rollback=="string"?e.rollback:void 0}function vv(e,t){if(t.trim().length===0)throw new l("--rollback requires a checkpoint id",d.USAGE);if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(mv(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function kv(e){if(!lv(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${dv}). Refusing to match every item.`,d.USAGE)}function Sv(e,t){let n=new Map;return[...e].sort((r,s)=>{let o=_f(s.id,t,n)-_f(r.id,t,n);return o!==0?o:r.id.localeCompare(s.id)})}function gf(e,t,n){return n||!Oe(e.status,t)}function Ev(e,t,n){return new Set(e.filter(r=>gf(r,t,n)).map(r=>r.id))}async function Tv(e){kv(e.options);let t=j(e.settings.schema),n=fv(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,s=await Et(e.options.status,pv(e.options.list),e.global),{childrenByParent:o,parentByChild:i}=await _v(e.pmRoot,e.settings),a=Sv(s.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(p=>p.trim()).filter(p=>p.length>0))],m=new Set(a.map(p=>p.id)),u=Ev(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:s,matched:a,unmatchedIds:c.filter(p=>!m.has(p)),planRows:gv(a,o,u,t,r)}}function Av(e){return{outcome:"effect",exit_code:d.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.length>0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function Cv(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 yv({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 yf(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=e.dryRun===!0,o=wv(e);if(uv(e.list),o!==void 0)return vv(e,o),hv({pmRoot:n,rollbackId:o,options:e,global:t});let i=await Tv({pmRoot:n,settings:r,options:e,global:t});if(s)return Av(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=S(),m=Os(Da,c),u=await Cv({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 bv({matched:i.matched,closableIds:a,reason:i.reason,closeOptions:p,global:t}),h=f.filter(b=>b.status==="closed").length,y=f.filter(b=>b.status==="skipped").length,g=f.filter(b=>b.status==="failed").length;return{...Ut({applied:h,skipped:y,failed:g,unmatched:i.unmatchedIds.length}),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:h,skipped_count:y,failed_count:g,rows:f,ids:_,...i.unmatchedIds.length>0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}import{readFile as Rv}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]="a7687052-a04e-536e-ace5-a665ebd477e3")}catch{}})();async function Ua(e,t){let n=e.add!==void 0,r=e.stdin===!0,s=typeof e.file=="string",o=Number(n)+Number(r)+Number(s);if(o===0)return;if(o>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",d.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add")??"",emptyFlag:"--add"};if(r)return{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);try{return{value:await Rv(i,"utf8"),emptyFlag:"--file"}}catch(a){if(Na(a)&&$t(a))throw new l(`--file path not found: ${i}`,d.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${i}": ${c}`,d.USAGE)}}async function Iv(e,t){let n=e.edit,r=e.delete,s=n!==void 0,o=r!==void 0;if(s&&o)throw new l("Specify only one of --edit or --delete",d.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",d.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",d.USAGE);if(o){if(await Ua(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(s){let c=await Ua(e,t);if(c===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let i=await Ua(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 bf(e,t,n){let r=Ne(),s=await Iv(t,r),o=s.mode==="add"||s.mode==="edit",i=s.value??"";return Rn(e,t,n,{input:{...s,rawValue:t.add??i,value:o?Cn(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(s.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]="93184f29-f215-5413-9628-fb5b34523995")}catch{}})();async function wf(e,t,n){return Rn(e,t,n,{input:await so(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Cn(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]="ebd9f151-593f-5081-97da-d78f83de4914")}catch{}})();function xv(e){if(e===void 0)return;if(e.trim().length===0)throw new l("--add-json must contain a JSON value",d.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new l("--add-json must be valid JSON",d.USAGE,{code:"structured_event_json_invalid"})}return t}function Ov(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 Pv(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new l("--since must be a valid ISO timestamp",d.USAGE,{code:"structured_event_since_invalid"});return t}async function vf(e,t,n){let r=xv(t.addJson),s=[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&&s)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let o=r===void 0?void 0:J(r),i=[t.since,t.eventType].some(h=>h!==void 0),a=Pv(t.since),c=Hn(t.limit),m=await Rn(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await so(o===void 0?t:{add:o},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>Cn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:Ov(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(h=>{let y=[h.format==="json",h.data!==void 0].every(Boolean),g=[a===void 0,Date.parse(h.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),b=[!u,h.event_type===u].includes(!0);return[!i,[y,g,b].every(Boolean)].includes(!0)}),f=i?Pa(p,c):p,_=f.filter(h=>h.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]="f9c9b926-c912-548e-a9c7-64c2c69767cd")}catch{}})();function ao(e,t){if(!t&&/[:,=]/.test(e))throw new l(`Invalid --dep value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE)}function rr(e,t,n=oa()){for(let r of t??[])try{zd(e,r.id,r.kind,n)}catch(s){throw new l(dn(s),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function kf(e,t){return(await K(e,{schema:t})).document.metadata.created_at}async function Nv(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await M(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:kf(n,t.schema)}function Lv(e){let t=e.registry.require(e.dependency.kind);return new l(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,d.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 Fv(e){let t=e.dependencies.filter(s=>e.registry.resolve(s.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(s.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:s,located:o})=>o===null?[]:[[s,o]])),r=new Map(await Promise.all([...new Set(t.map(({id:s})=>s))].map(async s=>[s,await kf(n.get(s),e.context.schema)])));for(let s of e.holders){let o=await Nv(s,e.context);if(o!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(o),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw Lv({holder:s,dependency:i,sourceCreatedAt:o,targetCreatedAt:a,registry:e.registry})}}}async function Ht(e){let t=e.registry??oa(),n=(e.dependencies??[]).filter(i=>!zu(i.source_kind)),r=[...new Set(n.map(i=>i.id))],s=await Promise.all(r.map(async i=>({target:i,located:await M(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),o=s.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(o.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${o.length===1?"":"s"} not found: ${o.join(", ")}`,d.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:o,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 ${o.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:o,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${o[0]}" --limit 10`}});return await Fv({dependencies:n,missingTargets:o,resolutions:s,holders:e.holders??[],registry:t,context:e}),o.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]="dcbb6070-7457-5454-abf1-fa8153c8efd6")}catch{}})();function co(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function lo(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function mo(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Cr.includes(t))return t;let n=se(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new l("Confidence must be an integer 0..100 or one of low|med|medium|high",d.USAGE);return n}function uo(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new l("Regression must be one of true|false|1|0",d.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]="afc4f3d5-ba5e-5dd7-abc9-531b319cdb4e")}catch{}})();var $v=new Set(["none","null"]);function po(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 Ge(e){return e===void 0?!1:$v.has(e.trim().toLowerCase())}function fo(e,t,n){if(!Ge(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function ge(e,t,n){if(!e||e.length===0||!e.some(o=>Ge(o)))return;let s=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${s}`.trim(),d.USAGE)}function _o(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 l(`${n.valueFlag} entries must be strings.`,d.USAGE);let s=r;if(!s.some(a=>Ge(a)))continue;if(s.filter(a=>!Ge(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.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]="2fcfbe50-039b-5031-8b18-a208908a0d87")}catch{}})();function Ef(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,d.USAGE)}function Ga(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function ye(e,t,n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE);return e}var Tf=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Mv(e,t){return t==="defined"?e!==void 0:!!e}function Sf(e,t,n){if(!Mv(e,n))return;let r=se(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function Dv(e,t,n){let r=e?Q(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new l("--event recur_until must be at or after start",d.USAGE);return r}function Uv(e){return Array.from(new Set(Ga(e).map(t=>ye(t.toLowerCase(),Md,"event weekday")))).sort((t,n)=>ki(t)-ki(n))}function Gv(e){return Array.from(new Set(Ga(e).map(t=>{let n=se(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new l("--event recur_by_month_day values must be integers 1..31",d.USAGE);return n}))).sort((t,n)=>t-n)}function jv(e,t){return Array.from(new Set(Ga(e).map(n=>Q(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Af(e,t,n,r){let s=e.recur_freq?.trim(),o=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(![s,o,i,a,c,m,u].some(E=>E!==void 0))return;if(!s)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let f=ye(s.toLowerCase(),$d,"event recurrence frequency"),_=Sf(o,"recur_interval",r),h=Sf(i,"recur_count",r),y=Dv(a,t,n),g=Uv(c),b=Gv(m),v=jv(u,n);return{freq:f,interval:_,count:h,until:y,by_weekday:g.length>0?g:void 0,by_month_day:b.length>0?b:void 0,exdates:v.length>0?v: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]="8248687e-ba97-5e1b-afbf-a322a72eb1aa")}catch{}})();var Cf="--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.",qv="--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).",Kv=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,zv=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,If=1e3,ja=60*If,Bv=60*ja;function Rf(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new l(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,d.USAGE);return n.toISOString()}function Hv(e,t){let n=new Date(e),r=t.trim(),s=Kv.exec(r);if(s){let a=s[1]==="-"?-1:1,c=Number.parseInt(s[2],10)*a;return Rf(n.getTime()+c*ja,r)}let o=zv.exec(r);if(o){let[,a,c,m,u]=o;if(c||m||u){let f=a==="-"?-1:1,_=Number.parseInt(c??"0",10),h=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),g=_*Bv+h*ja+y*If;return Rf(n.getTime()+f*g,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return Q(i,n,"event.duration")}function xf(e,t,n,r){if(t&&n)throw new l(qv,d.USAGE);if(n){let o=Hv(e,n);if(o<e)throw new l(Cf,d.USAGE);return o===e?void 0:o}if(!t)return;let s=Q(t,r,"event.end");if(s<e)throw new l(Cf,d.USAGE);if(s!==e)return 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]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var Vv=["at","date","text","title"],Wv=["start","date","end","duration","title","description","location","timezone","all_day",...Tf],Yv=["key","value"];function Of(e,t){return t==="trimmed"?e?.trim():e}function Jv(e,t){return t==="defined"?e!==void 0:!!e}function ho(e,t,n){return e.map(r=>{let s=te(r,"--reminder");Ue(s,"--reminder",Vv);let o=Of(s.at??s.date,n.valueMode),i=Of(s.text??s.title,n.valueMode);if(!o||!i)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let a=i.trim();if(!a)throw new l("--reminder text must not be empty",d.USAGE);return{at:Q(o,t,"reminder.at"),text:a}})}function go(e,t,n){return e.map(r=>{let s=te(r,"--event");Ue(s,"--event",Wv);let o=(s.start??s.date)?.trim();if(!o)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let i=Q(o,t,"event.start"),a=s.end?.trim(),c=s.duration?.trim(),m=xf(i,a,c,t),u=s.title,p=s.description,f=s.location,_=s.timezone,h=u?.trim(),y=p?.trim(),g=f?.trim(),b=_?.trim(),v=[["title",u,h],["description",p,y],["location",f,g],["timezone",_,b]];for(let[$,G,Ie]of v)if(G!==void 0&&!Ie)throw new l(`--event ${$} must not be empty`,d.USAGE);let E=s.all_day?.trim(),N=Af(s,i,t,n.recurrenceEmptyNumericGuard),P=Jv(E,n.allDayEmptyGuard)?Ef(E,"--event all_day"):void 0;return{start_at:i,end_at:m,title:h,description:y,location:g,all_day:P,timezone:b,recurrence:N}})}function yo(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new l("--type-option values must not be empty",d.USAGE);let s,o;if(r.includes(",")||r.includes(`
|
|
5
|
-
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=
|
|
6
|
-
`)?!0:ek.test(e)}function wo(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!Qv.has(i)){r.push(s);continue}if(Object.hasOwn(n,i))throw new l(`${t} provides key "${s}" more than once after case normalization`,d.USAGE);n[i]=o}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(s=>`"${s}"`).join(", ")}. Allowed keys: ${Vt.join(", ")}.`,d.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new l(`${t} command and cmd must match when both are provided`,d.USAGE);let{cmd:s,...o}=n;return{...o,command:o.command??s}}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]="74163bed-a473-543e-ae6a-0d5091b3b3a9")}catch{}})();var Yt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Bs,np,"FORCE_COLOR"]),So=/^[A-Za-z_][A-Za-z0-9_]*$/,Wt=["schema","tracker","auto"];function sr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1);if(!So.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(Yt.has(i.toUpperCase()))throw new l(`${t} env_set key "${i}" is reserved for sandbox safety`,d.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function or(e,t){if(!e)return;let n=Sn(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,d.USAGE);for(let r of n){if(!So.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(Yt.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function Eo(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,d.USAGE)}function To(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Wt.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${Wt.join(", ")}`,d.USAGE)}function Jt(e){if(!e)return;let t=Sn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function xn(e,t,n){let r=Jt(e);if(!(!r||r.length===0)){for(let s of r)try{new RegExp(s,"m")}catch(o){throw new l(`${t} ${n} includes invalid regex "${s}": ${o instanceof Error?o.message:String(o)}`,d.USAGE)}return r}}function Ao(e,t){if(!e)return;let n=se(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,d.USAGE);return n}function Co(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function Ro(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,d.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${i}" must be numeric`,d.USAGE);r[i]=c}return Object.keys(r).length>0?r:void 0}var tk=new Set(Vt);function Io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nk(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!tk.has(i)){r.push(s);continue}if(Object.hasOwn(n,i))throw t(`provides key "${s}" more than once after case normalization`);n[i]=o}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(s=>`"${s}"`).join(", ")}. Allowed keys: ${Vt.join(", ")}.`);return n}function In(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 vo(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let s=typeof r=="string"?[r]:r;if(!Array.isArray(s)||s.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let o=s.filter(i=>i.length>0);return o.length>0?o:void 0}function Nf(e,t,n){let r=vo(e,t,n);if(r){for(let s of r)try{new RegExp(s,"m")}catch(o){throw n(`field "${t}" includes invalid regex "${s}": ${o instanceof Error?o.message:String(o)}`)}return r}}function ko(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 rk(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let s=n===void 0?void 0:ko(n,"timeout_seconds",t),o=r===void 0?void 0:ko(r,"timeout",t);if(s!==void 0&&o!==void 0&&s!==o)throw t("timeout and timeout_seconds must match when both are provided");let i=s??o;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function sk(e,t){let n=In(e,"scope",t);if(n===void 0)return"project";if(!Ze.includes(n))throw t(`field "scope" must be one of: ${Ze.join(", ")}`);return n}function ok(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Io(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[s,o]of Object.entries(n)){if(typeof o!="string")throw t(`field "env_set" value for "${s}" must be a string`);if(!So.test(s))throw t(`field "env_set" key "${s}" is invalid`);if(Yt.has(s.toUpperCase()))throw t(`field "env_set" key "${s}" is reserved for sandbox safety`);r[s]=o}return Object.keys(r).length>0?r:void 0}function ik(e,t){let n=vo(e,"env_clear",t);if(n){for(let r of n){if(!So.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(Yt.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function ak(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 ck(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=ko(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 dk(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Io(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[s,o]of Object.entries(n)){if(s.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean")throw t(`field "assert_json_field_equals" value for "${s}" must be a string, number, or boolean`);r[s]=String(o)}return Object.keys(r).length>0?r:void 0}function lk(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Io(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[s,o]of Object.entries(n)){if(s.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[s]=ko(o,`assert_json_field_gte.${s}`,t)}return Object.keys(r).length>0?r:void 0}function mk(e,t,n){let r=p=>new l(`${n} ${t} ${p}`,d.USAGE);if(!Io(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Vt.join(", ")}.`);let s=nk(e,r),o=In(s,"command",r),i=In(s,"cmd",r);if(o!==void 0&&i!==void 0&&o!==i)throw r("command and cmd must match when both are provided");let a=o??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=In(s,"path",r),m=In(s,"pm_context_mode",r);if(m!==void 0&&!Wt.includes(m))throw r(`field "pm_context_mode" must be one of: ${Wt.join(", ")}`);let u=In(s,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:sk(s,r),timeout_seconds:rk(s,r),pm_context_mode:m,env_set:ok(s,r),env_clear:ik(s,r),shared_host_safe:ak(s,"shared_host_safe",r),assert_stdout_contains:vo(s,"assert_stdout_contains",r),assert_stdout_regex:Nf(s,"assert_stdout_regex",r),assert_stderr_contains:vo(s,"assert_stderr_contains",r),assert_stderr_regex:Nf(s,"assert_stderr_regex",r),assert_stdout_min_lines:ck(s,r),assert_json_field_equals:dk(s,r),assert_json_field_gte:lk(s,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function Lf(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,d.USAGE);let r;try{r=JSON.parse(n)}catch(o){throw new l(`${t} value is not valid JSON: ${o instanceof Error?o.message:String(o)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let s=Array.isArray(r)?r:[r];if(s.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return s.map((o,i)=>mk(o,s.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]="0062e981-158a-5e6a-b028-6c7cef0f59ba")}catch{}})();var qa=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Ka=[{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"}],Ff=[...qa,...Ka],xo=[{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 Oo(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 s=r.trim().toLowerCase();if(!s)throw new l("--unset values must not be empty",d.USAGE);if(Ge(s))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let o=e.resolveDefinition(s);if(!o)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(o.metadataKey),n.add(o.optionKey)}return{metadataKeys:t,optionKeys:n}}function Po(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let s=n.command_to_fields?.get(t)??[];for(let o of s){if(o.allow_unset===!1)continue;let i=new Set;if(typeof o.key=="string"&&o.key.length>0&&i.add(o.key.toLowerCase()),typeof o.metadata_key=="string"&&o.metadata_key.length>0&&i.add(o.metadata_key.toLowerCase()),typeof o.cli_flag=="string"&&o.cli_flag.length>0&&(i.add(o.cli_flag.replaceAll("-","_").toLowerCase()),i.add(o.cli_flag.toLowerCase())),Array.isArray(o.cli_aliases))for(let a of o.cli_aliases)typeof a!="string"||a.length===0||(i.add(a.replaceAll("-","_").toLowerCase()),i.add(a.toLowerCase()));if(i.has(r))return{optionKey:o.key,metadataKey:o.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]="002f45a2-edc3-5aa0-9af8-d9b1dfecc097")}catch{}})();var uk={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 pk(e){return uk[e]}function za(e){return pk(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]="7d69bb56-9fab-5059-9357-5b6bea2078b9")}catch{}})();var fk=["strict","progressive"],_k=["lightweight"],Uf=new Set(["Reminder","Meeting","Event"]),hk=new Set(["author","created_at","text"]),Ha=[...Ff,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...xo],gk=(()=>{let e=new Map;for(let t of Ha)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),No=new Map(Ha.map(e=>[e.optionKey,e.canonical])),yk=Ha.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function bk(e,t){let n=ne(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function wk(e,t){let n=e.default_status;if(n!==void 0){let r=ne(n,t);if(r)return r}return t.open_status}function Ba(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}var vk=po();function Gf(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=s=>{let o=t.unset?[...t.unset]:[];o.includes(s)||o.push(s),t.unset=o};Ge(t.template)&&(t.template=void 0);let r=new Set([...No.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Ge(o))continue;let i=s==="rank"?"order":No.get(s)??s;n(i),t[s]=void 0}return _o(t,vk)}function ce(e){if(e!==void 0)return e}function kk(e,t){return Oo({raw:e,supportedFields:yk,resolveDefinition:n=>gk.get(n)??Po(n,"create",t)})}var $f=["id","kind","type","author","created_at","source_kind"],Lo=["path","scope","note"];function Sk(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let i=o.trim(),a=Va(i,$f);ao(i,a);let c=a?te(o,"--dep"):{id:i,kind:"related"};a&&Ue(c,"--dep",$f);let m=ce(c.id),u=Ek(ce(c.kind??c.type));if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",d.USAGE);if(m.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=Vn(ce(c.source_kind)),f=ce(c.author);return{id:Wn(m,n,p),kind:ye(u,Ft,"dependency kind"),created_at:Ba(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function Ek(e){return typeof e=="string"?Nr(e)??e.trim():e}function Va(e,t){if(e.startsWith("```")||e.includes(`
|
|
7
|
-
`))return!0;let n=t.map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${n})\\s*[:=]`,"i").test(e)?!0:qs(e)}function Qt(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(ge(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 l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:a}},m;try{m=te(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!hk.has(f)).length>0)return{created_at:Ba(m.created_at,n),author:ce(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:Ba(m.created_at,n),author:ce(m.author)??r,text:p}}),explicitEmpty:!1})}function Wa(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),s=Va(r,Lo),o=s?te(n,"--file"):{path:r};if(s&&Ue(o,"--file",Lo),!o.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:o.path,scope:ye(o.scope??"project",Ze,"file scope"),note:ce(o.note)}}),explicitEmpty:!1})}function Ya(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),s=bo(r)?wo(te(n,"--test"),"--test"):{command:r},o=ce(s.command),i=ce(s.path);if(!o)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let a=ce(s.timeout_seconds),c=ce(s.timeout);if(a&&c&&a!==c)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let m=a??c;return{command:o,path:i,scope:ye(s.scope??"project",Ze,"test scope"),timeout_seconds:m?se(m,"timeout_seconds"):void 0,pm_context_mode:To(s.pm_context_mode,"--test"),env_set:sr(s.env_set,"--test"),env_clear:or(s.env_clear,"--test"),shared_host_safe:Eo(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Jt(s.assert_stdout_contains),assert_stdout_regex:xn(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Jt(s.assert_stderr_contains),assert_stderr_regex:xn(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Ao(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:Co(s.assert_json_field_equals,"--test"),assert_json_field_gte:Ro(s.assert_json_field_gte,"--test"),note:ce(s.note)}}),explicitEmpty:!1})}function Ja(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),s=Va(r,Lo),o=s?te(n,"--doc"):{path:r};if(s&&Ue(o,"--doc",Lo),!o.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:o.path,scope:ye(o.scope??"project",Ze,"doc scope"),note:ce(o.note)}}),explicitEmpty:!1})}function Tk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--reminder","Use --clear-reminders to clear reminders."),{values:ho(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function Ak(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--event","Use --clear-events to clear linked events."),{values:go(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function Ck(e,t,n,r=[]){let s=[...Rr.filter(o=>e[o]!==void 0),...r.filter(o=>e[o]!==void 0),...t.length>0?["body"]:[],...n.map(o=>`unset:${o}`)];return Array.from(new Set(s))}function Rk(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Mf(e,t,n){let r=Dn("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function Ik(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 jf(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 xk(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Mf(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Mf(r,e.name,"required_create_repeatables"));return n}function Ok(e,t,n,r){for(let s of e)if(!(!jf(t,s)&&!n.has(s)))throw new l(`Option ${fe("create",s)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function Pk(e,t,n){if(t!=="strict")return;let r=e.filter(o=>n.has(o)&&!za(o));if(r.length===0)return;let s=[...new Set(r.map(o=>fe("create",o)))].sort((o,i)=>o.localeCompare(i));throw new l(`Strict create mode requires concrete values for ${s.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function Nk(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:yo(e),explicitEmpty:!1})}async function Lk(e){let t=Ne();return{...e,body:await t.resolveValue(e.body,"--body"),dep:await t.resolveList(e.dep,"--dep"),comment:await t.resolveList(e.comment,"--comment"),note:await t.resolveList(e.note,"--note"),learning:await t.resolveList(e.learning,"--learning"),file:await t.resolveList(e.file,"--file"),test:await t.resolveList(e.test,"--test"),doc:await t.resolveList(e.doc,"--doc"),reminder:await t.resolveList(e.reminder,"--reminder"),event:await t.resolveList(e.event,"--event"),typeOption:await t.resolveList(e.typeOption,"--type-option"),field:await t.resolveList(e.field,"--field")}}function Fk(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${fk.join(", ")}`,d.USAGE)}function $k(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new l("--schedule-preset must not be empty",d.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new l(`Invalid --schedule-preset value "${e}". Allowed: ${_k.join(", ")}`,d.USAGE)}function Mk(e,t,n){let r=Fk(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",d.USAGE);return"progressive"}function Dk(e,t,n,r){let s=e.name,o=Ik(t),i=xk(e,n),a=cn(e,"create",i);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);Ok(a.disabled,o,r,s),Pk(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&za(u)?!0:jf(o,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>fe("create",u)))].sort((u,p)=>u.localeCompare(p))}var qf=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function Uk(e,t){let n=[];for(let r of e){let s=r.match(qf);s&&s[2]===t&&n.push(s[1])}return[...new Set(n)].sort((r,s)=>r.localeCompare(s))}function Gk(e,t){return e.filter(n=>{let r=n.match(qf);return!r||r[2]!==t})}function jk(e,t,n,r){let s=Gk(e,t);if(s.length===0)return;let o=Kf(n,[],[],r.open_status);throw new l(s.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[o],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function qk(e,t){let r=e.options.find(s=>s.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function Kk(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 Kf(e,t,n,r){let s=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],o=["--status","--priority","--message"],i=[...new Set([...o,...t])],a=new Set(["--title","--description","--type"]);for(let c of i)a.has(c)||(s.push(...Kk(c,e.name,r)),a.add(c));for(let c of n){let m=qk(e,c);s.push("--type-option",`${c}=${m}`)}return s.join(" ")}function Xa(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new l("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",d.USAGE):new l('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.',d.USAGE):new l(`Missing required option ${t}`,d.USAGE);return n}function zk(e){return kn(e)}function Bk(e,t){let n={};for(let[r,s]of Object.entries(e))n[r]=Array.isArray(s)?[...s]:s;for(let[r,s]of Object.entries(t))s!==void 0&&(n[r]=Array.isArray(s)?[...s]:s);return n}function Hk(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Vk(){let e=I();return e?e.commands.some(t=>t.action==="templates-show"||Hk(t.command)==="templates show"):!1}function Wk(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new l(`Templates package returned invalid payload for template "${t}". Expected an options object.`,d.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Templates package returned invalid options for template "${t}".`,d.GENERIC_FAILURE);let r={};for(let[s,o]of Object.entries(n)){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"){r[s]=o;continue}if(Array.isArray(o)&&o.every(i=>typeof i=="string")){r[s]=[...o];continue}throw new l(`Templates package returned unsupported option value for "${s}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function Yk(e,t,n){if(!Vk())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await ys({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let s=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${s}`,d.USAGE)}return Wk(r.result,e)}function Jk(e){return k(C(e)).then(t=>{if(!t)throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)})}function B(e,t,n){return e.has(t)||n===void 0?void 0:ce(n)}function Xt(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var Xk=new Set(["milestone","meeting","reminder","event"]);function zf(e,t,n,r){let s=t!==void 0,o=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return Xk.has(e.toLowerCase())&&!s&&!o&&!i}function Qk(e,t,n,r,s){let o=[];return e.toLowerCase()==="event"&&(s===void 0||s.length===0)&&o.push(`event_without_schedule:${t}:no_time_set`),zf(e,n,r,s)&&o.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)`),o}async function Zk(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let s=await bs(r);return s===void 0?{parent:e,parentSource:void 0}:{parent:s,parentSource:"focus"}}async function eS(e,t,n,r,s,o){let i=Ms(s);if(Us(r,i,t.id_prefix),await M(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let c=_e(i,t.id_prefix);return{parent:i,warnings:Ds(c,o).warnings}}async function tS(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await eS(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function nS(e){if(e.explicitId===void 0)return Bn(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 l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||xu(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=_e(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",d.USAGE);return n}function Df(e,t,n,r,s){let o=B(e,t,n);if(o===void 0)return{value:void 0,warnings:[]};let i=Ks(r,o,s);return{value:i.value,warnings:i.warnings}}async function rS(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:s,blockedBy:o,status:i,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(o===void 0)return{dependencyValues:u,status:i};let p=_e(o,n.id_prefix),f=await M(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 h=s.blocked_statuses.has("blocked")?"blocked":[...s.blocked_statuses].sort((y,g)=>y.localeCompare(g))[0]??s.open_status;return{dependencyValues:u,status:h}}function sS(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let s=t.governance.create_default_type?.trim();if(s&&s.length>0&&ue(s,n)){e.type=s;return}ue("Task",n)&&(e.type="Task")}function oS(e,t){return e.options.filter(n=>Dn("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function iS(e,t,n,r,s){let o=e,i=[];if(o.template!==void 0){let h=o.template.trim();if(h.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let y=await Yk(h,t,n);o=Gf(Bk(y,o))}if(o.type===void 0&&sS(o,r,s),o.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let a=ue(o.type,s);if(!a){let h=Pu(o.type),y=h?ue(h,s):void 0;if(y)i.push(`type_coercion:${o.type.trim()}:${y}`),o.type=y,a=y;else throw new l(gt(o.type,s.types,yt(n,r.schema)),d.USAGE)}let c=Or(a,s);if(!c)throw new l(`Invalid type value "${o.type}"`,d.USAGE);let m=c.name,u=oS(c,o),p=u.map(h=>`${h.key}=${String(o[h.key])}`);if(p.length>0){o.typeOption=[...p,...o.typeOption??[]];for(let h of u)delete o[h.key]}let f=$k(o.schedulePreset);if(f!==void 0&&!Uf.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=Mk(o.createMode,f,r.governance.create_mode_default);return{resolvedOptions:o,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function aS(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),s=[{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 o of s)if(o.enabled){if(o.values&&o.values.length>0)throw new l(`Cannot combine ${o.clearFlag} with ${o.valueFlag}`,d.USAGE);n.add(o.metadataKey),r.add(o.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function cS(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,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=No.get(r)??r;throw new l(`Cannot combine --unset ${o} with ${fe("create",r)}`,d.USAGE)}}function dS(e){let t=(n,r)=>{let s=No.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;fo(n,fe("create",r),o)};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 lS(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,d.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,d.USAGE)}function mS(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:s,openStatus:o,type:i,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(_=>{let h=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${h}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),u=[Kf(n,r,s,o),...m.map(_=>_.example)].join(" "),p=[`Run "pm create --help --type ${i}" for type-aware required option guidance.`];t.includes("--title")&&p.push('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".'),Uf.has(i)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&p.push(`Required custom field formats: ${m.map(_=>_.description).join("; ")}.`);let f=t.length===1?`Missing required option ${t[0]} for type "${i}"`:`Missing required options ${t.join(", ")} for type "${i}"`;throw new l(f,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${i}" in one invocation.`,examples:[u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:["--create-mode progressive",...t]}:void 0})}function uS(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?St(t.tags):[];return wn(n,t.addTags)}function pS(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new l("--order and --rank must match when both are provided",d.USAGE);let n=t.order??t.rank,r=Xt(e,"order",n,s=>se(s,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function fS(e,t,n,r,s,o){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",d.USAGE);let i=e!==t.close_status?void 0:r.completedAt===void 0?o:Q(r.completedAt,new Date(o),"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:s}:{explicit:r.closeReason};return{closeReason:Fa(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function _S(e){let{pmRoot:t,type:n,id:r,settings:s,typeRegistry:o,author:i,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=Mt(t,n,r,s.item_format,o.type_to_folder),g=ke(t,r),b=await xe(t,r,s.locks.ttl_seconds,i,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),v=[];try{let E=c.metadata.dependencies&&c.metadata.dependencies.length>0?await re(t,s.item_format,o.type_to_folder,void 0,s.schema):void 0;if(await M(t,r,s.id_prefix,s.item_format,o.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);await gs({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:As({pmRoot:t,settings:s,typeToFolder:o.type_to_folder})});let P=await gn(t,i,{required:s.governance.duplicate_detection_mode==="strict"&&h!==!0}),$=[];try{s.governance.duplicate_detection_mode==="strict"&&h!==!0&&await An(_,{pmRoot:t,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1}),await me(y,Me(c,{format:s.item_format,schema:s.schema,extensionFieldNames:a}));try{let G=De({nowIso:f,author:i,op:"create",before:m,after:c,message:u});await wt(g,G)}catch(G){throw await an(y),G}$=await yn({pmRoot:t,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:y,document:c})}finally{await P()}v=[...E?Qs(E,[...E,c.metadata],r):[],...$,...await z({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await z({path:g,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],mn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Gt(c.metadata,p),changed_fields:p})}finally{await b()}return v}async function At(e,t){let n=Gf(await Lk(e)),r=T(process.cwd(),t.path);await Jk(r);let s=await A(r),o=j(s.schema),i=Be(s.schema),a=x(s,I()),c=await iS(n,t,r,s,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=kk(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=aS(n,f);cS(n,f),dS(n);let y=Dk(m,n,p,h),g=S(),b=R(ce(n.author),s.author_default),v=Sk(n.dep,g,s.id_prefix,b),E=Qt("--comment",n.comment,g,b),N=Qt("--note",n.note,g,b),P=Qt("--learning",n.learning,g,b),$=Wa(n.file),G=Ya(n.test),Ie=Ja(n.doc),ee=Tk(n.reminder,g),pe=Ak(n.event,g),ie=Nk(n.typeOption),Xe=Un(u,ie.values,a),ze=I(),Pt=ft(ze),ut=Ir(n.field,ze),Nt=eu(n,i,u),ui=new Set(Nt.missing_required_flags),wr=i.definitions.filter(H=>ui.has(`--${H.cli_flag}`));lS(ut,Nt,f);let Qe=Uk(Xe.errors,u),yd=Qe.map(H=>`--type-option ${H}=<value>`),vr=[...new Set([...y,...yd,...Nt.missing_required_flags])].sort((H,wi)=>H.localeCompare(wi));mS({combinedMissingFlags:vr,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:Qe,openStatus:o.open_status,type:u,createMode:p,missingRequiredRuntimeFields:wr}),jk(Xe.errors,u,m,o);let ae=await nS({pmRoot:r,settings:s,typeRegistry:a,explicitId:n.id}),ve=n.status!==void 0?bk(n.status,o):wk(m,o),pi=n.priority!==void 0?zk(n.priority):2,O=f.metadataKeys,kr=uS(O,n),fi=Xt(O,"deadline",n.deadline,H=>Q(H,new Date(g),"deadline")),nb=Xt(O,"estimated_minutes",n.estimatedMinutes,H=>vn(H,"estimated-minutes")),rb=B(O,"acceptance_criteria",n.acceptanceCriteria),sb=B(O,"definition_of_ready",n.definitionOfReady),ob=pS(O,n),ib=B(O,"goal",n.goal),ab=B(O,"objective",n.objective),cb=B(O,"value",n.value),db=B(O,"impact",n.impact),lb=B(O,"outcome",n.outcome),mb=B(O,"why_now",n.whyNow),ub=B(O,"assignee",n.assignee),pb=O.has("author")?void 0:ce(n.author)??b,fb=B(O,"parent",n.parent),bd=await Zk(fb,n,O,r),_i=bd.parent,_b=bd.parentSource,hb=B(O,"reviewer",n.reviewer),gb=Xt(O,"risk",n.risk,H=>ye(co(H),sn,"risk")),yb=Xt(O,"confidence",n.confidence,H=>mo(H)),bb=n.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,wd=s.validation.sprint_release_format,Lt=[...c.warnings,...Qk(u,ae,fi,ee.values,pe.values)],vd=await tS({itemId:ae,parent:_i,pmRoot:r,settings:s,typeRegistry:a,policy:bb});_i=vd.parent,Lt.push(...vd.warnings);let kd=Df(O,"sprint",n.sprint,"sprint",wd),wb=kd.value;Lt.push(...kd.warnings);let Sd=Df(O,"release",n.release,"release",wd),vb=Sd.value;Lt.push(...Sd.warnings);let Ed=B(O,"blocked_by",n.blockedBy),Td=await rS({pmRoot:r,settings:s,typeRegistry:a,statusRegistry:o,blockedBy:Ed,dependencyValues:v.values,status:ve,statusExplicit:n.status!==void 0,nowValue:g,author:b}),hi=Td.dependencyValues;rr(ae,hi),Lt.push(...await Ht({pmRoot:r,dependencies:hi,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:ae,createdAt:g}],schema:s.schema})),ve=Td.status;let kb=B(O,"blocked_reason",n.blockedReason),Sb=B(O,"unblock_note",n.unblockNote),Eb=B(O,"reporter",n.reporter),Tb=Xt(O,"severity",n.severity,H=>ye(lo(H),on,"severity")),Ab=B(O,"environment",n.environment),Cb=B(O,"repro_steps",n.reproSteps),Ad=B(O,"resolution",n.resolution),Rb=B(O,"expected_result",n.expectedResult),Ib=B(O,"actual_result",n.actualResult),xb=B(O,"affected_version",n.affectedVersion),Ob=B(O,"fixed_version",n.fixedVersion),Pb=B(O,"component",n.component),Nb=Xt(O,"regression",n.regression,H=>uo(H)),Lb=B(O,"customer_impact",n.customerImpact),gi=Xa(n.title,"--title"),yi=n.description??"",Sr=n.body??"",Cd=await An({title:gi,description:yi,body:Sr},{pmRoot:r,mode:s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Lt.push(...Zs(Cd));let bi=fS(ve,o,s,n,Ad,g),Fb=bi.closeReason,$b=ve===o.close_status?g:void 0,Mb=bi.completedAt;Lt.push(...bi.warnings);let Er=Xi({id:ae,title:gi,description:yi,type:u,type_options:Xe.normalized,status:ve,closed_at:$b,completed_at:Mb,close_reason:Fb,priority:pi,tags:kr,created_at:g,updated_at:g,deadline:fi,assignee:ub,author:pb,estimated_minutes:nb,acceptance_criteria:rb,definition_of_ready:sb,order:ob,goal:ib,objective:ab,value:cb,impact:db,outcome:lb,why_now:mb,parent:_i,reviewer:hb,risk:gb,confidence:yb,sprint:wb,release:vb,blocked_by:Ed,blocked_reason:kb,unblock_note:Sb,reporter:Eb,severity:Tb,environment:Ab,repro_steps:Cb,resolution:Ad,expected_result:Rb,actual_result:Ib,affected_version:xb,fixed_version:Ob,component:Pb,regression:Nb,customer_impact:Lb,dependencies:hi,comments:E.values,notes:N.values,learnings:P.values,files:$.values,tests:G.values,docs:Ie.values,reminders:ee.values,events:pe.values,...ut,...Nt.values});try{xr(Er,ze)}catch(H){throw new l(H instanceof Error?H.message:"Invalid extension item field values",d.USAGE)}let Db=He({metadata:Er,body:Sr},{schema:s.schema,extensionFieldNames:Pt}),Ub={metadata:{},body:""},Rd=[..._].sort((H,wi)=>H.localeCompare(wi)),Gb=Rk(n.message,Rd),Id=Ck(Er,Sr,Rd,[...Object.keys(ut),...Object.keys(Nt.values??{})]),jb=await _S({pmRoot:r,type:u,id:ae,settings:s,typeRegistry:a,author:b,extensionFieldNames:Pt,afterDocument:Db,beforeDocument:Ub,historyMessage:Gb,changedFields:Id,nowValue:g,similarityCandidate:{title:gi,description:yi,body:Sr},allowDuplicate:n.allowDuplicate}),xd=structuredClone(Er);p==="strict"&&_.has("dependencies")&&(xd.dependencies=[]);let qb=Pf(ae,u,ve,o);return zf(u,fi,ee.values,pe.values)&&du(`[pm] warning: ${u} '${ae}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${ae} --deadline <ISO>' or 'pm update ${ae} --event "start=<ISO>,end=<ISO>"'.`),{item:xd,changed_fields:Id,warnings:[...Lt,...jb],...Object.fromEntries([["parent_source",_b],["next_transition",qb],["similarity_advisory",Cd]].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]="a421c150-13a9-5334-85a4-5b3199a5d2c7")}catch{}})();var tc=[...qa,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Ka,...xo],hS=(()=>{let e=new Map;for(let t of tc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Fo=new Map(tc.map(e=>[e.optionKey,e.canonical])),gS=tc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),yS=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),bS=po({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function wS(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=s=>{let o=t.unset?[...t.unset]:[];o.includes(s)||o.push(s),t.unset=o},r=new Set([...Fo.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Ge(o))continue;let i=s==="rank"?"order":Fo.get(s)??s;n(i),t[s]=void 0}return _o(t,bS)}function Zf(e,t,n=[]){return Oo({raw:e,supportedFields:gS,resolveDefinition:r=>{let s=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return hS.get(r)??Po(r,"update",t)??(s?{optionKey:"field",metadataKey:s}:void 0)}})}var Bf=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 Hf(e){let t=e.disallowedFlags.flatMap(r=>{let s=Bf.get(r);return s?[s(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let s=Bf.get(r);return s?[`Replace ${r} with: ${s(e.id)}`]:[]});return new l(e.message,d.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function vS(e,t,n){let r=t.ownershipMetadataBypass===!0,s=t.ownershipDependencyBypass===!0;if(!r&&!s)return;if(r&&s)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let o=(c,m,u)=>{c&&u.push(m)};if(s){let c=[];if(o(t.title!==void 0,"--title",c),o(t.description!==void 0,"--description",c),o(t.body!==void 0,"--body",c),o(t.status!==void 0,"--status",c),o(t.closeReason!==void 0,"--close-reason",c),o(t.priority!==void 0,"--priority",c),o(t.type!==void 0,"--type",c),o(t.tags!==void 0,"--tags",c),o(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),o(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),o(t.deadline!==void 0,"--deadline",c),o(t.estimatedMinutes!==void 0,"--estimate",c),o(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),o(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),o(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),o(t.definitionOfReady!==void 0,"--definition-of-ready",c),o(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),o(t.goal!==void 0,"--goal",c),o(t.objective!==void 0,"--objective",c),o(t.value!==void 0,"--value",c),o(t.impact!==void 0,"--impact",c),o(t.outcome!==void 0,"--outcome",c),o(t.whyNow!==void 0,"--why-now",c),o(t.assignee!==void 0,"--assignee",c),o(t.parent!==void 0,"--parent",c),o(t.reviewer!==void 0,"--reviewer",c),o(t.risk!==void 0,"--risk",c),o(t.confidence!==void 0,"--confidence",c),o(t.sprint!==void 0,"--sprint",c),o(t.release!==void 0,"--release",c),o(t.blockedBy!==void 0,"--blocked-by",c),o(t.blockedReason!==void 0,"--blocked-reason",c),o(t.unblockNote!==void 0,"--unblock-note",c),o(t.reporter!==void 0,"--reporter",c),o(t.severity!==void 0,"--severity",c),o(t.environment!==void 0,"--environment",c),o(t.reproSteps!==void 0,"--repro-steps",c),o(t.resolution!==void 0,"--resolution",c),o(t.expectedResult!==void 0,"--expected-result",c),o(t.actualResult!==void 0,"--actual-result",c),o(t.affectedVersion!==void 0,"--affected-version",c),o(t.fixedVersion!==void 0,"--fixed-version",c),o(t.component!==void 0,"--component",c),o(t.regression!==void 0,"--regression",c),o(t.customerImpact!==void 0,"--customer-impact",c),o(t.depRemove!==void 0,"--dep-remove",c),o(t.replaceDeps===!0,"--replace-deps",c),o(t.replaceTests===!0,"--replace-tests",c),o(t.replaceFiles===!0,"--replace-files",c),o(t.replaceDocs===!0,"--replace-docs",c),o(t.comment!==void 0,"--comment",c),o(t.note!==void 0,"--note",c),o(t.learning!==void 0,"--learning",c),o(t.file!==void 0,"--file",c),o(t.test!==void 0,"--test",c),o(t.doc!==void 0,"--doc",c),o(t.reminder!==void 0,"--reminder",c),o(t.event!==void 0,"--event",c),o(t.typeOption!==void 0,"--type-option",c),o(t.clearDeps===!0,"--clear-deps",c),o(t.clearComments===!0,"--clear-comments",c),o(t.clearNotes===!0,"--clear-notes",c),o(t.clearLearnings===!0,"--clear-learnings",c),o(t.clearFiles===!0,"--clear-files",c),o(t.clearTests===!0,"--clear-tests",c),o(t.clearDocs===!0,"--clear-docs",c),o(t.clearReminders===!0,"--clear-reminders",c),o(t.clearEvents===!0,"--clear-events",c),o(t.clearTypeOptions===!0,"--clear-type-options",c),o(t.force===!0,"--force",c),o(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw Hf({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=[];o(t.status!==void 0,"--status",i),o(t.closeReason!==void 0,"--close-reason",i),o(t.assignee!==void 0,"--assignee",i),o(t.parent!==void 0,"--parent",i),o(t.blockedBy!==void 0,"--blocked-by",i),o(t.blockedReason!==void 0,"--blocked-reason",i),o(t.unblockNote!==void 0,"--unblock-note",i),o(t.dep!==void 0,"--dep",i),o(t.depRemove!==void 0,"--dep-remove",i),o(t.replaceDeps===!0,"--replace-deps",i),o(t.replaceTests===!0,"--replace-tests",i),o(t.replaceFiles===!0,"--replace-files",i),o(t.replaceDocs===!0,"--replace-docs",i),o(t.note!==void 0,"--note",i),o(t.learning!==void 0,"--learning",i),o(t.test!==void 0,"--test",i),o(t.reminder!==void 0,"--reminder",i),o(t.event!==void 0,"--event",i),o(t.clearDeps===!0,"--clear-deps",i),o(t.clearComments===!0,"--clear-comments",i),o(t.clearNotes===!0,"--clear-notes",i),o(t.clearLearnings===!0,"--clear-learnings",i),o(t.clearFiles===!0,"--clear-files",i),o(t.clearTests===!0,"--clear-tests",i),o(t.clearDocs===!0,"--clear-docs",i),o(t.clearReminders===!0,"--clear-reminders",i),o(t.clearEvents===!0,"--clear-events",i);let a=[...n].filter(c=>yS.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw Hf({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 kS(e,t){let n=ne(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function SS(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=vm({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=ne(e.fromStatus,e.statusRegistry)??e.fromStatus,r=ne(e.toStatus,e.statusRegistry)??e.toStatus,s=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${km(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(s,d.USAGE);return`workflow_transition_not_allowed: ${s}`}function ES(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}function $o(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var TS=["id","kind","type","author","created_at","source_kind"],AS=["id","kind","type","source_kind"];function CS(e){return e.startsWith("```")||e.includes(`
|
|
8
|
-
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:qs(e)}function e_(e){return typeof e=="string"?Nr(e)??e.trim():e}function Mo(e,t,n,r){return e?(ge(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=CS(i);ao(i,a);let c=a?te(o,"--dep"):{id:i,kind:"related"};a&&Ue(c,"--dep",TS);let m=c.id?.trim(),u=e_((c.kind??c.type)?.trim());if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",d.USAGE);if(m.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=Vn($o(c.source_kind)),f=$o(c.author);return{id:Wn(m,t,p),kind:ye(u,Ft,"dependency kind"),created_at:ES(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function RS(e,t){return e?(ge(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new l("--dep-remove requires id or key/value selectors",d.USAGE);if(r.includes("=")||/^(?:[-*+]\s+)?(?:id|kind|type|source_kind)\s*[:=]/i.test(r)||r.startsWith("```")){let s=te(r,"--dep-remove");Ue(s,"--dep-remove",AS);let o=s.id?.trim();if(!o)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(o.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${o}"`,d.USAGE);let i=e_($o(s.kind??s.type)),a=Vn($o(s.source_kind));return{id:Wn(o,t,a),kind:i?ye(i,Ft,"dependency kind"):void 0,source_kind:a}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:_e(r,t)}})):[]}function Vf(e){let t=e.source_kind?.trim().toLowerCase()??"";return`${e.id.trim().toLowerCase()}::${e.kind}::${t}`}function IS(e,t,n,r){let s=[...e??[]],o=!1;if(t===void 0){let i=s.filter(a=>a.kind!=="blocked_by");return i.length!==s.length&&(s=i,o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}return s.some(i=>i.kind==="blocked_by"&&i.id===t)||(s.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}async function xS(e,t,n,r,s,o){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await M(n,_e(i,r),r,s,o);return a?{id:a.id}:{unresolved:i}}function OS(e,t,n,r,s){let o=IS(e.dependencies,t,n,r);o.changed&&(o.dependencies===void 0?delete e.dependencies:e.dependencies=o.dependencies,s.includes("dependencies")||s.push("dependencies"))}function PS(e){return`${e.path}::${e.scope}`}function NS(e){return`${e.path}::${e.scope}`}function LS(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}`}function FS(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())}function $S(e){return kn(e)}function Wf(e,t){let n=Dn("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function MS(e,t,n){let r=new Set,s=(o,i)=>{i&&r.add(o)};if(s("title",e.title!==void 0),s("description",e.description!==void 0),s("body",e.body!==void 0),s("status",e.status!==void 0),s("closeReason",e.closeReason!==void 0),s("priority",e.priority!==void 0),s("type",e.type!==void 0),s("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),s("deadline",e.deadline!==void 0),s("estimatedMinutes",e.estimatedMinutes!==void 0),s("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),s("definitionOfReady",e.definitionOfReady!==void 0),s("order",e.order!==void 0||e.rank!==void 0),s("goal",e.goal!==void 0),s("objective",e.objective!==void 0),s("value",e.value!==void 0),s("impact",e.impact!==void 0),s("outcome",e.outcome!==void 0),s("whyNow",e.whyNow!==void 0),s("author",e.author!==void 0),s("message",e.message!==void 0),s("assignee",e.assignee!==void 0),s("parent",e.parent!==void 0),s("reviewer",e.reviewer!==void 0),s("risk",e.risk!==void 0),s("confidence",e.confidence!==void 0),s("sprint",e.sprint!==void 0),s("release",e.release!==void 0),s("blockedBy",e.blockedBy!==void 0),s("blockedReason",e.blockedReason!==void 0),s("unblockNote",e.unblockNote!==void 0),s("reporter",e.reporter!==void 0),s("severity",e.severity!==void 0),s("environment",e.environment!==void 0),s("reproSteps",e.reproSteps!==void 0),s("resolution",e.resolution!==void 0),s("expectedResult",e.expectedResult!==void 0),s("actualResult",e.actualResult!==void 0),s("affectedVersion",e.affectedVersion!==void 0),s("fixedVersion",e.fixedVersion!==void 0),s("component",e.component!==void 0),s("regression",e.regression!==void 0),s("customerImpact",e.customerImpact!==void 0),s("dep",e.dep!==void 0),s("depRemove",e.depRemove!==void 0),s("dep",e.replaceDeps===!0),s("comment",e.comment!==void 0),s("note",e.note!==void 0),s("learning",e.learning!==void 0),s("file",e.file!==void 0),s("test",e.test!==void 0),s("test",e.replaceTests===!0),s("file",e.replaceFiles===!0),s("doc",e.replaceDocs===!0),s("doc",e.doc!==void 0),s("reminder",e.reminder!==void 0),s("event",e.event!==void 0),s("typeOption",e.typeOption!==void 0),s("field",e.field!==void 0),s("force",e.force===!0),s("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),s("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),s("dep",e.clearDeps===!0),s("comment",e.clearComments===!0),s("note",e.clearNotes===!0),s("learning",e.clearLearnings===!0),s("file",e.clearFiles===!0),s("test",e.clearTests===!0),s("doc",e.clearDocs===!0),s("reminder",e.clearReminders===!0),s("event",e.clearEvents===!0),s("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let o=Zf(e.unset,t,n);for(let i of o.optionKeys)s(i,!0)}return r}function DS(e,t,n,r,s){let o=Or(e,n);if(!o)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=cn(o,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let a=MS(t,r,s);for(let c of i.disabled)if(a.has(Wf(c,e)))throw new l(`Option ${fe("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of i.required)if(!a.has(Wf(c,e)))throw new l(`Missing required option ${fe("update",c)} for type "${e}"`,d.USAGE)}var US=new Set(["order","rank"]),GS=Ii.filter(e=>!US.has(e)),t_=["tags","closeReason",...GS],jS=["title","description","body","status","closeReason","completedAt","priority","type",...Ii,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],qS=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>Q(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>vn(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"}],KS=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>ye(co(e),sn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>mo(e)}],zS=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>ye(lo(e),on,"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=>uo(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function ec(e,t,n){for(let r of e){let s=t[r.optionKey],o=n.clearItemMetadataKeys.has(r.metadataKey);if(!(s===void 0&&!o)){if(o){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof s!="string")throw new l(`${fe("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(s,n):s.trim(),n.changedFields.push(r.metadataKey)}}}async function BS(e){let t=Ne();return wS({...e,body:await t.resolveValue(e.body,"--body"),dep:await t.resolveList(e.dep,"--dep"),depRemove:await t.resolveList(e.depRemove,"--dep-remove"),comment:await t.resolveList(e.comment,"--comment"),note:await t.resolveList(e.note,"--note"),learning:await t.resolveList(e.learning,"--learning"),file:await t.resolveList(e.file,"--file"),test:await t.resolveList(e.test,"--test"),doc:await t.resolveList(e.doc,"--doc"),reminder:await t.resolveList(e.reminder,"--reminder"),event:await t.resolveList(e.event,"--event"),typeOption:await t.resolveList(e.typeOption,"--type-option"),field:await t.resolveList(e.field,"--field")})}function HS(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 Qa(e){if(e.enabled&&(!e.values||e.values.length===0))throw new l(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,d.USAGE);if(e.enabled&&e.clearEnabled)throw new l(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,d.USAGE)}function nc(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new l("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",d.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new l("--replace-deps requires at least one --dep entry",d.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new l("--replace-deps cannot be combined with --dep-remove",d.USAGE);Qa({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Qa({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Qa({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function VS(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new l(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,d.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function WS(e){let t={};for(let n of t_)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function YS(e,t){let n=WS(e);for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=Fo.get(r)??r;throw new l(`Cannot combine --unset ${o} with ${fe("update",r)}`,d.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --add-ac",d.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --remove-ac",d.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new l("Cannot combine --unset tags with --remove-tags",d.USAGE)}}function JS(e){let t=(n,r)=>{let s=Fo.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;fo(n,fe("update",r),o)};for(let n of t_)t(e[n],String(n));t(e.order??e.rank,"order"),ge(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),ge(e.event,"--event","Use --clear-events to clear linked events.")}function XS(e,t){let n={};for(let r of jS)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 QS(e){let t=await M(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await it(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await K(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function ZS(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function eE(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new l("--order and --rank must match when both are provided",d.USAGE)}async function tE(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Ms(e.options.parent);if(Us(e.id,t,e.settings.id_prefix),await M(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=_e(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:Ds(r,e.parentReferencePolicy).warnings}}function nE(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function rE(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await M(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await it(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await K(t,{schema:e.settings.schema}),r=e.options.type!==void 0?ue(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",s=SS({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return s?[s]:[]}async function sE(e){if(!e.fieldFlags.status||ne(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=[],s=[];if(n.length>0){let a=await at(e.id,{...e.options,status:void 0,closeReason:void 0,message:void 0},e.global);s=a.changed_fields,r.push(...a.warnings)}let o=await Tt(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,...o.warnings,"auto_routed_from_update_to_close"];return{item:o.item,changed_fields:[...s,...o.changed_fields],warnings:i}}function oE(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Xa(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")),ne(e.metadata.status,n)??e.metadata.status}function iE(e,t,n,r,s){let o=kS(n,t.statusRegistry);if(e.metadata.status=o,s.push("status"),o===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,s.push("closed_at","completed_at");return}o!==t.statusRegistry.close_status&&r===t.statusRegistry.close_status&&e.metadata.closed_at!==void 0&&(delete e.metadata.closed_at,s.push("closed_at"),e.metadata.completed_at!==void 0&&(delete e.metadata.completed_at,s.push("completed_at")))}function aE(e,t,n,r){if(t.options.status!==void 0&&iE(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!Oe(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=Q(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function cE(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 s=t.options.closeReason?.trim()??"";if(s.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=s}r.push("close_reason");return}t.options.status!==void 0&&n===t.statusRegistry.close_status&&e.metadata.status!==t.statusRegistry.canceled_status&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function dE(e,t,n,r){aE(e,t,n,r),cE(e,t,n,r)}function lE(e,t,n){let r=ue(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=$S(t.options.priority),n.push("priority")),t.options.type!==void 0){let s=ue(t.options.type,t.typeRegistry);if(!s)throw new l(gt(t.options.type,t.typeRegistry.types,yt(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=s,r=s,n.push("type")}return DS(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),mE(e,t,r,n),r}function mE(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 o=yo(t.options.typeOption??[]),i=Un(n,o,t.typeRegistry);if(i.errors.length>0)throw new l(i.errors.join("; "),d.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 s=Un(n,e.metadata.type_options,t.typeRegistry);if(s.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${s.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=s.normalized}function uE(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){let s=new Set(r.map(o=>Vf(o)));for(let o of t.dependencyUpdates.additions){let i=Vf(o);s.has(i)||(r.push(o),s.add(i))}}t.dependencyRemovals.length>0&&(r=r.filter(s=>!t.dependencyRemovals.some(o=>FS(s,o)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function pE(e,t,n){Za(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Za(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Za(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Za(e,t,n,r,s,o){n===void 0&&!s.has(t)||(s.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],o.push(t))}function fE(e,t,n){Yf(e,"files",t.options.file,t.fileUpdates.values,PS,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),_E(e,t,n),Yf(e,"docs",t.options.doc,t.docUpdates.values,NS,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Yf(e,t,n,r,s,o,i,a){if(!(n===void 0&&!i.has(t))){if(o)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=>s(u)));for(let u of r){let p=s(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function _E(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Jf(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Jf([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Jf(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let s=LS(r);n.has(s)||(t.push(r),n.add(s))}return t}function hE(e,t,n){let r=t.options.addTags,s=t.options.removeTags,o=Array.isArray(r)&&r.length>0||Array.isArray(s)&&s.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||o){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?St(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=js(wn(i,r),s),n.changedFields.push("tags")}ec(qS,t.options,n),yE(e,t,n.changedFields)}function gE(e,t,n){let r=t.options.addAc,s=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(s)&&s.length>0))return;let o=Gs(bn(e.metadata.acceptance_criteria),r,s);if(o.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${o.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:o.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=o.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 yE(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 s=se(r??"","order");if(!Number.isInteger(s))throw new l("Order must be an integer",d.USAGE);e.metadata.order=s}n.push("order")}}function bE(e,t,n,r){wE(e,t,n.changedFields),vE(e,t,n.changedFields),ec(KS,t.options,n),Xf(e,t,"sprint",r,n.changedFields),Xf(e,t,"release",r,n.changedFields),kE(e,t,n.changedFields),ec(zS,t.options,n)}function wE(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new l("--assignee must not be empty. Use --unset assignee to clear it.",d.USAGE);e.metadata.assignee=r}n.push("assignee")}}function vE(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 Xf(e,t,n,r,s){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let o=Ks(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=o.value,r.push(...o.warnings)}s.push(n)}}function kE(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)&&OS(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function SE(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=ho(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=go(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function EE(e,t,n){Qf(e,t.runtimeFieldRegistry.definitions.map(s=>s.metadata_key),t.clearItemMetadataKeys,n),Qf(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[s,o]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(s)){let i=s.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===s)?.cli_flag??i;throw new l(`Cannot combine --unset ${i} with --${c}`,d.USAGE)}tt(e[s],o)||(e[s]=o,n.push(s))}let r=Ir(t.options.field,t.extensionRegistrations);for(let s of Object.keys(r))if(t.clearItemMetadataKeys.has(s))throw new l(`Cannot combine --unset ${s.replaceAll("_","-")} with --field ${s}=...`,d.USAGE);for(let[s,o]of Object.entries(r))tt(e[s],o)||(e[s]=o,n.push(s))}function Qf(e,t,n,r){for(let s of t)!n.has(s)||e[s]===void 0||(delete e[s],r.push(s))}function TE(e,t){let n=structuredClone(e.metadata),r=e.body,s=[],o=[],i=oE(e,t.options,t.statusRegistry,s),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:s,nowValue:t.nowValue};dE(e,t,i,s),lE(e,t,s),uE(e,t,s),pE(e,t,s),fE(e,t,s),hE(e,t,c),gE(e,t,c),bE(e,t,c,o),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&rr(e.metadata.id,e.metadata.dependencies),ne(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,s.includes("assignee")||s.push("assignee")),SE(e,t,s),EE(a,t,s);try{xr(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(p){throw new l(p instanceof Error?p.message:"Invalid extension item field values",d.USAGE)}let m=e.metadata,u=[...new Set(s)].filter(p=>p==="body"?e.body!==r:!tt(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&o.push(`acceptance_criteria_replaced:${bn(n.acceptance_criteria).length}:${bn(m.acceptance_criteria).length}`),{changedFields:u,warnings:o}}async function at(e,t,n){t=await BS(t);let r=T(process.cwd(),n.path);await ZS(r);let s=await A(r),o=j(s.schema),i=Be(s.schema),a=I(),c=ft(a),m=x(s,a),u=s.governance.workflow_enforcement??"off",p=u==="off"?[]:wm(s.schema),f=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],_=Zf(t.unset,i,c),h=new Set(_.optionKeys),y=new Set(_.metadataKeys);nc(t),VS({definitions:HS(t),options:t,clearOptionKeys:h,clearItemMetadataKeys:y}),vS(e,t,y),YS(t,_),JS(t);let g=R(t.author,s.author_default),b=new Date,v=b.toISOString(),E=Mo(t.dep,s.id_prefix,v,g);rr(e,E.additions);let N=await Ht({pmRoot:r,dependencies:E.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:m.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),P=RS(t.depRemove,s.id_prefix),$=Qt("--comment",t.comment,v,g),G=t.ownershipMetadataBypass===!0&&$.values?{...$,values:$.values.map(O=>({...O,author:g}))}:$,Ie=Qt("--note",t.note,v,g),ee=Qt("--learning",t.learning,v,g),pe=Wa(t.file),ie=Ya(t.test),Xe=Ja(t.doc),ze=[],Pt=await tE({id:e,options:t,unsetTargets:_,pmRoot:r,settings:s,typeRegistry:m,parentReferencePolicy:f}),ut=await xS(t.blockedBy,y.has("blocked_by"),r,s.id_prefix,s.item_format,m.type_to_folder),Nt=ut.id,ui=[...Pt.warnings,...nE(ut)],wr=vs(t,i,t.runtimeFieldCommands),Qe=XS(t,wr);if(!Object.values(Qe).some(Boolean))return QS({pmRoot:r,id:e,settings:s,typeRegistry:m});ze.push(...await rE({options:t,fieldFlags:Qe,workflowEnforcement:u,typeWorkflows:p,statusRegistry:o,typeRegistry:m,pmRoot:r,id:e,settings:s}));let vr=await sE({options:t,fieldFlags:Qe,statusRegistry:o,workflowTransitionWarnings:ze,global:n,id:e});if(vr)return vr;eE(t);let ae=Qe.dep||Qe.depRemove||Qe.blockedBy?await re(r,s.item_format,m.type_to_folder,void 0,s.schema):void 0,ve=await Y({pmRoot:r,settings:s,typeToFolder:m.type_to_folder,id:e,op:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0?"update_ownership_bypass":"update",author:g,message:t.message,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:c,skipNoop:!0,mutate(O){return ae=ae?.map(kr=>kr.id===O.metadata.id?structuredClone(O.metadata):kr),TE(O,{options:t,settings:s,typeRegistry:m,statusRegistry:o,runtimeFieldRegistry:i,extensionRegistrations:a,extensionFieldNames:c,clearItemMetadataKeys:y,dependencyUpdates:E,dependencyRemovals:P,commentUpdates:G,noteUpdates:Ie,learningUpdates:ee,fileUpdates:pe,testUpdates:ie,docUpdates:Xe,resolvedParentValue:Pt.resolvedParentValue,resolvedBlockedByDependencyId:Nt,runtimeFieldUpdates:wr,nowValue:b,nowIso:v,author:g,pmRoot:r})}}),pi=ae?Qs(ae,ae.map(O=>O.id===ve.item.id?ve.item:O),ve.item.id):[];return{item:ve.item,changed_fields:ve.changedFields,warnings:[...ze,...ui,...N,...pi,...ve.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]="e797d654-df89-554b-876b-cb2faa350bd0")}catch{}})();var r_=1,sc="update-many",AE=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),CE=["--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(", "),RE={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"},IE=[{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"}],xE={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"},s_=e=>{let t={};for(let[n,r]of Object.entries(e))AE.has(n)||r!==void 0&&(t[n]=r);return t},OE=e=>Object.keys(s_(e)).length>0,o_=e=>typeof e=="string"?e.trim():e,PE=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},rc=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},NE=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??o_(e)},LE={priority:PE,estimatedMinutes:rc,order:rc,rank:rc,regression:NE},FE=(e,t)=>{if(t!==void 0)return(LE[e]??o_)(t)},$E=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return xE[t]??t},Do=(e,t)=>tt(e,t),ME=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],DE=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,UE=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",n_=(e,t)=>t===void 0?void 0:e[t],On=e=>Array.isArray(e)?e.length:0,GE=(e,t,n)=>{let r=n[e.addKey],s=n_(n,e.removeKey),o=On(r),i=On(s),a=n[e.clearKey]===!0,c=n_(n,e.replaceKey)===!0;if(![a,c,o>0,i>0].includes(!0))return;let m=ME(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:UE({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:o,remove_count:i,before_count:DE(e.field,m)}}},jE=(e,t)=>{let n=[];for(let r of IE){let s=GE(r,e,t);s!==void 0&&n.push(s)}return n},qE=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],KE=(e,t)=>{if(![t.tags!==void 0,On(t.addTags)>0,On(t.removeTags)>0].includes(!0))return;let n=qE(e.tags),r=t.tags===void 0?n:St(t.tags),s=wn(r,t.addTags),o=js(s,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!Do(i,o))return{field:"tags",before:n,after:o}},zE=(e,t)=>{let n=e.acceptance_criteria,r=Gs(bn(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let s=r.criteria.join("; ");if(!Do(typeof n=="string"?n:"",s))return{field:"acceptance_criteria",before:n,after:s}},BE=(e,t,n)=>{for(let[r,s]of Object.entries(RE)){let o=n[r];if(o===void 0)continue;let i=t[s],a=FE(r,o);Do(i,a)||e.push({field:s,before:i,after:a})}},HE=(e,t,n,r)=>{let s=vs(n,r,["update_many"]);for(let[o,i]of Object.entries(s)){let a=t[o];Do(a,i)||e.push({field:o,before:a,after:i})}},VE=(e,t,n)=>{for(let r of n??[]){let s=$E(r),o=t[s];o!==void 0&&e.push({field:s,before:o,after:null})}},WE=(e,t,n={})=>{let r=e,s=[],o=KE(r,n);if(o&&s.push(o),BE(s,r,n),On(n.addAc)>0||On(n.removeAc)>0){let i=zE(r,n);i!==void 0&&s.push(i)}return s.push(...jE(r,n)),HE(s,r,n,t),VE(s,r,n.unset),{id:e.id,changes:s}},YE=(e,t)=>Ou(e,t,{strict:!0,flagLabel:"--filter-status"}),JE=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)},XE=[({update:e})=>{e.priority!==void 0&&kn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,I());if(!ue(e.type,r))throw new l(gt(e.type,r.types,yt(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!ne(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,d.USAGE)}},({update:e})=>{e.deadline!==void 0&&Q(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&vn(e.estimatedMinutes,"estimated-minutes")}],QE=(e,t,n,r)=>{let s={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let o of XE)o(s)},ZE=async e=>{let t=await Ns(e.pmRoot,sc,e.rollbackId,r_),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Ls(t.items,(s,o)=>Bt(s,o,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...Ut({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}},eT=async e=>{let t={schema_version:r_,id:e.checkpointId,created_at:e.nowValue,author:R(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Ps(e.pmRoot,sc,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},tT=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(s=>s.trim()).filter(s=>s.length>0))],r=new Set(t.map(s=>s.id));return n.filter(s=>!r.has(s))},oc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},nT=async e=>{let t=T(process.cwd(),e.path);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:j(n.schema),runtimeFieldRegistry:Be(n.schema)}},rT=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Xn(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",d.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",d.USAGE);return ZE({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},sT=async e=>{YE(e.options.status,e.runtime.statusRegistry);let t=await Et(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(s=>{let o=WE(s,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?o:{...o,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await Et(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(s=>s.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:tT(e.options.list?.ids,r)}},oT=e=>({outcome:"effect",exit_code:d.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:[],...oc(e)}),iT=e=>({...Ut({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:[],...oc(e)}),aT=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,s=new Set(e.plans.filter(o=>o.changes.length>0).map(o=>o.id));for(let o of e.items){if(!s.has(o.id)){t.push({id:o.id,status:"skipped"});continue}try{let i=await at(o.id,{...e.options.update,message:r,runtimeFieldCommands:["update_many"]},e.global);t.push({id:o.id,status:"updated",changed_fields:i.changed_fields,warnings:i.warnings}),n.push(o.id)}catch(i){t.push({id:o.id,status:"failed",error:dn(i)})}}return{rows:t,updatedIds:n}},cT=async e=>{if(e.plan.actionable.length===0)return iT(e.plan);let t=S(),n=Os(sc,t),r=new Set(e.plan.actionable.map(p=>p.id)),s=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),o=e.options.checkpoint===!1?void 0:await eT({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:s}),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{...Ut({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,...o?{checkpoint:o}:{},updated_count:c,skipped_count:m,failed_count:u,rows:i.rows,ids:i.updatedIds,...oc(e.plan)}},i_=async(e,t)=>{let n=await nT(t),r=typeof e.rollback=="string"?e.rollback:void 0,s=s_(e.update);if(JE(e.list),r!==void 0)return rT({runtime:n,rollbackId:r,options:e,global:t,updateSummary:s});if(!OE(e.update))throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${CE}).`,d.USAGE);QE(e.update,n.settings,n.statusRegistry,n.pmRoot),nc(e.update);let o=await Ht({pmRoot:n.pmRoot,dependencies:Mo(e.update.dep,n.settings.id_prefix,S(),R(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await sT({options:e,global:t,runtime:n,updateSummary:s,dependencyWarnings:o});return await Ht({pmRoot:n.pmRoot,dependencies:Mo(e.update.dep,n.settings.id_prefix,S(),R(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,I()).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?oT(i):cT({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]="3d5ea029-26ef-51bc-bacc-b1d4d807a024")}catch{}})();var dT=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],a_=["brief","standard","deep"],l_="plan-step-",mc="draft",lc=["bug-investigation","feature-implementation","refactoring-sprint"],c_={"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 lT(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(c_,t)?c_[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${lc.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${lc[0]}`]});return n.map(r=>({...r}))}function mT(e,t){return t>0?Math.round(e/t*100):0}function m_(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 Fe(e){return Array.isArray(e)?e.flatMap(t=>Sn(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?Sn(e,{unique:!1}):[]}function be(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function u_(e,t=mc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Si.find(s=>s===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${Si.join(", ")}`,d.USAGE);return r}function uc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ei.find(s=>s===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${Ei.join(", ")}`,d.USAGE);return r}function p_(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ai.find(s=>s===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${Ai.join(", ")}`,d.USAGE);return r}function uT(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ti.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${Ti.join(", ")}`,d.USAGE);return n}function pT(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=a_.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${a_.join(", ")}`,d.USAGE);return n}function fT(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new l("Plan --fields requires a comma-separated list of plan field names",d.USAGE);return t}var ic=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function _T(e,t){let n=e,r={},s=[];for(let o of t){let i=o.startsWith("plan.")?o.slice(5):o;if(i.length!==0){if(!ic.has(i)){s.push(o);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(s.length>0)throw new l(`Unknown Plan --fields value(s): ${s.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...ic].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:s,suggested_retry:`pm plan show <id> --fields ${[...ic].join(",")}`}});return r}function pc(e,t){let n={};for(let r of e.split(",")){let s=r.trim();if(s.length===0)continue;let o=s.indexOf("=");if(o<=0)throw new l(`Invalid ${t} entry "${s}"; expected key=value`,d.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[s.slice(0,o).trim().toLowerCase()]=s.slice(o+1).trim()}return n}function fc(e){let t=pc(e,"--file");if(!t.path)throw new l("--file requires path=<value>",d.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 _c(e){let t=pc(e,"--test");if(!t.command&&!t.path)throw new l("--test requires at least command=<value> or path=<value>",d.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 hc(e){let t=pc(e,"--doc");if(!t.path)throw new l("--doc requires path=<value>",d.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 hT(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=mT(t.completed,t.total),t}function gT(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${l_}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new l("Could not allocate step id (limit reached)",d.GENERIC_FAILURE)}function Pn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(s=>s.id===n);if(r)return r;if(/^\d+$/.test(n)){let s=Number.parseInt(n,10),o=e.find(i=>i.order===s);if(o)return o}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function d_(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 yT(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],s=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",d.USAGE);for(let i of e.slice().sort((a,c)=>a.order-c.order)){let a=d_(i);if(a){s.push({from_step:i.id,...a});continue}r.push(i)}return{targets:r,skipped:s}}let o=new Set;for(let i of t){let a=Pn(e,i);if(o.has(a.id))continue;o.add(a.id);let c=d_(a);if(c){s.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:s}}function bT(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 wT(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function vT(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 Te(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=hT(n),s=wT(n),o={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??mc,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:s?{id:s.id,order:s.order,title:s.title,status:s.status}:void 0,blocked_steps:vT(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(o.steps=n),t==="deep"&&(o.decisions=e.plan_decisions??[],o.discoveries=e.plan_discoveries??[],o.validation=e.plan_validation??[]),o}function Ae(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&&!sa(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function f_(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new l(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,d.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 kT(e){let t=T(process.cwd(),e.path);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=await A(t);return{pmRoot:t,settings:n}}async function __(e,t){let n=x(e.settings,I()),r=await M(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,d.NOT_FOUND);let s=await K(r,{schema:e.settings.schema});return f_(s.document.metadata),{document:s.document,itemId:r.id}}function ST(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of Fe(e.related))t.push(`id=${n},kind=related`);for(let n of Fe(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of Fe(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function ET(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 TT(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||Fe(e.dependsOn).length>0||Fe(e.link).length>0}function AT(e){let t=e.stepTitle?.trim()||void 0,n=m_(e.step),r=e.template?.trim()?lT(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(s=>s.title)],templateSteps:r}}function CT(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",d.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${lc[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",d.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 RT(e,t){let n=uc(e.stepStatus,"pending"),r=gc(e,"depends_on"),s=be(e.file).map(fc),o=be(e.test).map(_c),i=be(e.doc).map(hc),a=S();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:s.length>0?s:void 0,tests:o.length>0?o:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function IT(e){let t=AT(e),n=TT(e);if(CT(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[RT(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=S();return{steps:t.stepTitles.map((s,o)=>({id:`${l_}${String(o+1).padStart(3,"0")}`,order:o+1,title:s,body:t.templateSteps[o]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}async function xT(e,t,n){let r=e.title?.trim();if(!r)throw new l("pm plan create requires --title",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let s=u_(e.mode,mc),o=uT(e.harness),i=e.fromSearch?.trim(),a=ET(e),{steps:c,hasPerStepDetailOptions:m}=IT(e);if(c.length===0&&m)throw new l("pm plan create step options require --step-title (or a single --step)",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?R(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:be(e.file),test:be(e.test),doc:be(e.doc),field:be(e.field),assignee:R(e.author,n.settings.author_default),blockedBy:void 0,dep:ST(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")},_=await At(f,t),h=await Y({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:R(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let b=["plan_mode"];g.metadata.plan_mode=s,o&&(g.metadata.plan_harness=o,b.push("plan_harness"));let v=e.scope?.trim();v&&(g.metadata.plan_scope=v,b.push("plan_scope"));let E=e.resumeContext?.trim();return E&&(g.metadata.plan_resume_context=E,b.push("plan_resume_context")),g.metadata.plan_steps=c,b.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],b.push("plan_validation")),p&&(g.metadata.assignee=p,b.push("assignee")),{changedFields:b}}}),y=Te(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Ae(_.item.id,y),warnings:[..._.warnings],generated_at:S()}}async function OT(e,t,n){let r=pT(t.depth),s=fT(t.fields),{document:o,itemId:i}=await __(n,e),a=Te(o.metadata,s===null?r:"deep");return{action:"show",plan:s===null?a:_T(a,s),next_actions:Ae(i,a),warnings:[],generated_at:S()}}function PT(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,s])=>[r,JSON.stringify(s)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function We(e){let t=R(e.options.author,e.ctx.settings.author_default),n,r=await Y({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(s){f_(s.metadata);let o=j(e.ctx.settings.schema);if(Oe(s.metadata.status,o)||sa(s.metadata.plan_mode))throw new l(`Plan ${s.metadata.id} is terminal (status=${s.metadata.status}, plan_mode=${s.metadata.plan_mode??"unset"}) and cannot be mutated.`,d.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=(s.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(s.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,s);n=c.resultStep;let m=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));s.metadata.plan_steps=m;let u=PT(a,s.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 NT(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let s=uc(t.stepStatus,"pending"),o=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await We({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;h_(u,void 0,s,o);let f=LT(u,t,{order:p,title:r,status:s});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Te(i.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Ae(c,m),warnings:[],generated_at:S()}}function h_(e,t,n,r){if(n!=="in_progress"||r)return;let s=e.find(o=>o.id!==t&&o.status==="in_progress");if(s)throw new l(`Plan already has step ${s.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function LT(e,t,n){let r=gc(t,"depends_on"),s=be(t.file).map(fc),o=be(t.test).map(_c),i=be(t.doc).map(hc),a=S();return{id:gT(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:s.length>0?s:void 0,tests:o.length>0?o:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function gc(e,t){let n=Fe(e.dependsOn).map(u=>({id:u,kind:t})),r=Fe(e.related).map(u=>({id:u,kind:"related"})),s=Fe(e.blocks).map(u=>({id:u,kind:"blocks"})),o=Fe(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=Fe(e.link),a=p_(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,...s,...o,...m]}async function ac(e,t,n,r){let{document:s,resultStep:o,itemId:i}=await We({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=Pn(c,r.stepRef),p=S(),f=r.finalStatus??uc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return h_(c,u.status==="in_progress"?u.id:void 0,f,_),FT(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Te(s.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:o,next_actions:Ae(i,a),warnings:[],generated_at:S()}}function FT(e,t,n,r){$T(e,t,n),MT(e,t),e.status=n,e.updated_at=r,DT(e,n,r)}function $T(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new l("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",d.USAGE)}function MT(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=be(t.file).map(fc),s=be(t.test).map(_c),o=be(t.doc).map(hc);r.length>0&&(e.files=cc(e.files,r)),s.length>0&&(e.tests=cc(e.tests,s)),o.length>0&&(e.docs=cc(e.docs,o))}function cc(e,t){let n=[...e??[]],r=new Set(n.map(s=>JSON.stringify(s)));for(let s of t){let o=JSON.stringify(s);r.has(o)||(r.add(o),n.push(s))}return n}function DT(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function UT(e,t,n,r,s){let{document:o,itemId:i}=await We({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${s}`,mutator(c){let m=Pn(c,r),u=c.filter(f=>f.id!==m.id),p=Math.max(1,Math.min(s,u.length+1));return u.splice(p-1,0,m),u.forEach((f,_)=>{f.order=_+1,f.updated_at=S()}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=Te(o.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Ae(i,a),warnings:[],generated_at:S()}}async function GT(e,t,n,r){let{document:s,itemId:o}=await We({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=Pn(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=Te(s.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Ae(o,i),warnings:[],generated_at:S()}}async function jT(e,t,n,r){let s=gc(t,p_(t.linkKind,"related"));if(s.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let o=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await We({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Pn(u,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of s){let b=h(g);y.has(b)||(_.push(g),y.add(b))}if(f.linked_items=_,f.updated_at=S(),o){let g=p.metadata.dependencies??[],b=E=>`${E.kind}:${E.id}`,v=new Set(g.map(b));for(let E of s){let N=E.kind==="depends_on"?"blocked_by":E.kind,P={id:E.id,kind:N,created_at:S(),author:R(t.author,n.settings.author_default)};v.has(b(P))||(g.push(P),v.add(b(P)))}p.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),m=Te(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ae(a,m),warnings:[],generated_at:S()}}async function qT(e,t,n,r){let s=Fe(t.link);if(s.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:o,itemId:i,resultStep:a}=await We({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=Pn(m,r),p=(u.linked_items??[]).filter(f=>!s.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=S(),{changedSteps:[u.id],resultStep:u}}}),c=Te(o.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Ae(i,c),warnings:[],generated_at:S()}}async function dc(e,t,n,r){let s=bT(r,t);if(!s){let m=`--${r}-text`,u=`--${r}`;throw new l(`pm plan ${r} requires ${m}`,d.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 o=R(t.author,n.settings.author_default),{document:i,itemId:a}=await We({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,u){let p=S();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:o,decision:s,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:o,text:s}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:s,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Te(i.metadata,"deep");return{action:r,plan:c,next_actions:Ae(a,c),warnings:[],generated_at:S()}}async function KT(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:s,itemId:o}=await We({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=Te(s.metadata,"brief");return{action:"resume",plan:i,next_actions:Ae(o,i),warnings:[],generated_at:S()}}async function zT(e,t,n){let r=u_(t.mode??"approved","approved"),{document:s,itemId:o}=await We({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=Te(s.metadata,"brief");return{action:"approve",plan:i,next_actions:Ae(o,i),warnings:[],generated_at:S()}}function g_(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function BT(e,t){let n=Te(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ae(e.itemId,n),warnings:g_(t),generated_at:S()}}function HT(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let s of n.linked_items??[]){let o=s.kind==="blocked_by"||s.kind==="blocks"||s.kind==="related"||s.kind==="discovered_from"?s.kind:"related";r.push(`id=${s.id},kind=${o}`)}return r}async function VT(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let s of be(e.options.field)){let o=s.indexOf("=");if(o<=0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.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 l(`Invalid --field entry "${s}"; expected name=value`,d.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 l(`Invalid --field entry "${s}"; "${p}" is reserved by materialize and cannot be overridden`,d.USAGE);n[p]=a}for(let s of e.targets){let o=await At({...n,title:s.title,description:s.body?.trim()||s.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${s.id}`,dep:HT(e.parent,e.planItemId,s)},{path:e.pmRoot});t.push({id:o.item.id,title:o.item.title,type:e.resolvedTypeName,parent:o.item.parent,tags:o.item.tags??[],from_step:s.id})}return t}function WT(e,t,n){for(let r of t){let s=n.find(a=>a.from_step===r.id);if(!s)continue;let o=e.find(a=>a.id===r.id);if(!o)continue;let i=o.linked_items??[];i.push({id:s.id,kind:"implements",note:`materialized as ${s.type}`}),o.linked_items=i,o.updated_at=S()}}async function YT(e,t,n){let r=Fe(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let s=t.materializeType?.trim()||"Task",o=x(n.settings,I()),i=ue(s,o);if(!i)throw new l(`Invalid --materialize-type "${s}"`,d.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await __(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=yT(u,r);if(p.length===0){if(f.length>0)return BT(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await VT({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await We({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(b){return WT(b,p,_),{changedSteps:p.map(v=>v.id)}}}),g=Te(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ae(y,g),warnings:g_(f),generated_at:S()}}function JT(e){if(e.subcommand==="create")return e;let t=m_(e.options.step);if(t.length>1)throw new l(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,d.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:{...e.options,stepTitle:t[0]}}:e}function ct(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function Zt(e,t){let n=ct(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function XT(e){let t=Zt(e,"reorder-step");if(e.reorderTo===void 0)throw new l("pm plan reorder-step requires <plan-id> <step> <new-order>",d.USAGE);return{...t,reorderTo:e.reorderTo}}var QT={create:(e,t)=>xT(e.options,e.global,t),show:(e,t)=>OT(ct(e,"show"),e.options,t),"add-step":(e,t)=>NT(ct(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=Zt(e,"update-step");return ac(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=Zt(e,"complete-step");return ac(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=Zt(e,"block-step");return ac(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=XT(e);return UT(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=Zt(e,"remove-step");return GT(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=Zt(e,"link");return jT(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=Zt(e,"unlink");return qT(n.id,e.options,t,n.stepRef)},decision:(e,t)=>dc(ct(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>dc(ct(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>dc(ct(e,"validation"),e.options,t,"validation"),resume:(e,t)=>KT(ct(e,"resume"),e.options,t),approve:(e,t)=>zT(ct(e,"approve"),e.options,t),materialize:(e,t)=>YT(ct(e,"materialize"),e.options,t)};function ZT(e){let t=QT[e];if(!t)throw Ee({command_path:"plan",token:e,allowed:dT});return t}async function y_(e){let t=await kT(e.global),n=JT(e);return ZT(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]="4eb2056a-4444-514a-a0db-79b8875c3d65")}catch{}})();function eA(e,t){return[...new Set([...Rr.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,s)=>r.localeCompare(s))}function tA(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function yc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await M(r,e,s.id_prefix,s.item_format,o.type_to_folder);if(!i)throw await it(r,e,s.id_prefix,o.type_to_folder);let a=await K(i,{schema:s.schema}),c=a.document.metadata,m=S(),u=R(t.author,s.author_default),p=await Bn(r,s.id_prefix,{tokenLength:s.ids.token_length,typeToFolder:o.type_to_folder,probeExisting:!1}),f=j(s.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let h={...c,id:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let y=ft(I()),g=He({metadata:h,body:a.document.body},{schema:s.schema,extensionFieldNames:y}),b=await An({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=eA(g.metadata,g.body),E=Mt(r,g.metadata.type,p,s.item_format,o.type_to_folder),N=ke(r,p),P=await xe(r,p,s.locks.ttl_seconds,u,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),$={metadata:{},body:""},G,Ie;try{let ee=await gn(r,u,{required:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await An({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1});let pe=await M(r,p,s.id_prefix,s.item_format,o.type_to_folder);if(pe)throw new l(`Cannot copy to ${p}: an item with that id already exists at ${pe.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${pe.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await me(E,Me(g,{format:s.item_format,schema:s.schema,extensionFieldNames:y}));try{let ie=De({nowIso:m,author:u,op:"create",before:$,after:g,message:tA(i.id,t.message)});await wt(N,ie)}catch(ie){throw await an(E),ie}Ie=await yn({pmRoot:r,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:E,document:g})}finally{await ee()}G=[...await z({path:E,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:$,after:g,changed_fields:v}),...await z({path:N,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:$,after:g,changed_fields:v})],mn({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Gt(g.metadata,v),changed_fields:v})}finally{await P()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:v,warnings:[...Zs(b),...Ie,...G],...b===void 0?{}:{similarity_advisory:b}}}import Uo 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]="14aa55e1-cb5f-55ea-bf4c-412217d87449")}catch{}})();async function bc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=R(t.author,s.author_default),i=await vu({pmRoot:r,settings:s,id:e,author:o,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?Uo.relative(r,i.targetPath).split(Uo.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:Uo.relative(r,ke(r,i.item.id)).split(Uo.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]="0f43df79-0b27-53b3-b8bd-9f2a35561733")}catch{}})();async function nA(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}async function wc(e,t,n){let r=T(process.cwd(),n.path);if(await nA(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",d.USAGE);let p=await A(r),f=fn(R(void 0,p.author_default));return await Zm(r),await Xs({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 bs(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 rA(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let o=await A(r),i=x(o,I()),a=await M(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await it(r,e,o.id_prefix,i.type_to_folder);let c=_e(a.id,o.id_prefix),m=await K(a,{schema:o.schema}),u=b_(m.document.metadata.title);return await Qm(r,c),await Xs({pmRoot:r,settings:o,principal:fn(R(void 0,o.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 rA(e,t){let n=await A(e),r=x(n,I()),s=await M(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!s)return null;let o=await K(s,{schema:n.schema});return b_(o.document.metadata.title)}function b_(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]="4f4f5f10-793d-5baa-8985-c0ec855b16c4")}catch{}})();var w_=new Set(["item_format"]),v_=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"]),sA=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","telemetry_tracking"]),oA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","telemetry_tracking"]),iA={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function aA(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(w_.has(t)||v_.has(t)||sA.has(t)||t==="context")return t}function cA(e){let t=e.trim().toLowerCase();return iA[t]??e}function k_(e,t){let n=aA(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."}:w_.has(n)?{routable:!0,flag:"format",value:t}:v_.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:oA.has(n)?cA(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]="a9a8d99c-df4e-55b3-81f5-27124d598c5f")}catch{}})();var S_=["project","global"],dt={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"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],context:["context"]},dA=Object.keys(dt).map(e=>dt[e][0]),lA=Object.fromEntries(Object.keys(dt).flatMap(e=>dt[e].map(t=>[t,e]))),mA={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.",telemetry_tracking:"Telemetry usage reporting policy.",context:"Context command settings (depth, section toggles, limits)."},uA=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],pA=new Set(["metadata_required_fields",...uA]),fA=new Set(["test_result_tracking","telemetry_tracking"]),_A=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),hA=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),gA=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),yA=new Set(["governance_preset","governance_create_default_type"]),R_=e=>pA.has(e),bA=e=>hA.has(e),wA=e=>gA.has(e),vA=e=>yA.has(e);function vc(e){return e==="definition_of_done"||R_(e)}function kA(e){if(S_.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${S_.join(", ")}`,d.USAGE)}function SA(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Ee({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function EA(e){let t=lA[e];if(t)return t;let n=Li.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${dA.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function TA(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,s)=>r.localeCompare(s));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",d.USAGE);return n}function AA(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",d.USAGE):new l("Config set item-format requires --format toon",d.USAGE)}function I_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",d.USAGE)}function x_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set test-result-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function O_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function Sc(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",d.USAGE)}function P_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",d.USAGE)}function N_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",d.USAGE)}function L_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",d.USAGE)}function F_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",d.USAGE)}function $_(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 l("Config set governance-workflow-enforcement requires one of: off, warn, strict",d.USAGE)}function M_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",d.USAGE)}function D_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",d.USAGE)}function E_(e,t){switch(e){case"history_missing_stream_policy":return I_(t);case"sprint_release_format_policy":return ra(t);case"parent_reference_policy":case"governance_parent_reference_policy":return $s(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Sc(t);case"governance_preset":return P_(t);case"governance_ownership_enforcement":return N_(t);case"governance_create_mode_default":return L_(t);case"governance_close_validation_default":return F_(t);case"governance_require_close_reason":return D_(t);case"governance_workflow_enforcement":return $_(t);case"governance_force_required_for_stale_lock":return M_(t);case"test_result_tracking":return x_(t);case"telemetry_tracking":return O_(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var T_={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},CA=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function RA(e,t){let n=[...new Set((e??[]).map(o=>o.trim()).filter(o=>o.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",d.USAGE);let r=n.map(o=>o.toLowerCase().replaceAll("-","_")),s=r.filter(o=>T_[o]===void 0);if(s.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${s.join(", ")}. Supported values: ${CA.join(", ")}`,d.USAGE);return[...new Set(r.map(o=>T_[o]))].sort((o,i)=>o.localeCompare(i))}function IA(e,t,n){let r=[...new Set((t??[]).map(s=>s.trim().toLowerCase()).filter(s=>s.length>0))].sort((s,o)=>s.localeCompare(o));if(n){if(r.length>0)throw new l(`Config set ${dt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${dt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function xA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function OA(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,d.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,d.USAGE);return EA(t)}function U_(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var PA={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",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",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 Ec(e,t){return PA[t](e)}function $e(e,t){return t.length===0?e:{...e,warnings:t}}async function NA(e,t){let n=process.cwd(),r=e==="project"?T(n,t.path):et(n),s=C(r);if(e==="project"&&!await k(s))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);return{pmRoot:r,settingsPath:s}}function LA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,d.USAGE)}function A_(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new l(`Context ${t} must be a positive integer`,d.USAGE)}async function FA(e,t,n,r,s){let o=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!Ci.includes(c))throw new l(`Context --default-depth must be one of ${Ci.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,o=!0)}if(t.activityLimit!==void 0){let c=A_(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,o=!0)}if(t.staleThresholdDays!==void 0){let c=A_(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,o=!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=LA(m);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,o=!0)}}return o&&await Se(n.pmRoot,e,"config:set:context"),$e({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:o},s)}function $A(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,d.USAGE);return{...n,value:t}}function MA(e,t,n,r,s,o){if(s===void 0)return o;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,d.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',d.USAGE);if(r)return $A(t,s,o);U_(n);let i=k_(n,s);if(!i.routable)throw new l(i.reason,d.USAGE);if(i.flag==="criterion"){if(o.criterion!==void 0&&o.criterion.length>0)throw new l(`Config set ${t} received both positional value "${s}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...o,criterion:i.values}}if(i.flag==="format")return{...o,format:i.value};if(o.policy!==void 0&&E_(n,o.policy)!==E_(n,i.value))throw new l(`Config set ${t} received both positional value "${s}" and --policy "${o.policy}". Pass only one.`,d.USAGE);return{...o,policy:i.value}}function DA(e){let t=Object.keys(dt).map(r=>({key:r,aliases:dt[r],value_kind:r==="context"?"object":vc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:vc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:mA[r],value:Ec(e.settings,r)})),n=Li.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Fi(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 $e({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function UA(e){let t=Object.fromEntries(Object.keys(dt).map(n=>[n,Ec(e.settings,n)]));return $e({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function GA(e,t){let n=Ec(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?$e({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?$e({...r,context_settings:n},e.warnings):Array.isArray(n)?$e({...r,criteria:n},e.warnings):$e({...r,policy:n},e.warnings)}async function jA(e,t,n,r){if(t==="get"){let a=Fi(e.settings,n);return $e({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 s=r.value;if(typeof s!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let o=bm(n,s);if(!o.ok)throw new l(o.error.message,d.USAGE);let i=fs(e.settings,n,o.parsed.value);return i&&await Se(e.target.pmRoot,e.settings,`config:set:${n.path}`),$e({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:o.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function X(e,t,n){t&&await Se(e.target.pmRoot,e.settings,n)}function C_(e,t,n){return e!==n||t!==n}function oe(e,t,n,r){return $e({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function kc(e,t,n,r){return $e({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function qA(e,t){let n=AA(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,s;if(r){let o=x(e.settings,I()),i=await Nu(e.target.pmRoot,n,"config:set:item_format:migrate",o.type_to_folder,e.settings.schema);s={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await Se(e.target.pmRoot,e.settings,"config:set:item_format")}return $e({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:s,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function KA(e,t,n){if(t==="history_missing_stream_policy"){let o=I_(n.policy),i=e.settings.history.missing_stream!==o;return e.settings.history.missing_stream=o,await X(e,i,"config:set:history_missing_stream_policy"),oe(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let o=ra(n.policy),i=e.settings.validation.sprint_release_format!==o;return e.settings.validation.sprint_release_format=o,await X(e,i,"config:set:sprint_release_format_policy"),oe(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let o=$s(n.policy),i=e.settings.validation.parent_reference!==o||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==o;return e.settings.validation.parent_reference=o,e.settings.governance.preset="custom",e.settings.governance.parent_reference=o,await X(e,i,"config:set:parent_reference_policy"),oe(e,t,e.settings.validation.parent_reference,i)}let r=Sc(n.policy),s=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 X(e,s,"config:set:metadata_validation_profile"),oe(e,t,e.settings.validation.metadata_profile,s)}async function zA(e,t,n){if(t==="metadata_required_fields"){let a=RA(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 X(e,c,"config:set:metadata_required_fields"),kc(e,t,[...e.settings.validation.metadata_required_fields],c)}let s={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],o=IA(t,n.criterion,n.clearCriteria),i=o.length!==s.length||o.some((a,c)=>a!==s[c]);return s.splice(0,s.length,...o),await X(e,i,`config:set:${t}`),kc(e,t,[...s],i)}async function BA(e,t,n){if(t==="governance_preset"){let c=P_(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await X(e,m,"config:set:governance_preset"),oe(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",s=r?n.policy.trim():"";if(r&&s.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await X(e,c,"config:set:governance_create_default_type"),oe(e,t,e.settings.governance.create_default_type??"",c)}if(s.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let o=x(e.settings,I()),i=ue(s,o);if(!i)throw new l(gt(s,o.types,yt(e.target.pmRoot,e.settings.schema)),d.USAGE);let a=e.settings.governance.create_default_type!==i;return e.settings.governance.create_default_type=i,await X(e,a,"config:set:governance_create_default_type"),oe(e,t,e.settings.governance.create_default_type,a)}async function HA(e,t,n){if(t==="governance_ownership_enforcement"){let o=N_(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==o;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=o,await X(e,i,"config:set:governance_ownership_enforcement"),oe(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let o=L_(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==o;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=o,await X(e,i,"config:set:governance_create_mode_default"),oe(e,t,e.settings.governance.create_mode_default,i)}let r=F_(n.policy),s=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 X(e,s,"config:set:governance_close_validation_default"),oe(e,t,e.settings.governance.close_validation_default,s)}async function VA(e,t,n){if(t==="governance_parent_reference_policy"){let o=$s(n.policy),i=e.settings.governance.preset!=="custom"||C_(e.settings.governance.parent_reference,e.settings.validation.parent_reference,o);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=o,e.settings.validation.parent_reference=o,await X(e,i,"config:set:governance_parent_reference_policy"),oe(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let o=Sc(n.policy),i=e.settings.governance.preset!=="custom"||C_(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,o);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=o,e.settings.validation.metadata_profile=o,await X(e,i,"config:set:governance_metadata_validation_profile"),oe(e,t,e.settings.governance.metadata_profile,i)}let r=$_(n.policy),s=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await X(e,s,"config:set:governance_workflow_enforcement"),oe(e,t,e.settings.governance.workflow_enforcement,s)}async function WA(e,t,n){if(t==="governance_require_close_reason"){let a=D_(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await X(e,c,"config:set:governance_require_close_reason"),oe(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let s=M_(n.policy)==="enabled",o=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==s;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=s,await X(e,o,"config:set:governance_force_required_for_stale_lock"),oe(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function YA(e,t,n){if(t==="test_result_tracking"){let a=x_(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await X(e,c,"config:set:test_result_tracking"),oe(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}let s=O_(n.policy)==="enabled",o=e.settings.telemetry.enabled!==s||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=s,e.settings.telemetry.first_run_prompt_completed=!0,await X(e,o,"config:set:telemetry_tracking"),oe(e,t,e.settings.telemetry.enabled?"enabled":"disabled",o)}async function JA(e,t,n){let r=TA(n.criterion,n.clearCriteria),s=r.length!==e.settings.workflow.definition_of_done.length||r.some((o,i)=>o!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await X(e,s,"config:set:definition_of_done"),kc(e,t,[...e.settings.workflow.definition_of_done],s)}async function XA(e,t,n){if(n.clearCriteria===!0&&!vc(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?qA(e,n):t==="context"?FA(e.settings,n,e.target,e.scope,e.warnings):t==="definition_of_done"?JA(e,t,n):R_(t)?zA(e,t,n):fA.has(t)?YA(e,t,n):_A.has(t)?WA(e,t,n):bA(t)?HA(e,t,n):wA(t)?VA(e,t,n):vA(t)?BA(e,t,n):KA(e,t,n)}async function G_(e,t,n,r,s,o){let i=kA(e),a=SA(t),c=a==="get"||a==="set"?ps(n):void 0,m=c?void 0:OA(a,n),u=MA(a,n,m,c,o,r),p=await NA(i,s),{settings:f,metadata:_,warnings:h}=await yu(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:xA(h)};return c?jA(y,a,c,u):a==="list"?DA(y):a==="export"?UA(y):(U_(m),a==="get"?GA(y,m):XA(y,m,u))}import AC from"node:fs/promises";import V from"node:path";import CC from"node:readline/promises";import{stdin as RC,stdout as Ce}from"node:process";import q_ from"node:fs/promises";import je from"node:path";import QA from"node:readline/promises";import{stdin as ZA,stdout as Go}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]="b7c97e30-02c8-547c-b3db-c6c59e662b54")}catch{}})();var K_=["ask","add","skip","status"],eC=["AGENTS.md","CLAUDE.md"],tC=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],nC=8,Ac=1,rC="<!-- pm-cli:agent-guidance:start:",sC=`<!-- pm-cli:agent-guidance:start:v${Ac} -->`,Tc="<!-- pm-cli:agent-guidance:end -->",cr="Add workflow guidance later: pm init --agent-guidance add";var oC=()=>QA.createInterface({input:ZA,output:Go});function ir(e,t){let n=je.relative(e,t);return n.length===0?je.basename(t):n.split(je.sep).join("/")}function j_(e){return e.endsWith(`
|
|
4
|
+
`,{changedFields:["body"]}}});return{item:m.item,appended:c,changed_fields:m.changedFields}}import{readFile as Gw}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]="0af9967c-ca72-563a-9518-2e68da0c0fe0")}catch{}})();function io(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,t}function pf(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,d.USAGE,{code:"structured_event_immutable"})}function Fa(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Vt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function xn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let o=ne(n,"--add");return Object.keys(o).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:o.text?.trim()||n}catch{return n}}function $a(e){return typeof e=="object"&&e!==null&&"code"in e}async function jw(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,d.USAGE);let r=Le();if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add")??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return{value:await r.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let s=e.file.trim();if(!s)throw new l("--file path cannot be empty",d.USAGE);try{return{value:await Gw(s,"utf8"),emptyFlag:"--file"}}catch(o){if($a(o)&&Ut(o))throw new l(`--file path not found: ${s}`,d.USAGE);let i=o instanceof Error?o.message:String(o);throw new l(`Failed to read --file path "${s}": ${i}`,d.USAGE)}}async function ao(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",d.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",d.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",d.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",d.USAGE);let n=await jw(e,t);if(e.edit!==void 0){if(!n)throw new l("--edit requires replacement text from --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function ar(e,t){throw e instanceof l&&e.exitCode===d.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function _f(e){return e==="comments"?"--stdin":"--add -"}function qw(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let s=_f(t.collectionKey),o=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new l(`--add value "${r}" looks like an option, not annotation text. Use ${s} to read stdin, or use text=${r} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${s} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${o} ${s}`,`${o} --add text=${r}`]})}function Kw(e,t){if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,d.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> ${_f(e.collectionKey)}`]})}async function On(e,t,n,r){Kw(r,t);let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=x(o,I()),a=Xn(t.limit);if(r.input.mode==="list"){let _=await D(s,e,o.id_prefix,o.item_format,i.type_to_folder);if(!_)throw new l(`Item ${e} not found`,d.NOT_FOUND);let h=await K(_,{schema:o.schema}),y=Vt(h.document.metadata,r.collectionKey);return oo(_.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=R(t.author,o.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,h;try{h=await Z({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Vt(g.metadata,r.collectionKey),v=ff(r.input.index,b.length,r.collectionKey);return pf(b[v],"deleted"),b.splice(v,1),g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){ar(g,r.conflictGuidance)}let y=Vt(h.item,r.collectionKey);return oo(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let m=r.input.rawValue??r.input.value??"";qw(m,r);let u=r.parseText(r.input.value??"");if(!u.trim())throw new l(`${r.input.emptyFlag??"--add"} text cannot be empty`,d.USAGE);if(r.input.mode==="edit"){let _=r.editOp??r.op,h;try{h=await Z({pmRoot:s,settings:o,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(g){let b=Vt(g.metadata,r.collectionKey),v=ff(r.input.index,b.length,r.collectionKey),E=b[v];return pf(E,"edited"),b[v]={...E,text:u,edited_at:S()},g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){ar(g,r.conflictGuidance)}let y=Vt(h.item,r.collectionKey);return oo(h.item.id,r.collectionKey,y,a,t.includeMeta===!0,{action:"edit",entryIndex:r.input.index,entry:y[r.input.index-1]},t.fullHistory===!0)}let p;try{p=await Z({pmRoot:s,settings:o,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(_){let h=Vt(_.metadata,r.collectionKey),y={created_at:S(),author:c,text:u};return h.push(r.createEntry(y)),_.metadata[r.collectionKey]=h,{changedFields:[r.collectionKey]}}})}catch(_){ar(_,r.conflictGuidance)}let f=Vt(p.item,r.collectionKey);return oo(p.item.id,r.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:f.length,entry:f.at(-1)},t.fullHistory===!0)}function ff(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),s=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,o=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${s} index ${e??"(missing)"} out of range (item has ${o})`,d.USAGE)}return e-1}function oo(e,t,n,r,s,o,i=!1){let a=o===void 0||i?Fa(n,o!==void 0&&i?void 0:r):o.entry===void 0?[]:[o.entry],c=o!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...[s,o!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...o===void 0?{}:{mutation_receipt:{action:o.action,entry_index:o.entryIndex,changed_count:1,full_history_included:!c},omission_receipt:{has_omissions:c,omitted_field_group_count:c?1:0,omitted_field_groups:c?[{name:`${t}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0579277-f123-5f96-8664-dfe05ade1b24")}catch{}})();async function hf(e,t,n){return[...await Et(Se(e,t),t).catch(()=>[])].reverse().find(o=>o.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]="f70f1329-4dfb-5625-ae0a-66c858d88f7b")}catch{}})();var gf="no_available_next_item";function yf(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 co(e,t,n,r={}){let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=M(o.schema),a=R(r.author,o.author_default),c=gn(a),m=null,u=!1,p=[],f=await Z({pmRoot:s,settings:o,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",g=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,vm(_.metadata.status,i)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&g!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let v=await hf(s,_.metadata.id,y);throw new l(`Item ${_.metadata.id} is already ${v}. Use --force to take over, or --if-available to skip without failing.`,d.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}`)}return _.metadata.assignee=a,_.metadata.claim_principal=c,{changedFields:["assignee","claim_principal"],warnings:p}}});return u||await Ea({pmRoot:s,settings:o,principal:c,itemId:f.item.id}),{item:f.item,claimed_by:u&&m!==null?m:a,previous_assignee:m,forced:t,...u?{skipped:!0}:{},...p.length>0?{warnings:p}:{}}}async function bf(e,t,n={},r={}){let s=zw(n.maxAttempts),o=await A(T(process.cwd(),t.path)),i={...n,author:R(n.author,o.author_default)},a=await sr({...r,callerAuthor:i.author,limit:String(s)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return Bw(c.slice(0,s),e,t,i)}function zw(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new l("--max-attempts must be an integer from 1 to 100",d.USAGE);return t}async function Bw(e,t,n,r={},s=co){let o=0;for(let a of e){o+=1;try{let c=await s(a.id,t,n,r),m={...c,recommendation:a,attempts:o,available:!0};if(!c.skipped)return m}catch(c){if(!yf(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:R(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:o,warnings:[gf]};let i=o===0;throw new l(i?"No actionable items matched the selection filters":"No actionable item remained available to claim",i?d.NOT_FOUND:d.CONFLICT,{code:gf,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 lo(e,t,n,r={}){let s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=R(r.author,o.author_default),a=gn(i),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await Z({pmRoot:s,settings:o,id:e,op:"release",author:i,message:r.message,force:t,bypassAssigneeConflict:c,mutate(p){return m=p.metadata.assignee??null,!m&&!p.metadata.claim_principal?{changedFields:[]}:(delete p.metadata.assignee,delete p.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(p){ar(p,{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."]})}return await Ta({pmRoot:s,principal:a,itemId:u.item.id}),{item:u.item,released_by:i,previous_assignee:m,forced: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]="a7ae3c89-b50b-5e4f-8273-8318bc976d84")}catch{}})();var Hw=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function wf(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 Ma(e,t){return Da(e,t,{operation:"close"})}function Da(e,t,n){let r=wf(e);if(!t||r.closeReason!==void 0)return r;let s=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",d.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:s,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 Ua(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,s=e.dependencies??[],o=s.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"&&o.length>0){let m=s.filter(u=>u.kind!=="blocked_by");m.length>0?e.dependencies=m:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...o.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]="83affe54-a56c-5d84-b6b0-9634d4238ff5")}catch{}})();var Vw=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function Ww(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new l(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,d.USAGE)}function Yw(e){let t=[];for(let n of Vw){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function Jw(e,t,n){let r=new Set,s=t;for(;typeof s=="string"&&s.trim().length>0;){let o=s.trim();if(o===n)return!0;if(r.has(o))return!1;r.add(o),s=(await e(o))?.duplicate_of}return!1}function Xw(e){return typeof e!="string"||e.trim().length===0}async function Qw(e,t,n,r){let s=n?.trim();if(!s)return;if(s===r)throw new l("An item cannot be closed as a duplicate of itself.",d.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let o=x(t,I()),i=new Map,a=async m=>{if(i.has(m))return i.get(m)??null;let u=await D(e,m,t.id_prefix,t.item_format,o.type_to_folder);if(!u)return i.set(m,null),null;let{document:p}=await K(u,{schema:t.schema});return i.set(m,p.metadata),p.metadata},c=await a(s);if(!c)throw new l(`Duplicate target "${s}" was not found. Create or locate the canonical item first.`,d.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 ${s}" --duplicate-of ${s}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await Jw(a,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${s}" points back to "${r}".`,d.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new l(`Duplicate target "${s}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,d.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 Zw(e,t,n){return e.filter(r=>r.parent===t&&!se(r.status,n)).map(r=>r.id).sort((r,s)=>r.localeCompare(s))}function ev(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),s=Qp(e),o=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:s.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(o)).filter(({blockerIds:a})=>a.every(c=>{if(c===o)return!0;let m=r.get(c);return m!==void 0&&se(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function tv(e,t,n,r,s,o){let i=ev(n,r,o),a=[];for(let c of i)try{let m=await Z({pmRoot:e,settings:t,id:c.id,op:"update",author:s,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(h=>{let y=h.id.trim().toLowerCase();return h.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=o.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 nv(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:s,key:o}of r){if(typeof s!="string")continue;let i=s.trim();i.length!==0&&(e[o]=i,n.push(o))}return n}function rv(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:s,value:o}of r)Xw(e[s])&&(e[s]=o,n.push(s));return n}function sv(e,t,n,r){let s=[];if(t!=="off"){let o=Yw(e);if(o.length>0){let i=o.map(a=>a.label);if(t==="strict"){let a=o.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(m=>[m,"<value>"])];throw new l(`Cannot close item ${e.id}: missing ${i.join(", ")}. Populate fields or use --validate-close warn.`,d.USAGE,{code:"close_validation_missing_fields",recovery:{missing:a,suggested_retry:bs(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."]})}s.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new l(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,d.USAGE);s.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return s}return n.length>0&&s.push(`closed_with_active_children:${e.id}:${n.join(",")}`),s}function ov(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function iv(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function av(e,t){if(se(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use --force to close again.`,d.CONFLICT);let n=nv(e,t.options),r=rv(e,t.duplicateOf),s=sv(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let o=t.options.completedAt!==void 0||e.completed_at===void 0;o&&(e.completed_at=t.completedAt);let i=["status","closed_at",...o?["completed_at"]:[],...ov(e,t.closeReason),...n];if(zu(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(...iv(e));let a=Ua(e,t.lifecyclePolicy);return i.push(...a.changedFields),s.push(...a.warnings),{changedFields:i,...s.length>0?{warnings:s}:{}}}async function vf(e,t,n,r){let s=T(process.cwd(),r.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=M(o.schema),a=R(n.author,o.author_default),c=x(o,I()).type_to_folder,m=await D(s,e,o.id_prefix,o.item_format,c);if(!m)throw await ot(s,e,o.id_prefix,c);let u=await Qw(s,o,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Ma({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=Ww(n.validateClose)??o.governance.close_validation_default,h=await oe(s,o.item_format,c,void 0,o.schema),y=Zw(h,m.id,i),g=new Date().toISOString(),b=n.completedAt===void 0?g:Q(n.completedAt,new Date(g),"completed-at"),v=await Z({pmRoot:s,settings:o,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(E){return av(E.metadata,{pmRoot:s,statusRegistry:i,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:g,completedAt:b,lifecyclePolicy:p})}});return{item:v.item,changed_fields:v.changedFields,warnings:[...v.warnings,...await tv(s,o,h,m.id,a,i)]}}function it(e,t,n,r){return vf(e,t,n,r)}import cv from"fast-json-patch";import Ga 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]="353be665-9f67-5d0e-99c9-6bbb7e927e0b")}catch{}})();function dv(e,t){return Pu(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function lv(e){let t=oa(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:We(zt(t))}async function mv(e,t,n,r){let s=await D(e,t,n.id_prefix,n.item_format,r);if(s){let c=Se(e,s.id),m=await Ru({pmRoot:e,settings:n,itemId:s.id,commandLabel:"restore"});return{id:s.id,historyPath:c,located:s,historyPolicyWarnings:m.warnings}}let o=ge(t,n.id_prefix),i=na(t),a=o===i?[o]:[o,i];for(let c of a){let m=Se(e,c);if(await k(m))return{id:c,historyPath:m,located:null,historyPolicyWarnings:[]}}throw new l(`Item ${t} not found`,d.NOT_FOUND)}function uv(e,t){let n=Bt(e),r=Bt(t),s=cv.compare(n,r),o=new Set;for(let i of s){if(i.path==="/body"||i.path.startsWith("/body/")){o.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];o.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(o).sort((i,a)=>i.localeCompare(a))}async function pv(e){if(await q(e.subject.historyPath)!==e.historyRawBeforeLock)throw new l(`History for ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);let n=await D(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),r=n?await K(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==e.currentItemRawBeforeLock)throw new l(`Item ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);return{loadedItemUnderLock:r,existingItemPath:n?.itemPath??null}}function fv(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:lv(t),originalRaw:null}}function _v(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new l(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,d.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function hv(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await ue(e.existingItemPath,e.resolvedOriginalRaw),await Ga.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await ue(e.existingItemPath,e.resolvedOriginalRaw);return}await Ga.rm(e.restoredItemPath,{force:!0})}async function gv(e){return[...await z({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 z({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 Wt(e,t,n,r){let s=T(process.cwd(),r.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s),i=x(o,I()),a=await mv(s,e,o,i.type_to_folder),c=a.id,m=await q(a.historyPath),u=await Et(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let p=dv(t,u),f=Nu(oa(u,p.historyIndex),p),_=wu(f,{schema:o.schema});if(_.metadata.id!==c)throw new l(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,d.GENERIC_FAILURE);let y=(a.located?await K(a.located,{schema:o.schema}):null)?.raw??null,g=R(n.author,o.author_default),b=await Pe(s,c,o.locks.ttl_seconds,g,!!n.force,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let{loadedItemUnderLock:v,existingItemPath:E}=await pv({pmRoot:s,resolvedId:c,subject:a,settings:o,typeToFolder:i.type_to_folder,historyRawBeforeLock:m,currentItemRawBeforeLock:y}),N="toon",O=fv(v,u),j=_v({document:O.document,author:g,force:n.force,enforcement:o.governance.ownership_enforcement,resolvedId:c}),$=uv(O.document,_);await ws({pm_root:s,operation:"restore",before:O.document,after:_,changed_fields:$,sdk:Is({pmRoot:s,settings:o,typeToFolder:i.type_to_folder})});let xe=je(_,{format:N,schema:o.schema}),te=Gt(s,_.metadata.type,c,N,i.type_to_folder),_e=await wn(s,g),ce=[];try{await ue(te,xe),E&&te!==E&&await Ga.rm(E);let pt=qe({nowIso:S(),author:g,op:"restore",before:O.document,after:_,message:n.message});try{await Tt(a.historyPath,pt)}catch(ft){throw await hv({existingItemPath:E,resolvedOriginalRaw:O.originalRaw,restoredItemPath:te}),ft}ce=await vn({pmRoot:s,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:te,previousItemPath:E??void 0,document:_})}finally{await _e()}let Qe=await gv({restoredItemPath:te,historyPath:a.historyPath,before:O.document,after:_});fn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:O.document.metadata.status,status:_.metadata.status,previous:Kt(O.document.metadata,$),current:Kt(_.metadata,$),changed_fields:$});let ut=u[p.historyIndex];return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,entry_ts:ut.ts,entry_op:ut.op},changed_fields:$,warnings:[...a.historyPolicyWarnings,...j,...ce,...Qe]}}finally{await 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]="4da07a98-855e-59cf-a6a4-2f59a8b3c0bd")}catch{}})();var Sf=1,ja="close-many",yv=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function bv(e,t){return nr(e,t,{includePagination:!1})}function wv(e,t){return nr(e,t)}function vv(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)}function kv(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(s=>s.trim().length>0)||(t[n]=r);return t}function Sv(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new l("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",d.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 Ev(e,t){let n=M(t.schema),r=x(t,I()),s=await oe(e,t.item_format,r.type_to_folder,void 0,t.schema),o=new Map,i=new Map;for(let a of s){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),se(a.status,n)))continue;let c=o.get(a.parent);c?c.push(a.id):o.set(a.parent,[a.id])}for(let a of o.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:o,parentByChild:i}}function kf(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let s=0,o=t.get(e),i=[],a=new Set,c=!1;for(;o!==void 0&&!a.has(o);){let m=n?.get(o);if(m!==void 0){s+=m+1;break}a.add(o),i.push(o),s+=1,o=t.get(o)}if(o!==void 0&&a.has(o)&&(c=!0),!c){n?.set(e,s);for(let[m,u]of i.entries())n?.set(u,s-m-1)}return s}async function Tv(e){let t=await $s(e.pmRoot,ja,e.rollbackId,Sf),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Ms(t.items,(s,o)=>Wt(s,o,{author:e.options.author,message:n,force:!0},e.global));return{...qt({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 Av(e,t,n,r,s){return e.map(o=>{let i=(t.get(o.id)??[]).filter(c=>!n.has(c)),a=!Ef(o,r,s);return{id:o.id,title:typeof o.title=="string"?o.title:"",status:o.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function Cv(e){let t=await Fs(e.pmRoot,ja,e.checkpointId,{schema_version:Sf,id:e.checkpointId,created_at:e.nowValue,author:R(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function Rv(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 s=await it(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:s.changed_fields,...s.warnings&&s.warnings.length>0?{warnings:s.warnings}:{}}),n.push(r.id)}catch(s){t.push({id:r.id,status:"failed",error:un(s)})}}return{rows:t,closedIds:n}}function Iv(e){return typeof e.rollback=="string"?e.rollback:void 0}function xv(e,t){if(t.trim().length===0)throw new l("--rollback requires a checkpoint id",d.USAGE);if(e.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(wv(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function Ov(e){if(!bv(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${yv}). Refusing to match every item.`,d.USAGE)}function Pv(e,t){let n=new Map;return[...e].sort((r,s)=>{let o=kf(s.id,t,n)-kf(r.id,t,n);return o!==0?o:r.id.localeCompare(s.id)})}function Ef(e,t,n){return n||!se(e.status,t)}function Nv(e,t,n){return new Set(e.filter(r=>Ef(r,t,n)).map(r=>r.id))}async function Lv(e){Ov(e.options);let t=M(e.settings.schema),n=Sv(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,s=await It(e.options.status,kv(e.options.list),e.global),{childrenByParent:o,parentByChild:i}=await Ev(e.pmRoot,e.settings),a=Pv(s.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(p=>p.trim()).filter(p=>p.length>0))],m=new Set(a.map(p=>p.id)),u=Nv(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:s,matched:a,unmatchedIds:c.filter(p=>!m.has(p)),planRows:Av(a,o,u,t,r)}}function Fv(e){return{outcome:"effect",exit_code:d.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.length>0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function $v(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 Cv({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 Tf(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=e.dryRun===!0,o=Iv(e);if(vv(e.list),o!==void 0)return xv(e,o),Tv({pmRoot:n,rollbackId:o,options:e,global:t});let i=await Lv({pmRoot:n,settings:r,options:e,global:t});if(s)return Fv(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=S(),m=Ls(ja,c),u=await $v({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 Rv({matched:i.matched,closableIds:a,reason:i.reason,closeOptions:p,global:t}),h=f.filter(b=>b.status==="closed").length,y=f.filter(b=>b.status==="skipped").length,g=f.filter(b=>b.status==="failed").length;return{...qt({applied:h,skipped:y,failed:g,unmatched:i.unmatchedIds.length}),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:h,skipped_count:y,failed_count:g,rows:f,ids:_,...i.unmatchedIds.length>0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}import{readFile as Mv}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]="a7687052-a04e-536e-ace5-a665ebd477e3")}catch{}})();async function qa(e,t){let n=e.add!==void 0,r=e.stdin===!0,s=typeof e.file=="string",o=Number(n)+Number(r)+Number(s);if(o===0)return;if(o>1)throw new l("Specify comment text using only one input source: --add, --stdin, or --file",d.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add")??"",emptyFlag:"--add"};if(r)return{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);try{return{value:await Mv(i,"utf8"),emptyFlag:"--file"}}catch(a){if($a(a)&&Ut(a))throw new l(`--file path not found: ${i}`,d.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${i}": ${c}`,d.USAGE)}}async function Dv(e,t){let n=e.edit,r=e.delete,s=n!==void 0,o=r!==void 0;if(s&&o)throw new l("Specify only one of --edit or --delete",d.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new l("--edit must be a positive integer",d.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new l("--delete must be a positive integer",d.USAGE);if(o){if(await qa(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(s){let c=await qa(e,t);if(c===void 0)throw new l("--edit requires replacement text via positional [text], --add, --stdin, or --file",d.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let i=await qa(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 Af(e,t,n){let r=Le(),s=await Dv(t,r),o=s.mode==="add"||s.mode==="edit",i=s.value??"";return On(e,t,n,{input:{...s,rawValue:t.add??i,value:o?xn(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(s.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]="93184f29-f215-5413-9628-fb5b34523995")}catch{}})();async function Cf(e,t,n){return On(e,t,n,{input:await ao(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>xn(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]="ebd9f151-593f-5081-97da-d78f83de4914")}catch{}})();function Uv(e){if(e===void 0)return;if(e.trim().length===0)throw new l("--add-json must contain a JSON value",d.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new l("--add-json must be valid JSON",d.USAGE,{code:"structured_event_json_invalid"})}return t}function Gv(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 jv(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new l("--since must be a valid ISO timestamp",d.USAGE,{code:"structured_event_since_invalid"});return t}async function Rf(e,t,n){let r=Uv(t.addJson),s=[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&&s)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let o=r===void 0?void 0:J(r),i=[t.since,t.eventType].some(h=>h!==void 0),a=jv(t.since),c=Xn(t.limit),m=await On(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await ao(o===void 0?t:{add:o},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:h=>xn(h),createEntry:h=>r===void 0?h:{...h,format:"json",data:r,event_type:Gv(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(h=>{let y=[h.format==="json",h.data!==void 0].every(Boolean),g=[a===void 0,Date.parse(h.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),b=[!u,h.event_type===u].includes(!0);return[!i,[y,g,b].every(Boolean)].includes(!0)}),f=i?Fa(p,c):p,_=f.filter(h=>h.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]="f9c9b926-c912-548e-a9c7-64c2c69767cd")}catch{}})();function mo(e,t){if(!t&&/[:,=]/.test(e))throw new l(`Invalid --dep value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE)}function cr(e,t,n=ca()){for(let r of t??[])try{Yd(e,r.id,r.kind,n)}catch(s){throw new l(un(s),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function If(e,t){return(await K(e,{schema:t})).document.metadata.created_at}async function qv(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await D(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:If(n,t.schema)}function Kv(e){let t=e.registry.require(e.dependency.kind);return new l(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,d.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 zv(e){let t=e.dependencies.filter(s=>e.registry.resolve(s.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(s.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:s,located:o})=>o===null?[]:[[s,o]])),r=new Map(await Promise.all([...new Set(t.map(({id:s})=>s))].map(async s=>[s,await If(n.get(s),e.context.schema)])));for(let s of e.holders){let o=await qv(s,e.context);if(o!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(o),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw Kv({holder:s,dependency:i,sourceCreatedAt:o,targetCreatedAt:a,registry:e.registry})}}}async function Yt(e){let t=e.registry??ca(),n=(e.dependencies??[]).filter(i=>!ep(i.source_kind)),r=[...new Set(n.map(i=>i.id))],s=await Promise.all(r.map(async i=>({target:i,located:await D(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),o=s.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(o.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${o.length===1?"":"s"} not found: ${o.join(", ")}`,d.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:o,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 ${o.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:o,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${o[0]}" --limit 10`}});return await zv({dependencies:n,missingTargets:o,resolutions:s,holders:e.holders??[],registry:t,context:e}),o.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]="dcbb6070-7457-5454-abf1-fa8153c8efd6")}catch{}})();function uo(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function po(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function fo(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(xr.includes(t))return t;let n=ie(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new l("Confidence must be an integer 0..100 or one of low|med|medium|high",d.USAGE);return n}function _o(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new l("Regression must be one of true|false|1|0",d.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]="afc4f3d5-ba5e-5dd7-abc9-531b319cdb4e")}catch{}})();var Bv=new Set(["none","null"]);function ho(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:Bv.has(e.trim().toLowerCase())}function go(e,t,n){if(!ze(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function be(e,t,n){if(!e||e.length===0||!e.some(o=>ze(o)))return;let s=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${s}`.trim(),d.USAGE)}function yo(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 l(`${n.valueFlag} entries must be strings.`,d.USAGE);let s=r;if(!s.some(a=>ze(a)))continue;if(s.filter(a=>!ze(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.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]="2fcfbe50-039b-5031-8b18-a208908a0d87")}catch{}})();function Of(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new l(`${t} must be one of true|false|1|0|yes|no`,d.USAGE)}function Ka(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function we(e,t,n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE);return e}var Pf=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Hv(e,t){return t==="defined"?e!==void 0:!!e}function xf(e,t,n){if(!Hv(e,n))return;let r=ie(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function Vv(e,t,n){let r=e?Q(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new l("--event recur_until must be at or after start",d.USAGE);return r}function Wv(e){return Array.from(new Set(Ka(e).map(t=>we(t.toLowerCase(),qd,"event weekday")))).sort((t,n)=>Ti(t)-Ti(n))}function Yv(e){return Array.from(new Set(Ka(e).map(t=>{let n=ie(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new l("--event recur_by_month_day values must be integers 1..31",d.USAGE);return n}))).sort((t,n)=>t-n)}function Jv(e,t){return Array.from(new Set(Ka(e).map(n=>Q(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Nf(e,t,n,r){let s=e.recur_freq?.trim(),o=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(![s,o,i,a,c,m,u].some(E=>E!==void 0))return;if(!s)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let f=we(s.toLowerCase(),jd,"event recurrence frequency"),_=xf(o,"recur_interval",r),h=xf(i,"recur_count",r),y=Vv(a,t,n),g=Wv(c),b=Yv(m),v=Jv(u,n);return{freq:f,interval:_,count:h,until:y,by_weekday:g.length>0?g:void 0,by_month_day:b.length>0?b:void 0,exdates:v.length>0?v: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]="8248687e-ba97-5e1b-afbf-a322a72eb1aa")}catch{}})();var Lf="--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.",Xv="--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).",Qv=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,Zv=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,$f=1e3,za=60*$f,ek=60*za;function Ff(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new l(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,d.USAGE);return n.toISOString()}function tk(e,t){let n=new Date(e),r=t.trim(),s=Qv.exec(r);if(s){let a=s[1]==="-"?-1:1,c=Number.parseInt(s[2],10)*a;return Ff(n.getTime()+c*za,r)}let o=Zv.exec(r);if(o){let[,a,c,m,u]=o;if(c||m||u){let f=a==="-"?-1:1,_=Number.parseInt(c??"0",10),h=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),g=_*ek+h*za+y*$f;return Ff(n.getTime()+f*g,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return Q(i,n,"event.duration")}function Mf(e,t,n,r){if(t&&n)throw new l(Xv,d.USAGE);if(n){let o=tk(e,n);if(o<e)throw new l(Lf,d.USAGE);return o===e?void 0:o}if(!t)return;let s=Q(t,r,"event.end");if(s<e)throw new l(Lf,d.USAGE);if(s!==e)return 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]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var nk=["at","date","text","title"],rk=["start","date","end","duration","title","description","location","timezone","all_day",...Pf],sk=["key","value"];function Df(e,t){return t==="trimmed"?e?.trim():e}function ok(e,t){return t==="defined"?e!==void 0:!!e}function bo(e,t,n){return e.map(r=>{let s=ne(r,"--reminder");Ke(s,"--reminder",nk);let o=Df(s.at??s.date,n.valueMode),i=Df(s.text??s.title,n.valueMode);if(!o||!i)throw new l("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",d.USAGE);let a=i.trim();if(!a)throw new l("--reminder text must not be empty",d.USAGE);return{at:Q(o,t,"reminder.at"),text:a}})}function wo(e,t,n){return e.map(r=>{let s=ne(r,"--event");Ke(s,"--event",rk);let o=(s.start??s.date)?.trim();if(!o)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let i=Q(o,t,"event.start"),a=s.end?.trim(),c=s.duration?.trim(),m=Mf(i,a,c,t),u=s.title,p=s.description,f=s.location,_=s.timezone,h=u?.trim(),y=p?.trim(),g=f?.trim(),b=_?.trim(),v=[["title",u,h],["description",p,y],["location",f,g],["timezone",_,b]];for(let[j,$,xe]of v)if($!==void 0&&!xe)throw new l(`--event ${j} must not be empty`,d.USAGE);let E=s.all_day?.trim(),N=Nf(s,i,t,n.recurrenceEmptyNumericGuard),O=ok(E,n.allDayEmptyGuard)?Of(E,"--event all_day"):void 0;return{start_at:i,end_at:m,title:h,description:y,location:g,all_day:O,timezone:b,recurrence:N}})}function vo(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new l("--type-option values must not be empty",d.USAGE);let s,o;if(r.includes(",")||r.includes(`
|
|
5
|
+
`)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=ne(r,"--type-option");Ke(a,"--type-option",sk),s=a.key?.trim(),o=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 l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);s=r.slice(0,m).trim(),o=r.slice(m+1).trim()}if(!s||!o)throw new l("--type-option requires key and value",d.USAGE);t[s]=o}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]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var ik=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Uf(e,t,n,r){if(ik.has(t.trim().toLowerCase())||n!==r.open_status)return;let s=_s("in_progress",r);if(!(s===void 0||s===r.open_status))return{command:`pm start-task ${e}`,to_status: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]="2b20ab37-ffbe-5c65-ac0f-800abf876e16")}catch{}})();var Jt=["command","cmd","path","scope","timeout","timeout_seconds","pm_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"],ak=new Set(Jt),ck=Jt.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),dk=new RegExp(`^(?:[-*+]\\s+)?(?:${ck})\\s*[:=]`,"i");function ko(e){return e.startsWith("```")||e.includes(`
|
|
6
|
+
`)?!0:dk.test(e)}function So(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!ak.has(i)){r.push(s);continue}if(Object.hasOwn(n,i))throw new l(`${t} provides key "${s}" more than once after case normalization`,d.USAGE);n[i]=o}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(s=>`"${s}"`).join(", ")}. Allowed keys: ${Jt.join(", ")}.`,d.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new l(`${t} command and cmd must match when both are provided`,d.USAGE);let{cmd:s,...o}=n;return{...o,command:o.command??s}}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]="74163bed-a473-543e-ae6a-0d5091b3b3a9")}catch{}})();var Qt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Ws,up,"FORCE_COLOR"]),Ao=/^[A-Za-z_][A-Za-z0-9_]*$/,Xt=["schema","tracker","auto"];function dr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1);if(!Ao.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(Qt.has(i.toUpperCase()))throw new l(`${t} env_set key "${i}" is reserved for sandbox safety`,d.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function lr(e,t){if(!e)return;let n=An(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,d.USAGE);for(let r of n){if(!Ao.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(Qt.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function Co(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,d.USAGE)}function Ro(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Xt.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${Xt.join(", ")}`,d.USAGE)}function Zt(e){if(!e)return;let t=An(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Nn(e,t,n){let r=Zt(e);if(!(!r||r.length===0)){for(let s of r)try{new RegExp(s,"m")}catch(o){throw new l(`${t} ${n} includes invalid regex "${s}": ${o instanceof Error?o.message:String(o)}`,d.USAGE)}return r}}function Io(e,t){if(!e)return;let n=ie(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,d.USAGE);return n}function xo(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,d.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function Oo(e,t){if(!e)return;let n=e.split(/[;\n]/).map(s=>s.trim()).filter(s=>s.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,d.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${i}" must be numeric`,d.USAGE);r[i]=c}return Object.keys(r).length>0?r:void 0}var lk=new Set(Jt);function Po(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mk(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!lk.has(i)){r.push(s);continue}if(Object.hasOwn(n,i))throw t(`provides key "${s}" more than once after case normalization`);n[i]=o}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(s=>`"${s}"`).join(", ")}. Allowed keys: ${Jt.join(", ")}.`);return n}function Pn(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 Eo(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let s=typeof r=="string"?[r]:r;if(!Array.isArray(s)||s.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let o=s.filter(i=>i.length>0);return o.length>0?o:void 0}function Gf(e,t,n){let r=Eo(e,t,n);if(r){for(let s of r)try{new RegExp(s,"m")}catch(o){throw n(`field "${t}" includes invalid regex "${s}": ${o instanceof Error?o.message:String(o)}`)}return r}}function To(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 uk(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let s=n===void 0?void 0:To(n,"timeout_seconds",t),o=r===void 0?void 0:To(r,"timeout",t);if(s!==void 0&&o!==void 0&&s!==o)throw t("timeout and timeout_seconds must match when both are provided");let i=s??o;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function pk(e,t){let n=Pn(e,"scope",t);if(n===void 0)return"project";if(!Ze.includes(n))throw t(`field "scope" must be one of: ${Ze.join(", ")}`);return n}function fk(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Po(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[s,o]of Object.entries(n)){if(typeof o!="string")throw t(`field "env_set" value for "${s}" must be a string`);if(!Ao.test(s))throw t(`field "env_set" key "${s}" is invalid`);if(Qt.has(s.toUpperCase()))throw t(`field "env_set" key "${s}" is reserved for sandbox safety`);r[s]=o}return Object.keys(r).length>0?r:void 0}function _k(e,t){let n=Eo(e,"env_clear",t);if(n){for(let r of n){if(!Ao.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(Qt.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function hk(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 gk(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=To(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 yk(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Po(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[s,o]of Object.entries(n)){if(s.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean")throw t(`field "assert_json_field_equals" value for "${s}" must be a string, number, or boolean`);r[s]=String(o)}return Object.keys(r).length>0?r:void 0}function bk(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Po(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[s,o]of Object.entries(n)){if(s.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[s]=To(o,`assert_json_field_gte.${s}`,t)}return Object.keys(r).length>0?r:void 0}function wk(e,t,n){let r=p=>new l(`${n} ${t} ${p}`,d.USAGE);if(!Po(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Jt.join(", ")}.`);let s=mk(e,r),o=Pn(s,"command",r),i=Pn(s,"cmd",r);if(o!==void 0&&i!==void 0&&o!==i)throw r("command and cmd must match when both are provided");let a=o??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=Pn(s,"path",r),m=Pn(s,"pm_context_mode",r);if(m!==void 0&&!Xt.includes(m))throw r(`field "pm_context_mode" must be one of: ${Xt.join(", ")}`);let u=Pn(s,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:pk(s,r),timeout_seconds:uk(s,r),pm_context_mode:m,env_set:fk(s,r),env_clear:_k(s,r),shared_host_safe:hk(s,"shared_host_safe",r),assert_stdout_contains:Eo(s,"assert_stdout_contains",r),assert_stdout_regex:Gf(s,"assert_stdout_regex",r),assert_stderr_contains:Eo(s,"assert_stderr_contains",r),assert_stderr_regex:Gf(s,"assert_stderr_regex",r),assert_stdout_min_lines:gk(s,r),assert_json_field_equals:yk(s,r),assert_json_field_gte:bk(s,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function jf(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,d.USAGE);let r;try{r=JSON.parse(n)}catch(o){throw new l(`${t} value is not valid JSON: ${o instanceof Error?o.message:String(o)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let s=Array.isArray(r)?r:[r];if(s.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return s.map((o,i)=>wk(o,s.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]="0062e981-158a-5e6a-b028-6c7cef0f59ba")}catch{}})();var Ba=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Ha=[{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"}],qf=[...Ba,...Ha],No=[{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 Lo(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 s=r.trim().toLowerCase();if(!s)throw new l("--unset values must not be empty",d.USAGE);if(ze(s))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let o=e.resolveDefinition(s);if(!o)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(o.metadataKey),n.add(o.optionKey)}return{metadataKeys:t,optionKeys:n}}function Fo(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let s=n.command_to_fields?.get(t)??[];for(let o of s){if(o.allow_unset===!1)continue;let i=new Set;if(typeof o.key=="string"&&o.key.length>0&&i.add(o.key.toLowerCase()),typeof o.metadata_key=="string"&&o.metadata_key.length>0&&i.add(o.metadata_key.toLowerCase()),typeof o.cli_flag=="string"&&o.cli_flag.length>0&&(i.add(o.cli_flag.replaceAll("-","_").toLowerCase()),i.add(o.cli_flag.toLowerCase())),Array.isArray(o.cli_aliases))for(let a of o.cli_aliases)typeof a!="string"||a.length===0||(i.add(a.replaceAll("-","_").toLowerCase()),i.add(a.toLowerCase()));if(i.has(r))return{optionKey:o.key,metadataKey:o.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]="002f45a2-edc3-5aa0-9af8-d9b1dfecc097")}catch{}})();var vk={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 kk(e){return vk[e]}function Va(e){return kk(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]="7d69bb56-9fab-5059-9357-5b6bea2078b9")}catch{}})();var Sk=["strict","progressive"],Ek=["lightweight"],Hf=new Set(["Reminder","Meeting","Event"]),Tk=new Set(["author","created_at","text"]),Ya=[...qf,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...No],Ak=(()=>{let e=new Map;for(let t of Ya)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),$o=new Map(Ya.map(e=>[e.optionKey,e.canonical])),Ck=Ya.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function Rk(e,t){let n=W(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function Ik(e,t){let n=e.default_status;if(n!==void 0){let r=W(n,t);if(r)return r}return t.open_status}function Wa(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}var xk=ho();function Vf(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=s=>{let o=t.unset?[...t.unset]:[];o.includes(s)||o.push(s),t.unset=o};ze(t.template)&&(t.template=void 0);let r=new Set([...$o.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!ze(o))continue;let i=s==="rank"?"order":$o.get(s)??s;n(i),t[s]=void 0}return yo(t,xk)}function de(e){if(e!==void 0)return e}function Ok(e,t){return Lo({raw:e,supportedFields:Ck,resolveDefinition:n=>Ak.get(n)??Fo(n,"create",t)})}var Kf=["id","kind","type","author","created_at","source_kind"],Mo=["path","scope","note"];function Pk(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let i=o.trim(),a=Ja(i,Kf);mo(i,a);let c=a?ne(o,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",Kf);let m=de(c.id),u=Nk(de(c.kind??c.type));if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to create a related dependency",d.USAGE);if(m.trim().toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=Qn(de(c.source_kind)),f=de(c.author);return{id:Zn(m,n,p),kind:we(u,Dt,"dependency kind"),created_at:Wa(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function Nk(e){return typeof e=="string"?$r(e)??e.trim():e}function Ja(e,t){if(e.startsWith("```")||e.includes(`
|
|
7
|
+
`))return!0;let n=t.map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${n})\\s*[:=]`,"i").test(e)?!0:Bs(e)}function tn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(be(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 l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:a}},m;try{m=ne(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!Tk.has(f)).length>0)return{created_at:Wa(m.created_at,n),author:de(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:Wa(m.created_at,n),author:de(m.author)??r,text:p}}),explicitEmpty:!1})}function Xa(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),s=Ja(r,Mo),o=s?ne(n,"--file"):{path:r};if(s&&Ke(o,"--file",Mo),!o.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:o.path,scope:we(o.scope??"project",Ze,"file scope"),note:de(o.note)}}),explicitEmpty:!1})}function Qa(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),s=ko(r)?So(ne(n,"--test"),"--test"):{command:r},o=de(s.command),i=de(s.path);if(!o)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let a=de(s.timeout_seconds),c=de(s.timeout);if(a&&c&&a!==c)throw new l("--test timeout and timeout_seconds must match when both are provided",d.USAGE);let m=a??c;return{command:o,path:i,scope:we(s.scope??"project",Ze,"test scope"),timeout_seconds:m?ie(m,"timeout_seconds"):void 0,pm_context_mode:Ro(s.pm_context_mode,"--test"),env_set:dr(s.env_set,"--test"),env_clear:lr(s.env_clear,"--test"),shared_host_safe:Co(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Zt(s.assert_stdout_contains),assert_stdout_regex:Nn(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Zt(s.assert_stderr_contains),assert_stderr_regex:Nn(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Io(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:xo(s.assert_json_field_equals,"--test"),assert_json_field_gte:Oo(s.assert_json_field_gte,"--test"),note:de(s.note)}}),explicitEmpty:!1})}function Za(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),s=Ja(r,Mo),o=s?ne(n,"--doc"):{path:r};if(s&&Ke(o,"--doc",Mo),!o.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:o.path,scope:we(o.scope??"project",Ze,"doc scope"),note:de(o.note)}}),explicitEmpty:!1})}function Lk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--reminder","Use --clear-reminders to clear reminders."),{values:bo(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function Fk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--event","Use --clear-events to clear linked events."),{values:wo(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function $k(e,t,n,r=[]){let s=[...Or.filter(o=>e[o]!==void 0),...r.filter(o=>e[o]!==void 0),...t.length>0?["body"]:[],...n.map(o=>`unset:${o}`)];return Array.from(new Set(s))}function Mk(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function zf(e,t,n){let r=Kn("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function Dk(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 Wf(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 Uk(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(zf(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(zf(r,e.name,"required_create_repeatables"));return n}function Gk(e,t,n,r){for(let s of e)if(!(!Wf(t,s)&&!n.has(s)))throw new l(`Option ${he("create",s)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function jk(e,t,n){if(t!=="strict")return;let r=e.filter(o=>n.has(o)&&!Va(o));if(r.length===0)return;let s=[...new Set(r.map(o=>he("create",o)))].sort((o,i)=>o.localeCompare(i));throw new l(`Strict create mode requires concrete values for ${s.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function qk(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(be(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:vo(e),explicitEmpty:!1})}async function Kk(e){let t=Le();return{...e,body:await t.resolveValue(e.body,"--body"),dep:await t.resolveList(e.dep,"--dep"),comment:await t.resolveList(e.comment,"--comment"),note:await t.resolveList(e.note,"--note"),learning:await t.resolveList(e.learning,"--learning"),file:await t.resolveList(e.file,"--file"),test:await t.resolveList(e.test,"--test"),doc:await t.resolveList(e.doc,"--doc"),reminder:await t.resolveList(e.reminder,"--reminder"),event:await t.resolveList(e.event,"--event"),typeOption:await t.resolveList(e.typeOption,"--type-option"),field:await t.resolveList(e.field,"--field")}}function zk(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${Sk.join(", ")}`,d.USAGE)}function Bk(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new l("--schedule-preset must not be empty",d.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new l(`Invalid --schedule-preset value "${e}". Allowed: ${Ek.join(", ")}`,d.USAGE)}function Hk(e,t,n){let r=zk(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",d.USAGE);return"progressive"}function Vk(e,t,n,r){let s=e.name,o=Dk(t),i=Uk(e,n),a=mn(e,"create",i);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);Gk(a.disabled,o,r,s),jk(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&Va(u)?!0:Wf(o,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>he("create",u)))].sort((u,p)=>u.localeCompare(p))}var Yf=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function Wk(e,t){let n=[];for(let r of e){let s=r.match(Yf);s&&s[2]===t&&n.push(s[1])}return[...new Set(n)].sort((r,s)=>r.localeCompare(s))}function Yk(e,t){return e.filter(n=>{let r=n.match(Yf);return!r||r[2]!==t})}function Jk(e,t,n,r){let s=Yk(e,t);if(s.length===0)return;let o=Jf(n,[],[],r.open_status);throw new l(s.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[o],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function Xk(e,t){let r=e.options.find(s=>s.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function Qk(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 Jf(e,t,n,r){let s=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],o=["--status","--priority","--message"],i=[...new Set([...o,...t])],a=new Set(["--title","--description","--type"]);for(let c of i)a.has(c)||(s.push(...Qk(c,e.name,r)),a.add(c));for(let c of n){let m=Xk(e,c);s.push("--type-option",`${c}=${m}`)}return s.join(" ")}function ec(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new l("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",d.USAGE):new l('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.',d.USAGE):new l(`Missing required option ${t}`,d.USAGE);return n}function Zk(e){return Tn(e)}function eS(e,t){let n={};for(let[r,s]of Object.entries(e))n[r]=Array.isArray(s)?[...s]:s;for(let[r,s]of Object.entries(t))s!==void 0&&(n[r]=Array.isArray(s)?[...s]:s);return n}function tS(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function nS(){let e=I();return e?e.commands.some(t=>t.action==="templates-show"||tS(t.command)==="templates show"):!1}function rS(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new l(`Templates package returned invalid payload for template "${t}". Expected an options object.`,d.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Templates package returned invalid options for template "${t}".`,d.GENERIC_FAILURE);let r={};for(let[s,o]of Object.entries(n)){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"){r[s]=o;continue}if(Array.isArray(o)&&o.every(i=>typeof i=="string")){r[s]=[...o];continue}throw new l(`Templates package returned unsupported option value for "${s}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function sS(e,t,n){if(!nS())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await vs({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let s=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${s}`,d.USAGE)}return rS(r.result,e)}function oS(e){return k(C(e)).then(t=>{if(!t)throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)})}function B(e,t,n){return e.has(t)||n===void 0?void 0:de(n)}function en(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var iS=new Set(["milestone","meeting","reminder","event"]);function Xf(e,t,n,r){let s=t!==void 0,o=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return iS.has(e.toLowerCase())&&!s&&!o&&!i}function aS(e,t,n,r,s){let o=[];return e.toLowerCase()==="event"&&(s===void 0||s.length===0)&&o.push(`event_without_schedule:${t}:no_time_set`),Xf(e,n,r,s)&&o.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)`),o}async function cS(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let s=await ks(r);return s===void 0?{parent:e,parentSource:void 0}:{parent:s,parentSource:"focus"}}async function dS(e,t,n,r,s,o){let i=Gs(s);if(qs(r,i,t.id_prefix),await D(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let c=ge(i,t.id_prefix);return{parent:i,warnings:js(c,o).warnings}}async function lS(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await dS(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function mS(e){if(e.explicitId===void 0)return Jn(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 l("--id must be a string",d.USAGE);let t=e.explicitId.trim();if(t.length===0||Gu(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=ge(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new l("--id must contain only letters, numbers, and dashes after normalization",d.USAGE);return n}function Bf(e,t,n,r,s){let o=B(e,t,n);if(o===void 0)return{value:void 0,warnings:[]};let i=Hs(r,o,s);return{value:i.value,warnings:i.warnings}}async function uS(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:s,blockedBy:o,status:i,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(o===void 0)return{dependencyValues:u,status:i};let p=ge(o,n.id_prefix),f=await D(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 h=s.blocked_statuses.has("blocked")?"blocked":[...s.blocked_statuses].sort((y,g)=>y.localeCompare(g))[0]??s.open_status;return{dependencyValues:u,status:h}}function pS(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let s=t.governance.create_default_type?.trim();if(s&&s.length>0&&pe(s,n)){e.type=s;return}pe("Task",n)&&(e.type="Task")}function fS(e,t){return e.options.filter(n=>Kn("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new l(`Template custom type option "${n.key}" must be a string, number, or boolean value`,d.USAGE)})}async function _S(e,t,n,r,s){let o=e,i=[];if(o.template!==void 0){let h=o.template.trim();if(h.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let y=await sS(h,t,n);o=Vf(eS(y,o))}if(o.type===void 0&&pS(o,r,s),o.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let a=pe(o.type,s);if(!a){let h=qu(o.type),y=h?pe(h,s):void 0;if(y)i.push(`type_coercion:${o.type.trim()}:${y}`),o.type=y,a=y;else throw new l(kt(o.type,s.types,St(n,r.schema)),d.USAGE)}let c=Lr(a,s);if(!c)throw new l(`Invalid type value "${o.type}"`,d.USAGE);let m=c.name,u=fS(c,o),p=u.map(h=>`${h.key}=${String(o[h.key])}`);if(p.length>0){o.typeOption=[...p,...o.typeOption??[]];for(let h of u)delete o[h.key]}let f=Bk(o.schedulePreset);if(f!==void 0&&!Hf.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=Hk(o.createMode,f,r.governance.create_mode_default);return{resolvedOptions:o,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function hS(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),s=[{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 o of s)if(o.enabled){if(o.values&&o.values.length>0)throw new l(`Cannot combine ${o.clearFlag} with ${o.valueFlag}`,d.USAGE);n.add(o.metadataKey),r.add(o.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function gS(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,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=$o.get(r)??r;throw new l(`Cannot combine --unset ${o} with ${he("create",r)}`,d.USAGE)}}function yS(e){let t=(n,r)=>{let s=$o.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;go(n,he("create",r),o)};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 bS(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,d.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new l(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,d.USAGE)}function wS(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:s,openStatus:o,type:i,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(_=>{let h=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${h}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),u=[Jf(n,r,s,o),...m.map(_=>_.example)].join(" "),p=[`Run "pm create --help --type ${i}" for type-aware required option guidance.`];t.includes("--title")&&p.push('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".'),Hf.has(i)&&p.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),m.length>0&&p.push(`Required custom field formats: ${m.map(_=>_.description).join("; ")}.`);let f=t.length===1?`Missing required option ${t[0]} for type "${i}"`:`Missing required options ${t.join(", ")} for type "${i}"`;throw new l(f,d.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${i}" in one invocation.`,examples:[u],nextSteps:p,recovery:a==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:["--create-mode progressive",...t]}:void 0})}function vS(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?Rt(t.tags):[];return Sn(n,t.addTags)}function kS(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new l("--order and --rank must match when both are provided",d.USAGE);let n=t.order??t.rank,r=en(e,"order",n,s=>ie(s,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function SS(e,t,n,r,s,o){if(r.completedAt!==void 0&&e!==t.close_status)throw new l("--completed-at requires a terminal create status.",d.USAGE);let i=e!==t.close_status?void 0:r.completedAt===void 0?o:Q(r.completedAt,new Date(o),"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:s}:{explicit:r.closeReason};return{closeReason:Da(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function ES(e){let{pmRoot:t,type:n,id:r,settings:s,typeRegistry:o,author:i,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:h}=e,y=Gt(t,n,r,s.item_format,o.type_to_folder),g=Se(t,r),b=await Pe(t,r,s.locks.ttl_seconds,i,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),v=[];try{let E=c.metadata.dependencies&&c.metadata.dependencies.length>0?await oe(t,s.item_format,o.type_to_folder,void 0,s.schema):void 0;if(await D(t,r,s.id_prefix,s.item_format,o.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);await ws({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:Is({pmRoot:t,settings:s,typeToFolder:o.type_to_folder})});let O=await wn(t,i,{required:s.governance.duplicate_detection_mode==="strict"&&h!==!0}),j=[];try{s.governance.duplicate_detection_mode==="strict"&&h!==!0&&await In(_,{pmRoot:t,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1}),await ue(y,je(c,{format:s.item_format,schema:s.schema,extensionFieldNames:a}));try{let $=qe({nowIso:f,author:i,op:"create",before:m,after:c,message:u});await Tt(g,$)}catch($){throw await ln(y),$}j=await vn({pmRoot:t,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:y,document:c})}finally{await O()}v=[...E?to(E,[...E,c.metadata],r):[],...j,...await z({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await z({path:g,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],fn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Kt(c.metadata,p),changed_fields:p})}finally{await b()}return v}async function xt(e,t){let n=Vf(await Kk(e)),r=T(process.cwd(),t.path);await oS(r);let s=await A(r),o=M(s.schema),i=Ve(s.schema),a=x(s,I()),c=await _S(n,t,r,s,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=Ok(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=hS(n,f);gS(n,f),yS(n);let y=Vk(m,n,p,h),g=S(),b=R(de(n.author),s.author_default),v=Pk(n.dep,g,s.id_prefix,b),E=tn("--comment",n.comment,g,b),N=tn("--note",n.note,g,b),O=tn("--learning",n.learning,g,b),j=Xa(n.file),$=Qa(n.test),xe=Za(n.doc),te=Lk(n.reminder,g),_e=Fk(n.event,g),ce=qk(n.typeOption),Qe=zn(u,ce.values,a),ut=I(),pt=bt(ut),ft=Pr(n.field,ut),_t=du(n,i,u),hi=new Set(_t.missing_required_flags),gi=i.definitions.filter(H=>hi.has(`--${H.cli_flag}`));bS(ft,_t,f);let jn=Wk(Qe.errors,u),ht=jn.map(H=>`--type-option ${H}=<value>`),Sd=[...new Set([...y,...ht,..._t.missing_required_flags])].sort((H,Si)=>H.localeCompare(Si));wS({combinedMissingFlags:Sd,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:jn,openStatus:o.open_status,type:u,createMode:p,missingRequiredRuntimeFields:gi}),Jk(Qe.errors,u,m,o);let ke=await mS({pmRoot:r,settings:s,typeRegistry:a,explicitId:n.id}),Oe=n.status!==void 0?Rk(n.status,o):Ik(m,o),$t=n.priority!==void 0?Zk(n.priority):2,P=f.metadataKeys,gt=vS(P,n),qn=en(P,"deadline",n.deadline,H=>Q(H,new Date(g),"deadline")),Ue=en(P,"estimated_minutes",n.estimatedMinutes,H=>En(H,"estimated-minutes")),Tr=B(P,"acceptance_criteria",n.acceptanceCriteria),pb=B(P,"definition_of_ready",n.definitionOfReady),fb=kS(P,n),_b=B(P,"goal",n.goal),hb=B(P,"objective",n.objective),gb=B(P,"value",n.value),yb=B(P,"impact",n.impact),bb=B(P,"outcome",n.outcome),wb=B(P,"why_now",n.whyNow),vb=B(P,"assignee",n.assignee),kb=P.has("author")?void 0:de(n.author)??b,Sb=B(P,"parent",n.parent),Ed=await cS(Sb,n,P,r),yi=Ed.parent,Eb=Ed.parentSource,Tb=B(P,"reviewer",n.reviewer),Ab=en(P,"risk",n.risk,H=>we(uo(H),cn,"risk")),Cb=en(P,"confidence",n.confidence,H=>fo(H)),Rb=n.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,Td=s.validation.sprint_release_format,Mt=[...c.warnings,...aS(u,ke,qn,te.values,_e.values)],Ad=await lS({itemId:ke,parent:yi,pmRoot:r,settings:s,typeRegistry:a,policy:Rb});yi=Ad.parent,Mt.push(...Ad.warnings);let Cd=Bf(P,"sprint",n.sprint,"sprint",Td),Ib=Cd.value;Mt.push(...Cd.warnings);let Rd=Bf(P,"release",n.release,"release",Td),xb=Rd.value;Mt.push(...Rd.warnings);let Id=B(P,"blocked_by",n.blockedBy),xd=await uS({pmRoot:r,settings:s,typeRegistry:a,statusRegistry:o,blockedBy:Id,dependencyValues:v.values,status:Oe,statusExplicit:n.status!==void 0,nowValue:g,author:b}),bi=xd.dependencyValues;cr(ke,bi),Mt.push(...await Yt({pmRoot:r,dependencies:bi,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:ke,createdAt:g}],schema:s.schema})),Oe=xd.status;let Ob=B(P,"blocked_reason",n.blockedReason),Pb=B(P,"unblock_note",n.unblockNote),Nb=B(P,"reporter",n.reporter),Lb=en(P,"severity",n.severity,H=>we(po(H),dn,"severity")),Fb=B(P,"environment",n.environment),$b=B(P,"repro_steps",n.reproSteps),Od=B(P,"resolution",n.resolution),Mb=B(P,"expected_result",n.expectedResult),Db=B(P,"actual_result",n.actualResult),Ub=B(P,"affected_version",n.affectedVersion),Gb=B(P,"fixed_version",n.fixedVersion),jb=B(P,"component",n.component),qb=en(P,"regression",n.regression,H=>_o(H)),Kb=B(P,"customer_impact",n.customerImpact),wi=ec(n.title,"--title"),vi=n.description??"",Ar=n.body??"",Pd=await In({title:wi,description:vi,body:Ar},{pmRoot:r,mode:s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Mt.push(...no(Pd));let ki=SS(Oe,o,s,n,Od,g),zb=ki.closeReason,Bb=Oe===o.close_status?g:void 0,Hb=ki.completedAt;Mt.push(...ki.warnings);let Cr=ea({id:ke,title:wi,description:vi,type:u,type_options:Qe.normalized,status:Oe,closed_at:Bb,completed_at:Hb,close_reason:zb,priority:$t,tags:gt,created_at:g,updated_at:g,deadline:qn,assignee:vb,author:kb,estimated_minutes:Ue,acceptance_criteria:Tr,definition_of_ready:pb,order:fb,goal:_b,objective:hb,value:gb,impact:yb,outcome:bb,why_now:wb,parent:yi,reviewer:Tb,risk:Ab,confidence:Cb,sprint:Ib,release:xb,blocked_by:Id,blocked_reason:Ob,unblock_note:Pb,reporter:Nb,severity:Lb,environment:Fb,repro_steps:$b,resolution:Od,expected_result:Mb,actual_result:Db,affected_version:Ub,fixed_version:Gb,component:jb,regression:qb,customer_impact:Kb,dependencies:bi,comments:E.values,notes:N.values,learnings:O.values,files:j.values,tests:$.values,docs:xe.values,reminders:te.values,events:_e.values,...ft,..._t.values});try{Nr(Cr,ut)}catch(H){throw new l(H instanceof Error?H.message:"Invalid extension item field values",d.USAGE)}let Vb=We({metadata:Cr,body:Ar},{schema:s.schema,extensionFieldNames:pt}),Wb={metadata:{},body:""},Nd=[..._].sort((H,Si)=>H.localeCompare(Si)),Yb=Mk(n.message,Nd),Ld=$k(Cr,Ar,Nd,[...Object.keys(ft),...Object.keys(_t.values??{})]),Jb=await ES({pmRoot:r,type:u,id:ke,settings:s,typeRegistry:a,author:b,extensionFieldNames:pt,afterDocument:Vb,beforeDocument:Wb,historyMessage:Yb,changedFields:Ld,nowValue:g,similarityCandidate:{title:wi,description:vi,body:Ar},allowDuplicate:n.allowDuplicate}),Fd=structuredClone(Cr);p==="strict"&&_.has("dependencies")&&(Fd.dependencies=[]);let Xb=Uf(ke,u,Oe,o);return Xf(u,qn,te.values,_e.values)&&yu(`[pm] warning: ${u} '${ke}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${ke} --deadline <ISO>' or 'pm update ${ke} --event "start=<ISO>,end=<ISO>"'.`),{item:Fd,changed_fields:Ld,warnings:[...Mt,...Jb],...Object.fromEntries([["parent_source",Eb],["next_transition",Xb],["similarity_advisory",Pd]].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]="3ab4f16d-ce37-546e-a2f6-0495fd1967c7")}catch{}})();var sc=[...Ba,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Ha,...No],TS=(()=>{let e=new Map;for(let t of sc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Do=new Map(sc.map(e=>[e.optionKey,e.canonical])),AS=sc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),CS=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),RS=ho({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function IS(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=s=>{let o=t.unset?[...t.unset]:[];o.includes(s)||o.push(s),t.unset=o},r=new Set([...Do.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!ze(o))continue;let i=s==="rank"?"order":Do.get(s)??s;n(i),t[s]=void 0}return yo(t,RS)}function i_(e,t,n=[]){return Lo({raw:e,supportedFields:AS,resolveDefinition:r=>{let s=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return TS.get(r)??Fo(r,"update",t)??(s?{optionKey:"field",metadataKey:s}:void 0)}})}var Qf=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 Zf(e){let t=e.disallowedFlags.flatMap(r=>{let s=Qf.get(r);return s?[s(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let s=Qf.get(r);return s?[`Replace ${r} with: ${s(e.id)}`]:[]});return new l(e.message,d.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function xS(e,t,n){let r=t.ownershipMetadataBypass===!0,s=t.ownershipDependencyBypass===!0;if(!r&&!s)return;if(r&&s)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let o=(c,m,u)=>{c&&u.push(m)};if(s){let c=[];if(o(t.title!==void 0,"--title",c),o(t.description!==void 0,"--description",c),o(t.body!==void 0,"--body",c),o(t.status!==void 0,"--status",c),o(t.closeReason!==void 0,"--close-reason",c),o(t.priority!==void 0,"--priority",c),o(t.type!==void 0,"--type",c),o(t.tags!==void 0,"--tags",c),o(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),o(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),o(t.deadline!==void 0,"--deadline",c),o(t.estimatedMinutes!==void 0,"--estimate",c),o(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),o(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),o(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),o(t.definitionOfReady!==void 0,"--definition-of-ready",c),o(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),o(t.goal!==void 0,"--goal",c),o(t.objective!==void 0,"--objective",c),o(t.value!==void 0,"--value",c),o(t.impact!==void 0,"--impact",c),o(t.outcome!==void 0,"--outcome",c),o(t.whyNow!==void 0,"--why-now",c),o(t.assignee!==void 0,"--assignee",c),o(t.parent!==void 0,"--parent",c),o(t.reviewer!==void 0,"--reviewer",c),o(t.risk!==void 0,"--risk",c),o(t.confidence!==void 0,"--confidence",c),o(t.sprint!==void 0,"--sprint",c),o(t.release!==void 0,"--release",c),o(t.blockedBy!==void 0,"--blocked-by",c),o(t.blockedReason!==void 0,"--blocked-reason",c),o(t.unblockNote!==void 0,"--unblock-note",c),o(t.reporter!==void 0,"--reporter",c),o(t.severity!==void 0,"--severity",c),o(t.environment!==void 0,"--environment",c),o(t.reproSteps!==void 0,"--repro-steps",c),o(t.resolution!==void 0,"--resolution",c),o(t.expectedResult!==void 0,"--expected-result",c),o(t.actualResult!==void 0,"--actual-result",c),o(t.affectedVersion!==void 0,"--affected-version",c),o(t.fixedVersion!==void 0,"--fixed-version",c),o(t.component!==void 0,"--component",c),o(t.regression!==void 0,"--regression",c),o(t.customerImpact!==void 0,"--customer-impact",c),o(t.depRemove!==void 0,"--dep-remove",c),o(t.replaceDeps===!0,"--replace-deps",c),o(t.replaceTests===!0,"--replace-tests",c),o(t.replaceFiles===!0,"--replace-files",c),o(t.replaceDocs===!0,"--replace-docs",c),o(t.comment!==void 0,"--comment",c),o(t.note!==void 0,"--note",c),o(t.learning!==void 0,"--learning",c),o(t.file!==void 0,"--file",c),o(t.test!==void 0,"--test",c),o(t.doc!==void 0,"--doc",c),o(t.reminder!==void 0,"--reminder",c),o(t.event!==void 0,"--event",c),o(t.typeOption!==void 0,"--type-option",c),o(t.clearDeps===!0,"--clear-deps",c),o(t.clearComments===!0,"--clear-comments",c),o(t.clearNotes===!0,"--clear-notes",c),o(t.clearLearnings===!0,"--clear-learnings",c),o(t.clearFiles===!0,"--clear-files",c),o(t.clearTests===!0,"--clear-tests",c),o(t.clearDocs===!0,"--clear-docs",c),o(t.clearReminders===!0,"--clear-reminders",c),o(t.clearEvents===!0,"--clear-events",c),o(t.clearTypeOptions===!0,"--clear-type-options",c),o(t.force===!0,"--force",c),o(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw Zf({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=[];o(t.status!==void 0,"--status",i),o(t.closeReason!==void 0,"--close-reason",i),o(t.assignee!==void 0,"--assignee",i),o(t.parent!==void 0,"--parent",i),o(t.blockedBy!==void 0,"--blocked-by",i),o(t.blockedReason!==void 0,"--blocked-reason",i),o(t.unblockNote!==void 0,"--unblock-note",i),o(t.dep!==void 0,"--dep",i),o(t.depRemove!==void 0,"--dep-remove",i),o(t.replaceDeps===!0,"--replace-deps",i),o(t.replaceTests===!0,"--replace-tests",i),o(t.replaceFiles===!0,"--replace-files",i),o(t.replaceDocs===!0,"--replace-docs",i),o(t.note!==void 0,"--note",i),o(t.learning!==void 0,"--learning",i),o(t.test!==void 0,"--test",i),o(t.reminder!==void 0,"--reminder",i),o(t.event!==void 0,"--event",i),o(t.clearDeps===!0,"--clear-deps",i),o(t.clearComments===!0,"--clear-comments",i),o(t.clearNotes===!0,"--clear-notes",i),o(t.clearLearnings===!0,"--clear-learnings",i),o(t.clearFiles===!0,"--clear-files",i),o(t.clearTests===!0,"--clear-tests",i),o(t.clearDocs===!0,"--clear-docs",i),o(t.clearReminders===!0,"--clear-reminders",i),o(t.clearEvents===!0,"--clear-events",i);let a=[...n].filter(c=>CS.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw Zf({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 OS(e,t){let n=W(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function PS(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Cm({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=W(e.fromStatus,e.statusRegistry)??e.fromStatus,r=W(e.toStatus,e.statusRegistry)??e.toStatus,s=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Rm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(s,d.USAGE);return`workflow_transition_not_allowed: ${s}`}function NS(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(n).toISOString()}function Uo(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var LS=["id","kind","type","author","created_at","source_kind"],FS=["id","kind","type","source_kind"];function $S(e){return e.startsWith("```")||e.includes(`
|
|
8
|
+
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Bs(e)}function a_(e){return typeof e=="string"?$r(e)??e.trim():e}function Go(e,t,n,r){return e?(be(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=$S(i);mo(i,a);let c=a?ne(o,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",LS);let m=c.id?.trim(),u=a_((c.kind??c.type)?.trim());if(!m||!u)throw new l("--dep requires id and kind, or a bare item id to add a related dependency",d.USAGE);if(m.toLowerCase()==="undefined")throw new l(`--dep id must not use placeholder token "${m}". Use --clear-deps to clear dependencies.`,d.USAGE);let p=Qn(Uo(c.source_kind)),f=Uo(c.author);return{id:Zn(m,t,p),kind:we(u,Dt,"dependency kind"),created_at:NS(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function MS(e,t){return e?(be(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new l("--dep-remove requires id or key/value selectors",d.USAGE);if(r.includes("=")||/^(?:[-*+]\s+)?(?:id|kind|type|source_kind)\s*[:=]/i.test(r)||r.startsWith("```")){let s=ne(r,"--dep-remove");Ke(s,"--dep-remove",FS);let o=s.id?.trim();if(!o)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(o.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${o}"`,d.USAGE);let i=a_(Uo(s.kind??s.type)),a=Qn(Uo(s.source_kind));return{id:Zn(o,t,a),kind:i?we(i,Dt,"dependency kind"):void 0,source_kind:a}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:ge(r,t)}})):[]}function e_(e){let t=e.source_kind?.trim().toLowerCase()??"";return`${e.id.trim().toLowerCase()}::${e.kind}::${t}`}function DS(e,t,n,r){let s=[...e??[]],o=!1;if(t===void 0){let i=s.filter(a=>a.kind!=="blocked_by");return i.length!==s.length&&(s=i,o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}return s.some(i=>i.kind==="blocked_by"&&i.id===t)||(s.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),o=!0),o?{dependencies:s.length>0?s:void 0,changed:!0}:{dependencies:e,changed:!1}}async function US(e,t,n,r,s,o){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await D(n,ge(i,r),r,s,o);return a?{id:a.id}:{unresolved:i}}function GS(e,t,n,r,s){let o=DS(e.dependencies,t,n,r);o.changed&&(o.dependencies===void 0?delete e.dependencies:e.dependencies=o.dependencies,s.includes("dependencies")||s.push("dependencies"))}function jS(e){return`${e.path}::${e.scope}`}function qS(e){return`${e.path}::${e.scope}`}function KS(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}`}function zS(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())}function BS(e){return Tn(e)}function t_(e,t){let n=Kn("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function HS(e,t,n){let r=new Set,s=(o,i)=>{i&&r.add(o)};if(s("title",e.title!==void 0),s("description",e.description!==void 0),s("body",e.body!==void 0),s("status",e.status!==void 0),s("closeReason",e.closeReason!==void 0),s("priority",e.priority!==void 0),s("type",e.type!==void 0),s("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),s("deadline",e.deadline!==void 0),s("estimatedMinutes",e.estimatedMinutes!==void 0),s("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),s("definitionOfReady",e.definitionOfReady!==void 0),s("order",e.order!==void 0||e.rank!==void 0),s("goal",e.goal!==void 0),s("objective",e.objective!==void 0),s("value",e.value!==void 0),s("impact",e.impact!==void 0),s("outcome",e.outcome!==void 0),s("whyNow",e.whyNow!==void 0),s("author",e.author!==void 0),s("message",e.message!==void 0),s("assignee",e.assignee!==void 0),s("parent",e.parent!==void 0),s("reviewer",e.reviewer!==void 0),s("risk",e.risk!==void 0),s("confidence",e.confidence!==void 0),s("sprint",e.sprint!==void 0),s("release",e.release!==void 0),s("blockedBy",e.blockedBy!==void 0),s("blockedReason",e.blockedReason!==void 0),s("unblockNote",e.unblockNote!==void 0),s("reporter",e.reporter!==void 0),s("severity",e.severity!==void 0),s("environment",e.environment!==void 0),s("reproSteps",e.reproSteps!==void 0),s("resolution",e.resolution!==void 0),s("expectedResult",e.expectedResult!==void 0),s("actualResult",e.actualResult!==void 0),s("affectedVersion",e.affectedVersion!==void 0),s("fixedVersion",e.fixedVersion!==void 0),s("component",e.component!==void 0),s("regression",e.regression!==void 0),s("customerImpact",e.customerImpact!==void 0),s("dep",e.dep!==void 0),s("depRemove",e.depRemove!==void 0),s("dep",e.replaceDeps===!0),s("comment",e.comment!==void 0),s("note",e.note!==void 0),s("learning",e.learning!==void 0),s("file",e.file!==void 0),s("test",e.test!==void 0),s("test",e.replaceTests===!0),s("file",e.replaceFiles===!0),s("doc",e.replaceDocs===!0),s("doc",e.doc!==void 0),s("reminder",e.reminder!==void 0),s("event",e.event!==void 0),s("typeOption",e.typeOption!==void 0),s("field",e.field!==void 0),s("force",e.force===!0),s("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),s("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),s("dep",e.clearDeps===!0),s("comment",e.clearComments===!0),s("note",e.clearNotes===!0),s("learning",e.clearLearnings===!0),s("file",e.clearFiles===!0),s("test",e.clearTests===!0),s("doc",e.clearDocs===!0),s("reminder",e.clearReminders===!0),s("event",e.clearEvents===!0),s("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let o=i_(e.unset,t,n);for(let i of o.optionKeys)s(i,!0)}return r}function VS(e,t,n,r,s){let o=Lr(e,n);if(!o)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=mn(o,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let a=HS(t,r,s);for(let c of i.disabled)if(a.has(t_(c,e)))throw new l(`Option ${he("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of i.required)if(!a.has(t_(c,e)))throw new l(`Missing required option ${he("update",c)} for type "${e}"`,d.USAGE)}var WS=new Set(["order","rank"]),YS=Pi.filter(e=>!WS.has(e)),c_=["tags","closeReason",...YS],JS=["title","description","body","status","closeReason","completedAt","priority","type",...Pi,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],XS=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>Q(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>En(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"}],QS=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>we(uo(e),cn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>fo(e)}],ZS=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>we(po(e),dn,"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=>_o(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function rc(e,t,n){for(let r of e){let s=t[r.optionKey],o=n.clearItemMetadataKeys.has(r.metadataKey);if(!(s===void 0&&!o)){if(o){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof s!="string")throw new l(`${he("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(s,n):s.trim(),n.changedFields.push(r.metadataKey)}}}async function eE(e){let t=Le();return IS({...e,body:await t.resolveValue(e.body,"--body"),dep:await t.resolveList(e.dep,"--dep"),depRemove:await t.resolveList(e.depRemove,"--dep-remove"),comment:await t.resolveList(e.comment,"--comment"),note:await t.resolveList(e.note,"--note"),learning:await t.resolveList(e.learning,"--learning"),file:await t.resolveList(e.file,"--file"),test:await t.resolveList(e.test,"--test"),doc:await t.resolveList(e.doc,"--doc"),reminder:await t.resolveList(e.reminder,"--reminder"),event:await t.resolveList(e.event,"--event"),typeOption:await t.resolveList(e.typeOption,"--type-option"),field:await t.resolveList(e.field,"--field")})}function tE(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 tc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new l(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,d.USAGE);if(e.enabled&&e.clearEnabled)throw new l(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,d.USAGE)}function oc(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new l("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",d.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new l("--replace-deps requires at least one --dep entry",d.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new l("--replace-deps cannot be combined with --dep-remove",d.USAGE);tc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),tc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),tc({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 l(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,d.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function rE(e){let t={};for(let n of c_)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function sE(e,t){let n=rE(e);for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=Do.get(r)??r;throw new l(`Cannot combine --unset ${o} with ${he("update",r)}`,d.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --add-ac",d.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new l("Cannot combine --unset acceptance-criteria with --remove-ac",d.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new l("Cannot combine --unset tags with --add-tags",d.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new l("Cannot combine --unset tags with --remove-tags",d.USAGE)}}function oE(e){let t=(n,r)=>{let s=Do.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;go(n,he("update",r),o)};for(let n of c_)t(e[n],String(n));t(e.order??e.rank,"order"),be(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),be(e.event,"--event","Use --clear-events to clear linked events.")}function iE(e,t){let n={};for(let r of JS)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 aE(e){let t=await D(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await ot(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await K(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function cE(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function dE(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new l("--order and --rank must match when both are provided",d.USAGE)}async function lE(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Gs(e.options.parent);if(qs(e.id,t,e.settings.id_prefix),await D(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:js(r,e.parentReferencePolicy).warnings}}function mE(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function uE(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await D(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await ot(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await K(t,{schema:e.settings.schema}),r=e.options.type!==void 0?pe(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",s=PS({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return s?[s]:[]}async function pE(e){if(!e.fieldFlags.status||W(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=[],s=[];if(n.length>0){let a=await at(e.id,{...e.options,status:void 0,closeReason:void 0,message:void 0},e.global);s=a.changed_fields,r.push(...a.warnings)}let o=await it(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,...o.warnings,"auto_routed_from_update_to_close"];return{item:o.item,changed_fields:[...s,...o.changed_fields],warnings:i}}function fE(e,t,n,r){return t.title!==void 0&&(e.metadata.title=ec(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")),W(e.metadata.status,n)??e.metadata.status}function _E(e,t,n,r,s){let o=OS(n,t.statusRegistry);if(e.metadata.status=o,s.push("status"),o===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,s.push("closed_at","completed_at");return}!se(o,t.statusRegistry)&&se(r,t.statusRegistry)&&e.metadata.closed_at!==void 0&&(delete e.metadata.closed_at,s.push("closed_at"),e.metadata.completed_at!==void 0&&(delete e.metadata.completed_at,s.push("completed_at")))}function hE(e,t,n,r){if(t.options.status!==void 0&&_E(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!se(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=Q(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function gE(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 s=t.options.closeReason?.trim()??"";if(s.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=s}r.push("close_reason");return}t.options.status!==void 0&&se(n,t.statusRegistry)&&!se(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function yE(e,t,n,r){hE(e,t,n,r),gE(e,t,n,r)}function bE(e,t,n){let r=pe(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=BS(t.options.priority),n.push("priority")),t.options.type!==void 0){let s=pe(t.options.type,t.typeRegistry);if(!s)throw new l(kt(t.options.type,t.typeRegistry.types,St(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=s,r=s,n.push("type")}return VS(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),wE(e,t,r,n),r}function wE(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 o=vo(t.options.typeOption??[]),i=zn(n,o,t.typeRegistry);if(i.errors.length>0)throw new l(i.errors.join("; "),d.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 s=zn(n,e.metadata.type_options,t.typeRegistry);if(s.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${s.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=s.normalized}function vE(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){let s=new Set(r.map(o=>e_(o)));for(let o of t.dependencyUpdates.additions){let i=e_(o);s.has(i)||(r.push(o),s.add(i))}}t.dependencyRemovals.length>0&&(r=r.filter(s=>!t.dependencyRemovals.some(o=>zS(s,o)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function kE(e,t,n){nc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),nc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),nc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function nc(e,t,n,r,s,o){n===void 0&&!s.has(t)||(s.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],o.push(t))}function SE(e,t,n){n_(e,"files",t.options.file,t.fileUpdates.values,jS,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),EE(e,t,n),n_(e,"docs",t.options.doc,t.docUpdates.values,qS,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function n_(e,t,n,r,s,o,i,a){if(!(n===void 0&&!i.has(t))){if(o)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=>s(u)));for(let u of r){let p=s(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function EE(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=r_(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=r_([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function r_(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let s=KS(r);n.has(s)||(t.push(r),n.add(s))}return t}function TE(e,t,n){let r=t.options.addTags,s=t.options.removeTags,o=Array.isArray(r)&&r.length>0||Array.isArray(s)&&s.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||o){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?Rt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=zs(Sn(i,r),s),n.changedFields.push("tags")}rc(XS,t.options,n),CE(e,t,n.changedFields)}function AE(e,t,n){let r=t.options.addAc,s=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(s)&&s.length>0))return;let o=Ks(kn(e.metadata.acceptance_criteria),r,s);if(o.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${o.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:o.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=o.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 CE(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 s=ie(r??"","order");if(!Number.isInteger(s))throw new l("Order must be an integer",d.USAGE);e.metadata.order=s}n.push("order")}}function RE(e,t,n,r){IE(e,t,n.changedFields),xE(e,t,n.changedFields),rc(QS,t.options,n),s_(e,t,"sprint",r,n.changedFields),s_(e,t,"release",r,n.changedFields),OE(e,t,n.changedFields),rc(ZS,t.options,n)}function IE(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new l("--assignee must not be empty. Use --unset assignee to clear it.",d.USAGE);e.metadata.assignee=r}n.push("assignee")}}function xE(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 s_(e,t,n,r,s){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let o=Hs(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=o.value,r.push(...o.warnings)}s.push(n)}}function OE(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)&&GS(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function PE(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=bo(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=wo(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function NE(e,t,n){o_(e,t.runtimeFieldRegistry.definitions.map(s=>s.metadata_key),t.clearItemMetadataKeys,n),o_(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[s,o]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(s)){let i=s.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===s)?.cli_flag??i;throw new l(`Cannot combine --unset ${i} with --${c}`,d.USAGE)}tt(e[s],o)||(e[s]=o,n.push(s))}let r=Pr(t.options.field,t.extensionRegistrations);for(let s of Object.keys(r))if(t.clearItemMetadataKeys.has(s))throw new l(`Cannot combine --unset ${s.replaceAll("_","-")} with --field ${s}=...`,d.USAGE);for(let[s,o]of Object.entries(r))tt(e[s],o)||(e[s]=o,n.push(s))}function o_(e,t,n,r){for(let s of t)!n.has(s)||e[s]===void 0||(delete e[s],r.push(s))}function LE(e,t){let n=structuredClone(e.metadata),r=e.body,s=[],o=[],i=fE(e,t.options,t.statusRegistry,s),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:s,nowValue:t.nowValue};yE(e,t,i,s),bE(e,t,s),vE(e,t,s),kE(e,t,s),SE(e,t,s),TE(e,t,c),AE(e,t,c),RE(e,t,c,o),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&cr(e.metadata.id,e.metadata.dependencies),W(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,s.includes("assignee")||s.push("assignee")),PE(e,t,s),NE(a,t,s);try{Nr(a,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(p){throw new l(p instanceof Error?p.message:"Invalid extension item field values",d.USAGE)}let m=e.metadata,u=[...new Set(s)].filter(p=>p==="body"?e.body!==r:!tt(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&o.push(`acceptance_criteria_replaced:${kn(n.acceptance_criteria).length}:${kn(m.acceptance_criteria).length}`),{changedFields:u,warnings:o}}async function d_(e,t,n,r={}){t=await eE(t);let s=T(process.cwd(),n.path);await cE(s);let o=await A(s),i=M(o.schema),a=Ve(o.schema),c=I(),m=bt(c),u=x(o,c),p=o.governance.workflow_enforcement??"off",f=p==="off"?[]:Am(o.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][o.validation.parent_reference],h=i_(t.unset,a,m),y=new Set(h.optionKeys),g=new Set(h.metadataKeys);oc(t),nE({definitions:tE(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:g}),xS(e,t,g),sE(t,h),oE(t);let b=R(t.author,o.author_default),v=new Date,E=v.toISOString(),N=Go(t.dep,o.id_prefix,E,b);cr(e,N.additions);let O=await Yt({pmRoot:s,dependencies:N.additions,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:o.schema}),j=MS(t.depRemove,o.id_prefix),$=tn("--comment",t.comment,E,b),xe=t.ownershipMetadataBypass===!0&&$.values?{...$,values:$.values.map(Ue=>({...Ue,author:b}))}:$,te=tn("--note",t.note,E,b),_e=tn("--learning",t.learning,E,b),ce=Xa(t.file),Qe=Qa(t.test),ut=Za(t.doc),pt=[],ft=await lE({id:e,options:t,unsetTargets:h,pmRoot:s,settings:o,typeRegistry:u,parentReferencePolicy:_}),_t=await US(t.blockedBy,g.has("blocked_by"),s,o.id_prefix,o.item_format,u.type_to_folder),hi=_t.id,gi=[...ft.warnings,...mE(_t)],jn=Es(t,a,t.runtimeFieldCommands),ht=iE(t,jn);if(!Object.values(ht).some(Boolean))return aE({pmRoot:s,id:e,settings:o,typeRegistry:u});pt.push(...await uE({options:t,fieldFlags:ht,workflowEnforcement:p,typeWorkflows:f,statusRegistry:i,typeRegistry:u,pmRoot:s,id:e,settings:o}));let ke=await pE({options:t,fieldFlags:ht,statusRegistry:i,workflowTransitionWarnings:pt,global:n,id:e});if(ke)return ke;dE(t);let Oe=ht.dep||ht.depRemove||ht.blockedBy?await oe(s,o.item_format,u.type_to_folder,void 0,o.schema):void 0,$t,P,gt=await xu({pmRoot:s,settings:o,typeToFolder:u.type_to_folder,id:e,op:FE(t,r),author:b,message:t.message,resolveHistoryContext:()=>P,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(Ue){return $t=$E({document:Ue,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),P=$t?{recurrence:$t}:void 0,Oe=Oe?.map(Tr=>Tr.id===Ue.metadata.id?structuredClone(Ue.metadata):Tr),LE(Ue,{options:t,settings:o,typeRegistry:u,statusRegistry:i,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:g,dependencyUpdates:N,dependencyRemovals:j,commentUpdates:xe,noteUpdates:te,learningUpdates:_e,fileUpdates:ce,testUpdates:Qe,docUpdates:ut,resolvedParentValue:ft.resolvedParentValue,resolvedBlockedByDependencyId:hi,runtimeFieldUpdates:jn,nowValue:v,nowIso:E,author:b,pmRoot:s})}}),qn=Oe?to(Oe,Oe.map(Ue=>Ue.id===gt.item.id?gt.item:Ue),gt.item.id):[];return{item:gt.item,changed_fields:gt.changedFields,warnings:[...pt,...gi,...O,...qn,...gt.warnings],...$t===void 0?{}:{lifecycle_transition:$t}}}function FE(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function $E(e){if(e.recurrenceReason===void 0)return;let t=W(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!se(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,d.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=W(n,e.statusRegistry)??n,s=e.document.metadata,o=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(i=>{let a=s[i];return typeof a=="string"?[[i,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:o}}async function at(e,t,n){return d_(e,t,n)}async function l_(e,t,n,r){let s=await d_(e,t,n,{recurrenceReason:r});if(s.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,d.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{...s,lifecycle_transition:s.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]="e797d654-df89-554b-876b-cb2faa350bd0")}catch{}})();var u_=1,ac="update-many",ME=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),DE=["--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(", "),UE={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"},GE=[{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"}],jE={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"},p_=e=>{let t={};for(let[n,r]of Object.entries(e))ME.has(n)||r!==void 0&&(t[n]=r);return t},qE=e=>Object.keys(p_(e)).length>0,f_=e=>typeof e=="string"?e.trim():e,KE=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},ic=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},zE=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??f_(e)},BE={priority:KE,estimatedMinutes:ic,order:ic,rank:ic,regression:zE},HE=(e,t)=>{if(t!==void 0)return(BE[e]??f_)(t)},VE=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return jE[t]??t},jo=(e,t)=>tt(e,t),WE=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],YE=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,JE=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",m_=(e,t)=>t===void 0?void 0:e[t],Ln=e=>Array.isArray(e)?e.length:0,XE=(e,t,n)=>{let r=n[e.addKey],s=m_(n,e.removeKey),o=Ln(r),i=Ln(s),a=n[e.clearKey]===!0,c=m_(n,e.replaceKey)===!0;if(![a,c,o>0,i>0].includes(!0))return;let m=WE(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:JE({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:o,remove_count:i,before_count:YE(e.field,m)}}},QE=(e,t)=>{let n=[];for(let r of GE){let s=XE(r,e,t);s!==void 0&&n.push(s)}return n},ZE=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],eT=(e,t)=>{if(![t.tags!==void 0,Ln(t.addTags)>0,Ln(t.removeTags)>0].includes(!0))return;let n=ZE(e.tags),r=t.tags===void 0?n:Rt(t.tags),s=Sn(r,t.addTags),o=zs(s,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!jo(i,o))return{field:"tags",before:n,after:o}},tT=(e,t)=>{let n=e.acceptance_criteria,r=Ks(kn(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let s=r.criteria.join("; ");if(!jo(typeof n=="string"?n:"",s))return{field:"acceptance_criteria",before:n,after:s}},nT=(e,t,n)=>{for(let[r,s]of Object.entries(UE)){let o=n[r];if(o===void 0)continue;let i=t[s],a=HE(r,o);jo(i,a)||e.push({field:s,before:i,after:a})}},rT=(e,t,n,r)=>{let s=Es(n,r,["update_many"]);for(let[o,i]of Object.entries(s)){let a=t[o];jo(a,i)||e.push({field:o,before:a,after:i})}},sT=(e,t,n)=>{for(let r of n??[]){let s=VE(r),o=t[s];o!==void 0&&e.push({field:s,before:o,after:null})}},oT=(e,t,n={})=>{let r=e,s=[],o=eT(r,n);if(o&&s.push(o),nT(s,r,n),Ln(n.addAc)>0||Ln(n.removeAc)>0){let i=tT(r,n);i!==void 0&&s.push(i)}return s.push(...QE(r,n)),rT(s,r,n,t),sT(s,r,n.unset),{id:e.id,changes:s}},iT=(e,t)=>ju(e,t,{strict:!0,flagLabel:"--filter-status"}),aT=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new l("--ids requires at least one non-empty item ID",d.USAGE)},cT=[({update:e})=>{e.priority!==void 0&&Tn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=x(t,I());if(!pe(e.type,r))throw new l(kt(e.type,r.types,St(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!W(e.status,t)){let n=t.definitions.map(r=>r.id);throw new l(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,d.USAGE)}},({update:e})=>{e.deadline!==void 0&&Q(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&En(e.estimatedMinutes,"estimated-minutes")}],dT=(e,t,n,r)=>{let s={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let o of cT)o(s)},lT=async e=>{let t=await $s(e.pmRoot,ac,e.rollbackId,u_),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Ms(t.items,(s,o)=>Wt(s,o,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...qt({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}},mT=async e=>{let t={schema_version:u_,id:e.checkpointId,created_at:e.nowValue,author:R(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Fs(e.pmRoot,ac,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},uT=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(s=>s.trim()).filter(s=>s.length>0))],r=new Set(t.map(s=>s.id));return n.filter(s=>!r.has(s))},cc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},pT=async e=>{let t=T(process.cwd(),e.path);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=await A(t);return{pmRoot:t,settings:n,statusRegistry:M(n.schema),runtimeFieldRegistry:Ve(n.schema)}},fT=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(nr(e.options.list,e.options.status))throw new l("Rollback mode does not accept filter options",d.USAGE);if(Object.keys(e.updateSummary).length>0)throw new l("Rollback mode does not accept update mutation flags",d.USAGE);return lT({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},_T=async e=>{iT(e.options.status,e.runtime.statusRegistry);let t=await It(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(s=>{let o=oT(s,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?o:{...o,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await It(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(s=>s.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:uT(e.options.list?.ids,r)}},hT=e=>({outcome:"effect",exit_code:d.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:[],...cc(e)}),gT=e=>({...qt({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:[],...cc(e)}),yT=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,s=new Set(e.plans.filter(o=>o.changes.length>0).map(o=>o.id));for(let o of e.items){if(!s.has(o.id)){t.push({id:o.id,status:"skipped"});continue}try{let i=await at(o.id,{...e.options.update,message:r,runtimeFieldCommands:["update_many"]},e.global);t.push({id:o.id,status:"updated",changed_fields:i.changed_fields,warnings:i.warnings}),n.push(o.id)}catch(i){t.push({id:o.id,status:"failed",error:un(i)})}}return{rows:t,updatedIds:n}},bT=async e=>{if(e.plan.actionable.length===0)return gT(e.plan);let t=S(),n=Ls(ac,t),r=new Set(e.plan.actionable.map(p=>p.id)),s=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),o=e.options.checkpoint===!1?void 0:await mT({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:s}),i=await yT({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{...qt({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,...o?{checkpoint:o}:{},updated_count:c,skipped_count:m,failed_count:u,rows:i.rows,ids:i.updatedIds,...cc(e.plan)}},__=async(e,t)=>{let n=await pT(t),r=typeof e.rollback=="string"?e.rollback:void 0,s=p_(e.update);if(aT(e.list),r!==void 0)return fT({runtime:n,rollbackId:r,options:e,global:t,updateSummary:s});if(!qE(e.update))throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${DE}).`,d.USAGE);dT(e.update,n.settings,n.statusRegistry,n.pmRoot),oc(e.update);let o=await Yt({pmRoot:n.pmRoot,dependencies:Go(e.update.dep,n.settings.id_prefix,S(),R(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,I()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await _T({options:e,global:t,runtime:n,updateSummary:s,dependencyWarnings:o});return await Yt({pmRoot:n.pmRoot,dependencies:Go(e.update.dep,n.settings.id_prefix,S(),R(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:x(n.settings,I()).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?hT(i):bT({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]="3d5ea029-26ef-51bc-bacc-b1d4d807a024")}catch{}})();var wT=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],h_=["brief","standard","deep"],b_="plan-step-",fc="draft",pc=["bug-investigation","feature-implementation","refactoring-sprint"],g_={"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 vT(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(g_,t)?g_[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${pc.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${pc[0]}`]});return n.map(r=>({...r}))}function kT(e,t){return t>0?Math.round(e/t*100):0}function w_(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 Me(e){return Array.isArray(e)?e.flatMap(t=>An(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?An(e,{unique:!1}):[]}function ve(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function v_(e,t=fc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ai.find(s=>s===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${Ai.join(", ")}`,d.USAGE);return r}function _c(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ci.find(s=>s===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${Ci.join(", ")}`,d.USAGE);return r}function k_(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ii.find(s=>s===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${Ii.join(", ")}`,d.USAGE);return r}function ST(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ri.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${Ri.join(", ")}`,d.USAGE);return n}function ET(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=h_.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${h_.join(", ")}`,d.USAGE);return n}function TT(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new l("Plan --fields requires a comma-separated list of plan field names",d.USAGE);return t}var dc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function AT(e,t){let n=e,r={},s=[];for(let o of t){let i=o.startsWith("plan.")?o.slice(5):o;if(i.length!==0){if(!dc.has(i)){s.push(o);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(s.length>0)throw new l(`Unknown Plan --fields value(s): ${s.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...dc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:s,suggested_retry:`pm plan show <id> --fields ${[...dc].join(",")}`}});return r}function hc(e,t){let n={};for(let r of e.split(",")){let s=r.trim();if(s.length===0)continue;let o=s.indexOf("=");if(o<=0)throw new l(`Invalid ${t} entry "${s}"; expected key=value`,d.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[s.slice(0,o).trim().toLowerCase()]=s.slice(o+1).trim()}return n}function gc(e){let t=hc(e,"--file");if(!t.path)throw new l("--file requires path=<value>",d.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 yc(e){let t=hc(e,"--test");if(!t.command&&!t.path)throw new l("--test requires at least command=<value> or path=<value>",d.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 bc(e){let t=hc(e,"--doc");if(!t.path)throw new l("--doc requires path=<value>",d.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 CT(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=kT(t.completed,t.total),t}function RT(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${b_}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new l("Could not allocate step id (limit reached)",d.GENERIC_FAILURE)}function Fn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(s=>s.id===n);if(r)return r;if(/^\d+$/.test(n)){let s=Number.parseInt(n,10),o=e.find(i=>i.order===s);if(o)return o}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function y_(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 IT(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],s=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",d.USAGE);for(let i of e.slice().sort((a,c)=>a.order-c.order)){let a=y_(i);if(a){s.push({from_step:i.id,...a});continue}r.push(i)}return{targets:r,skipped:s}}let o=new Set;for(let i of t){let a=Fn(e,i);if(o.has(a.id))continue;o.add(a.id);let c=y_(a);if(c){s.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:s}}function xT(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 OT(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function PT(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 Ae(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=CT(n),s=OT(n),o={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??fc,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:s?{id:s.id,order:s.order,title:s.title,status:s.status}:void 0,blocked_steps:PT(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(o.steps=n),t==="deep"&&(o.decisions=e.plan_decisions??[],o.discoveries=e.plan_discoveries??[],o.validation=e.plan_validation??[]),o}function Ce(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&&!aa(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function S_(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new l(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,d.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 NT(e){let t=T(process.cwd(),e.path);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=await A(t);return{pmRoot:t,settings:n}}async function E_(e,t){let n=x(e.settings,I()),r=await D(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new l(`Plan ${t} not found`,d.NOT_FOUND);let s=await K(r,{schema:e.settings.schema});return S_(s.document.metadata),{document:s.document,itemId:r.id}}function LT(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of Me(e.related))t.push(`id=${n},kind=related`);for(let n of Me(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of Me(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function FT(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 $T(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||Me(e.dependsOn).length>0||Me(e.link).length>0}function MT(e){let t=e.stepTitle?.trim()||void 0,n=w_(e.step),r=e.template?.trim()?vT(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(s=>s.title)],templateSteps:r}}function DT(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",d.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${pc[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",d.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 UT(e,t){let n=_c(e.stepStatus,"pending"),r=wc(e,"depends_on"),s=ve(e.file).map(gc),o=ve(e.test).map(yc),i=ve(e.doc).map(bc),a=S();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:s.length>0?s:void 0,tests:o.length>0?o:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function GT(e){let t=MT(e),n=$T(e);if(DT(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[UT(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=S();return{steps:t.stepTitles.map((s,o)=>({id:`${b_}${String(o+1).padStart(3,"0")}`,order:o+1,title:s,body:t.templateSteps[o]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}async function jT(e,t,n){let r=e.title?.trim();if(!r)throw new l("pm plan create requires --title",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let s=v_(e.mode,fc),o=ST(e.harness),i=e.fromSearch?.trim(),a=FT(e),{steps:c,hasPerStepDetailOptions:m}=GT(e);if(c.length===0&&m)throw new l("pm plan create step options require --step-title (or a single --step)",d.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let u=e.description?.trim()??e.scope?.trim()??r,p=e.claim?R(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:ve(e.file),test:ve(e.test),doc:ve(e.doc),field:ve(e.field),assignee:R(e.author,n.settings.author_default),blockedBy:void 0,dep:LT(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")},_=await xt(f,t),h=await Z({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:R(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let b=["plan_mode"];g.metadata.plan_mode=s,o&&(g.metadata.plan_harness=o,b.push("plan_harness"));let v=e.scope?.trim();v&&(g.metadata.plan_scope=v,b.push("plan_scope"));let E=e.resumeContext?.trim();return E&&(g.metadata.plan_resume_context=E,b.push("plan_resume_context")),g.metadata.plan_steps=c,b.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],b.push("plan_validation")),p&&(g.metadata.assignee=p,b.push("assignee")),{changedFields:b}}}),y=Ae(h.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Ce(_.item.id,y),warnings:[..._.warnings],generated_at:S()}}async function qT(e,t,n){let r=ET(t.depth),s=TT(t.fields),{document:o,itemId:i}=await E_(n,e),a=Ae(o.metadata,s===null?r:"deep");return{action:"show",plan:s===null?a:AT(a,s),next_actions:Ce(i,a),warnings:[],generated_at:S()}}function KT(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,s])=>[r,JSON.stringify(s)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function Ye(e){let t=R(e.options.author,e.ctx.settings.author_default),n,r=await Z({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(s){S_(s.metadata);let o=M(e.ctx.settings.schema);if(se(s.metadata.status,o)||aa(s.metadata.plan_mode))throw new l(`Plan ${s.metadata.id} is terminal (status=${s.metadata.status}, plan_mode=${s.metadata.plan_mode??"unset"}) and cannot be mutated.`,d.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=(s.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(s.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,s);n=c.resultStep;let m=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));s.metadata.plan_steps=m;let u=KT(a,s.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 zT(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let s=_c(t.stepStatus,"pending"),o=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await Ye({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;T_(u,void 0,s,o);let f=BT(u,t,{order:p,title:r,status:s});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Ae(i.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Ce(c,m),warnings:[],generated_at:S()}}function T_(e,t,n,r){if(n!=="in_progress"||r)return;let s=e.find(o=>o.id!==t&&o.status==="in_progress");if(s)throw new l(`Plan already has step ${s.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function BT(e,t,n){let r=wc(t,"depends_on"),s=ve(t.file).map(gc),o=ve(t.test).map(yc),i=ve(t.doc).map(bc),a=S();return{id:RT(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:s.length>0?s:void 0,tests:o.length>0?o:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function wc(e,t){let n=Me(e.dependsOn).map(u=>({id:u,kind:t})),r=Me(e.related).map(u=>({id:u,kind:"related"})),s=Me(e.blocks).map(u=>({id:u,kind:"blocks"})),o=Me(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=Me(e.link),a=k_(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,...s,...o,...m]}async function lc(e,t,n,r){let{document:s,resultStep:o,itemId:i}=await Ye({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=Fn(c,r.stepRef),p=S(),f=r.finalStatus??_c(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return T_(c,u.status==="in_progress"?u.id:void 0,f,_),HT(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Ae(s.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:o,next_actions:Ce(i,a),warnings:[],generated_at:S()}}function HT(e,t,n,r){VT(e,t,n),WT(e,t),e.status=n,e.updated_at=r,YT(e,n,r)}function VT(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new l("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",d.USAGE)}function WT(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=ve(t.file).map(gc),s=ve(t.test).map(yc),o=ve(t.doc).map(bc);r.length>0&&(e.files=mc(e.files,r)),s.length>0&&(e.tests=mc(e.tests,s)),o.length>0&&(e.docs=mc(e.docs,o))}function mc(e,t){let n=[...e??[]],r=new Set(n.map(s=>JSON.stringify(s)));for(let s of t){let o=JSON.stringify(s);r.has(o)||(r.add(o),n.push(s))}return n}function YT(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function JT(e,t,n,r,s){let{document:o,itemId:i}=await Ye({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${s}`,mutator(c){let m=Fn(c,r),u=c.filter(f=>f.id!==m.id),p=Math.max(1,Math.min(s,u.length+1));return u.splice(p-1,0,m),u.forEach((f,_)=>{f.order=_+1,f.updated_at=S()}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=Ae(o.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Ce(i,a),warnings:[],generated_at:S()}}async function XT(e,t,n,r){let{document:s,itemId:o}=await Ye({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=Fn(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=Ae(s.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Ce(o,i),warnings:[],generated_at:S()}}async function QT(e,t,n,r){let s=wc(t,k_(t.linkKind,"related"));if(s.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let o=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await Ye({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=Fn(u,r),_=f.linked_items??[],h=g=>`${g.kind}:${g.id}`,y=new Set(_.map(h));for(let g of s){let b=h(g);y.has(b)||(_.push(g),y.add(b))}if(f.linked_items=_,f.updated_at=S(),o){let g=p.metadata.dependencies??[],b=E=>`${E.kind}:${E.id}`,v=new Set(g.map(b));for(let E of s){let N=E.kind==="depends_on"?"blocked_by":E.kind,O={id:E.id,kind:N,created_at:S(),author:R(t.author,n.settings.author_default)};v.has(b(O))||(g.push(O),v.add(b(O)))}p.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),m=Ae(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Ce(a,m),warnings:[],generated_at:S()}}async function ZT(e,t,n,r){let s=Me(t.link);if(s.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:o,itemId:i,resultStep:a}=await Ye({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=Fn(m,r),p=(u.linked_items??[]).filter(f=>!s.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=S(),{changedSteps:[u.id],resultStep:u}}}),c=Ae(o.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Ce(i,c),warnings:[],generated_at:S()}}async function uc(e,t,n,r){let s=xT(r,t);if(!s){let m=`--${r}-text`,u=`--${r}`;throw new l(`pm plan ${r} requires ${m}`,d.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 o=R(t.author,n.settings.author_default),{document:i,itemId:a}=await Ye({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(m,u){let p=S();if(r==="decision"){let _=u.metadata.plan_decisions??[];return _.push({ts:p,author:o,decision:s,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:o,text:s}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:s,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Ae(i.metadata,"deep");return{action:r,plan:c,next_actions:Ce(a,c),warnings:[],generated_at:S()}}async function eA(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:s,itemId:o}=await Ye({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=Ae(s.metadata,"brief");return{action:"resume",plan:i,next_actions:Ce(o,i),warnings:[],generated_at:S()}}async function tA(e,t,n){let r=v_(t.mode??"approved","approved"),{document:s,itemId:o}=await Ye({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=Ae(s.metadata,"brief");return{action:"approve",plan:i,next_actions:Ce(o,i),warnings:[],generated_at:S()}}function A_(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function nA(e,t){let n=Ae(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ce(e.itemId,n),warnings:A_(t),generated_at:S()}}function rA(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let s of n.linked_items??[]){let o=s.kind==="blocked_by"||s.kind==="blocks"||s.kind==="related"||s.kind==="discovered_from"?s.kind:"related";r.push(`id=${s.id},kind=${o}`)}return r}async function sA(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let s of ve(e.options.field)){let o=s.indexOf("=");if(o<=0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.USAGE);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(i.length===0)throw new l(`Invalid --field entry "${s}"; expected name=value`,d.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 l(`Invalid --field entry "${s}"; expected name=value`,d.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 l(`Invalid --field entry "${s}"; "${p}" is reserved by materialize and cannot be overridden`,d.USAGE);n[p]=a}for(let s of e.targets){let o=await xt({...n,title:s.title,description:s.body?.trim()||s.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${s.id}`,dep:rA(e.parent,e.planItemId,s)},{path:e.pmRoot});t.push({id:o.item.id,title:o.item.title,type:e.resolvedTypeName,parent:o.item.parent,tags:o.item.tags??[],from_step:s.id})}return t}function oA(e,t,n){for(let r of t){let s=n.find(a=>a.from_step===r.id);if(!s)continue;let o=e.find(a=>a.id===r.id);if(!o)continue;let i=o.linked_items??[];i.push({id:s.id,kind:"implements",note:`materialized as ${s.type}`}),o.linked_items=i,o.updated_at=S()}}async function iA(e,t,n){let r=Me(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let s=t.materializeType?.trim()||"Task",o=x(n.settings,I()),i=pe(s,o);if(!i)throw new l(`Invalid --materialize-type "${s}"`,d.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await E_(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=IT(u,r);if(p.length===0){if(f.length>0)return nA(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await sA({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:h,itemId:y}=await Ye({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(b){return oA(b,p,_),{changedSteps:p.map(v=>v.id)}}}),g=Ae(h.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Ce(y,g),warnings:A_(f),generated_at:S()}}function aA(e){if(e.subcommand==="create")return e;let t=w_(e.options.step);if(t.length>1)throw new l(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,d.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:{...e.options,stepTitle:t[0]}}:e}function ct(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function nn(e,t){let n=ct(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function cA(e){let t=nn(e,"reorder-step");if(e.reorderTo===void 0)throw new l("pm plan reorder-step requires <plan-id> <step> <new-order>",d.USAGE);return{...t,reorderTo:e.reorderTo}}var dA={create:(e,t)=>jT(e.options,e.global,t),show:(e,t)=>qT(ct(e,"show"),e.options,t),"add-step":(e,t)=>zT(ct(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=nn(e,"update-step");return lc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=nn(e,"complete-step");return lc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=nn(e,"block-step");return lc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=cA(e);return JT(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=nn(e,"remove-step");return XT(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=nn(e,"link");return QT(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=nn(e,"unlink");return ZT(n.id,e.options,t,n.stepRef)},decision:(e,t)=>uc(ct(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>uc(ct(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>uc(ct(e,"validation"),e.options,t,"validation"),resume:(e,t)=>eA(ct(e,"resume"),e.options,t),approve:(e,t)=>tA(ct(e,"approve"),e.options,t),materialize:(e,t)=>iA(ct(e,"materialize"),e.options,t)};function lA(e){let t=dA[e];if(!t)throw Te({command_path:"plan",token:e,allowed:wT});return t}async function C_(e){let t=await NT(e.global),n=aA(e);return lA(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]="4eb2056a-4444-514a-a0db-79b8875c3d65")}catch{}})();function mA(e,t){return[...new Set([...Or.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,s)=>r.localeCompare(s))}function uA(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function vc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await D(r,e,s.id_prefix,s.item_format,o.type_to_folder);if(!i)throw await ot(r,e,s.id_prefix,o.type_to_folder);let a=await K(i,{schema:s.schema}),c=a.document.metadata,m=S(),u=R(t.author,s.author_default),p=await Jn(r,s.id_prefix,{tokenLength:s.ids.token_length,typeToFolder:o.type_to_folder,probeExisting:!1}),f=M(s.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let h={...c,id:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete h.closed_at,delete h.completed_at,delete h.close_reason,delete h.test_runs;let y=bt(I()),g=We({metadata:h,body:a.document.body},{schema:s.schema,extensionFieldNames:y}),b=await In({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=mA(g.metadata,g.body),E=Gt(r,g.metadata.type,p,s.item_format,o.type_to_folder),N=Se(r,p),O=await Pe(r,p,s.locks.ttl_seconds,u,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),j={metadata:{},body:""},$,xe;try{let te=await wn(r,u,{required:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await In({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1});let _e=await D(r,p,s.id_prefix,s.item_format,o.type_to_folder);if(_e)throw new l(`Cannot copy to ${p}: an item with that id already exists at ${_e.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${_e.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await ue(E,je(g,{format:s.item_format,schema:s.schema,extensionFieldNames:y}));try{let ce=qe({nowIso:m,author:u,op:"create",before:j,after:g,message:uA(i.id,t.message)});await Tt(N,ce)}catch(ce){throw await ln(E),ce}xe=await vn({pmRoot:r,preferredFormat:s.item_format,typeToFolder:o.type_to_folder,schema:s.schema,itemPath:E,document:g})}finally{await te()}$=[...await z({path:E,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:j,after:g,changed_fields:v}),...await z({path:N,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:j,after:g,changed_fields:v})],fn({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Kt(g.metadata,v),changed_fields:v})}finally{await O()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:v,warnings:[...no(b),...xe,...$],...b===void 0?{}:{similarity_advisory:b}}}import qo 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]="14aa55e1-cb5f-55ea-bf4c-412217d87449")}catch{}})();async function kc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=R(t.author,s.author_default),i=await Ou({pmRoot:r,settings:s,id:e,author:o,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?qo.relative(r,i.targetPath).split(qo.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:qo.relative(r,Se(r,i.item.id)).split(qo.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]="0f43df79-0b27-53b3-b8bd-9f2a35561733")}catch{}})();async function pA(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}async function Sc(e,t,n){let r=T(process.cwd(),n.path);if(await pA(r),t.clear===!0){if(e!==void 0)throw new l("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",d.USAGE);let p=await A(r),f=gn(R(void 0,p.author_default));return await cu(r),await eo({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 ks(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 fA(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let o=await A(r),i=x(o,I()),a=await D(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await ot(r,e,o.id_prefix,i.type_to_folder);let c=ge(a.id,o.id_prefix),m=await K(a,{schema:o.schema}),u=R_(m.document.metadata.title);return await au(r,c),await eo({pmRoot:r,settings:o,principal:gn(R(void 0,o.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 fA(e,t){let n=await A(e),r=x(n,I()),s=await D(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!s)return null;let o=await K(s,{schema:n.schema});return R_(o.document.metadata.title)}function R_(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]="4f4f5f10-793d-5baa-8985-c0ec855b16c4")}catch{}})();var I_=new Set(["item_format"]),x_=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"]),_A=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","telemetry_tracking"]),hA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","telemetry_tracking"]),gA={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function yA(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(I_.has(t)||x_.has(t)||_A.has(t)||t==="context")return t}function bA(e){let t=e.trim().toLowerCase();return gA[t]??e}function O_(e,t){let n=yA(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."}:I_.has(n)?{routable:!0,flag:"format",value:t}:x_.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:hA.has(n)?bA(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]="a9a8d99c-df4e-55b3-81f5-27124d598c5f")}catch{}})();var P_=["project","global"],dt={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"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],context:["context"]},wA=Object.keys(dt).map(e=>dt[e][0]),vA=Object.fromEntries(Object.keys(dt).flatMap(e=>dt[e].map(t=>[t,e]))),kA={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.",telemetry_tracking:"Telemetry usage reporting policy.",context:"Context command settings (depth, section toggles, limits)."},SA=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],EA=new Set(["metadata_required_fields",...SA]),TA=new Set(["test_result_tracking","telemetry_tracking"]),AA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),CA=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),RA=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),IA=new Set(["governance_preset","governance_create_default_type"]),M_=e=>EA.has(e),xA=e=>CA.has(e),OA=e=>RA.has(e),PA=e=>IA.has(e);function Ec(e){return e==="definition_of_done"||M_(e)}function NA(e){if(P_.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${P_.join(", ")}`,d.USAGE)}function LA(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Te({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function FA(e){let t=vA[e];if(t)return t;let n=Mi.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${wA.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function $A(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,s)=>r.localeCompare(s));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",d.USAGE);return n}function MA(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new l("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",d.USAGE):new l("Config set item-format requires --format toon",d.USAGE)}function D_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new l("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",d.USAGE)}function U_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set test-result-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function G_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set telemetry-tracking requires --policy with one of: enabled, disabled",d.USAGE)}function Ac(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new l("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",d.USAGE)}function j_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new l("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",d.USAGE)}function q_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new l("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",d.USAGE)}function K_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new l("Config set governance-create-mode-default requires --policy with one of: progressive, strict",d.USAGE)}function z_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new l("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",d.USAGE)}function B_(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 l("Config set governance-workflow-enforcement requires one of: off, warn, strict",d.USAGE)}function H_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",d.USAGE)}function V_(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new l("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",d.USAGE)}function N_(e,t){switch(e){case"history_missing_stream_policy":return D_(t);case"sprint_release_format_policy":return ia(t);case"parent_reference_policy":case"governance_parent_reference_policy":return Us(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Ac(t);case"governance_preset":return j_(t);case"governance_ownership_enforcement":return q_(t);case"governance_create_mode_default":return K_(t);case"governance_close_validation_default":return z_(t);case"governance_require_close_reason":return V_(t);case"governance_workflow_enforcement":return B_(t);case"governance_force_required_for_stale_lock":return H_(t);case"test_result_tracking":return U_(t);case"telemetry_tracking":return G_(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var L_={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"},DA=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function UA(e,t){let n=[...new Set((e??[]).map(o=>o.trim()).filter(o=>o.length>0))];if(t){if(n.length>0)throw new l("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",d.USAGE);return[]}if(n.length===0)throw new l("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",d.USAGE);let r=n.map(o=>o.toLowerCase().replaceAll("-","_")),s=r.filter(o=>L_[o]===void 0);if(s.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${s.join(", ")}. Supported values: ${DA.join(", ")}`,d.USAGE);return[...new Set(r.map(o=>L_[o]))].sort((o,i)=>o.localeCompare(i))}function GA(e,t,n){let r=[...new Set((t??[]).map(s=>s.trim().toLowerCase()).filter(s=>s.length>0))].sort((s,o)=>s.localeCompare(o));if(n){if(r.length>0)throw new l(`Config set ${dt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${dt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function jA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function qA(e,t){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new l(`Config action "${e}" does not accept <key>`,d.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new l(`Config action "${e}" requires <key>`,d.USAGE);return FA(t)}function W_(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var KA={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",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",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 Cc(e,t){return KA[t](e)}function De(e,t){return t.length===0?e:{...e,warnings:t}}async function zA(e,t){let n=process.cwd(),r=e==="project"?T(n,t.path):et(n),s=C(r);if(e==="project"&&!await k(s))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);return{pmRoot:r,settingsPath:s}}function BA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new l(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,d.USAGE)}function F_(e,t){let n=e.trim(),r=Number(n);if(/^\d+$/u.test(n)&&Number.isSafeInteger(r)&&r>0)return r;throw new l(`Context ${t} must be a positive integer`,d.USAGE)}async function HA(e,t,n,r,s){let o=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!xi.includes(c))throw new l(`Context --default-depth must be one of ${xi.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,o=!0)}if(t.activityLimit!==void 0){let c=F_(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,o=!0)}if(t.staleThresholdDays!==void 0){let c=F_(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,o=!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=BA(m);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,o=!0)}}return o&&await Ee(n.pmRoot,e,"config:set:context"),De({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:o},s)}function VA(e,t,n){if(n.value!==void 0&&n.value!==t)throw new l(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,d.USAGE);return{...n,value:t}}function WA(e,t,n,r,s,o){if(s===void 0)return o;if(e!=="set")throw new l(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,d.USAGE);if(typeof t!="string"||t.trim().length===0)throw new l('Config action "set" requires <key> before a positional <value>.',d.USAGE);if(r)return VA(t,s,o);W_(n);let i=O_(n,s);if(!i.routable)throw new l(i.reason,d.USAGE);if(i.flag==="criterion"){if(o.criterion!==void 0&&o.criterion.length>0)throw new l(`Config set ${t} received both positional value "${s}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...o,criterion:i.values}}if(i.flag==="format")return{...o,format:i.value};if(o.policy!==void 0&&N_(n,o.policy)!==N_(n,i.value))throw new l(`Config set ${t} received both positional value "${s}" and --policy "${o.policy}". Pass only one.`,d.USAGE);return{...o,policy:i.value}}function YA(e){let t=Object.keys(dt).map(r=>({key:r,aliases:dt[r],value_kind:r==="context"?"object":Ec(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:Ec(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:kA[r],value:Cc(e.settings,r)})),n=Mi.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Di(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 De({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function JA(e){let t=Object.fromEntries(Object.keys(dt).map(n=>[n,Cc(e.settings,n)]));return De({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function XA(e,t){let n=Cc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?De({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?De({...r,context_settings:n},e.warnings):Array.isArray(n)?De({...r,criteria:n},e.warnings):De({...r,policy:n},e.warnings)}async function QA(e,t,n,r){if(t==="get"){let a=Di(e.settings,n);return De({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 s=r.value;if(typeof s!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let o=Tm(n,s);if(!o.ok)throw new l(o.error.message,d.USAGE);let i=gs(e.settings,n,o.parsed.value);return i&&await Ee(e.target.pmRoot,e.settings,`config:set:${n.path}`),De({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:o.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function X(e,t,n){t&&await Ee(e.target.pmRoot,e.settings,n)}function $_(e,t,n){return e!==n||t!==n}function ae(e,t,n,r){return De({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Tc(e,t,n,r){return De({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function ZA(e,t){let n=MA(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,s;if(r){let o=x(e.settings,I()),i=await Ku(e.target.pmRoot,n,"config:set:item_format:migrate",o.type_to_folder,e.settings.schema);s={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await Ee(e.target.pmRoot,e.settings,"config:set:item_format")}return De({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:s,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function eC(e,t,n){if(t==="history_missing_stream_policy"){let o=D_(n.policy),i=e.settings.history.missing_stream!==o;return e.settings.history.missing_stream=o,await X(e,i,"config:set:history_missing_stream_policy"),ae(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let o=ia(n.policy),i=e.settings.validation.sprint_release_format!==o;return e.settings.validation.sprint_release_format=o,await X(e,i,"config:set:sprint_release_format_policy"),ae(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let o=Us(n.policy),i=e.settings.validation.parent_reference!==o||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==o;return e.settings.validation.parent_reference=o,e.settings.governance.preset="custom",e.settings.governance.parent_reference=o,await X(e,i,"config:set:parent_reference_policy"),ae(e,t,e.settings.validation.parent_reference,i)}let r=Ac(n.policy),s=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 X(e,s,"config:set:metadata_validation_profile"),ae(e,t,e.settings.validation.metadata_profile,s)}async function tC(e,t,n){if(t==="metadata_required_fields"){let a=UA(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 X(e,c,"config:set:metadata_required_fields"),Tc(e,t,[...e.settings.validation.metadata_required_fields],c)}let s={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],o=GA(t,n.criterion,n.clearCriteria),i=o.length!==s.length||o.some((a,c)=>a!==s[c]);return s.splice(0,s.length,...o),await X(e,i,`config:set:${t}`),Tc(e,t,[...s],i)}async function nC(e,t,n){if(t==="governance_preset"){let c=j_(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await X(e,m,"config:set:governance_preset"),ae(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",s=r?n.policy.trim():"";if(r&&s.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await X(e,c,"config:set:governance_create_default_type"),ae(e,t,e.settings.governance.create_default_type??"",c)}if(s.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let o=x(e.settings,I()),i=pe(s,o);if(!i)throw new l(kt(s,o.types,St(e.target.pmRoot,e.settings.schema)),d.USAGE);let a=e.settings.governance.create_default_type!==i;return e.settings.governance.create_default_type=i,await X(e,a,"config:set:governance_create_default_type"),ae(e,t,e.settings.governance.create_default_type,a)}async function rC(e,t,n){if(t==="governance_ownership_enforcement"){let o=q_(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==o;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=o,await X(e,i,"config:set:governance_ownership_enforcement"),ae(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let o=K_(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==o;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=o,await X(e,i,"config:set:governance_create_mode_default"),ae(e,t,e.settings.governance.create_mode_default,i)}let r=z_(n.policy),s=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 X(e,s,"config:set:governance_close_validation_default"),ae(e,t,e.settings.governance.close_validation_default,s)}async function sC(e,t,n){if(t==="governance_parent_reference_policy"){let o=Us(n.policy),i=e.settings.governance.preset!=="custom"||$_(e.settings.governance.parent_reference,e.settings.validation.parent_reference,o);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=o,e.settings.validation.parent_reference=o,await X(e,i,"config:set:governance_parent_reference_policy"),ae(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let o=Ac(n.policy),i=e.settings.governance.preset!=="custom"||$_(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,o);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=o,e.settings.validation.metadata_profile=o,await X(e,i,"config:set:governance_metadata_validation_profile"),ae(e,t,e.settings.governance.metadata_profile,i)}let r=B_(n.policy),s=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await X(e,s,"config:set:governance_workflow_enforcement"),ae(e,t,e.settings.governance.workflow_enforcement,s)}async function oC(e,t,n){if(t==="governance_require_close_reason"){let a=V_(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await X(e,c,"config:set:governance_require_close_reason"),ae(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let s=H_(n.policy)==="enabled",o=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==s;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=s,await X(e,o,"config:set:governance_force_required_for_stale_lock"),ae(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function iC(e,t,n){if(t==="test_result_tracking"){let a=U_(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await X(e,c,"config:set:test_result_tracking"),ae(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}let s=G_(n.policy)==="enabled",o=e.settings.telemetry.enabled!==s||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=s,e.settings.telemetry.first_run_prompt_completed=!0,await X(e,o,"config:set:telemetry_tracking"),ae(e,t,e.settings.telemetry.enabled?"enabled":"disabled",o)}async function aC(e,t,n){let r=$A(n.criterion,n.clearCriteria),s=r.length!==e.settings.workflow.definition_of_done.length||r.some((o,i)=>o!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await X(e,s,"config:set:definition_of_done"),Tc(e,t,[...e.settings.workflow.definition_of_done],s)}async function cC(e,t,n){if(n.clearCriteria===!0&&!Ec(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?ZA(e,n):t==="context"?HA(e.settings,n,e.target,e.scope,e.warnings):t==="definition_of_done"?aC(e,t,n):M_(t)?tC(e,t,n):TA.has(t)?iC(e,t,n):AA.has(t)?oC(e,t,n):xA(t)?rC(e,t,n):OA(t)?sC(e,t,n):PA(t)?nC(e,t,n):eC(e,t,n)}async function Y_(e,t,n,r,s,o){let i=NA(e),a=LA(t),c=a==="get"||a==="set"?hs(n):void 0,m=c?void 0:qA(a,n),u=WA(a,n,m,c,o,r),p=await zA(i,s),{settings:f,metadata:_,warnings:h}=await Cu(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:jA(h)};return c?QA(y,a,c,u):a==="list"?YA(y):a==="export"?JA(y):(W_(m),a==="get"?XA(y,m):cC(y,m,u))}import UC from"node:fs/promises";import V from"node:path";import GC from"node:readline/promises";import{stdin as jC,stdout as Re}from"node:process";import Ic from"node:fs/promises";import re from"node:path";import dC from"node:readline/promises";import{stdin as lC,stdout as Ko}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]="e404796d-439b-5f4c-9330-5b12ff41d7b2")}catch{}})();var X_=["ask","add","skip","status"],mC=["AGENTS.md","CLAUDE.md"],uC=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],pC=8,xc=1,fC="<!-- pm-cli:agent-guidance:start:",_C=`<!-- pm-cli:agent-guidance:start:v${xc} -->`,Rc="<!-- pm-cli:agent-guidance:end -->",pr="Add workflow guidance later: pm init --agent-guidance add";var hC=()=>dC.createInterface({input:lC,output:Ko});function mr(e,t){let n=re.relative(e,t);return n.length===0?re.basename(t):n.split(re.sep).join("/")}function J_(e){return e.endsWith(`
|
|
9
9
|
`)?e:`${e}
|
|
10
|
-
`}function
|
|
10
|
+
`}function gC(e){return e.includes(`\r
|
|
11
11
|
`)?`\r
|
|
12
12
|
`:`
|
|
13
|
-
`}function
|
|
14
|
-
`)?
|
|
15
|
-
`)?
|
|
13
|
+
`}function Q_(e){let t=e.indexOf(fC);if(t===-1)return null;let n=e.indexOf(Rc,t);return n===-1?null:{start_index:t,end_index:n+Rc.length}}function yC(e){return Q_(e)!==null}function bC(e,t="<your project test command>"){return[_C,"## pm Workflow (Agent Quickstart)","",'- Orient before mutate: `pm context --limit 10`, `pm search "<keywords>" --limit 10`, `pm list --status open --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`, `pm close <id> "<evidence>" --validate-close warn`, `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Rc,""].join(e)}function wC(e,t="<your project test command>"){let n=gC(e),r=bC(n,t),s=Q_(e);if(s){let a=e.slice(s.end_index),c=a.startsWith(`\r
|
|
14
|
+
`)?a.slice(2):a.startsWith(`
|
|
15
|
+
`)?a.slice(1):a,m=J_(`${e.slice(0,s.start_index)}${r}${c}`);return{next_content:m,changed:m!==e}}let o=e.length===0?"":e.endsWith(`
|
|
16
16
|
`)?`
|
|
17
17
|
`:`
|
|
18
18
|
|
|
19
|
-
`,
|
|
19
|
+
`,i=J_(`${e}${o}${r}`);return{next_content:i,changed:i!==e}}async function vC(e){if(await k(re.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Ic.readFile(re.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=kC(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 k(re.join(e,"pnpm-lock.yaml"))?"pnpm test":await k(re.join(e,"bun.lock"))||await k(re.join(e,"bun.lockb"))?"bun run test":await k(re.join(e,"yarn.lock"))?"yarn test":"npm test"}function kC(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 SC(e,t){let n=re.dirname(e);return re.basename(e)==="pm"&&re.basename(n)===".agents"?re.dirname(n):re.resolve(t,e)}function EC(e,t){let n=e.find(s=>re.basename(s.file_path)==="AGENTS.md"&&s.exists);if(n)return n.file_path;let r=e.find(s=>s.exists);return r?r.file_path:re.join(t,"AGENTS.md")}function TC(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function AC(e){let t=hC();try{Ko.write(`
|
|
20
20
|
Agent guidance check
|
|
21
|
-
`),
|
|
22
|
-
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return
|
|
23
|
-
`),
|
|
24
|
-
`),
|
|
21
|
+
`),Ko.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
|
|
22
|
+
`);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return Ko.write(`
|
|
23
|
+
`),TC(n,!0)}finally{t.close()}}function Z_(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:xc,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 eh(e){let t=[];for(let n of mC){let r=re.join(e,n),s=await k(r);if(!s){t.push({file_path:r,exists:s,has_guidance:!1,has_marker:!1});continue}let o=await Ic.readFile(r,"utf8"),i=o.toLowerCase(),a=uC.filter(m=>i.includes(m)),c=yC(o);t.push({file_path:r,exists:s,has_guidance:c||a.length>=pC,has_marker:c})}return t}function fr(e,t){e.includes(t)||e.push(t)}function CC(e,t){let n=Z_(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function RC(e,t=re.dirname(e)){let r=await k(e)?await Ic.readFile(e,"utf8"):"",s=wC(r,await vC(t));return s.changed?(await ue(e,s.next_content),{changed:!0,warnings:await z({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function IC(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=>mr(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>mr(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>mr(e.projectRoot,t.file_path))}}async function xC(e,t,n){return e?await eh(n):t}function ur(e,t,n){e.state={...e.state,...n,template_version:xc,last_checked_files:t}}async function th(e,t){if(t.presentBefore)return;let n=await RC(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function OC(e,t){t||(e.warnings.push("agent_guidance:missing"),fr(e.nextSteps,pr))}function PC(e,t){e.skipped=!0,ur(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),fr(e.nextSteps,pr)}async function NC(e,t){await th(e,t),ur(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function LC(e,t){e.state.declined&&ur(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function FC(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),fr(e.nextSteps,pr)}async function $C(e,t){if(e.prompted=!0,await AC(t.targetRelativePath)){await th(e,t),ur(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,ur(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),fr(e.nextSteps,pr)}function MC(e){e.warnings.push("agent_guidance:missing_non_interactive"),fr(e.nextSteps,pr)}async function DC(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(OC(n,t.presentBefore),n):t.mode==="skip"?(PC(n,t.checkedFiles),n):t.mode==="add"?(await NC(n,t),n):t.presentBefore?(LC(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(FC(n),n):t.interactive?(await $C(n,t),n):(MC(n),n)}async function nh(e){let t=SC(e.pm_root,e.cwd),n=await eh(t),r=EC(n,t),s=mr(t,r),o=n.map(u=>mr(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await DC(Z_(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:s,checkedFiles:o,presentBefore:i,projectRoot:t}),c=CC(e.settings,a.state);return n=await xC(a.applied,n,t),{summary:IC({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:s,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]="75c0d2d2-6a89-508f-b7dd-b43d55978b44")}catch{}})();var qC=()=>GC.createInterface({input:jC,output:Re});function KC(){return structuredClone(yt)}var zC=["minimal","default","strict"];function sh(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--preset must not be empty",d.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new l(`Invalid --preset value "${e}". Allowed: ${zC.join(", ")}`,d.USAGE)}function BC(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return hm(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${_m.join(", ")}`,d.USAGE)}}}function HC(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new l("--author must not be empty",d.USAGE);return t}function Oc(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:V.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function VC(e,t,n,r){let s=r?.trim();if(r!==void 0&&s?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(s!==void 0){if(t.path!==void 0||Oc(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=V.resolve(e,s),u=V.join(m,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:m}}}if(t.path===void 0&&Oc(n)){let m=V.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let o=T(e,t.path),i=V.join(V.resolve(e),".agents","pm"),a=V.dirname(V.dirname(o)),c=V.resolve(o)===i?"current":"ancestor";return{pmRoot:o,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:o,workspace_root:a,discovery:c,requested_cwd:V.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:o}}}function WC(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new l("--id-prefix must not be empty",d.USAGE);if(Oc(t))throw new l(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,d.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&&Ct(e)!==Ct(t))throw new l(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,d.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Ct(e)}`,`pm init --id-prefix ${Ct(t)}`]});return t}function YC(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new l("--agent-guidance must not be empty",d.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new l(`Invalid --agent-guidance value "${e}". Allowed: ${X_.join(", ")}`,d.USAGE)}function JC(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function oh(e,t){let n=Kd[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function XC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function QC(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(XC).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function ZC(e,t,n){let r=fs(t.schema),s=rt(e,r.files.types,nt.types),i=pm(await q(s)),a=[],c=[];for(let m of gm(n)){let u=fm(i,m);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await At({pmRoot:e,filePath:s,raw:us(i),op:"init:type-preset",author:R(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:s}}async function eR(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",V.join(".agents","pm")];for(let n of t)if(await k(V.join(e,n)))return!0;return!1}async function tR(e,t,n){if(!t||n||await k(V.join(e,"settings.json"))||!await eR(e))return;let r=V.join(e,".agents","pm");throw new l(`Refusing to initialize tracker files directly in workspace root "${e}".`,d.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 ih(e,t){let n=[],r=[];for(let s of t){let o=s?V.join(e,s):e,i=await k(o);await UC.mkdir(o,{recursive:!0}),i?r.push(`already_exists:${o}`):n.push(o),r.push(...await z({path:o,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function nR(e,t){let n=qC();try{Re.write(`pm init setup wizard (agent-optimized)
|
|
24
|
+
`),Re.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
25
25
|
|
|
26
|
-
`),
|
|
27
|
-
`),
|
|
28
|
-
`);let r=await n.question(`Item ID prefix [${e}]: `),s=r.trim().length>0?
|
|
26
|
+
`),Re.write(`1/3 Item ID prefix
|
|
27
|
+
`),Re.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
|
|
28
|
+
`);let r=await n.question(`Item ID prefix [${e}]: `),s=r.trim().length>0?Ct(r):e;Re.write(`
|
|
29
29
|
2/3 Governance preset
|
|
30
|
-
`),
|
|
31
|
-
`),
|
|
32
|
-
`),
|
|
33
|
-
`);let o=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),i=o.trim().length>0?o.trim():"minimal",a="minimal";try{a=
|
|
34
|
-
`)}
|
|
30
|
+
`),Re.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
31
|
+
`),Re.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
32
|
+
`),Re.write(`strict: ownership blocking, strict create defaults, close validation strict.
|
|
33
|
+
`);let o=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),i=o.trim().length>0?o.trim():"minimal",a="minimal";try{a=sh(i)}catch{Re.write(`Unrecognized governance preset "${i}"; using minimal.
|
|
34
|
+
`)}Re.write(`
|
|
35
35
|
3/3 Project telemetry
|
|
36
|
-
`),
|
|
37
|
-
`);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=
|
|
38
|
-
`),{prefix:s,preset:a,telemetry_enabled:u}}finally{n.close()}}function zC(e){return{presetFromOption:J_(e.preset),useDefaults:e.defaults===!0,authorFromOption:NC(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:$C(e.agentGuidance),typePreset:PC(e.typePreset)}}function BC(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 HC(e,t,n,r){if(t.length===0||n)return;let s=r.discovery==="ancestor";throw new l(`${s?`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.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:s?"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",...s?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...s?['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 VC(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&&(X_(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 WC(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=BC({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return HC(e.settingsPath,n,e.options.force===!0,e.target),VC({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Se(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function YC(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,s=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await KC(t,pt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,s=!0}let o=n??"minimal",i=xC();i.id_prefix=t,X_(i,o);let a=ws()?.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 Se(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:s}}async function Y_(e){return e.settingsExists?await WC(e):await YC({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function JC(e){let t=await W_({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 Se(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function XC(e,t){let n=[],r=[],s=await fm(e,t.schema);for(let o of s.created_paths)n.push(o),r.push(...await z({path:o,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function QC(e){if(e.typePreset===void 0)return;let t=await GC(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await z({path:t.file,scope:"project",op:"init:type_preset"})),t}async function ZC(e){let n=x(e.settings,I()).folders.filter(s=>!Ri.includes(s)),r=await Q_(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function eR(e){let t=V.resolve(e.tracker_root),n=V.dirname(t);return V.basename(t)==="pm"&&V.basename(n)===".agents"?V.dirname(n):e.workspace_root}async function tR(e,t,n,r){if(!e)return;let s=await En("all",{install:!0,project:!0},{...t,path:n});r.push(...s.warnings);let o=UC(s),i=o.packages.filter(a=>!a.ok).map(a=>a.alias);if(!o.installed_all||i.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${i.length>0?`: ${i.join(", ")}`:"."}`,d.GENERIC_FAILURE);return o}function nR(e){let t=r=>hs([...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 s=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(s)||n.push(s)}return n}async function rR(e,t,n,r=op){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 s=await r({pmRoot:e,workspaceRoot:t});s.gitattributes.changed&&n.push(`updated:merge_fence:${s.gitattributes.path}`)}catch(s){if(!(s instanceof l))throw s;n.push(`merge_fence_skipped:install_failed:${s.context.code??"pm_error"}:${s.message}:run pm merge install after resolving the Git repository error`)}}async function lr(e,t,n={}){let r=process.cwd(),s=LC(r,t,e,n.workspace),o=s.pmRoot;e=FC(s.prefixArg,n.idPrefix);let i=zC(n);await qC(o,s.target.mode==="tracker-path",n.force===!0);let a=[],c=[],m=V.join(o,"settings.json"),u=await k(m),p;u&&(p=await Y_({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:kt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target}));let f=await Q_(o,Ri);a.push(...f.createdDirs),c.push(...f.warnings),p??=await Y_({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:kt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target});let{settings:_}=p,h=eR(s.target),y=await rp(h??V.dirname(o)),g=h??y,b=await JC({pmRoot:o,cwd:g??r,agentGuidanceMode:i.agentGuidanceMode,settings:_,warnings:c}),v=await XC(o,_);a.push(...v.createdDirs),c.push(...v.warnings);let E=await QC({pmRoot:o,settings:_,typePreset:i.typePreset,warnings:c});if(E&&(_=await A(o)),await ZC({pmRoot:o,settings:_,createdDirs:a,warnings:c}),g&&i.agentGuidanceMode!=="status"){let $=await Ki(g,{pmRoot:o});$.changed&&c.push(`updated:gitignore:${$.path}`)}!u&&n.mergeFence!==!1&&i.agentGuidanceMode!=="status"&&await rR(o,y,c);let N=await tR(i.installBundledPackages,t,o,c),P=nR({installBundledPackages:i.installBundledPackages,registeredTypePreset:E,agentGuidanceNextSteps:b.next_steps,target:s.target});return{ok:!0,path:o,target:s.target,settings:_,created_dirs:a,warnings:c,governance_preset:_.governance.preset,wizard_used:p.wizardUsed,...E?{registered_type_preset:E}:{},...N?{installed_packages:N}:{},next_steps:P,agent_guidance:b}}import lR from"node:fs/promises";import xc 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]="70e06a73-6602-5384-a25b-fd3df5f6438e")}catch{}})();var eh=10,en="https://schema.unbrained.dev/pm/eval-query-set/v1";var jo={schema:en,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},qe=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},sR=new Set(["keyword","semantic","hybrid"]);function Z_(e,t){let n=0,r=Math.min(t,e.length);for(let s=0;s<r;s+=1)n+=e[s]/Math.log2(s+2);return n}function oR(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),s=Z_(r,n),o=Array.from({length:t.size},()=>1),i=Z_(o,n);return i===0?0:s/i}function iR(e,t,n){let r=Math.min(n,e.length);for(let s=0;s<r;s+=1)if(t.has(e[s]))return 1/(s+1);return 0}function Rc(e,t,n){let r=Math.min(n,e.length),s=0;for(let o=0;o<r;o+=1)t.has(e[o])&&(s+=1);return s}function aR(e,t,n){return n<=0?0:Rc(e,t,n)/n}function cR(e,t,n){return t.size===0?0:Rc(e,t,n)/t.size}function th(e,t,n){return{ndcg:oR(e,t,n),mrr:iR(e,t,n),precision:aR(e,t,n),recall:cR(e,t,n),relevant_total:t.size,retrieved_relevant:Rc(e,t,n)}}function nh(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,s)=>({ndcg:r.ndcg+s.ndcg,mrr:r.mrr+s.mrr,precision:r.precision+s.precision,recall:r.recall+s.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 dR(e,t){if(typeof e!="object"||e===null)throw new qe(`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 qe(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new qe(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(o=>typeof o!="string"))throw new qe(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let s=[...new Set(n.relevant_ids.map(o=>o.trim()).filter(o=>o.length>0))];if(s.length===0)throw new qe(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!sR.has(n.mode)))throw new qe(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:s,...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Ic(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==en)throw new qe(`Unsupported eval query set schema; expected "${en}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new qe('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new qe("Eval query set must contain at least one query");return{schema:en,queries:n.map((r,s)=>dR(r,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]="b90a064c-f423-5bf7-9fbf-1fb273c7b5af")}catch{}})();var mR=xc.join("search","eval-queries.json"),Oc={schema:en,examples:[JSON.stringify(jo)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},uR=new Set(["keyword","semantic","hybrid"]),pR=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!uR.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},fR=e=>{if(e===void 0||e==="")return eh;let t=jd(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},_R=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new l("Eval --fail-under must be a number in the range [0, 1]",d.USAGE);return n},Ct=e=>Math.round(e*1e4)/1e4,hR=async e=>{try{return await lR.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Oc,examples:[`echo '${JSON.stringify(jo)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},gR=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new l(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,d.USAGE,Oc)}},yR=e=>{try{return Ic(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Oc)}},bR=async e=>yR(gR(await hR(e),e)),wR=(e,t)=>t?xc.resolve(process.cwd(),t):xc.join(e,mR),vR=async(e,t,n,r)=>{let s=e.mode??t,i=(await er(e.query,{mode:s,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=th(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,mode:s,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:Ct(a.ndcg),mrr:Ct(a.mrr),precision:Ct(a.precision),recall:Ct(a.recall)}}},kR=(e,t,n,r)=>{let s=nh(n);return{k:e,query_count:t.length,aggregate:{ndcg:Ct(s.ndcg),mrr:Ct(s.mrr),precision:Ct(s.precision),recall:Ct(s.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||s.ndcg>=r}},rh=async(e,t)=>{let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=fR(e.k),s=pR(e.mode),o=_R(e.failUnder),i=wR(n,e.queries),a=await bR(i),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await vR(u,s,r,t);m.push(f),c.push(p)}return kR(r,c,m,o)};import{readFile as NR,writeFile as LR}from"node:fs/promises";import FR 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]="3c9d6924-ae7c-57c3-a346-1e2189c532fa")}catch{}})();function Pc(e,t){let n=ks(e);if(n)throw new l(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,d.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(i)try{let a=JSON.parse(i);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new l(`History merge input (${t}) contains invalid JSON at line ${s+1}.`,d.GENERIC_FAILURE)}}return r}function Rt(e){return J({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function SR(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Rt(e[r])===Rt(t[r]);)r+=1;return r}function sh(e,t,n){Pc(e,"base");let r=Pc(t,"ours"),s=Pc(n,"theirs"),o=SR(r,s);if(o===r.length&&o===s.length)return{merged:ot(r),strategy:"identical",common_entries:o,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===s.length)return{merged:ot(r),strategy:"fast_forward_ours",common_entries:o,entries_from_ours:r.length-o,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===r.length)return{merged:ot(s),strategy:"fast_forward_theirs",common_entries:o,entries_from_ours:0,entries_from_theirs:s.length-o,entries_total:s.length,reanchored:!1};let i=r.slice(o),a=new Set(i.map(Rt)),c=s.slice(o).filter(p=>!a.has(Rt(p))),m=[...i,...c].sort((p,f)=>{let _=_n(p.ts,f.ts);if(_!==0)return _;let h=a.has(Rt(p)),y=a.has(Rt(f));return h!==y?Number(y)-Number(h):Rt(p).localeCompare(Rt(f))}),u=Es([...r.slice(0,o),...m]);return{merged:ot(u.entries),strategy:"union_reanchor",common_entries:o,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:u.entries.length,reanchored:!0}}function Nc(e,t){let n=ks(e);if(n)throw new l(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,d.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{throw new l(`Relationship merge input (${t}) contains invalid JSON at line ${s+1}.`,d.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new l(`Relationship merge input (${t}) line ${s+1} is not a relationship event (eventId + sequence required).`,d.GENERIC_FAILURE);r.push(a)}return r}function qo(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
36
|
+
`),Re.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
|
|
37
|
+
`);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=JC(m,t);return Re.write(`
|
|
38
|
+
`),{prefix:s,preset:a,telemetry_enabled:u}}finally{n.close()}}function rR(e){return{presetFromOption:sh(e.preset),useDefaults:e.defaults===!0,authorFromOption:HC(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:YC(e.agentGuidance),typePreset:BC(e.typePreset)}}function sR(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 oR(e,t,n,r){if(t.length===0||n)return;let s=r.discovery==="ancestor";throw new l(`${s?`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.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:s?"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",...s?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...s?['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 iR(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&&(oh(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 aR(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=sR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return oR(e.settingsPath,n,e.options.force===!0,e.target),iR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Ee(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function cR(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,s=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await nR(t,yt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,s=!0}let o=n??"minimal",i=KC();i.id_prefix=t,oh(i,o);let a=Ss()?.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 Ee(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:s}}async function rh(e){return e.settingsExists?await aR(e):await cR({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function dR(e){let t=await nh({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 Ee(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function lR(e,t){let n=[],r=[],s=await wm(e,t.schema);for(let o of s.created_paths)n.push(o),r.push(...await z({path:o,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function mR(e){if(e.typePreset===void 0)return;let t=await ZC(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await z({path:t.file,scope:"project",op:"init:type_preset"})),t}async function uR(e){let n=x(e.settings,I()).folders.filter(s=>!Oi.includes(s)),r=await ih(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function pR(e){let t=V.resolve(e.tracker_root),n=V.dirname(t);return V.basename(t)==="pm"&&V.basename(n)===".agents"?V.dirname(n):e.workspace_root}async function fR(e,t,n,r){if(!e)return;let s=await Cn("all",{install:!0,project:!0},{...t,path:n});r.push(...s.warnings);let o=QC(s),i=o.packages.filter(a=>!a.ok).map(a=>a.alias);if(!o.installed_all||i.length>0)throw new l(`pm init --with-packages did not install all bundled packages successfully${i.length>0?`: ${i.join(", ")}`:"."}`,d.GENERIC_FAILURE);return o}function _R(e){let t=r=>bs([...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 s=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(s)||n.push(s)}return n}async function hR(e,t,n,r=_p){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 s=await r({pmRoot:e,workspaceRoot:t});s.gitattributes.changed&&n.push(`updated:merge_fence:${s.gitattributes.path}`)}catch(s){if(!(s instanceof l))throw s;n.push(`merge_fence_skipped:install_failed:${s.context.code??"pm_error"}:${s.message}:run pm merge install after resolving the Git repository error`)}}async function _r(e,t,n={}){let r=process.cwd(),s=VC(r,t,e,n.workspace),o=s.pmRoot;e=WC(s.prefixArg,n.idPrefix);let i=rR(n);await tR(o,s.target.mode==="tracker-path",n.force===!0);let a=[],c=[],m=V.join(o,"settings.json"),u=await k(m),p;u&&(p=await rh({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:Ct(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target}));let f=await ih(o,Oi);a.push(...f.createdDirs),c.push(...f.warnings),p??=await rh({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:Ct(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target});let{settings:_}=p,h=pR(s.target),y=await pp(h??V.dirname(o)),g=h??y,b=await dR({pmRoot:o,cwd:g??r,agentGuidanceMode:i.agentGuidanceMode,settings:_,warnings:c}),v=await lR(o,_);a.push(...v.createdDirs),c.push(...v.warnings);let E=await mR({pmRoot:o,settings:_,typePreset:i.typePreset,warnings:c});if(E&&(_=await A(o)),await uR({pmRoot:o,settings:_,createdDirs:a,warnings:c}),g&&i.agentGuidanceMode!=="status"){let j=await Hi(g,{pmRoot:o});j.changed&&c.push(`updated:gitignore:${j.path}`)}!u&&n.mergeFence!==!1&&i.agentGuidanceMode!=="status"&&await hR(o,y,c);let N=await fR(i.installBundledPackages,t,o,c),O=_R({installBundledPackages:i.installBundledPackages,registeredTypePreset:E,agentGuidanceNextSteps:b.next_steps,target:s.target});return{ok:!0,path:o,target:s.target,settings:_,created_dirs:a,warnings:c,governance_preset:_.governance.preset,wizard_used:p.wizardUsed,...E?{registered_type_preset:E}:{},...N?{installed_packages:N}:{},next_steps:O,agent_guidance:b}}import SR from"node:fs/promises";import Lc 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]="70e06a73-6602-5384-a25b-fd3df5f6438e")}catch{}})();var ch=10,rn="https://schema.unbrained.dev/pm/eval-query-set/v1";var zo={schema:rn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Be=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},gR=new Set(["keyword","semantic","hybrid"]);function ah(e,t){let n=0,r=Math.min(t,e.length);for(let s=0;s<r;s+=1)n+=e[s]/Math.log2(s+2);return n}function yR(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),s=ah(r,n),o=Array.from({length:t.size},()=>1),i=ah(o,n);return i===0?0:s/i}function bR(e,t,n){let r=Math.min(n,e.length);for(let s=0;s<r;s+=1)if(t.has(e[s]))return 1/(s+1);return 0}function Pc(e,t,n){let r=Math.min(n,e.length),s=0;for(let o=0;o<r;o+=1)t.has(e[o])&&(s+=1);return s}function wR(e,t,n){return n<=0?0:Pc(e,t,n)/n}function vR(e,t,n){return t.size===0?0:Pc(e,t,n)/t.size}function dh(e,t,n){return{ndcg:yR(e,t,n),mrr:bR(e,t,n),precision:wR(e,t,n),recall:vR(e,t,n),relevant_total:t.size,retrieved_relevant:Pc(e,t,n)}}function lh(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,s)=>({ndcg:r.ndcg+s.ndcg,mrr:r.mrr+s.mrr,precision:r.precision+s.precision,recall:r.recall+s.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 kR(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(o=>typeof o!="string"))throw new Be(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let s=[...new Set(n.relevant_ids.map(o=>o.trim()).filter(o=>o.length>0))];if(s.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"||!gR.has(n.mode)))throw new Be(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:s,...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function Nc(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==rn)throw new Be(`Unsupported eval query set schema; expected "${rn}"`);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:rn,queries:n.map((r,s)=>kR(r,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]="b90a064c-f423-5bf7-9fbf-1fb273c7b5af")}catch{}})();var ER=Lc.join("search","eval-queries.json"),Fc={schema:rn,examples:[JSON.stringify(zo)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},TR=new Set(["keyword","semantic","hybrid"]),AR=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!TR.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},CR=e=>{if(e===void 0||e==="")return ch;let t=Hd(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},RR=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new l("Eval --fail-under must be a number in the range [0, 1]",d.USAGE);return n},Ot=e=>Math.round(e*1e4)/1e4,IR=async e=>{try{return await SR.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Fc,examples:[`echo '${JSON.stringify(zo)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},xR=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new l(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,d.USAGE,Fc)}},OR=e=>{try{return Nc(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Fc)}},PR=async e=>OR(xR(await IR(e),e)),NR=(e,t)=>t?Lc.resolve(process.cwd(),t):Lc.join(e,ER),LR=async(e,t,n,r)=>{let s=e.mode??t,i=(await or(e.query,{mode:s,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=dh(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,mode:s,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:Ot(a.ndcg),mrr:Ot(a.mrr),precision:Ot(a.precision),recall:Ot(a.recall)}}},FR=(e,t,n,r)=>{let s=lh(n);return{k:e,query_count:t.length,aggregate:{ndcg:Ot(s.ndcg),mrr:Ot(s.mrr),precision:Ot(s.precision),recall:Ot(s.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||s.ndcg>=r}},mh=async(e,t)=>{let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=CR(e.k),s=AR(e.mode),o=RR(e.failUnder),i=NR(n,e.queries),a=await PR(i),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await LR(u,s,r,t);m.push(f),c.push(p)}return FR(r,c,m,o)};import{readFile as HR,writeFile as VR}from"node:fs/promises";import WR 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]="3c9d6924-ae7c-57c3-a346-1e2189c532fa")}catch{}})();function $c(e,t){let n=Ts(e);if(n)throw new l(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,d.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(i)try{let a=JSON.parse(i);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new l(`History merge input (${t}) contains invalid JSON at line ${s+1}.`,d.GENERIC_FAILURE)}}return r}function Pt(e){return J({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function $R(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Pt(e[r])===Pt(t[r]);)r+=1;return r}function uh(e,t,n){$c(e,"base");let r=$c(t,"ours"),s=$c(n,"theirs"),o=$R(r,s);if(o===r.length&&o===s.length)return{merged:st(r),strategy:"identical",common_entries:o,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===s.length)return{merged:st(r),strategy:"fast_forward_ours",common_entries:o,entries_from_ours:r.length-o,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===r.length)return{merged:st(s),strategy:"fast_forward_theirs",common_entries:o,entries_from_ours:0,entries_from_theirs:s.length-o,entries_total:s.length,reanchored:!1};let i=r.slice(o),a=new Set(i.map(Pt)),c=s.slice(o).filter(p=>!a.has(Pt(p))),m=[...i,...c].sort((p,f)=>{let _=yn(p.ts,f.ts);if(_!==0)return _;let h=a.has(Pt(p)),y=a.has(Pt(f));return h!==y?Number(y)-Number(h):Pt(p).localeCompare(Pt(f))}),u=Cs([...r.slice(0,o),...m]);return{merged:st(u.entries),strategy:"union_reanchor",common_entries:o,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:u.entries.length,reanchored:!0}}function Mc(e,t){let n=Ts(e);if(n)throw new l(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,d.GENERIC_FAILURE);let r=[];for(let[s,o]of e.split(/\r?\n/).entries()){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{throw new l(`Relationship merge input (${t}) contains invalid JSON at line ${s+1}.`,d.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new l(`Relationship merge input (${t}) line ${s+1} is not a relationship event (eventId + sequence required).`,d.GENERIC_FAILURE);r.push(a)}return r}function Bo(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
39
39
|
`)}
|
|
40
|
-
`}function
|
|
41
|
-
`,conflict_paths:c,paths_from_theirs:m,preferred: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]="8d79e3a4-6104-5855-837f-69a041b87b27")}catch{}})();var mh=["item","history","relationship","json"];function $R(e){let t=e.trim().toLowerCase();if(mh.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${mh.join(", ")}.`,d.USAGE)}function MR(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new l(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,d.USAGE)}async function Dc(e,t){try{return await NR(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function DR(e){let t=T(process.cwd(),e.path);return await k(C(t))?A(t):null}function UR(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function uh(e,t){let n=$R(e.artifact),r=MR(e.prefer),s=FR.resolve(e.outputPath??e.oursPath),[o,i,a]=await Promise.all([Dc(e.basePath,"base"),Dc(e.oursPath,"ours"),Dc(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=sh(o,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 _=oh(o,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 DR(t),h=ch(o,i,a,{format:UR(e.itemPath??s,_),schema:_?.schema,extensionFieldNames:ft(I()),preferred:r,conflictResolution:"stable_value_order"});c=h.merged,u.push(...h.conflict_fields),p.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0&&(m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,decisions:h.conflict_decisions})}else{let _=lh(o,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await LR(s,c,"utf8"),m!==void 0){let _=await Ep(m);_!==null&&(p.receipt=Yn(_))}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 direction-independent stable value. ${_} 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:s,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:S()}}import _h from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de9b7f82-0f51-599d-b1fa-2d54e3acbdbc")}catch{}})();function ph(e,t){return t==="body"?e.body:e.metadata[t]}function Uc(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(s=>{let o=t.findIndex((i,a)=>!r.has(a)&&Uc(s,i));return o<0?!1:(r.add(o),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,s])=>Object.hasOwn(n,r)&&Uc(s,n[r]))}function fh(e,t){let n=new Set(t),r=[];for(let s=e.length-1;s>=0&&n.size>0;s-=1){let o=e[s],i=new Set;for(let c of uu(o.patch))i.add(Fs(c.path)),c.from&&i.add(Fs(c.from));let a=[...n].filter(c=>i.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:s+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,m)=>c.localeCompare(m))})}}return r.reverse()}function GR(e,t,n){let r=_h.compare(t,n);if(r.length===0)return;let s=new Set;for(let h of r)s.add(Fs(h.path));let o=new Set([...s].filter(h=>Uc(ph(t,h),ph(n,h)))),i=new Set([...s].filter(h=>!o.has(h))),a=fh(e,i),c=fh(e,o),m=[...s].sort((h,y)=>h.localeCompare(y)),u=[...i].sort((h,y)=>h.localeCompare(y)),p=[...o].sort((h,y)=>h.localeCompare(y)),f=[...new Set(a.map(h=>h.author))].sort((h,y)=>h.localeCompare(y)),_=[...new Set(c.map(h=>h.author))].sort((h,y)=>h.localeCompare(y));return{reconciled_field_count:s.size,reconciled_fields:m,reverted_field_count:i.size,reverted_fields:u,discarded_events:a,discarded_authors:f,preserved_field_count:o.size,preserved_fields:p,preserved_events:c,preserved_authors:_,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function jR(e,t,n,r){let s=e.located?.itemPath??null,o=e.located?await K(e.located,{schema:t.schema}):null;if(!o)return{currentItemReplay:null,currentItemPath:s,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let i=qt(o.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:i,currentItemPath:s,matchedChainBefore:Pe(i,r)===a,currentItemRawBeforeLock:o.raw,loadedItem:o}}function qR(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function KR(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:S(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?_h.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Pe(e.finalReplay,e.itemHashVersion),after_hash:Pe(n,e.itemHashVersion),message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function zR(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function BR(e){return Is({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Rs({historyPath:e.historyPath,nextHistoryRaw:ot(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function mr(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await xs(r,e,s,o.type_to_folder);if(!await k(i.historyPath))throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let a=await q(i.historyPath),c=await bt(i.historyPath,i.id);if(c.length===0)throw new l(`No history entries exist for ${i.id}; nothing to repair.`,d.USAGE);let m=hn(c),u=pu(c),p=t.normalizeProvenance?kp(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=fu(p.entries),_=new Set(p.entries.map(ie=>ie.item_hash_version).filter(ie=>ie!==void 0)),h=Es(p.entries,f),y=await jR(i,s,c,f),g=h.finalDocument,b=y.currentItemReplay!==null&&Pe(g,f)!==Pe(y.currentItemReplay,f),v=b&&y.currentItemReplay?GR(h.entries,g,y.currentItemReplay):void 0,E=[h.entriesRehashed>0,h.entriesPatchRepaired>0,b,t.forceAuditEntry===!0,p.receipt.changed].some(Boolean),N=R(t.author,s.author_default),P=!!t.dryRun,$=qR({message:t.message,entriesRehashed:h.entriesRehashed,entriesPatchRepaired:h.entriesPatchRepaired,reconcileNeeded:b}),{rewrittenEntries:G,auditEntryAdded:Ie}=KR({reanchorEntries:h.entries,changed:E,reconcileNeeded:b,currentItemReplay:y.currentItemReplay,finalReplay:g,author:N,message:$,auditOperation:t.auditOperation??"history_repair",auditContext:p.receipt.changed?{...t.auditContext,provenance_normalization:p.receipt}:t.auditContext,itemHashVersion:f,explicitItemHashVersion:h.explicitItemHashVersion}),ee=hn(G);if(!ee.ok)throw new l(`history-repair produced an invalid rewritten chain (${ee.errors.join(", ")}).`,d.GENERIC_FAILURE);let pe=zR(E,h.skippedOps,v);return E&&!P&&pe.push(...await BR({pmRoot:r,subject:i,settings:s,typeRegistry:o,historyRawBeforeLock:a,currentItemRawBeforeLock:y.currentItemRawBeforeLock,author:N,force:t.force,loadedItem:y.loadedItem,historyPath:i.historyPath,rewrittenEntries:G})),{id:i.id,dry_run:P,changed:E,history:{path:i.historyPath,entries_scanned:c.length,chain_drift_before:!m.ok,entries_rehashed:h.entriesRehashed,entries_patch_repaired:h.entriesPatchRepaired,converted_replace_to_add:h.convertedReplaceToAdd,skipped_ops:h.skippedOps,reconciled_with_item:b,audit_entry_added:Ie,verify_ok:ee.ok,verify_errors:ee.errors,item_hash_version_before:u.item_hash_version??null,item_hash_version_after:f,version_disposition:_.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:y.currentItemPath!==null,path:y.currentItemPath,matched_chain_before:y.matchedChainBefore},provenance_normalization:{requested:t.normalizeProvenance===!0,...p.receipt},...v?{reconciliation:v}:{},warnings:[...new Set(pe)].sort((ie,Xe)=>ie.localeCompare(Xe)),generated_at:S()}}function hh(e,t){if(t&&e!==void 0)throw new l("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",d.USAGE);if(!t&&e===void 0)throw new l("history-repair: provide an item <id> or pass --all to repair every drifted stream.",d.USAGE)}async function Ko(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=x(r,I()),o=[],i=await Ts(n,r.item_format,s.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await Vu(n,i),c=e.normalizeProvenance?await Sp(n):[],m=[...new Set([...a.driftedItems,...c])].sort((_,h)=>_.localeCompare(h)),u=[],p=[],f={repaired:0,skipped_clean:0,failed:0};for(let _ of m)try{let h=await mr(_,{...e,auditContext:e.auditContextById?.[_],auditContextById:void 0},t),y=h.changed?"repaired":"skipped_clean";f[y]+=1,p.push(...h.warnings.map(g=>`${_}:${g}`)),u.push({id:_,outcome:y,entries_rehashed:h.history.entries_rehashed,entries_patch_repaired:h.history.entries_patch_repaired,reconciled_with_item:h.history.reconciled_with_item,...h.reconciliation?{reconciliation:h.reconciliation}:{},warnings:h.warnings})}catch(h){f.failed+=1,u.push({id:_,outcome:"failed",error:h instanceof Error?h.message:String(h)})}return e.dryRun||await lu(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:i.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:u,totals:f,warnings:[...new Set([...o,...p])].sort((_,h)=>_.localeCompare(h)),generated_at: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]="c5620467-6c8c-5702-b742-57fba9e302c5")}catch{}})();async function gh(e,t){let n=e.dryRun===!0,r=await Tp(process.cwd(),{includeLossless:!0}),{pendingDecisions:s}=Ap(r);if(!n&&e.force!==!0&&s.length>0)throw new l(`Merge reconciliation would accept ${s.length} receipt(s) containing discarded scalar values. Review pm merge report and rerun with --force only after deciding which values to retain or re-apply.`,d.CONFLICT,{code:"merge_reconcile_discards_require_acceptance",required:"Explicitly review every discarded field before accepting reconciliation.",nextSteps:s.map(g=>`Review receipt ${g.id} for ${g.item_id}: ${g.decisions.map(b=>b.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let o=r.reduce((g,b)=>((g[b.item_id]??=[]).push(b),g),{}),i=Object.fromEntries(Object.entries(o).map(([g,b])=>[g,{merge:{receipts:b.map(Yn)}}])),a=await Ko({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:i},t),c=new Set(a.streams.map(g=>g.id)),m=Object.keys(o).filter(g=>!c.has(g));(await Promise.allSettled(m.map(g=>mr(g,{dryRun:n,author:e.author??t.author,message:e.message??"record field-aware branch merge provenance",force:e.force,auditOperation:"merge_reconcile",auditContext:i[g],forceAuditEntry:!0},t)))).forEach((g,b)=>{let v=m[b];if(g.status==="fulfilled"){let E=g.value.changed?"repaired":"skipped_clean";a.streams.push({id:v,outcome:E,entries_rehashed:g.value.history.entries_rehashed,entries_patch_repaired:g.value.history.entries_patch_repaired,reconciled_with_item:g.value.history.reconciled_with_item,warnings:g.value.warnings}),a.totals[E]+=1}else a.streams.push({id:v,outcome:"failed",error:g.reason instanceof Error?g.reason.message:String(g.reason)}),a.totals.failed+=1});let p=0;!n&&a.totals.failed===0&&(await Promise.all(r.map(g=>Cp(process.cwd(),g))),p=r.length);let f=await Ys({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),_=f.checks.every(g=>g.status==="ok"),h=a.totals.failed===0&&_,y=n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.","No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:h?["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.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:h,dry_run:n,repair:a,receipts:{pending_before:r.length,reconciled:p,summaries:r.map(Yn)},validation:f,guidance:y,generated_at:f.generated_at}}import{createHash as HR}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]="e8cd5790-eacf-5ef7-bc0a-11ea3fe17d2d")}catch{}})();var wh=1,vh=/^[A-Za-z0-9_-]+$/,VR=100,yh=1e3;var xG=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function Ke(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,s)=>r.localeCompare(s));return n.length===0?void 0:n}function WR(e){return HR("sha256").update(J({type:Ke(e.type),author:Ke(e.author),item:Ke(e.item),harness:Ke(e.harness),agent_instance:Ke(e.agentInstance),provenance:Ke(e.provenanceFilter)})).digest("hex").slice(0,24)}function bh(e,t){let n={version:wh,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 YR(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===wh,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 JR(e,t){let n=e.trim();if(n.length===0||n.length>4096||!vh.test(n))throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"})}if(!YR(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function XR(e){let t=e??VR;if(!Number.isSafeInteger(t)||t<0||t>yh)throw new l(`Mutation event limit must be an integer from 0 to ${yh}.`,d.USAGE,{code:"invalid_event_limit"});return t}function QR(e,t){let n=e?.trim();if(!n)return{};if(vh.test(n))return{cursor:JR(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new l("Mutation event --since must be an event cursor or ISO timestamp.",d.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function ZR(e,t){let n=await Qi(e,t);if(n===null){if(!await au(e))return{...await cu(e,t),source:"authoritative_history"};n=await Qi(e,t)}if(n===null)throw new l("Mutation event index could not be opened after rebuild.",d.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function eI(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});return t}async function zo(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=XR(e.limit),r=eI(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new l("Mutation event projections are mutually exclusive. Use --provenance or --full.",d.USAGE);let s=await A(t),o=s.agent_identity.identity_vocabulary,i=$u(s.agent_identity.harness_signals),a=Mu({provenance:e.provenanceFilter},i),c=Ke(e.harness),m=WR(e),{cursor:u,sinceTimestamp:p}=QR(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:Ke(e.type),authors:Ke(e.author),harnesses:c,harness_alias_authors:c?Object.entries(o.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:Ke(e.agentInstance),provenance:[...a].map(([y,g])=>({dimension:y,values:[...g]})),stream_ids:Ke(e.item),limit:n},_=await ZR(t,f),h=_.events.map(y=>({...r==="row"?{cursor:bh(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:Du(y.entry,o,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:bh(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Uu(_.events.map(y=>y.entry),o,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]="32223457-5f57-5049-99cf-c5d766413fb6")}catch{}})();var tI="1h",nI="now",rI="+1d";function It(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function kh(e,t,n){return{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}}async function Sh(e,t,n,r){let s=kh(e,t,n),o=[];return It(o,"start",n.start??nI),n.end!==void 0?It(o,"end",n.end):It(o,"duration",n.duration??tI),It(o,"location",n.location),It(o,"timezone",n.timezone),n.allDay===!0&&It(o,"all_day","true"),s.event=[o.join(",")],At(s,r)}function Eh(e,t,n){return Sh("Meeting",e,t,n)}function Th(e,t,n){return Sh("Event",e,t,n)}function Ah(e,t,n){let r=kh("Reminder",e,t),s=[];return It(s,"at",t.at??rI),It(s,"text",t.text??e),r.reminder=[s.join(",")],At(r,n)}import pr from"node:crypto";import{cp as Rh,lstat as dI,mkdir as nn,readFile as Nn,readdir as jc,rename as Oh,rm as Kc,writeFile as Ho}from"node:fs/promises";import L from"node:path";import{constants as xt}from"node:os";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1c74b5a9-67b8-597c-98de-a4487691081f")}catch{}})();var Ch=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),sI=/^[a-z][a-z0-9_]{0,63}$/u,oI=new Map([[xt.errno.EACCES,"EACCES"],[xt.errno.EDQUOT,"EDQUOT"],[xt.errno.EMFILE,"EMFILE"],[xt.errno.ENFILE,"ENFILE"],[xt.errno.ENOMEM,"ENOMEM"],[xt.errno.ENOSPC,"ENOSPC"],[xt.errno.EPERM,"EPERM"],[xt.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),iI={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function aI(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&Ch.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:oI.get(Math.abs(t.errno))??null}function cI(e,t,n={}){let r=aI(e);if(r===null)return null;if(!sI.test(t))throw new l("Host environment operation labels must be bounded identifiers.",d.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let s=Ch.get(r);return new l(`Host filesystem operation ${t} ${s.summary}.`,d.GENERIC_FAILURE,{code:n.codes?.[s.category]??iI[s.category].code,reason:r,required:s.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[s.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function Bo(e,t,n={}){try{return await t()}catch(r){throw cI(r,e,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]="2580e043-8675-5070-b57e-30cae333228c")}catch{}})();var Ph="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var Nh=L.join("runtime","workspace-snapshots"),lI=new Set(["checkpoints","locks","runtime","search","transactions"]),mI=/^[a-z0-9][a-z0-9._-]*$/,ur="sdk-workspace-transaction",Gc={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Lh={renameEntry:Oh,removeEntry:async e=>{await Kc(e,{recursive:!0,force:!0})}},qc=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 Nn(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!==ur||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await me(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
|
|
42
|
-
`)}};async function
|
|
43
|
-
`).filter(t=>t.trim().length>0).length}async function
|
|
44
|
-
`,"utf8"),await
|
|
45
|
-
`,"utf8"),await Oh(m,L.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function fr(e,t){let n=await _I(e,t),r=await Uh(L.join(rn(e),"objects",n,"manifest.json"),t);if(r.schema!==Ph||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,d.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 Hc(e){let t=rn(e),n=await jc(L.join(t,"objects")).catch(s=>{if(s instanceof Error&&"code"in s&&_t(s))return[];throw s}),r=await jc(L.join(t,"refs")).catch(s=>{if(s instanceof Error&&"code"in s&&_t(s))return[];throw s});return{objects:await Promise.all(n.filter(s=>/^[a-f0-9]{64}$/.test(s)).sort().map(s=>fr(e,s))),references:await Promise.all(r.filter(s=>s.endsWith(".json")).sort().map(async s=>JSON.parse(await Nn(L.join(t,"refs",s),"utf8"))))}}async function Vc(e,t){let n=await fr(e,t),{manifest:r,contents:s}=await $h(e),o=new Map(r.files.map((p,f)=>[p,s[f]])),i=await uI(L.join(rn(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=o.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=Ih(o.get(p)),_=Ih(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 Gh(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",d.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",s=n.lockTtlSeconds??60,o=n.lockWaitMs??5e3,i=await xe(e,ur,s,r,!1,!1,o),a=new qc(Pr(e,ur),r,s);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await Vc(e,t),f=await fr(e,t),_=await Bc(e),h=f.fingerprint,y=rn(e),g=L.join(y,"objects",h,"files"),b=L.dirname(e),v=L.basename(e);c=L.join(b,`.${v}.restore-${pr.randomUUID()}`);let E=L.join(b,`.${v}.backup-${pr.randomUUID()}`);await Mh("restore_stage",async()=>{await nn(c,{recursive:!0}),await Rh(g,c,{recursive:!0,force:!1}),await nn(L.join(c,"runtime"),{recursive:!0}),await Rh(y,L.join(c,Nh),{recursive:!0,force:!1})});let N=await _u({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,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:s,lockWaitMs:o}),P=L.relative(c,N.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let $=Pr(c,ur);return await nn(L.dirname($),{recursive:!0}),await Ho($,await Nn(Pr(e,ur)),{flag:"wx"}),m=!0,await fI(c,e,E,Lh,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:P,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([Kc(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function jh(e,t){zc(t);let n=rn(e);if(!/^[a-f0-9]{64}$/.test(t))return await xh(L.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Hc(e);if(r.some(s=>s.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await xh(L.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]="0492d773-2af2-5072-8164-9f8aab536191")}catch{}})();function _r(e){return{...e.args,...e.options}}function lt(e,t){let n=w(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Ln(e){return typeof e=="string"?[e]:he(e)}function qh(e){return rh(_r(e),e.global)}function Kh(e){let t=_r(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return zo({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Ln(t.type),author:Ln(t.author),item:Ln(t.item),limit:t.limit===void 0?void 0:Le(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:Ln(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Ln(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Ln(t.provenanceFilter)}})}function zh(e){let t=_r(e),n=lt(t,"subcommand");if(n==="install")return sp({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return gh({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return Rp({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return uh({artifact:lt(t,"artifact"),basePath:lt(t,"basePath"),oursPath:lt(t,"oursPath"),theirsPath:lt(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw Ee({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Bh(e){let t=_r(e),n=lt(t,"subcommand");if(n!=="snapshot")throw Ee({command_path:"workspace",token:n,allowed:["snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??lt(t,"snapshot_action"),s=T(process.cwd(),e.global.path);if(r==="create")return Bc(s,{name:w(t,"name")});if(r==="list")return Hc(s);let o=lt(t,"target");if(r==="inspect")return fr(s,o);if(r==="delete")return jh(s,o);if(r==="restore")return t.dryRun===!0?Vc(s,o):Gh(s,o,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Le(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Le(t.lockWaitMs,"lockWaitMs")});throw Ee({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Vo(e){let t=_r(e),n=lt(t,"title");return e.action==="meet"?Eh(n,t,e.global):e.action==="event"?Th(n,t,e.global):Ah(n,t,e.global)}import RI from"node:path";import hI from"node:fs/promises";import Hh 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]="f232e106-54f4-572e-8f6e-054f52290267")}catch{}})();var gI="templates",yI=".json",bI=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,wI=_s.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),vI=new Set(wI);function kI(e){let t=e.trim();if(!bI.test(t))throw new l(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,d.USAGE);return t}function Vh(e){return Hh.join(e,gI)}function Wh(e,t){return Hh.join(Vh(e),`${t}${yI}`)}async function SI(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function Yh(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function EI(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(vI.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let s=r.filter(o=>typeof o=="string");s.length>0&&(t[n]=s);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(s=>typeof s=="string")&&(t[n]=[...r])}return Yh(t)}function TI(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new l(`Template "${t}" has invalid options payload.`,d.GENERIC_FAILURE);let n=e,r={};for(let[s,o]of Object.entries(n)){let i=s.trim();if(i.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof o=="string"){r[i]=o;continue}if(Array.isArray(o)&&o.every(a=>typeof a=="string")){r[i]=[...o];continue}throw new l(`Template "${t}" contains invalid value for option "${i}".`,d.GENERIC_FAILURE)}return Yh(r)}function AI(e,t){let n;try{n=JSON.parse(e)}catch{throw new l(`Template "${t}" contains invalid JSON.`,d.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Template "${t}" has invalid document shape.`,d.GENERIC_FAILURE);let r=n,s=TI(r.options,t),o=S();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:o,updated_at:typeof r.updated_at=="string"?r.updated_at:o,options:s}}async function CI(e,t){let n=await q(Wh(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return AI(n,t)}async function Wc(e,t,n){let r=T(process.cwd(),n.path);await SI(r);let s=kI(e),o=EI(t);if(Object.keys(o).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let i=S(),a=Wh(r,s),c=i;await k(a)&&(c=(await CI(r,s)).created_at);let m={name:s,created_at:c,updated_at:i,options:o},u=await A(r);return await hI.mkdir(Vh(r),{recursive:!0}),await vt({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
|
|
46
|
-
`,op:"templates:save",author:R(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]="a1e34cfb-3d4e-5b79-8585-3162e71e574c")}catch{}})();var Zh=["list","show","apply","lint"],II="schema-types",xI="schema-statuses",OI="schema-fields";function Wo(){let e=I();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function eg(){let{profiles:e,warnings:t}=um(Wo());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:gm(n.definition)})),warnings:t,generated_at:S()}}function tg(e){let t;try{t=ls(e,Wo())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...ym(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function ng(e){let t;try{t=ls(e,Wo())}catch(s){throw new l(s instanceof Error?s.message:String(s),d.USAGE)}let{resolved:n}=t,r=Fm(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:S()}}function PI(e,t){return RI.join(e,"templates",`${t}.json`)}async function NI(e,t){let n=await q(PI(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let s=r.options;if(s!==null&&typeof s=="object"&&!Array.isArray(s))return s}}catch{}}async function Jh(e,t,n,r){let s=new Map;for(let o of r.templates){let i=await NI(e,o.name);i!==void 0&&s.set(o.name,i)}return{typesRaw:await q(rt(e,t.files.types,nt.types)),statusesRaw:await q(rt(e,t.files.statuses,nt.statuses)),fieldsRaw:await q(rt(e,t.files.fields,nt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:s,installedPackages:new Set}}function Fn(e){let t=[],n=[],r=[];for(let s of e)(s.status==="add"?t:s.status==="update"?n:r).push(s.key);return{added:t,updated:n,unchanged:r}}function Xh(e,t,n,r,s){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Fn(t.types.changes),statuses:Fn(t.statuses.changes),fields:Fn(t.fields.changes),workflows:Fn(t.workflows.changes.map(o=>({key:o.type,status:o.status}))),config:Fn(t.config.changes),templates:Fn(t.templates.changes.map(o=>({key:o.name,status:o.status}))),packages:t.packages,warnings:[...new Set(s)].sort((o,i)=>o.localeCompare(i)),generated_at:S()}}async function LI(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function FI(e){try{let t=ls(e,Wo());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function rg(e,t,n){let r=T(process.cwd(),n.path);await LI(r);let s=FI(e),o=s.profile,i=s.warnings,a=t.dryRun===!0,c=await A(r),m=ms(c.schema);if(a){let b=await Jh(r,m,c,o),v=Qh(o,b);return Xh(o,v,!1,!0,[...i])}let u=R(t.author,c.author_default),p=gu(c),f=!!t.force,_=[...i],h=[],y=async b=>{h.push(await xe(r,b,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(II),await y(xI),await y(OI);let b=await Jh(r,m,c,o);if(g=Qh(o,b),g.types.changed){let v=rt(r,m.files.types,nt.types);await vt({pmRoot:r,filePath:v,raw:ds(g.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let E=new Set(o.types.map(P=>im(P).name)),N=g.types.file.definitions.filter(P=>E.has(P.name));await lp(r,N,_,"profile:apply-type-folder"),_.push(...await z({path:v,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let v=rt(r,m.files.statuses,nt.statuses);await vt({pmRoot:r,filePath:v,raw:hm(g.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let v=rt(r,m.files.fields,nt.fields);await vt({pmRoot:r,filePath:v,raw:pm(g.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let v of g.config.changes){if(v.status==="unchanged")continue;let E=ps(v.key);E!==void 0&&fs(c,E,v.value)}c.schema.type_workflows=g.workflows.result,await Se(r,c,"profile:apply-config")}for(let v of g.templates.changes)v.status!=="unchanged"&&await Wc(v.name,{...v.options},n)}finally{for(let b of h.reverse())try{await b()}catch{}}return Xh(o,g,g.changed,!1,_)}function Qh(e,t){try{return $m(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import og from"node:fs/promises";import ig 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]="7e0f84f6-9528-55c5-8976-6f85cd920486")}catch{}})();function $I(e,t,n){let r=new Set,s=[];for(let o of e){let i=o.trim();if(i.length===0||r.has(i))continue;r.add(i);let a=t.get(i);if(a===void 0){s.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){s.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}s.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return s}function MI(e,t){let n=[...e].sort((s,o)=>o.entries-s.entries||s.id.localeCompare(o.id)),r=[];for(let s of n){if(t.scope==="closed"&&s.bucket!=="closed"){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(s.entries<=t.minEntries){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&s.entries<=t.allOver){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:s.id,entries:s.entries,selected:!0,skip_reason:null})}return r}function sg(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return $I(t.ids,n,t.minEntries)}return MI(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]="c6609492-75a9-5111-b9b3-1b81908f3084")}catch{}})();function DI(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(n)){let o=Number.parseInt(n,10);if(!Number.isSafeInteger(o)||o<1||o>t.length+1)throw new l(`history-compact --before version must be between 1 and ${t.length+1}.`,d.USAGE);let i=Math.max(0,Math.min(t.length,o-1));return{kind:"version",raw:n,compactCount:i,retainedCount:t.length-i}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let s=0;for(let[o,i]of t.entries()){let a=Date.parse(i.ts);if(!Number.isFinite(a))throw new l(`History for this item contains invalid timestamp at entry ${o+1}.`,d.GENERIC_FAILURE);if(a>=r)break;s+=1}return{kind:"timestamp",raw:n,compactCount:s,retainedCount:t.length-s}}function UI(e,t){let n=Ss(),r=Ss();for(let s=0;s<e.length;s+=1){let o=e[s];if(Pe(n)!==o.before_hash)throw new l(`history-compact detected before-hash drift at entry ${s+1}; run pm history-repair first.`,d.CONFLICT);if(n=Cs(n,o.patch,s+1,o.op),Pe(n)!==o.after_hash)throw new l(`history-compact detected after-hash drift at entry ${s+1}; run pm history-repair first.`,d.CONFLICT);s+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function GI(e,t,n){let r=structuredClone(t),s=[];for(let[o,i]of e.entries()){let a=Pe(r);r=Cs(r,i.patch,n+o+1,i.op),s.push({...i,before_hash:a,after_hash:Pe(r)})}return{entries:s,finalReplay:r}}async function jI(e,t,n){let r=e.located?await K(e.located,{schema:t.schema}):null;return r?{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:Pe(qt(r.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function qI(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 KI(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 zI(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=UI(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),s=GI(r,t,e.boundary.compactCount),i=[De({nowIso:S(),author:e.author,op:"history_compact_baseline",before:jt(Ss()),after:jt(t),message:KI(e.boundary)}),...s.entries];return e.dryRun||i.push(De({nowIso:S(),author:e.author,op:"history_compact",before:jt(n),after:jt(n),message:qI(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function BI(e){return Is({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-compact",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Rs({historyPath:e.historyPath,nextHistoryRaw:ot(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function Yc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await xs(r,e,s,o.type_to_folder),a=i.historyPath,c=await q(a);if(c===null)throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let m=await bt(a,i.id);if(m.length===0)throw new l(`No history entries exist for ${i.id}; nothing to compact.`,d.USAGE);let u=hn(m);if(!u.ok)throw new l(`history-compact requires a valid history chain (${u.errors.join(", ")}). Run pm history-repair ${i.id} first.`,d.CONFLICT);let p=DI(t.before,m),f=p.compactCount>0,_=!!t.dryRun,h=R(t.author,s.author_default),y=[];f||y.push("history_compact_noop_before_boundary");let g=await jI(i,s,m);g.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:E}=zI({historyEntries:m,boundary:p,changed:f,dryRun:_,author:h,options:t}),N=hn(b);if(!N.ok)throw new l(`history-compact produced an invalid rewritten chain (${N.errors.join(", ")}).`,d.GENERIC_FAILURE);f&&!_&&y.push(...await BI({pmRoot:r,subject:i,settings:s,typeRegistry:o,historyRawBeforeLock:c,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:h,force:t.force,loadedItem:g.loadedItem,historyPath:a,rewrittenEntries:b}));let P=p.retainedCount>0?p.compactCount+1:null;return{id:i.id,dry_run:_,changed:f,compact_boundary:{kind:p.kind,before:p.raw,entries_compacted:p.compactCount,entries_retained:p.retainedCount,first_retained_entry:P},history:{path:a,entries_scanned:m.length,entries_after:b.length,baseline_entry_added:v,audit_entry_added:E,verify_ok:N.ok,verify_errors:N.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:g.matchedChainBefore},warnings:[...new Set(y)].sort(($,G)=>$.localeCompare(G)),generated_at:S()}}var HI=3;function ag(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function VI(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function WI(e){let t=j(e.settings.schema),n=Js(t),r=await re(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),s=new Map(r.map(m=>[m.id,n.classify(m.status)])),o=ig.join(e.pmRoot,"history"),i=[],a=[];if(!await k(o))return{candidates:i,preselectionErrors:a};let c=(await og.readdir(o)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=ig.join(o,m),p=m.slice(0,-6);try{let f=await og.readFile(u,"utf8");await un({path:u,scope:"project"}),i.push({id:p,entries:VI(f),bucket:s.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 YI(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 Yc(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 cg(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=x(r,I()),{candidates:o,preselectionErrors:i}=await WI({pmRoot:n,settings:r,typeToFolder:s.type_to_folder}),a=e.ids!==void 0&&e.ids.length>0?"ids":"scan",c=e.minEntries??HI,m=r.history.compact_policy,u=a==="scan"&&e.allOver===void 0&&m.enabled,p=e.allOver??(u?m.max_entries:void 0),f=sg(o,{ids:e.ids,scope:e.scope,minEntries:c,allOver:p}),_=!!e.dryRun,h=[...i],y={streams_considered:o.length+i.length,selected:0,items_compacted:0,items_skipped:0,items_errored:i.length};for(let g of f){let b=await YI({row:g,options:e,dryRun:_,global:t});if(h.push(b.result),!b.selected){y.items_skipped+=1;continue}y.selected+=1,b.compacted&&(y.items_compacted+=1),b.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:_,mode:a,scope:e.scope??null,criteria:{min_entries:c,all_over:p??null,policy_threshold_applied:u},totals:y,results:h,generated_at: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]="f762b5e6-8224-531f-9dd1-f71dc18c3ddf")}catch{}})();function dg(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return hh(n,t),t?Ko(e.options,e.global):mr(n,e.options,e.global)}function lg(e){let t=e.options.ids,n=Array.isArray(t)?t.map(String).filter(m=>m.trim().length>0):typeof t=="string"?t.split(",").map(m=>m.trim()).filter(Boolean):void 0,r=Le(e.options.allOver??e.options.all_over,"history-compact allOver"),s=Le(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),o=w(e.options,"scope"),i=[];e.options.closed===!0&&i.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&i.push("all-streams"),(o==="closed"||o==="all-streams")&&i.push(o);let a=[...new Set(i)];if(a.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let c=a[0];return ag(e.id,{ids:n,allOver:r,scope:c}),e.id!==void 0?Yc(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):cg({ids:n,scope:c,allOver:r,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]="c2ef0de1-bc44-5550-862c-f3929334fbef")}catch{}})();function mg(e,t,n){let r;if(typeof e.lines=="string")r=Hs(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=Hs(`${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]="90896fb6-ee3e-575d-b103-bbc1a83c6672")}catch{}})();var JI=qi("list").properties.outputSession,XI={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:{...JI},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},ug={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},Z={type:"string",description:"pm item id, for example pm-abc1."},QI=`Operation name (one of): ${Di.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,ZI={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."}},ex={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 D(e,t=[]){return{...ug,properties:{...ug.properties,...e},required:t}}var tx=[{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:D({action:{type:"string",enum:[...Di],description:QI},id:Z,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."},...XI},["action"])},{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:D({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:D({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:D({query:{type:"string"},options:{type:"object"},...ex},["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:D({options:{type:"object"},...ZI})},{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:D({id:Z,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:D({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:D({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:D({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:Z,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:D({id:Z,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:D({id:Z,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:D({id:Z,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:D({id:Z,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:D({id:Z,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:D({id:Z,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:D({id:Z,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. 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:D({id:Z,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:D({id:Z,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:D({id:Z,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List or add structured notes on a pm item. Use options.add to append a note; omit it to list existing notes.",inputSchema:D({id:Z,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List or add learnings on a pm item. Use options.add to capture a learning/insight; omit it to list existing learnings.",inputSchema:D({id:Z,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:D({id:Z,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:D({subcommand:{type:"string",enum:[...Im]},id:Z,target:Z,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:D({id:Z,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:D({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:D({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:D({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:D({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:D({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:D({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:D({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."}})}],nx={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"},rx=tx.map(e=>{let t=nx[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:qi(t,{properties:n,required:r})}});function pg(){return rx.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,s)=>r.localeCompare(s)):[];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]="30d9b9dd-f0a1-578e-90d6-3c019e0435b5")}catch{}})();var fg=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"]]]),sx=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],Eg=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Jo=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","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),Tg=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"]]),Ag=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"]]),Cg=new Map([...Ag.entries()].flatMap(([e,t])=>mt(t).map(n=>[n,e]))),Rg=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],Ig=new Map(Rg.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),ox=10,ix=20,_g=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["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 work through typed operations."],["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 portable workspace primitives."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),xg=[["init",wl],["install",kl],["uninstall",Sl],["explore",El],["manage",xl],["describe",Tl],["reload",Ol],["doctor",Pl],["catalog",Nl],["adopt",Ll],["adopt-all",Al],["activate",Cl],["deactivate",Rl],["migrate",Il]],ax=xg.map(([e,t])=>e==="init"?[e,vl]:[e,t]),cx=[...xg.map(([e,t])=>[`extension ${e}`,t]),...ax.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",qr],["config",bl],["extension",Kr],["package",Gn],["packages",Gn],["install",Fl],["create",Yr],["item mutate",tm],["item complete",nm],["copy",Jr],["focus",Xr],["update",Qr],["update-many",Zr],["upgrade",$l],["calendar",jn],["cal",jn],["context",qn],["ctx",qn],["get",ts],["search",is],["eval",sm],["workspace",ht],["workspace snapshot",ht],["workspace snapshot create",ht],["workspace snapshot list",ht],["workspace snapshot inspect",ht],["workspace snapshot restore",ht],["workspace snapshot delete",ht],["next",os],["aggregate",Dr],["deps",rs],["graph",ss],["guide",ns],["reindex",Ml],["history",Ur],["history-compact",hl],["history-redact",fl],["history-repair",_l],["history-author-acknowledge",Gr],["merge",pl],["schema",gl],["profile",yl],["plan",jr],["restore",Gl],["delete",jl],["close",Dl],["close-many",zr],["append",Br],["claim",Ul],["release",ql],["start-task",Kl],["pause-task",zl],["close-task",Bl],["comments",cl],["notes",dl],["learnings",ll],["files",ml],["docs",ul],["test",Wl],["test-all",Yl],["telemetry",Jl],["test-runs",Xl],["gc",Ql],["stats",Hr],["duplicates",Vr],["validate",Zl],["health",Wr],["assurance",em],...om,["contracts",as],["completion",cs],["activity",es],...[...Eg].map(e=>[e,Mr])],Zc=new Map(cx);function dx(e){let t=Cg.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function hg(e){return $i.includes(e)?we(e):e.startsWith("extension-")?we(`extension ${e.slice(10)}`):e.startsWith("package-")?we(`package ${e.slice(8)}`):e.startsWith("test-runs-")?we(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?we(`templates ${e.slice(10)}`):Jo.has(e)?Ag.get(e)??we(e):null}function lx(e,t){return e.command_path===null?!1:mt(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `)||t.startsWith(`${n} `))}function mt(e){return e.split("|").map(t=>we(t)).filter(t=>t.length>0)}function mx(e,t){let n=new Set(t),r=new Set;for(let s of e)if(s.command_path)for(let o of mt(s.command_path)){let i=o.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((s,o)=>s.localeCompare(o))}function Yo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function gr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function ux(e,t){if(!t)return{...e};let r=gr(e).filter(s=>{let o=s.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:r}}function Jc(e,t){let r=gr(e).filter(s=>{let o=s.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function we(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Og(e){return e.replace(/\s+/g,"-")}function Ye(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function gg(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=Ye(r);!s||n.has(s)||(n.add(s),t.push(s))}return t}function Xc(e,t,n){n&&(e[t]=!0)}function yg(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 px(e){let t=yg(e.long,"long"),n=yg(e.short,"short"),r=t??n;if(!r)return null;let s={flag:r};n&&t&&(s.short=n),Xc(s,"required",e.required===!0),Xc(s,"repeatable",e.repeatable===!0),Xc(s,"list",e.list===!0);let o=Ye(e.description);o&&(s.description=o);let i=Ye(e.value_name);i&&(s.value_name=i);let a=[Ye(e.value_type),Ye(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(s.value_type=a),s}function Pg(e){let t=new Map;for(let r of e){let s=we(r.target_command);if(s.length===0)continue;let o=t.get(s)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;o.sourceDedupe.has(i)||(o.sourceDedupe.add(i),o.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=px(a);if(!c)continue;let m=`${c.flag}|${c.short??""}`;o.dedupe.has(m)||(o.dedupe.add(m),o.flags.push(c))}t.set(s,o)}let n=new Map;for(let[r,s]of t.entries())n.set(r,{flags:s.flags,sources:s.sources.sort((o,i)=>{let a=o.layer.localeCompare(i.layer);return a!==0?a:(o.name??"").localeCompare(i.name??"")})});return n}function fx(e){let t=Pg(e.flagRegistrations),n=new Map;for(let o of e.commandDefinitions){let i=we(o.command);if(i.length===0)continue;let a=Ye(o.action)??Og(i),c=Array.isArray(o.arguments)?o.arguments.map(m=>{let u=Ye(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:Ye(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{command:i,action:a,source:{layer:o.layer,name:o.name},description:Ye(o.description),intent:Ye(o.intent),arguments:c,flags:t.get(i)?.flags??[],examples:gg(o.examples),failure_hints:gg(o.failure_hints)})}let r=new Set;for(let o of e.handlers)r.add(we(o));for(let o of n.keys())r.add(o);for(let o of t.keys())r.add(o);let s=[];for(let o of[...r].sort((i,a)=>i.localeCompare(a))){let i=n.get(o);s.push(_x(o,i,t.get(o)?.flags??[]))}return s}function _x(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Og(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function hx(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(s,o)=>o.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function gx(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function yx(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",s=e.repeatable===!0||e.list===!0;return{type:s?"array":r,...s?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function bx(e){let t=e.command.split("|").map(s=>s.trim()).filter(s=>s.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let s of e.arguments)n[s.name]=gx(s,e.action),s.required&&r.push(s.name);for(let s of e.flags){let o=hx(s);!o||n[o]!==void 0||(n[o]=yx(s,e.action),s.required===!0&&r.push(o))}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 wx(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 vx(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((o,i)=>o.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let s=new Set(r.flags.map(o=>`${o.flag}|${o.short??""}`));for(let o of n.flags){let i=`${o.flag}|${o.short??""}`;if(!s.has(i))s.add(i),r.flags.push(o);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);a&&wx(a,o)}}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 kx(e,t=A){let n={mode:pt.extensions.policy.mode,trust_mode:pt.extensions.policy.trust_mode,default_sandbox_profile:pt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=T(process.cwd(),e.path);if(!await k(C(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let s=await t(r),o=await Lr({pmRoot:r,settings:s,cwd:process.cwd(),noExtensions:!1}),i=await Fr({...o,loaded:o.loaded});return{handlers:new Set(i.commands.handlers.map(c=>we(c.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:o.policy.mode,trust_mode:o.policy.trust_mode,default_sandbox_profile:o.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 Mi){let s=Jo.has(r);if(s&&!t.includePackageOwnedActions)continue;let o=hg(r);n.set(r,{action:r,provider:s?"extension":"core",requires_extension:s,command_path:o})}if(t.includePackageOwnedActions)for(let r of Jo)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:hg(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:we(r.command)});return[...n.values()].sort((r,s)=>(r.action??"").localeCompare(s.action??""))}function Ex(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?mt(e.command_path):[],r=n.some(i=>t.handlers.has(i)),s=n.map(i=>Tg.get(i)).find(i=>typeof i=="string"),o=t.disabledReason===null&&r;return{action:e.action,invocable:o,available:o,requires_extension:!0,provider:"extension",disabled_reason:o?null:t.disabledReason??(s?`optional_package_not_installed:${s}`:"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 Ng(e){return Zc.get(e)??$r}function Tx(e){return hr.has(e)?!1:Zc.has(e)}function Ax(e){return Eg.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function bg(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function Cx(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function Rx(e){let t=new Map;for(let r of e.definitions){let s=bg(r.cli_flag);if(!s)continue;let o=r.cli_aliases.map(a=>Cx(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>bg(a)).filter(a=>a!==null&&a!==s);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=o?{flag:s,short:o}:{flag:s},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,s]of t.entries())n.set(r,Ni(s.flags));return n}function wg(e,t){let n=[],r=new Set;for(let s of[...e,...t]){let o=`${s.flag}|${s.short??""}`;r.has(o)||(r.add(o),n.push(s))}return Ni(n)}function Ix(e,t,n,r){return e.map(s=>{let o=Tx(s),i=o?Ng(s):[],a=n.get(Ax(s))??[],c=t.get(s),m=wg(i,a),u=wg(m,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":o?"core":"extension";return{command:s,flags:u,...r?{canonical_command:Qc(s),visibility:Vm(Qc(s)),positionals:ol(s)?.slots??[],flag_invocations:Hm(s,u)}:{},provider:p,extension_sources:c?.sources}}).sort((s,o)=>s.command.localeCompare(o.command))}function xx(e,t=Kn){let n=new Set(e),r=new Map;for(let s of Rg){let o=s.aliases.filter(i=>n.has(i));r.set(s.canonical,{canonical:s.canonical,aliases:o,contracts:[]})}for(let s of t){if(!n.has(s.canonical)||s.registration==="commander"&&!n.has(s.alias))continue;let o=r.get(s.canonical)??{canonical:s.canonical,aliases:[],contracts:[]};o.aliases.includes(s.alias)||o.aliases.push(s.alias),o.contracts.push(s),r.set(s.canonical,o)}return[...r.values()].map(({contracts:s,...o})=>s.length===0?o:{...o,contracts:s}).sort((s,o)=>s.canonical.localeCompare(o.canonical))}function Ox(){return{create_string_options:Mm,create_repeatable_options:_s,update_string_options:Dm,update_repeatable_options:Um,list_string_options:el,search_string_options:tl,calendar_string_options:nl,context_string_options:rl,activity_string_options:sl}}function vg(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=cn(e,"create",n),s=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),o=[...new Set(s.map(a=>fe("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:s,required_flags:o,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function Px(e){let t={},n={};for(let r of[...e.types].sort((s,o)=>s.localeCompare(o))){let s=e.by_type[r];t[r]=vg(s,"strict"),n[r]=vg(s,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Nx(e,t){let n=gr(e);if(n.length===0)return e;let r=!1,s=n.map(o=>{let i=o.properties;if(typeof i!="object"||i===null)return o;let a=i.action;return typeof a!="object"||a===null||a.const!=="create"?o:(r=!0,{...o,"x-create-required-options":t})});return r?{...e,oneOf:s}:e}function Lx(e){let t=Yo(e.action)!==void 0||Yo(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,s=e.schemaOnly===!0,o=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=Yo(e.action),u=Yo(e.command),p=!r&&!c&&!s&&!o&&!i&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:s,flagsOnly:o,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function Fx(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",d.USAGE)}async function $x(e,t=A){try{return await t(e)}catch{return structuredClone(pt)}}async function Mx(e,t){let n=await $x(t),r=await kx(e),s=x(n,r.registrations??I()),o=Be(n.schema),i=fx(r);return{settings:n,runtimeProbe:r,typeRegistry:s,statusRegistry:j(n.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:Rx(o),createRequiredOptionContracts:Px(s),extensionContracts:i,mergedExtensionContracts:vx(i),extensionFlagMap:Pg(r.flagRegistrations)}}function kg(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Jo.has(e.selectedAction)||e.selectedCommand!==void 0&&hr.has(e.selectedCommand))}function Dx(e,t){let n=Sx(t,{includePackageOwnedActions:kg(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Om);return n.filter(s=>!r.has(s.action))}return kg(e)&&e.selectedCommand!==void 0&&hr.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:dx(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function Ux(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new l(`Unknown action: "${e.selectedAction}".`,d.USAGE)}function Gx(e,t){return[...new Set([...$i.filter(n=>!hr.has(n)),...[...Zc.keys()].filter(n=>!hr.has(n)),...e.flatMap(n=>n.command_path?mt(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>we(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function jx(e,t){let n=t.slice(0,ox),r=t.length-n.length,s=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),o=t.slice(0,ix),i=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new l(`Command "${e}" is a command namespace. Choose a concrete child command: ${s}.`,d.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:o.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function qx(e,t){return new l(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,d.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 Kx(e){return new l(`Unknown command: "${e}".`,d.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 zx(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(o=>o.startsWith(`${e.selectedCommand} `));if(r.length>0)throw jx(e.selectedCommand,r);let s=Tg.get(e.selectedCommand);throw s?qx(e.selectedCommand,s):Kx(e.selectedCommand)}function Bx(e,t){let n=Dx(e,t.mergedExtensionContracts);Ux(e,n);let r=Gx(n,t.mergedExtensionContracts);zx(e,r);let s=e.selectedCommand?Cg.get(e.selectedCommand):void 0,o=e.selectedCommand?n.filter(m=>s?m.action===s:lx(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!o.some(m=>m.action===e.selectedAction))throw new l(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,d.USAGE);let i=e.selectedAction?o.filter(m=>m.action===e.selectedAction):o,a=[...new Map(i.map(m=>Ex(m,t.runtimeProbe)).map(m=>[s?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:o,scopedActionDescriptors:i,selectedPackageOwnedAction:s,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function Hx(e){return new Set(gr(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 s=r.const;return typeof s=="string"?s:null}).filter(t=>t!==null))}function Vx(e){let t=Lm,n=gr(t),r=Hx(t),s=e.filter(o=>!r.has(o.action)).map(o=>bx(o));return s.length>0?{...t,oneOf:[...n,...s]}:t}function Sg(e,t,n){let r=new Set(t.actionDescriptors.map(o=>o.action)),s=e.selectedAction?ux(n,e.selectedAction):e.selectedCommand?Jc(n,new Set(t.scopedActionDescriptors.map(o=>o.action))):Jc(n,r);return e.runtimeOnly&&!e.selectedAction?Jc(s,new Set(t.actions)):s}function Wx(e,t,n){let r=Vx(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?Nx(Sg(e,n,r),t.createRequiredOptionContracts):Sg(e,n,r);return{mergedSchema:r,filteredSchema:o}}function Yx(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?mx(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(Kn.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function Qc(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":Ig.get(t)??t}var Xx=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"]]),Qx=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function Zx(e,t){let n=_g.get(e)??(e.includes(" ")?void 0:_g.get(Qc(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>mt(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 s=e.split(" "),o=s.at(-1),i=s.slice(0,-1).join(" "),a=Xx.get(o),c=Qx.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function eO(e,t=[],n={}){let r=n.includeFormatBudgets??!0,s=n.includeIntentProvenance??!0;return[...new Set(e.map(we))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i)).map(o=>{let i=Ui(o,{generateFallback:!0}),a=o.split(" ")[0],c=Ig.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),m=new Set([...Ng(o).map(f=>f.flag),...t.filter(f=>mt(f.command).includes(o)).flatMap(f=>f.flags.map(_=>_.flag))]),u=(fg.get(o)??fg.get(c)??sx).filter(f=>m.has(f)),p=Zx(o,t);return{command:o,intent:p.intent,...s||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 tO(e){return e.map(t=>({budget:Ui(t,{generateFallback:!0}),envelope:Ym(t)}))}function nO(e){let t=new Map;for(let n of e){let r=jm(n),s=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,o=s.join(","),i=t.get(o)??{commands:[],exit_codes:s};i.commands.push(n),t.set(o,i)}return[...t.values()]}function rO(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>mt(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(s=>mt(s.command).some(o=>r.has(o)))}return t.extensionContracts}function sO(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 oO(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(s=>s.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(([s])=>r===void 0||s===r).map(([s,o])=>[s,[...new Set(o.map(i=>`--${i.cli_flag}`))].sort((i,a)=>i.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Sm],services:[...Em],policy_modes:[...Tm],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Rm],trust_modes:[...Am],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Cm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Pd],create_modes:[...Nd],close_validation_modes:[...Ld],workflow_enforcement_modes:[...Fd]},e.relationship_kind_contracts=[...qd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(s=>s.definitions)].sort((s,o)=>s.kind.localeCompare(o.kind)).map(s=>({canonical:s.kind,aliases:[...s.aliases??[]],...s.inverse===void 0?{}:{inverse:s.inverse},ordering:s.ordering,hierarchy:s.hierarchy})))}function iO(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 aO(e,t,n,r,s){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=Ix(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let o=new Set(r);e.list_projections=Object.entries(Vp).filter(([i])=>o.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...Hp],compact_fields:[...Bp]}))}e.command_aliases=s}}function cO(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=Ox();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function dO(e,t,n,r){e.command_summaries=eO(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Pm],allows_unbounded_opt_out:!0},e.grammar_contracts={nouns:Dt.nouns,shared_verbs:Dt.shared_verbs,scope_before_verb:Dt.scope_before_verb,visible_top_level_ceiling:Dt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Dt.ceiling_raise_requires_pm_item,positional_shape_budget:Dt.positional_shape_budget,positional_shape_count:new Set(Pi.map(({slots:s})=>al(s))).size,positional_action_count:Oi.length,positional_action_parents:[...new Set(Oi.map(({parent:s})=>s))].sort((s,o)=>s.localeCompare(o)),...r.includePositionalSignatures?{positional_signatures:Pi}:{}}}async function Lg(e,t){let n=Lx(e);Fx(n);let r=T(process.cwd(),t.path),s=await Mx(t,r),o=Bx(n,s),i=Wx(n,s,o),a=Yx(n,o),c=Jx(n,a),m=sO(n,i,o,c),u=rO(n,s,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&dO(m,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p}),n.summary)return m;let f=xx(o.commandCatalog);return n.flagsOnly&&!n.fullOutput||oO(m,s,n),iO(m,n,i,u),aO(m,n,s,c,f),cO(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...Ku],gate_triggers:[...qu]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=il),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=pg(),m.context_intents=qm(),m.read_output_dimensions=Gi,m.error_codes=Bm,m.command_output_contracts=tO(c),m.command_exit_contracts={vocabulary:Gm,command_sets:nO(c)}),m}import HO from"node:fs/promises";import Qg 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]="ed44fc89-8b6e-5c83-a4f4-ced4e9031dac")}catch{}})();function Xo(e,t,n,r,s,o="min"){let i=s==="min"?e-t:t-e,a=o==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&a<0}function lO(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,s=null,o=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)||(Xo(f,i,p,s,"min")&&(i=f,s=p),Xo(f,a,p,o,"max","max")&&(a=f,o=p))}return{id:e,bytes:n,lines:r,oldest_ts:s,newest_ts:o}}function Fg(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),s=e.map(({id:_,raw:h})=>lO(_,h)),o=0,i=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of s){if(o+=_.lines,i+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);Xo(h,m,_.id,a?.id??null,"min")&&(m=h,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);Xo(h,u,_.id,c?.id??null,"max")&&(u=h,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...s].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...s].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:o,total_bytes:i,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as uO}from"node:crypto";import{execFile as pO}from"node:child_process";import Dg from"node:path";import{promisify as fO}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]="939d5f93-d287-5c1c-bc78-d013f76735f2")}catch{}})();var $g=1;function mO(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 ed(e){if(e===null)return{format_version:$g,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==$g||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!mO(r))throw new l("Improvement ledger contains an invalid observation.",d.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]="aaa927b3-4bc4-561f-aff1-85dc95c12ea1")}catch{}})();var _O=fO(pO),hO=50,Mg=1e3,gO=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Ug(e){let t=e.trim().toLowerCase();if(!gO.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function yO(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function yr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return n}}function bO(e){let t=e??hO;if(!Number.isSafeInteger(t)||t<0||t>Mg)throw new l(`Improvement observation limit must be an integer from 0 to ${Mg}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Gg(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function wO(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});let r=Ug(n.metric),s=yO(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||s==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let o=await kO(e,n.revision),i=yr(n.source,"source"),a=yr(n.itemId,"itemId"),c=yr(n.unit,"unit"),m=yr(n.idempotencyKey,"idempotencyKey")??(o.revision_source==="unversioned"?void 0:[o.revision,r,i??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:s,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Gg(n.observedAt??S(),"observedAt"),...o,author:R(n.author,t.author_default),...a===void 0?{}:{item_id:a},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:uO("sha256").update(J(u)).digest("hex").slice(0,24),...u}}function vO(e,t){let n=t.idempotency_key?e.observations.find(s=>s.idempotency_key===t.idempotency_key):e.observations.find(s=>s.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(s=>s.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function kO(e,t){let n=yr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await _O("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Gd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function SO(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,s=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:s,sample_count:e.length}}async function jg(e,t={}){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await wO(n,r,e),o=Dg.join(n,"improvement-ledger.json"),i=await hu({pmRoot:n,filePath:o,op:"improvement_observe",author:s.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${s.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=ed(a),m=vO(c,s);return m?{raw:a,result:m}:(c.observations.push(s),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${J(c)}
|
|
47
|
-
`,result:s})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function qg(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=e.metric===void 0?void 0:Ug(e.metric),r=e.since===void 0?void 0:Gg(e.since,"since"),s=bO(e.limit),i=ed(await q(Dg.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,s),total:i.length,truncated:i.length>s,trends:[...a].map(([,c])=>SO(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]="6162845d-f4b4-5d1f-a210-ddef1a5c38f6")}catch{}})();function Kg(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 EO(e,t,n){let r=t,s=new Set([e.id]);for(;r!==void 0&&!s.has(r.id);)s.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function TO(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,s)=>r.entries[0].ts.localeCompare(s.entries[0].ts)||r.id.localeCompare(s.id)),t.push(...n.map(r=>r.children))}}function td(e=zn,t=pn){return t.map(n=>{let r=e.filter(s=>((n==="model"?s.model_environment_keys:s.provenance_environment_keys?.[n])?.length??0)>0||s.provenance_resolvers?.[n]!==void 0).map(s=>s.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function AO(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let s=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?s.observed+=1:r.agent_provenance?.model===null?s.unavailable+=1:s.legacy_missing+=1,n.set(r.agent_harness,s)}return[...n.values()].map(r=>{let s=r.observed+r.unavailable;return{...r,coverage:s===0?null:r.observed/s,inert:s>=t&&r.observed===0}}).sort((r,s)=>r.harness.localeCompare(s.harness))}function nd(e,t=pn,n=1){let r=new Map;for(let s of e)if(s.agent_harness)for(let o of t){let i=`${s.agent_harness}\0${o}`,a=r.get(i)??{harness:s.agent_harness,dimension:o,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=s.agent_provenance?.[o];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(s=>{let o=s.observed+s.unavailable;return{...s,coverage:o===0?null:s.observed/o,inert:o>=n&&s.observed===0}}).sort((s,o)=>s.harness.localeCompare(o.harness)||s.dimension.localeCompare(o.dimension))}function CO(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 s=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=s.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),s.set(u,p)}let o=[...s.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=o.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:o,failures:a}}function RO(e){let t=[...e].sort((o,i)=>o.ts.localeCompare(i.ts)||o.author.localeCompare(i.author)||o.op.localeCompare(i.op)||o.before_hash.localeCompare(i.before_hash)||o.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let o of t){let i=o.agent_episode,a=Kg(o),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(o);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:[o],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let s=[];for(let o of n.values()){let i=o.parent_id?r.get(o.parent_id):void 0;i&&EO(o,i,r)?i.children.push(o):s.push(o)}return TO(s),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]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var IO=1e4,zg=1e5,xO=1e3,OO=30,PO=["append","comment","docs","file","learning","note","test_run"];function NO(e){let t=e??IO;if(!Number.isSafeInteger(t)||t<1||t>zg)throw new l(`History analytics event limit must be an integer from 1 to ${zg}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function Bg(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",d.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function LO(e){let t=e?.trim();if(!t)return new Date(Date.now()-OO*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let s=Number(n[1]),o=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(s)||s<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-s*o).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function Hg(e,t){let n=NO(t.eventLimit),r=LO(t.since),s=[],o=r,i=!1;for(;s.length<n;){let a=await zo({pmRoot:e,since:o,limit:Math.min(xO,n-s.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(s.push(...c),i=a.has_more,o=a.next_cursor,!a.has_more)break}return{events:s,receipt:{since:r,events:s.length,truncated:i,...i?{next_cursor:o}:{},source:"history_event_index"}}}function FO(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function $O(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 MO(e){return PO.some(t=>e.startsWith(t))}function Vg(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 DO(e,t,n){let r=new Map,s=new Map,o=new Map;for(let i of t){let a=FO(i.entry,e),c=$O(i.entry),m=s.get(i.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&s.set(i.item_id,u),!a)continue;let p=Vg(r,a);p.events+=1,MO(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,o.set(i.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:o}}function UO(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let s=new Set((r.dependencies??[]).filter(o=>o.kind==="discovered_from").map(o=>o.id));for(let o of s){let i=t.get(o);i&&(Vg(e,i).defectEscapes+=1)}}}function GO(e,t,n,r){let s=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:s==="available"?t.closes/r:null,rework_rate:s==="available"?t.reopens/t.closes:null,defect_escape_rate:s==="available"?t.defectEscapes/t.closes:null,sample_status:s}}function jO(e,t,n,r,s,o){let{buckets:i,lastCloseValue:a}=DO(e,t,r);return UO(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>GO(c,m,s,o)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function qO(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,s=Date.parse(n),o=Date.parse(r);return!Number.isFinite(s)||!Number.isFinite(o)?1:Math.max(1,(o-s)/864e5)}function KO(e,t,n){let r=td(t),s=nd(e,pn,n),o=s.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:s,inert:o,undeclared:i,warnings:[...o.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...i.map(a=>`provenance_dimension_undeclared:${a}`)]}}function Wg(e,t=zn,n={}){let r=Bg(n.minimumSample);return{...KO(e.events.map(s=>s.entry),t,r),window:e.receipt}}function Yg(e,t,n,r={}){let s=Bg(r.minimumSample),o=qO(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>jO(i,e.events,t,n,s,o)),minimum_sample:s,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]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var zO=32;function BO(e){let t=[];for(let n of e??[]){let r=[];for(let s of n.split(",")){let o=s.slice(0,s.indexOf("=")).trim();r.length>0&&o!=="unit"&&o!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(s)}t.push(r.join(","))}return t}function br(e,t){let n=BO(e).map(s=>{let[o,...i]=s.split(","),a=o.indexOf("="),c=o.slice(0,a).trim(),m=o.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${s}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,f;for(let _ of i){let h=_.indexOf("="),y=_.slice(0,h).trim(),g=_.slice(h+1).trim();if(y==="unit"&&g.length>0)p=g;else if(y==="threshold"&&g.length>0&&Number.isFinite(Number(g)))f=Number(g);else throw new l(`Invalid --measure attribute "${_}"`,d.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(s=>[s.name,s])).values()].sort((s,o)=>s.name.localeCompare(o.name)).slice(0,zO)}function Jg(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(s=>s.name===t&&s.value<n).map(s=>({...s,run_id:r.run_id})))}function Xg(e,t){let n=e.flatMap(o=>o.measurements??[]).filter(o=>o.name===t).sort((o,i)=>i.recorded_at.localeCompare(o.recorded_at)),r=n[0],s=n[1];return{name:t,latest:r?.value??null,previous:s?.value??null,delta:r!==void 0&&s!==void 0?r.value-s.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]="d28c7ac7-9801-5b0c-84c9-51deede398be")}catch{}})();function VO(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function WO(e,t,n,r,s){let o=Qn(e,"type",r),i=new Set(o.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),m=(s?[...o.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}}))]:o.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=VO([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>s||f>0));return{byType:m,byStatus:p,omitted:s?0:a.length+Object.values(u).filter(f=>f===0).length}}function YO(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function JO(e){let t=Qg.join(e,"history");if(!await k(t))return[];await un({path:t,scope:"project"});let n=(await HO.readdir(t)).filter(s=>s.endsWith(".jsonl")).sort((s,o)=>s.localeCompare(o)),r=[];for(let s of n){let o=Qg.join(t,s),i=await q(o);i!==null&&(await un({path:o,scope:"project"}),r.push({id:s.slice(0,-6),raw:i}))}return r}async function XO(e,t){let n=[],r=S();for(let s of br(t.observe,r))n.push(await jg({metric:s.name,value:s.value,direction:t.direction,unit:s.unit,threshold:s.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function QO(e,t,n){let r={};return t.byAssignee&&(r.assignee=Qn(e,"assignee",n)),t.byTag&&(r.tag=Qn(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=Qn(e,"priority",n)),r}async function ZO(e,t,n,r,s){let o={since:s.since,eventLimit:s.eventLimit,minimumSample:s.minimumSample},i=s.provenanceCoverage||s.fleetAttribution?await Hg(e,o):void 0;return{provenanceCoverage:s.provenanceCoverage&&i?Wg(i,n.agent_identity?.harness_signals,o):void 0,fleetAttribution:s.fleetAttribution&&i?Yg(i,t,r,o):void 0}}function eP(e,t,n,r,s){let o=Object.keys(s.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...s.metadataCoverage?{metadata_coverage:s.metadataCoverage}:{},...o?{breakdowns:s.breakdowns}:{},...s.storage?{storage:s.storage}:{},...s.fieldUtilization?{field_utilization:s.fieldUtilization}:{},...s.improvementLedger?{improvement_ledger:s.improvementLedger}:{},...s.recordedObservations.length>0?{recorded_observations:s.recordedObservations}:{},...s.provenanceCoverage?{provenance_coverage:s.provenanceCoverage}:{},...s.fleetAttribution?{fleet_attribution:s.fleetAttribution}:{},generated_at:S()}}async function rd(e,t={}){let n=T(process.cwd(),e.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await XO(e,t),o=x(r,I()),i=j(r.schema),a=t.fieldUtilization?await Ts(n,r.item_format,o.type_to_folder,void 0,r.schema):await re(n,r.item_format,o.type_to_folder,void 0,r.schema);await wu({pmRoot:n,settings:r,itemIds:a.map(E=>E.id),commandLabel:"stats"});let c=Js(i),m=WO(a,o.types,i.definitions.map(E=>E.id),c,t.includeEmpty===!0),u=await JO(n),p=0;for(let E of u)p+=YO(E.raw);let f=t.storage?Fg(u):void 0,_=t.metadataCoverage?Kp(a,c):void 0,h=QO(a,t,c),y=t.fieldUtilization?zp(a):void 0,g=t.measurements===!0||s.length>0?await qg({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:b,fleetAttribution:v}=await ZO(n,a,r,i.terminal_statuses,t);return eP({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:y,improvementLedger:g,recordedObservations:s,provenanceCoverage:b,fleetAttribution: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]="0e63298a-d2d7-5217-af50-a206348b4cd4")}catch{}})();function Zg(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:he(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 tP from"node:fs/promises";import Ot 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]="ad3110ca-e85b-5a7e-b0a1-591796c298eb")}catch{}})();var sy=Ot.join("runtime","telemetry","events.jsonl"),oy=Ot.join("runtime","telemetry","state.json"),nP=Ot.join("runtime","telemetry"),rP=20,ey=["status","flush","stats","clear"],ty=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},sd=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,ny=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},sP=e=>({command:sd(e.event.command,"<unknown>"),eventType:sd(e.event.event_type,"unknown"),eventSchemaVersion:ny(e.event.schema_version),clientSchemaVersion:ny(e.client_schema_version)}),oP=()=>({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:{}}),iP=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},aP=e=>{let t=e?.command_resolution;return sd(t,"")||void 0},iy=(e,t)=>{e[t]=(e[t]??0)+1},cP=(e,t)=>{let n=iP(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=aP(t);r!==void 0&&iy(e.resolution_counts,r)},dP=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,ry=(e,t)=>{t!==void 0&&e.add(t)},lP=(e,t)=>{let n=sP(t),r=e.get(n.command)??oP();r.count+=1,r.max_attempts=Math.max(r.max_attempts,dP(t.attempts)),iy(r.event_type_counts,n.eventType),ry(r.event_schema_versions,n.eventSchemaVersion),ry(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&cP(r,t.event.payload),e.set(n.command,r)},mP=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((o,i)=>o-i),s=Object.entries(t.resolution_counts).sort((o,i)=>o[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((o,i)=>o[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((o,i)=>o-i),client_schema_versions:[...t.client_schema_versions].sort((o,i)=>o-i),...r.length>0?{duration_p50_ms:ty(r,.5),duration_p95_ms:ty(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}:{},...s.length>0?{command_resolution_counts:Object.fromEntries(s)}:{}}},uP=e=>{let t=(e??"status").trim().toLowerCase();if(ey.includes(t))return t;throw Ee({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:ey,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},od=()=>{throw new l("--limit must be a positive integer",d.USAGE)},ay=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?od():e,pP=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?od():ay(Number.parseInt(t,10))},fP=e=>e===void 0?rP:typeof e=="number"?ay(e):typeof e=="string"?pP(e):od(),_P=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},hP=e=>{try{let t=JSON.parse(e);return _P(t)?t:void 0}catch{return}},gP=e=>e===null?[]:e.split(`
|
|
48
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),cy=e=>{let t=gP(e),n=[],r=0;for(let s of t){let o=hP(s);o===void 0?r+=1:n.push(o)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},yP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bP=e=>{try{let t=JSON.parse(e);return yP(t)?t:{}}catch{return{}}},wP=async e=>{let t=await q(e);return t===null||t.trim().length===0?{}:bP(t)},Qo=e=>e??null,Zo=async e=>{let t=await A(e),n=Ot.join(e,sy),r=Ot.join(e,oy),s=await q(n),o=cy(s),i=await wP(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:o.rows_total,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_size_bytes:Buffer.byteLength(s??"","utf8"),last_attempted_flush_at:Qo(i.last_attempted_flush_at),last_successful_flush_at:Qo(i.last_successful_flush_at),last_failed_flush_at:Qo(i.last_failed_flush_at),last_failed_flush_error:Qo(i.last_failed_flush_error)}},vP=e=>{let t=new Map;for(let n of e)lP(t,n);return[...t.entries()].map(([n,r])=>mP(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},kP=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Zo(t.globalPmRoot),generated_at:S()}),SP=async(e,t)=>{let n=await Zo(t.globalPmRoot);await Fu(t.globalPmRoot);let r=await Zo(t.globalPmRoot),s=Math.max(0,n.queue_entries-r.queue_entries),o=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:s,queue_progressed:s>0,queue_empty:o,queue_drained:o,status:r,generated_at:S()}},EP=async(e,t)=>{let n=fP(e.limit),r=await q(t.queuePath),s=cy(r),o=vP(s.entries),i=o.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:o.length,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_rows_total:s.rows_total,truncated:o.length>i.length,stats:i,generated_at:S()}},TP=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 Se(t.globalPmRoot,n,"telemetry:clear");let s=Ot.join(t.globalPmRoot,nP),o=await k(s);return await tP.rm(s,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:o&&!await k(s),queue_exists_after:await k(t.queuePath),state_exists_after:await k(t.statePath),status:await Zo(t.globalPmRoot),generated_at:S()}},AP={status:kP,flush:SP,stats:EP,clear:TP};async function dy(e,t){let n=uP(e.subcommand),r=et(process.cwd());return AP[n](e,{globalPmRoot:r,queuePath:Ot.join(r,sy),statePath:Ot.join(r,oy)})}import{spawn as Ry}from"node:child_process";import{cp as fy,mkdir as OP,mkdtemp as Iy,open as dd,readdir as ld,rm as xy}from"node:fs/promises";import{tmpdir as Oy}from"node:os";import le 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]="62af7c1e-c1c7-529e-ab30-117103ac4607")}catch{}})();var ly=20;function CP(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return ly;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?ly:t}function id(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,s)=>{let o=_n(r.recorded_at,s.recorded_at);if(o!==0)return o;let i=r.run_id.localeCompare(s.run_id);return i!==0?i:r.kind.localeCompare(s.kind)}),n=CP();return t.length>n?t.slice(t.length-n):t}async function ei(e){await Y({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=id([...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]="8a6a3402-dae3-56f8-b9ba-a4f6f8a47cda")}catch{}})();var my=100;function ad(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,d.USAGE);return n}function RP(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=my?n:`${n.slice(0,my-3)}...`}function uy(e){return e.map((t,n)=>`${n+1}. ${RP(t)}`).join("; ")}function IP(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 xP(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function py(e,t){let n=IP(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((s,o)=>o+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(s=>`--${s}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,d.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,d.USAGE);if(r==="match"){let s=t.match.trim().toLowerCase();if(s.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let o=[],i=[];for(let a=0;a<e.length;a+=1)xP(e[a],s)&&(i.push(e[a]),o.push(a+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${uy(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:o,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let s=ad(t.onlyIndex);if(s>e.length)throw new l(`--only-index ${s} is out of range: this item has ${e.length} linked test(s). Available entries: ${uy(e)}`,d.USAGE);return{selector:"only-index",requested:String(s),selected:[e[s-1]],selected_indexes:[s],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]="4322c352-6b95-5796-94eb-5a68745d53bc")}catch{}})();var ni=20*1024*1024,PP=3e3,NP=1e4,LP=5e3,_y=120,FP=new Set(["locks","extensions","runtime"]),$P=new Set(["history","index","search","extensions","locks","runtime"]),MP=[/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],DP=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,UP=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,GP=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 pd(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 jP(){return pd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",PP)}function qP(){return pd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",NP)}function KP(){return pd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",LP)}function zP(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 BP(e){let t=0,n=0,r=0;for(let s of e){if(s.status==="passed"){t+=1;continue}if(s.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function fd(e){let t=0,n=0,r=0,s=0;for(let o of e){let i=o.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&&(s+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:s}}function HP(e){let t=e??"project";if(!Ze.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function ri(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Wt.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${Wt.join(", ")}`,d.USAGE)}function Py(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:ri(e.pm_context_mode)}function Ny(e,t){return e==="auto"?t?"tracker":"schema":e}function VP(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 WP(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 YP(e,t){let n={};if(!e)return n;for(let r of e){let s=sr(r,t);if(s)for(let[o,i]of Object.entries(s))n[o]=i}return n}function JP(e,t){if(!e)return[];let n=[];for(let r of e){let s=or(r,t);s&&n.push(...s)}return[...new Set(n)]}function XP(e){let t=si(e);return Jn(t).some(n=>fa(n)!==null)}function Ly(e){let t=si(e);return Jn(t).some(n=>{let r=fa(n);if(!r)return!1;let s=Gp(r);return s?GP.has(s.subcommand):!1})}function ti(e){if(e)return Mp.has(e.subcommand)?Tn(e.args,Dp)?.subcommand:e.subcommand}function hy(e,t){if(e==="npx"||e==="bunx")return Ws(t)?.command;if(e==="pnpm")return ti(Tn(t,Np));if(e==="npm")return ti(Tn(t,Lp));if(e==="yarn")return ti(Tn(t,Fp));if(e==="bun")return ti(Tn(t,$p))}function gy(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function cd(e){return!e||!ha(e.command)&&!Up(e.command)?!1:Vs(e.args)==="test-all"}var QP=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])]),ZP=new Set(["npx","bunx"]);function Fy(e){let t=e.split(" ").filter(i=>i.length>0),n=_a(t);if(n.length===0)return!1;let[r,...s]=n,o=QP.get(r);if(o){let i=s.findIndex(a=>o.test(a));return i>=0?Fy(s.slice(i+1).join(" ")):!1}return ha(r)||ga(r)?Vs(s)==="test-all":r==="node"&&s.length>0&&ga(s[0])?Vs(s.slice(1))==="test-all":ZP.has(r)?cd(Ws(s)):r==="pnpm"?cd(ya(s)):r==="npm"?cd(ba(s)):!1}function $y(e){let t=si(e);return Jn(t).some(n=>Fy(n))}function My(e){if($y(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function si(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function eN(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function tN(e){let t=/\bpm_path\s*=/.test(e)||/\$env:pm_path\s*=/.test(e),n=/\bpm_global_path\s*=/.test(e)||/\$env:pm_global_path\s*=/.test(e);return t&&n}function nN(e){let t=e.split(" ").filter(o=>o.length>0),n=_a(t);if(n.length===0)return!1;let[r,...s]=n;return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?rN(s):sN(r,s)}function rN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function sN(e,t){return e==="npx"||e==="bunx"?gy(Ws(t)?.command):e==="pnpm"||e==="npm"?gy((e==="pnpm"?ya(t):ba(t))?.command)||hy(e,t)==="vitest":(e==="yarn"||e==="bun")&&hy(e,t)==="vitest"}function Dy(e){let t=si(e);if(Jn(t).some(s=>!eN(s)&&nN(s)&&!tN(s)))throw new l('Linked test runner commands must be sandbox-safe: use "node scripts/run-tests.mjs <test|coverage>", use a package-manager script such as "pnpm test", or include PM_PATH=... PM_GLOBAL_PATH=... INLINE in the command string (exporting them in your shell environment is not checked). Example: "PM_PATH=/tmp/pm-x PM_GLOBAL_PATH=/tmp/pm-x-g vitest run".',d.USAGE)}function oN(e){if($y(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function iN(e){return e?e.map(aN):[]}function aN(e){let t=e.trim(),n=bo(t)?wo(te(e,"--add"),"--add"):{command:t},r=de(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return My(r),Dy(r),{command:r,path:de(n.path),scope:HP(n.scope),timeout_seconds:cN(de(n.timeout_seconds),de(n.timeout)),pm_context_mode:To(de(n.pm_context_mode),"--add"),env_set:sr(de(n.env_set),"--add"),env_clear:or(de(n.env_clear),"--add"),shared_host_safe:Eo(de(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Jt(de(n.assert_stdout_contains)),assert_stdout_regex:xn(de(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Jt(de(n.assert_stderr_contains)),assert_stderr_regex:xn(de(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Ao(de(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Co(de(n.assert_json_field_equals),"--add"),assert_json_field_gte:Ro(de(n.assert_json_field_gte),"--add"),note:de(n.note)}}function de(e){let t=e?.trim();return t&&t.length>0?t:void 0}function cN(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",d.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(se(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function dN(e){return e?e.flatMap(t=>{let n=Lf(t,"--add-json");for(let r of n){let s=r.command;if(!s)throw new l("--add-json requires a non-empty command string",d.USAGE);My(s),Dy(s)}return n}):[]}function lN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",d.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let s=n.slice(r[0].length).trim();if(!s)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:s}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let s=te(n,"--remove"),o=s.path!==void 0?"path":"command",i=s.path??s.command;if(!i?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:o,value:i.trim()}}return{kind:"either",value:n}}):[]}function mN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function uN(e){try{e.stdin?.end()}catch{}}function Uy(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=_y?t:`${t.slice(0,_y-3)}...`}function Gy(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function md(e){try{process.stderr.write(`${e}
|
|
49
|
-
`)}catch{}}function
|
|
50
|
-
[pm linked-test output truncated at ${
|
|
51
|
-
`:""
|
|
52
|
-
`);return
|
|
53
|
-
${t}`;for(let r of NN)if(r.regex.test(n))return r.code;return null}function FN(e){return{root:e,schemaProjectPmPath:le.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:le.join(e,"schema","global"),trackerProjectPmPath:le.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:le.join(e,"tracker","global")}}async function $N(e,t=lr,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 MN(e,t,n){t&&(await vy(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await vy(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await ky(t.projectPmRoot,e.trackerProjectPmPath),await ky(t.globalPmRoot,e.trackerGlobalPmPath)))}function DN(e,t,n){return e.some(r=>{let s=r.command??"",o=s.length>0&&Ly(s),i=n?.autoPmContext===!0&&o?"auto":Py(r,t,n?.overrideLinkedPmContext===!0);return Ny(i,o)==="tracker"})}async function UN(e,t){return{sourceProjectItemCount:t?await $n(t.projectPmRoot):0,sourceGlobalItemCount:t?await $n(t.globalPmRoot):0,schemaProjectItemCount:await $n(e.schemaProjectPmPath),schemaGlobalItemCount:await $n(e.schemaGlobalPmPath),trackerProjectItemCount:await $n(e.trackerProjectPmPath),trackerGlobalItemCount:await $n(e.trackerGlobalPmPath)}}function GN(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,s=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,o=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount;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:s,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:o,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==s||e.counts.sourceGlobalItemCount!==o),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots}}function jN(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?ri(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?XP(n):!1,s=r&&n?Ly(n):!1,o=e.options?.autoPmContext===!0&&s,i=o?"auto":Py(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Ny(i,s);return{linkedOverridePmContextMode:t,executionContext:GN({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:s,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:o})}}function Ay(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function ud(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 qN(e){if(!e.linkedTest.command)return Ay(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=oN(e.linkedTest.command);if(t)return Ay(e.linkedTest,e.executionContext,t);let n=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,r=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(n||r){let s=WP({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return ud(e.linkedTest,e.executionContext,`${o} (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&&!VP(e.linkedTest)?ud(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function KN(e){let t=TN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return wy(n,e.runtimeDirectives),wy(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&EN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,n.PM_SOURCE_WORKSPACE_ROOT=process.env.PM_SOURCE_WORKSPACE_ROOT??process.cwd(),n.PM_SOURCE_PM_PATH=e.executionContext.source_project_pm_path,n[Bs]="read_only",n}function zN(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 BN(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}) while --fail-on-empty-test-run is enabled. Update test selection or disable --fail-on-empty-test-run for this run.`}}function HN(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:CN(e.execution),failure_category:kN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:wN(e.execution,e.timeoutMs)}}function VN(e){if(e.options?.failOnEmptyTestRun===!0){let n=LN(e.execution.stdout,e.execution.stderr);if(n)return BN({...e,emptyRunSignal:n})}let t=ON(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?ud(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):zN(e.linkedTest,e.executionContext,e.execution)}async function WN(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await bN(t,n,KN(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?VN({...e,execution:r}):HN({...e,execution:r,timeoutMs:n})}async function _d(e,t,n){let r=[],s=await Iy(le.join(Oy(),"pm-linked-test-")),o=FN(s),i=ri(n?.pmContext),a=n?.progress===!0?"always":"auto",c=AN(n?.envSet,n?.envClear,n?.sharedHostSafe),m=n?.sourceRoots,u=DN(e,i,n);try{await $N(o,lr,u),await MN(o,m,u);let p=await UN(o,m);for(let f=0;f<e.length;f+=1){let _=e[f],h=jN({linkedTest:_,layout:o,counts:p,sourceRoots:m,runLevelPmContextMode:i,options:n}),y=qN({linkedTest:_,executionContext:h.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:h.linkedOverridePmContextMode,options:n});if(y){r.push(y);continue}r.push(await WN({linkedTest:_,index:f,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:c,progressMode:a,executionContext:h.executionContext,options:n}))}}finally{await xy(o.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function YN(e){let{id:t,pmRoot:n,settings:r,typeToFolder:s}=e,o=await M(n,t,r.id_prefix,r.item_format,s);if(!o)throw new l(`Item ${t} not found`,d.NOT_FOUND);let i=await K(o,{schema:r.schema});return{itemId:o.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function JN(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode}function XN(e,t){let n=[...e];for(let r of t)n.some(s=>JN(s,r))||n.push(r);return n}function QN(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),s=e.filter((o,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?o.command===a.value:a.kind==="path"?o.path===a.value:o.command===a.value||o.path===a.value));return{tests:s,removed:e.length-s.length}}function ZN(e,t,n,r){return QN(XN(e,t),n,r)}function eL(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}function tL(e){if(eL(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",d.USAGE)}async function nL(e){let{id:t,options:n,pmRoot:r,settings:s,typeToFolder:o,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return YN({id:t,pmRoot:r,settings:s,typeToFolder:o});let m=0,u=await Y({pmRoot:r,settings:s,id:t,op:i.length>0?"tests_add":"tests_remove",author:R(n.author,s.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=ZN(f,i,a,c);if(m=_.removed,(a.length>0||c.length>0)&&m===0)throw new l("No linked tests matched the requested removal selector",d.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],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:tt(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 rL(e,t){tL(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:ad(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?py(t,n):void 0,s=e.timeout===void 0?void 0:se(e.timeout,"timeout");if(s!==void 0&&s<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:s,pmContextMode:ri(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function sL(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await _d(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,sourceRoots:{projectPmRoot:r,globalPmRoot:et(process.cwd())}})}function oL(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 s=fd(n);r.push(`context_preflight:checked_pm_commands=${s.checked_pm_commands};tracker_read_commands=${s.tracker_read_commands};mismatches=${s.mismatches};auto_remediated=${s.auto_remediated}`)}return r}function iL(e){let t=BP(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),s=S(),o=br(e.options.measure,s);return{run_id:zP("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:s,recorded_at:s,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:o.length>0?o:void 0}}async function aL(e){let{options:t,pmRoot:n,settings:r,itemId:s,runStartedAt:o,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!o)return;let m=iL({options:t,runStartedAt:o,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return m;try{return await ei({pmRoot:n,settings:r,itemId:s,author:R(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:${s}:${u instanceof Error?u.message:String(u)}`),m}}function Cy(e,t,n){let r;if(e.metricBelow!==void 0){let s=e.metricBelow.indexOf("="),o=e.metricBelow.slice(0,s).trim(),i=e.metricBelow.slice(s+1).trim(),a=Number(i);if(s<=0||o.length===0||i.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",d.USAGE);r=Jg(t,o,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Xg(t,e.metricDiff)}}async function ii(e,t,n){let r=Ne(),s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);br(t.measure,"validation"),Cy(t,[],void 0);let i=x(o,I()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...iN(a),...dN(c)],p=lN(m),f=mN(t.removeIndex),_=await nL({id:e,options:t,pmRoot:s,settings:o,typeToFolder:i.type_to_folder,adds:u,removes:p,removeIndexes:f}),h=rL(t,_.tests),y=t.run===!0?S():void 0,g=await sL({options:t,runOptions:h,pmRoot:s}),b=oi(g),v=t.run===!0&&t.failOnSkipped===!0&&g.some(G=>G.status==="skipped"),E=oL(t,h.runSelection,g),N=await aL({options:t,pmRoot:s,settings:o,itemId:_.itemId,runStartedAt:y,runResults:g,failOnSkippedTriggered:v,warnings:E}),P=N?id([..._.testRuns,N]):_.testRuns,$=Cy(t,P,N);return{ok:g.every(G=>G.status!=="failed")&&v!==!0,id:_.itemId,tests:_.tests,run_results:g,failure_categories:b,selection:h.runSelection?{selector:h.runSelection.selector,requested:h.runSelection.requested,selected_indexes:h.runSelection.selected_indexes,selected_count:h.runSelection.selected_count,skipped_count:h.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:v?!0:void 0,warnings:E.length>0?E:void 0,changed:_.changed,count:_.tests.length,..._.removed>0?{removed:_.removed}:{},...$}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7fea0ecb-35e2-5d40-931f-ffdd1a465fdc")}catch{}})();var cL=(e,t)=>{if(e===void 0)return;let n=ne(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},dL=e=>{if(e===void 0)return;let t=se(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},jy=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,d.USAGE);return n},lL=e=>e instanceof Error?e.message:String(e),mL=()=>{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)}`},uL=e=>e.trim().replaceAll(/\s+/g," "),pL=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),fL=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),_L=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},ai=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),qy=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),hL=e=>typeof e=="number"?e:void 0,gL=e=>{let t={assert_stdout_contains:ai(e.assert_stdout_contains),assert_stdout_regex:ai(e.assert_stdout_regex),assert_stderr_contains:ai(e.assert_stderr_contains),assert_stderr_regex:ai(e.assert_stderr_regex),assert_stdout_min_lines:hL(e.assert_stdout_min_lines),assert_json_field_equals:qy(e.assert_json_field_equals),assert_json_field_gte:qy(e.assert_json_field_gte)};return JSON.stringify(t)},yL=e=>{let t=hd(e.command);return t!==void 0?`command:${e.scope}:${uL(t)}`:`path:${e.scope}:${hd(e.path)??""}`},Ky=e=>{let t=pL(e.env_set),n=fL(e.env_clear),r=_L(e.pm_context_mode),s=e.shared_host_safe===!0?"true":"false",o=gL(e);return`${yL(e)}:${t}:${n}:${r}:${s}:${o}`},bL=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,wL=e=>{let t=0,n=0,r=0;for(let s of e){if(s.status==="passed"){t+=1;continue}if(s.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},vL=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},ci=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
54
|
-
`)}catch{}},kL=async(e,t,n)=>{let r=[],s=0;for(let o of e){let i=await ii(o.id,{run:!1},{...t,path:n});s+=i.tests.length,r.push({item:o,tests:i.tests})}return{itemTests:r,linkedTests:s}},SL=async e=>{let t=j(e.settings.schema),n=x(e.settings,I()),r=cL(e.options.status,t),s=jy(e.options.limit,"--limit"),o=jy(e.options.offset,"--offset")??0,a=(await re(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:s===void 0?a.slice(o):a.slice(o,o+s),statusFilter:r,limitFilter:s,offsetFilter:o}},EL=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let s=Ky(r);if(!t.has(s)){t.set(s,r.timeout_seconds);continue}t.set(s,bL(t.get(s),r.timeout_seconds))}return t},TL=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=Ky(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}}),s=n.length>0?await _d(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}):[],o=0,i=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=s[o];return o+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=wL(i),c=oi(i),m=await RL(e,a,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}}},AL=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),CL=e=>e?!0:void 0,RL=async(e,t,n)=>{if(!n.trackingEnabled)return[];try{let r=AL(t,n.options);await ei({pmRoot:n.pmRoot,settings:n.settings,itemId:e.item.id,author:n.trackingAuthor,message:`Track test-all run summary (${n.trackingRunId})`,entry:{run_id:n.trackingRunId,kind:"test-all",status:r?"failed":"passed",started_at:n.runStartedAt,finished_at:S(),recorded_at:S(),attempt:n.trackingAttempt,resumed_from:n.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:CL(n.options.failOnSkipped===!0&&t.skipped>0)}})}catch(r){return[`test_result_tracking_failed:${e.item.id}:${lL(r)}`]}return[]},IL=()=>{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},hd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},xL=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:et(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:EL(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:R(e.options.author,e.settings.author_default),trackingRunId:mL(),trackingAttempt:IL(),trackingResumedFrom:hd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),OL=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:oi([]),trackingWarnings:[]},s=e.failOnEmptyTestRun===!0&&t===0;return s&&(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:s}},PL=async(e,t,n)=>{for(let[r,s]of e.entries()){ci(t.options,`item ${r+1}/${e.length} start id=${s.item.id} linked_tests=${s.tests.length}`);let o=await TL(s,t);vL(n.failureCategories,o.failureCategories),n.passed+=o.passed,n.failed+=o.failed,n.skipped+=o.skipped,n.trackingWarnings.push(...o.trackingWarnings),n.results.push(o.result),ci(t.options,`item ${r+1}/${e.length} end id=${s.item.id} status=${o.failed===0?"passed":"failed"} passed=${o.passed} failed=${o.failed} skipped=${o.skipped}`)}},NL=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(s=>s.run_results),r=fd(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}`)},LL=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}),FL=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(" "),$L=async(e,t)=>{let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await SL({pmRoot:n,settings:r,options:e}),o=dL(e.timeout),i=S(),a=await kL(s.filteredItems,t,n);return ci(e,FL({...s,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:s.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:o,runStartedAt:i}},ML=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}},zy=async(e,t)=>{let n=await $L(e,t),{accumulation:r,failOnEmptyTestRunTriggered:s}=OL(e,n.linkedTests,n.filteredItems),o=xL({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await PL(n.itemTests,o,r),NL(e,r);let i=ML({options:e,accumulation:r,failOnEmptyTestRunTriggered:s});return ci(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),LL({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered: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]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function By(e){return us("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]="2643d11d-befc-5a87-8bec-760951eec4d0")}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]="c2567f6a-cd1c-56b5-a93d-41e92ed574bf")}catch{}})();function Hy(){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]="7be35c3f-df6f-5ed6-b887-a7d8d53910a7")}catch{}})();var Wy=[{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 install <target> --project","pm 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 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 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:"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"]}],Vy=new Map;for(let e of Wy){Vy.set(e.id,e);for(let t of e.aliases)Vy.set(t,e)}function gd(){return Wy.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]="27be0fa5-1c6a-53de-a0e8-179aab7c795a")}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]="48da3e98-ab96-54de-8993-7de0c4edf19b")}catch{}})();var Tz=[...Tr],Az=[...Ar],DL=new Set(Kn.filter(e=>e.hidden).map(e=>e.alias)),Cz=Wm("full").filter(e=>!DL.has(e)),Rz=F(Mr),Iz=F(Dr),xz=F(Br),Oz=F(Jr),Pz=F(Xr),Nz=F(Hl),Lz=F(Vl),Fz=F(Yr),$z=F(ts),Mz=F(Qr),Dz=F(Zr),Uz=F(zr),Gz=F(es),jz=F(Ur),qz=F(Gr,!1),Kz=F(rm),zz=F(jn),Bz=F(qn),Hz=F(os),Vz=F(rs),Wz=F(Vr),Yz=F(ss),Jz=F(ns),Xz=F(is),Qz=F(Hr),Zz=F(Wr),eB=F(qr),tB=F(as),nB=F(jr);var UL=F(cs),rB=`${UL} bash zsh fish`,sB=GL(gd());var oB=F(Kr),iB=F(Gn);var aB=$r.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function GL(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]="0224a672-e326-5555-a4b4-1fa3550d9e61")}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]="8f02f498-5cee-59fa-9f4e-fd882c58d401")}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]="95764dd9-1b0d-5732-9f10-b13b334ce27d")}catch{}})();var Qy=Symbol("pm.active-extension-host-context");function Re(e){return{fullChangedFields:!0,options:e}}var U=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[Qy]=!0,n}run(t,n={}){return Zy({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Qp(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return ta(await this.list(ea(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,...Re({...r,body:n})})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,s,o={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...s===void 0?{}:{value:s},options:o})}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,s){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...s?{fieldTypeScope:s}:{}}})}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={},s,o){return this.runTyped("plan",{...n===void 0?{}:{id:n},...s===void 0?{}:{stepRef:s},...o===void 0?{}:{reorderTo:o},options:{...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,s={}){return this.plan("reorder-step",t,s,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",Re(t))}update(t,n={}){return this.runTyped("update",{id:t,...Re(n)})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Re(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Re(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Re(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Re(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Re(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Re(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},...Re(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Re(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Re(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Re(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 qL(e={},t={}){return new U(t).context(e)}function KL(e={},t={}){return new U(t).list(e)}function zL(e={},t={}){return new U(t).listAllComplete(e)}function BL(e,t={},n={}){return new U(n).search(e,t)}function HL(e,t={},n={}){return new U(n).get(e,t)}function VL(e={},t={}){return new U(t).next(e)}function WL(e={},t={}){return new U(t).aggregate(e)}function YL(e,t={},n={}){return new U(n).comments(e,t)}function JL(e,t={},n={}){return new U(n).notes(e,t)}function XL(e,t={},n={}){return new U(n).learnings(e,t)}function QL(e,t={},n={}){return new U(n).files(e,t)}function ZL(e,t={},n={}){return new U(n).filesDiscover(e,t)}function eF(e,t={},n={}){return new U(n).docs(e,t)}function tF(e,t={},n={}){return new U(n).deps(e,t)}function nF(e,t={},n={},r={}){return new U(r).graph(e,t,n)}function rF(e,t,n={},r={}){return new U(r).append(e,t,n)}function sF(e={},t={}){return new U(t).create(e)}function oF(e,t={},n={}){return new U(n).update(e,t)}function iF(e,t,n={},r={}){return new U(r).close(e,t,n)}function aF(e,t={},n={}){return new U(n).claim(e,t)}function cF(e={},t={}){return new U(t).claimNext(e)}function dF(e,t={},n={}){return new U(n).release(e,t)}function lF(e,t={},n={}){return new U(n).copy(e,t)}function mF(e,t={},n={}){return new U(n).delete(e,t)}function uF(e,t,n={},r={}){return new U(r).restore(e,t,n)}function pF(e,t={},n={}){return new U(n).focus(e,t)}function Je(e,t){let n=w(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}var Yy=Jm(),fF=new jL;function di(){zi(Hd()),Bi(Vd()),Hi(Wd()),Vi(Yd()),Wi(Jd()),Yi(Xd()),Ji(Qd())}async function _F(e,t,n,r){return Xm(()=>t===void 0?Yy.read(()=>Jy(e,n,r)):Yy.write(()=>gF(t,()=>Jy(e,n,r))))}async function Jy(e,t,n){let r=T(t,e.path);if(e.noExtensions)return di(),Oa({pmRoot:r},()=>n(null));if(!await k(C(r)))return di(),n(null);let s=null,o;try{let i=await A(r),a=await Lr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Fr({...a,loaded:a.loaded});o={loadResult:a,activationResult:c},zi(c.hooks),Bi(c.commands),Hi(c.parsers),Vi(c.preflight),Wi(c.services),Yi(c.renderers),Ji(c.registrations),s={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){di(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Oa({pmRoot:r,packages:s?.packages},()=>n(s))}finally{di(),o&&await Zd(o.loadResult,o.activationResult).catch(()=>{})}}async function hF(e,t,n,r,s){if(!s)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let o=Kt(e),a=s.registrations.commands.find(m=>Kt(m.action)===o)?.command??s.commands.handlers.find(m=>Kt(m.command)===o)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=await ys({command:da(a),args:he(n.args??t.args),options:la(t,n),global:r,pm_root:s.pmRoot,sdk:nf(s.pmRoot,U.forActiveExtensionHost({pmRoot:s.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 l(`Unsupported native pm action: ${e}${m}`,d.USAGE)}return c.result}async function gF(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var yF=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function bF(e){let t=Je(e,"action"),n=Kt(t),r=mi(ef,n),s=r?.action??n,o={...e,action:s};return r?.options!==void 0&&(o.options={...r.options,...xi(e.options)}),s==="package"&&(o.options={...xi(o.options),vocabulary:"package"}),{action:s,args:o}}function wF(e){return!yF.has(Kt(e))}async function Zy(e){let t=bF(e),n=ia(t.args),r=wF(t.action),s=w(t.args,"cwd"),o=s??process.cwd();try{return e[Qy]===!0||fF.getStore()===!0?await Xy(t.action,t.args,n,null):await _F(n,s,o,i=>Xy(t.action,t.args,n,i))}finally{r&&Ca()}}function mi(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function li(e){return w(e.args,"target")??w(e.options,"target")}function W(e,t=e.options){return e.id??Je(t,"id")}async function vF(e){let t=ln("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),Aa(await Et(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function kF(e){let t=Je(e.args,"query"),n=ln("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Aa(await er(t,n,e.global),n)}async function SF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options);return st(await At(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function EF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options),s={...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 st(await yc(W(e,s),s,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function TF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options);return st(await at(W(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function AF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options),s=w(e.args,"reason")??w(e.args,"text")??w(r,"reason")??w(r,"text");return st(await Tt(W(e,r),s,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function CF(e){let t=ro(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")),bf(W(e),t,e.global)}function eb(e,t){return Pp(mg(e.options,t,Le),e.global)}function RF(e){let t=he(e.options.lookupPath);if(t&&t.length>0)return eb(e,t);let n=W(e);return e.options.discover===!0?pa(n,ca(e.options),e.global):Op(n,zs(e.options),e.global)}function IF(e){return dy({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:Ju(e.args,e.options)},e.global)}function xF(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Ip(e.global,t)}function OF(e){let t=w(e.args,"configAction")??w(e.options,"configAction")??w(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);return G_(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),e.options,e.global,w(e.args,"value")??w(e.options,"value"))}function PF(e){let t=e.options;return ju(Gu(t),e.global)}function NF(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}function LF(e){let t=w(e.args,"subcommand")??Je(e.options,"subcommand"),n=e.options;return y_({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:FF(e),reorderTo:NF(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function FF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function $F(e){let t=w(e.args,"subcommand")??Je(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:he(n)}}function MF(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,a=mi({list:()=>pp(t.global),show:()=>fp(r,t.global),"show-status":()=>_p(r,t.global),"list-fields":()=>yp(t.global),"show-field":()=>bp(r,t.global),"remove-type":()=>dp(r,{author:s,force:o},t.global),"remove-field":()=>gp(r,{author:s,force:o},t.global),"remove-status":()=>up(r,{author:s,force:o},t.global),"apply-preset":()=>wp(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:s,force:o},t.global)},n);return a?a():null}function DF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return hp(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:he(i),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:o,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:he(a),author:r,force:s},t.global)}function UF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e,i=t.args.role??t.options.role;return mp(n,{role:i===void 0?void 0:he(i),alias:o,description:w(t.args,"description")??w(t.options,"description"),order:Le(t.args.order??t.options.order,"schema add-status order"),author:r,force:s},t.global)}function GF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e;return cp(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:o,author:r,force:s},t.global)}function jF(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,i=w(t.args,"to")??Je(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 ip(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:s,force:o},t.global)}function qF(e){let t=$F(e),n=MF(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return jF(t);if(t.subcommand==="add-field")return DF(t);if(t.subcommand==="add-status")return UF(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?vp({minCount:Le(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):GF(t);throw Ee({command_path:"schema",token:t.subcommand,allowed:ap,exit_code:64})}function KF(e){let t=w(e.args,"subcommand")??Je(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),o=mi({list:()=>eg(),show:()=>tg(r),lint:()=>ng(r),apply:()=>rg(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(!o)throw Ee({command_path:"profile",token:t,allowed:Zh,exit_code:64});return o()}async function zF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options);return st(await sf(W(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function BF(e){let{changedFields:t,runnerOptions:n}=Ve(e.args,e.options);return st(await i_(ua(n),e.global),{changedFields:t})}async function HF(e){let{changedFields:t,runnerOptions:n}=Ve(e.args,e.options),r=w(e.args,"reason"),s=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&s.force===void 0&&(s.force=!0),st(await yf(ma(s),e.global),{changedFields:t})}async function VF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options),s=w(r,"target")??Je(e.args,"target");return st(await Bt(W(e,r),s,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function tb(e){let t={...e};return delete t.assignee,t}async function WF(e){let t=T(process.cwd(),e.global.path),n=await A(t),r=By(j(n.schema)),s=W(e),o=await oo(s,e.force,e.global,e.options),i=await at(s,{...tb(e.options),status:r,force:e.force},e.global);return{id:s,action:"start_task",claim:o,update:i}}async function YF(e){let t=T(process.cwd(),e.global.path),n=await A(t),r=W(e),s=j(n.schema).open_status,o=await at(r,{...tb(e.options),status:s,force:e.force},e.global),i=await io(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:o,release:i}}async function JF(e){let t=W(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await Tt(t,n,{...e.options,force:e.force},e.global),s=await io(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:s}}function XF(e){let t={...e.args,...e.options};return Hu(Je(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),Zu(t),e.global)}function QF(e){return tp(T(process.cwd(),e.global.path),{...e.args,...e.options})}var ZF={init:e=>lr(w(e.args,"prefix"),e.global,e.options),context:e=>Sa(ln("context",e.options),e.global),next:e=>Zn(ln("next",e.options),e.global),eval:qh,events:Kh,merge:zh,workspace:Bh,meet:Vo,event:Vo,remind:Vo,list:vF,get:e=>{let t=W(e);return Ea(t,e.global,ln("get",e.options,[t]))},search:kF,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:he(e.options.status);return Ta(e.global,{...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:Le(e.options.limit,"limit")})},create:SF,copy:EF,focus:e=>wc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:TF,restore:VF,claim:e=>e.options.next===!0||e.args.next===!0?uf(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):oo(W(e),e.force,e.global,e.options),release:e=>io(W(e),e.force,e.global,e.options),"start-task":WF,"pause-task":YF,"close-task":JF,close:AF,comments:CF,notes:e=>vf(W(e),ro(e.options),e.global),learnings:e=>wf(W(e),ro(e.options),e.global),files:RF,docs:e=>xp(W(e),zs(e.options),e.global),test:e=>ii(W(e),e.options,e.global),"test-all":e=>zy(e.options,e.global),telemetry:IF,validate:e=>Ys(e.options,e.global,{runUpdate:(t,n,r)=>at(t,n,r)}),health:xF,assurance:e=>jp(e.args,e.options,e.global),contracts:e=>Lg(e.options,e.global),config:OF,activity:PF,aggregate:e=>wa(e.options,e.global),extension:e=>En(li(e),e.options,e.global),package:e=>En(li(e),e.options,e.global),install:e=>En(li(e),{...e.options,install:!0},e.global),upgrade:e=>Yp(li(e),e.options,e.global),delete:e=>bc(W(e),e.options,e.global),deps:e=>Bu(W(e),e.options,e.global),graph:XF,"files-discover":e=>pa(W(e),e.options,e.global),"files-lookup":e=>eb(e,he(e.options.paths)),history:e=>Wp(W(e),e.options,e.global),"history-redact":e=>Eu(W(e),e.options,e.global),"history-repair":dg,"history-compact":lg,"history-author-acknowledge":QF,plan:LF,schema:qF,profile:KF,stats:e=>rd(e.global,Zg(e.options)),append:zF,"update-many":BF,"close-many":HF,gc:e=>Jp(e.global,e.options)};async function Xy(e,t,n,r){let s=aa(t,e);ji(e,s),Nm(e,s);let o={action:e,args:t,options:s,id:w(t,"id"),force:t.force===!0||s.force===!0,global:n,activeExtensions:r},i=mi(ZF,e),a=i?await i(o):await hF(e,t,s,n,r);return s.resolvedOutputFormat="json",zm(e,s,a)}var e$={closeManyOptionsFromFlat:ma,extensionOptionsFromArgs:la,globalOptions:ia,mutationListOptions:Qu,normalizeActionName:Kt,normalizeCommandPath:da,normalizeMcpUpdateOptions:ep,normalizeMcpOptionsArrays:Xu,optionsWithAuthor:aa,readRequiredString:Je,readScalarString:Wu,readScalarStringAllowBlank:Yu,readStringArray:he,updateManyOptionsFromFlat:ua,withAddNoteOption:zs,withFilesDiscoveryOptions:ca,withMutationCompaction:Ve};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=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]="d19cfa31-a02f-53a7-8685-5d169d6e051d")}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]="cc0d4dd1-20e8-59d4-acb5-9f8ed639d35f")}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]="3b27abec-8da3-531a-9bbc-71e97b8b65c5")}catch{}})();export{pn as AGENT_PROVENANCE_DIMENSIONS,tu as BASELINE_ITEM_FORMAT_VERSION,zn as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,Tr as BUILTIN_ITEM_TYPE_VALUES,Cr as CONFIDENCE_TEXT_VALUES,nu as CURRENT_ITEM_FORMAT_VERSION,Ft as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,on as ISSUE_SEVERITY_VALUES,Od as ITEM_TYPE_VALUES,Ra as PM_CLI_EXPECTED_ERROR_NAME,Xb as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,Yb as PM_READ_OUTPUT_DIMENSIONS,Jb as PM_READ_OUTPUT_OPTION_FLAGS,Gi as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,U as PmClient,sn as RISK_VALUES,yw as SEMANTIC_ATTRIBUTION_LIMITS,Ar as STATUS_VALUES,aw as agentSessionEnvironment,WL as aggregate,td as analyzeAgentProvenanceDescriptorCoverage,rw as analyzeSdkCliParameterCompleteness,rF as append,ew as applyReadOutputDimensions,zb as applyReadOutputSessionReferences,Bb as attachReadOutputSessionReceipt,sw as boundAgentEpisodeIdentity,He as canonicalDocument,aF as claim,cF as claimNext,ou as classifyItemFormatVersion,iF as close,YL as comments,qL as context,lF as copy,sF as create,tf as createPmCliExpectedError,Wb as decodeReadOutputContinuationCursor,mF as deleteItem,tF as deps,mw as detectAgentIdentity,fw as detectHarnessIdentity,uw as diagnoseAgentIdentity,eF as docs,ru as effectiveItemFormatVersion,Hy as emptyImportedDocument,Vb as encodeReadOutputContinuationCursor,CO as evaluateSemanticAttributionCoverage,hw as explainSourceTraceability,QL as files,ZL as filesDiscover,pF as focus,HL as get,nF as graph,RO as groupHistoryByEpisode,mf as isAlreadyClaimedError,eo as isPmCliExpectedError,tw as isReadOutputBudgetExceeded,XL as learnings,KL as list,zL as listAllComplete,VL as next,su as normalizeItemFormatVersion,_e as normalizeItemId,ne as normalizeStatusInput,JL as notes,S as nowIso,Kb as parseReadOutputSession,Hs as parseSourceLineRange,ws as readAuthorEnvironment,Hb as readOutputSessionRemainingTokens,va as recordClaimSemanticAttribution,Xs as recordFocusSemanticAttribution,ka as recordReleaseSemanticAttribution,cw as registerHarnessSignalDescriptors,dF as release,ow as resolveAgentSessionContextFromSignals,_w as resolveAuthorIdentity,Kg as resolveHistoryEpisodeGroupIdentity,Zb as resolveReadOutputDimensions,nw as resolveReadOutputEncoding,Qb as resolveReadOutputSurface,gw as resolveSemanticLineageIds,uF as restore,Zy as runAction,iw as runWithAgentSessionContext,dw as runWithHarnessDetectionSignals,lw as runWithWorkspaceHarnessSignalDescriptors,BL as search,bw as semanticAttributionAffinity,Me as serializeItemDocument,AO as summarizeAgentModelProvenance,nd as summarizeAgentProvenance,oF as update,ji as validateReadOutputOptions,pw as writeAuthorEnvironment};
|
|
40
|
+
`}function MR(e){return e.map((t,n)=>({...t,sequence:n+1}))}function ph(e,t,n){Mc(e,"base");let r=Mc(t,"ours"),s=Mc(n,"theirs"),o=Math.min(r.length,s.length),i=0;for(;i<o&&r[i].eventId===s[i].eventId;)i+=1;if(i===r.length&&i===s.length)return{merged:Bo(r),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===s.length)return{merged:Bo(r),strategy:"fast_forward_ours",common_entries:i,entries_from_ours:r.length-i,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===r.length)return{merged:Bo(s),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:s.length-i,entries_total:s.length,reanchored:!1};let a=r.slice(i),c=new Set(a.map(f=>f.eventId)),m=s.slice(i).filter(f=>!c.has(f.eventId)),u=[...a,...m].sort((f,_)=>{if(f.timestamp!==void 0&&_.timestamp!==void 0){let g=yn(f.timestamp,_.timestamp);if(g!==0)return g}else{if(f.timestamp===void 0&&_.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let h=c.has(f.eventId),y=c.has(_.eventId);return h!==y?Number(y)-Number(h):0}),p=MR([...r.slice(0,i),...u]);return{merged:Bo(p),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:m.length,entries_total:p.length,reanchored:!0}}var DR=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],UR=["updated_at"];function sn(e,t){return J(e??null)===J(t??null)}function GR(e,t,n){let r=u=>Array.isArray(u)?u:[],s=new Set(r(e).map(u=>J(u))),o=r(t),i=new Set(o.map(u=>J(u))),a=r(n),c=new Set(a.map(u=>J(u))),m=o.filter(u=>{let p=J(u);return!s.has(p)||c.has(p)});for(let u of a){let p=J(u);!i.has(p)&&!s.has(p)&&m.push(u)}return m}function jR(e,t){return yn(String(e),String(t))>=0?e:t}function fh(e,t,n,r){return sn(t,n)?{value:t,from_theirs:!1,conflict:!1}:sn(e,t)?{value:n,from_theirs:!0,conflict:!1}:sn(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function _h(e,t,n,r,s){let o=fh(e,t,n,r);if(!o.conflict||s==="preferred_side")return o;let i=J(n).localeCompare(J(t))<0;return{value:i?n:t,from_theirs:i,conflict:!0}}function Dc(e){return{...e.metadata}}function Uc(e,t,n){try{return We(_u(e,n),n)}catch(r){throw new l(`Item merge input (${t}) is not a readable item document: ${String(r)}`,d.GENERIC_FAILURE)}}function qR(e,t,n,r,s){let o=new Set(DR),i=new Set(UR),a=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((m,u)=>m.localeCompare(u)),c={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let m of a){let u=e[m],p=t[m],f=n[m];if(o.has(m)){let h=GR(u,p,f);c.merged[m]=h,sn(h,p)||c.unionFields.push(m);continue}if(i.has(m)){c.merged[m]=jR(p,f);continue}let _=_h(u,p,f,r,s);_.value!==void 0&&(c.merged[m]=_.value),_.conflict?(c.conflictFields.push(m),c.conflictDecisions.push({field:m,base:u,ours:p,theirs:f,retained:_.value,discarded:_.from_theirs?p:f})):_.from_theirs&&c.fieldsFromTheirs.push(m)}return c}function hh(e,t,n,r={}){let s=r.preferred??"ours",o=r.conflictResolution??"preferred_side",i=e.trim().length>0,a=Uc(t,"ours",r),c=Uc(n,"theirs",r),m=i?Uc(e,"base",r):a,u=i?Dc(m):{},p=Dc(a),f=Dc(c),{merged:_,conflictFields:h,fieldsFromTheirs:y,unionFields:g,conflictDecisions:b}=qR(u,p,f,s,o),v=_h(i?m.body:"",a.body,c.body,s,o);return v.conflict?(h.push("body"),b.push({field:"body",base:i?m.body:"",ours:a.body,theirs:c.body,retained:v.value,discarded:v.from_theirs?a.body:c.body})):v.from_theirs&&y.push("body"),{merged:je({metadata:_,body:v.value},r),conflict_fields:h,fields_from_theirs:y,union_fields:g,conflict_decisions:b,requested_preference:s,conflict_resolution:o}}function Gc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jc(e,t){let n=Ts(e);if(n)throw new l(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,d.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new l(`JSON merge input (${t}) is not valid JSON.`,d.GENERIC_FAILURE)}}function KR(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=m=>{let u=new Map;for(let p of m){let f=J(p);u.set(f,(u.get(f)??0)+1)}return u},s=r(e),o=r(t),i=r(n);for(let[m,u]of s)if((o.get(m)??0)<u||(i.get(m)??0)<u)return null;let a=new Map(o),c=[];for(let m of n){let u=J(m),p=a.get(u)??0;p>0?a.set(u,p-1):c.push(m)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function zR(e,t,n,r,s,o,i){if(!Gc(t)||!Gc(n))return null;let a=Gc(e)?e:{},c={},m=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,p)=>u.localeCompare(p));for(let u of m){let p=s.length>0?`${s}.${u}`:u,f=BR(a,t,n,u,r,p,o,i);f!==void 0&&(c[u]=f)}return c}function gh(e,t,n,r,s,o,i){if(sn(t,n))return t;let a=KR(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(s),a.merged;let c=zR(e,t,n,r,s,o,i);if(c!==null)return c;let m=fh(e,t,n,r);return m.conflict?o.push(s):m.from_theirs&&i.push(s),m.value}function BR(e,t,n,r,s,o,i,a){let c=Object.prototype.hasOwnProperty.call(t,r),m=Object.prototype.hasOwnProperty.call(n,r),u=Object.prototype.hasOwnProperty.call(e,r);if(c&&m)return gh(e[r],t[r],n[r],s,o,i,a);if(c){if(u&&sn(e[r],t[r])){a.push(o);return}return u?(i.push(o),s==="theirs"?void 0:t[r]):t[r]}if(!(u&&sn(e[r],n[r])))return u?(i.push(o),s==="theirs"?n[r]:void 0):(a.push(o),n[r])}function yh(e,t,n,r={}){let s=r.preferred??"ours",o=jc(e,"base"),i=jc(t,"ours"),a=jc(n,"theirs"),c=[],m=[],u=gh(o,i,a,s,"",c,m);return{merged:`${JSON.stringify(u??null,null,2)}
|
|
41
|
+
`,conflict_paths:c,paths_from_theirs:m,preferred: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]="8d79e3a4-6104-5855-837f-69a041b87b27")}catch{}})();var bh=["item","history","relationship","json"];function YR(e){let t=e.trim().toLowerCase();if(bh.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${bh.join(", ")}.`,d.USAGE)}function JR(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new l(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,d.USAGE)}async function qc(e,t){try{return await HR(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function XR(e){let t=T(process.cwd(),e.path);return await k(C(t))?A(t):null}function QR(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function wh(e,t){let n=YR(e.artifact),r=JR(e.prefer),s=WR.resolve(e.outputPath??e.oursPath),[o,i,a]=await Promise.all([qc(e.basePath,"base"),qc(e.oursPath,"ours"),qc(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=uh(o,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 _=ph(o,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 XR(t),h=hh(o,i,a,{format:QR(e.itemPath??s,_),schema:_?.schema,extensionFieldNames:bt(I()),preferred:r,conflictResolution:"stable_value_order"});c=h.merged,u.push(...h.conflict_fields),p.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0&&(m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,decisions:h.conflict_decisions})}else{let _=yh(o,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await VR(s,c,"utf8"),m!==void 0){let _=await Lp(m);_!==null&&(p.receipt=er(_))}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 direction-independent stable value. ${_} 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:s,requested_preference:r,conflicts:u,...p,guidance:f,generated_at:S()}}import Sh from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de9b7f82-0f51-599d-b1fa-2d54e3acbdbc")}catch{}})();function vh(e,t){return t==="body"?e.body:e.metadata[t]}function Kc(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(s=>{let o=t.findIndex((i,a)=>!r.has(a)&&Kc(s,i));return o<0?!1:(r.add(o),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,s])=>Object.hasOwn(n,r)&&Kc(s,n[r]))}function kh(e,t){let n=new Set(t),r=[];for(let s=e.length-1;s>=0&&n.size>0;s-=1){let o=e[s],i=new Set;for(let c of vu(o.patch))i.add(Ds(c.path)),c.from&&i.add(Ds(c.from));let a=[...n].filter(c=>i.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:s+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,m)=>c.localeCompare(m))})}}return r.reverse()}function ZR(e,t,n){let r=Sh.compare(t,n);if(r.length===0)return;let s=new Set;for(let h of r)s.add(Ds(h.path));let o=new Set([...s].filter(h=>Kc(vh(t,h),vh(n,h)))),i=new Set([...s].filter(h=>!o.has(h))),a=kh(e,i),c=kh(e,o),m=[...s].sort((h,y)=>h.localeCompare(y)),u=[...i].sort((h,y)=>h.localeCompare(y)),p=[...o].sort((h,y)=>h.localeCompare(y)),f=[...new Set(a.map(h=>h.author))].sort((h,y)=>h.localeCompare(y)),_=[...new Set(c.map(h=>h.author))].sort((h,y)=>h.localeCompare(y));return{reconciled_field_count:s.size,reconciled_fields:m,reverted_field_count:i.size,reverted_fields:u,discarded_events:a,discarded_authors:f,preserved_field_count:o.size,preserved_fields:p,preserved_events:c,preserved_authors:_,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function eI(e,t,n,r){let s=e.located?.itemPath??null,o=e.located?await K(e.located,{schema:t.schema}):null;if(!o)return{currentItemReplay:null,currentItemPath:s,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let i=Bt(o.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:i,currentItemPath:s,matchedChainBefore:Ne(i,r)===a,currentItemRawBeforeLock:o.raw,loadedItem:o}}function tI(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function nI(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:S(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Sh.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Ne(e.finalReplay,e.itemHashVersion),after_hash:Ne(n,e.itemHashVersion),message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function rI(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function sI(e){return Ps({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Os({historyPath:e.historyPath,nextHistoryRaw:st(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function hr(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await Ns(r,e,s,o.type_to_folder);if(!await k(i.historyPath))throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let a=await q(i.historyPath),c=await Et(i.historyPath,i.id);if(c.length===0)throw new l(`No history entries exist for ${i.id}; nothing to repair.`,d.USAGE);let m=bn(c),u=ku(c),p=t.normalizeProvenance?Pp(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=Su(p.entries),_=new Set(p.entries.map(ce=>ce.item_hash_version).filter(ce=>ce!==void 0)),h=Cs(p.entries,f),y=await eI(i,s,c,f),g=h.finalDocument,b=y.currentItemReplay!==null&&Ne(g,f)!==Ne(y.currentItemReplay,f),v=b&&y.currentItemReplay?ZR(h.entries,g,y.currentItemReplay):void 0,E=[h.entriesRehashed>0,h.entriesPatchRepaired>0,b,t.forceAuditEntry===!0,p.receipt.changed].some(Boolean),N=R(t.author,s.author_default),O=!!t.dryRun,j=tI({message:t.message,entriesRehashed:h.entriesRehashed,entriesPatchRepaired:h.entriesPatchRepaired,reconcileNeeded:b}),{rewrittenEntries:$,auditEntryAdded:xe}=nI({reanchorEntries:h.entries,changed:E,reconcileNeeded:b,currentItemReplay:y.currentItemReplay,finalReplay:g,author:N,message:j,auditOperation:t.auditOperation??"history_repair",auditContext:p.receipt.changed?{...t.auditContext,provenance_normalization:p.receipt}:t.auditContext,itemHashVersion:f,explicitItemHashVersion:h.explicitItemHashVersion}),te=bn($);if(!te.ok)throw new l(`history-repair produced an invalid rewritten chain (${te.errors.join(", ")}).`,d.GENERIC_FAILURE);let _e=rI(E,h.skippedOps,v);return E&&!O&&_e.push(...await sI({pmRoot:r,subject:i,settings:s,typeRegistry:o,historyRawBeforeLock:a,currentItemRawBeforeLock:y.currentItemRawBeforeLock,author:N,force:t.force,loadedItem:y.loadedItem,historyPath:i.historyPath,rewrittenEntries:$})),{id:i.id,dry_run:O,changed:E,history:{path:i.historyPath,entries_scanned:c.length,chain_drift_before:!m.ok,entries_rehashed:h.entriesRehashed,entries_patch_repaired:h.entriesPatchRepaired,converted_replace_to_add:h.convertedReplaceToAdd,skipped_ops:h.skippedOps,reconciled_with_item:b,audit_entry_added:xe,verify_ok:te.ok,verify_errors:te.errors,item_hash_version_before:u.item_hash_version??null,item_hash_version_after:f,version_disposition:_.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:y.currentItemPath!==null,path:y.currentItemPath,matched_chain_before:y.matchedChainBefore},provenance_normalization:{requested:t.normalizeProvenance===!0,...p.receipt},...v?{reconciliation:v}:{},warnings:[...new Set(_e)].sort((ce,Qe)=>ce.localeCompare(Qe)),generated_at:S()}}function Eh(e,t){if(t&&e!==void 0)throw new l("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",d.USAGE);if(!t&&e===void 0)throw new l("history-repair: provide an item <id> or pass --all to repair every drifted stream.",d.USAGE)}async function Ho(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=x(r,I()),o=[],i=await Rs(n,r.item_format,s.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await rp(n,i),c=e.normalizeProvenance?await Np(n):[],m=[...new Set([...a.driftedItems,...c])].sort((_,h)=>_.localeCompare(h)),u=[],p=[],f={repaired:0,skipped_clean:0,failed:0};for(let _ of m)try{let h=await hr(_,{...e,auditContext:e.auditContextById?.[_],auditContextById:void 0},t),y=h.changed?"repaired":"skipped_clean";f[y]+=1,p.push(...h.warnings.map(g=>`${_}:${g}`)),u.push({id:_,outcome:y,entries_rehashed:h.history.entries_rehashed,entries_patch_repaired:h.history.entries_patch_repaired,reconciled_with_item:h.history.reconciled_with_item,...h.reconciliation?{reconciliation:h.reconciliation}:{},warnings:h.warnings})}catch(h){f.failed+=1,u.push({id:_,outcome:"failed",error:h instanceof Error?h.message:String(h)})}return e.dryRun||await bu(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:i.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:u,totals:f,warnings:[...new Set([...o,...p])].sort((_,h)=>_.localeCompare(h)),generated_at: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]="c5620467-6c8c-5702-b742-57fba9e302c5")}catch{}})();async function Th(e,t){let n=e.dryRun===!0,r=await Fp(process.cwd(),{includeLossless:!0}),{pendingDecisions:s}=$p(r);if(!n&&e.force!==!0&&s.length>0)throw new l(`Merge reconciliation would accept ${s.length} receipt(s) containing discarded scalar values. Review pm merge report and rerun with --force only after deciding which values to retain or re-apply.`,d.CONFLICT,{code:"merge_reconcile_discards_require_acceptance",required:"Explicitly review every discarded field before accepting reconciliation.",nextSteps:s.map(g=>`Review receipt ${g.id} for ${g.item_id}: ${g.decisions.map(b=>b.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let o=r.reduce((g,b)=>((g[b.item_id]??=[]).push(b),g),{}),i=Object.fromEntries(Object.entries(o).map(([g,b])=>[g,{merge:{receipts:b.map(er)}}])),a=await Ho({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:i},t),c=new Set(a.streams.map(g=>g.id)),m=Object.keys(o).filter(g=>!c.has(g));(await Promise.allSettled(m.map(g=>hr(g,{dryRun:n,author:e.author??t.author,message:e.message??"record field-aware branch merge provenance",force:e.force,auditOperation:"merge_reconcile",auditContext:i[g],forceAuditEntry:!0},t)))).forEach((g,b)=>{let v=m[b];if(g.status==="fulfilled"){let E=g.value.changed?"repaired":"skipped_clean";a.streams.push({id:v,outcome:E,entries_rehashed:g.value.history.entries_rehashed,entries_patch_repaired:g.value.history.entries_patch_repaired,reconciled_with_item:g.value.history.reconciled_with_item,warnings:g.value.warnings}),a.totals[E]+=1}else a.streams.push({id:v,outcome:"failed",error:g.reason instanceof Error?g.reason.message:String(g.reason)}),a.totals.failed+=1});let p=0;!n&&a.totals.failed===0&&(await Promise.all(r.map(g=>Mp(process.cwd(),g))),p=r.length);let f=await Qs({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),_=f.checks.every(g=>g.status==="ok"),h=a.totals.failed===0&&_,y=n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.","No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:h?["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.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:h,dry_run:n,repair:a,receipts:{pending_before:r.length,reconciled:p,summaries:r.map(er)},validation:f,guidance:y,generated_at:f.generated_at}}import{createHash as oI}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]="e8cd5790-eacf-5ef7-bc0a-11ea3fe17d2d")}catch{}})();var Rh=1,Ih=/^[A-Za-z0-9_-]+$/,iI=100,Ah=1e3;var zG=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,s)=>r.localeCompare(s));return n.length===0?void 0:n}function aI(e){return oI("sha256").update(J({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 Ch(e,t){let n={version:Rh,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 cI(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Rh,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 dI(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Ih.test(n))throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new l("Invalid mutation event cursor.",d.USAGE,{code:"invalid_event_cursor"})}if(!cI(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function lI(e){let t=e??iI;if(!Number.isSafeInteger(t)||t<0||t>Ah)throw new l(`Mutation event limit must be an integer from 0 to ${Ah}.`,d.USAGE,{code:"invalid_event_limit"});return t}function mI(e,t){let n=e?.trim();if(!n)return{};if(Ih.test(n))return{cursor:dI(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new l("Mutation event --since must be an event cursor or ISO timestamp.",d.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function uI(e,t){let n=await ta(e,t);if(n===null){if(!await hu(e))return{...await gu(e,t),source:"authoritative_history"};n=await ta(e,t)}if(n===null)throw new l("Mutation event index could not be opened after rebuild.",d.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function pI(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Vo(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=lI(e.limit),r=pI(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new l("Mutation event projections are mutually exclusive. Use --provenance or --full.",d.USAGE);let s=await A(t),o=s.agent_identity.identity_vocabulary,i=Hu(s.agent_identity.harness_signals),a=Vu({provenance:e.provenanceFilter},i),c=He(e.harness),m=aI(e),{cursor:u,sinceTimestamp:p}=mI(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(o.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:He(e.agentInstance),provenance:[...a].map(([y,g])=>({dimension:y,values:[...g]})),stream_ids:He(e.item),limit:n},_=await uI(t,f),h=_.events.map(y=>({...r==="row"?{cursor:Ch(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:Wu(y.entry,o,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:h,count:h.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:Ch(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Yu(_.events.map(y=>y.entry),o,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]="32223457-5f57-5049-99cf-c5d766413fb6")}catch{}})();var fI="1h",_I="now",hI="+1d";function Nt(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function xh(e,t,n){return{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}}async function Oh(e,t,n,r){let s=xh(e,t,n),o=[];return Nt(o,"start",n.start??_I),n.end!==void 0?Nt(o,"end",n.end):Nt(o,"duration",n.duration??fI),Nt(o,"location",n.location),Nt(o,"timezone",n.timezone),n.allDay===!0&&Nt(o,"all_day","true"),s.event=[o.join(",")],xt(s,r)}function Ph(e,t,n){return Oh("Meeting",e,t,n)}function Nh(e,t,n){return Oh("Event",e,t,n)}function Lh(e,t,n){let r=xh("Reminder",e,t),s=[];return Nt(s,"at",t.at??hI),Nt(s,"text",t.text??e),r.reminder=[s.join(",")],xt(r,n)}import yr from"node:crypto";import{cp as $h,lstat as kI,mkdir as on,readFile as $n,readdir as Bc,rename as Uh,rm as Vc,writeFile as Yo}from"node:fs/promises";import L from"node:path";import{constants as Lt}from"node:os";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1c74b5a9-67b8-597c-98de-a4487691081f")}catch{}})();var Fh=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),gI=/^[a-z][a-z0-9_]{0,63}$/u,yI=new Map([[Lt.errno.EACCES,"EACCES"],[Lt.errno.EDQUOT,"EDQUOT"],[Lt.errno.EMFILE,"EMFILE"],[Lt.errno.ENFILE,"ENFILE"],[Lt.errno.ENOMEM,"ENOMEM"],[Lt.errno.ENOSPC,"ENOSPC"],[Lt.errno.EPERM,"EPERM"],[Lt.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),bI={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function wI(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&Fh.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:yI.get(Math.abs(t.errno))??null}function vI(e,t,n={}){let r=wI(e);if(r===null)return null;if(!gI.test(t))throw new l("Host environment operation labels must be bounded identifiers.",d.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let s=Fh.get(r);return new l(`Host filesystem operation ${t} ${s.summary}.`,d.GENERIC_FAILURE,{code:n.codes?.[s.category]??bI[s.category].code,reason:r,required:s.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[s.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function Wo(e,t,n={}){try{return await t()}catch(r){throw vI(r,e,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]="2580e043-8675-5070-b57e-30cae333228c")}catch{}})();var Gh="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var jh=L.join("runtime","workspace-snapshots"),SI=new Set(["checkpoints","locks","runtime","search","transactions"]),EI=/^[a-z0-9][a-z0-9._-]*$/,gr="sdk-workspace-transaction",zc={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},qh={renameEntry:Uh,removeEntry:async e=>{await Vc(e,{recursive:!0,force:!0})}},Hc=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 $n(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!==gr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await ue(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
|
|
42
|
+
`)}};async function Kh(e,t=""){let n=await Bc(L.join(e,t),{withFileTypes:!0}),r=[];for(let s of n.sort((o,i)=>o.name.localeCompare(i.name))){if(t.length===0&&SI.has(s.name))continue;let o=L.posix.join(t.replaceAll(L.sep,"/"),s.name);if(s.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${o}`);if(s.isDirectory())r.push(...await Kh(e,o));else if(s.isFile())r.push(o);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${o}`)}return r}async function zh(e){let t=await Kh(e),n=yr.createHash("sha256"),r=[],s=0;for(let i of t){let a=await $n(L.join(e,i));r.push(a),s+=a.byteLength,n.update(i),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let o=n.digest("hex");return{manifest:{schema:Gh,fingerprint:o,files:t,bytes:s},contents:r}}function Mh(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
|
|
43
|
+
`).filter(t=>t.trim().length>0).length}async function TI(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let s=t.slice(r,r+32),o=await Promise.all(s.map(async i=>[i,await $n(L.join(e,i))]));for(let[i,a]of o)n.set(i,a)}return n}function Wc(e){if(!EI.test(e))throw new l("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",d.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 Bh(e,t){return Wo(`workspace_snapshot_${e}`,t,{codes:{capacity:zc.capacity.code,permission:zc.permission.code,resource:zc.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 an(e){return L.join(e,jh)}function Hh(e){return new l(`Unknown workspace snapshot: ${e}`,d.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 Vh(e,t){try{return JSON.parse(await $n(e,"utf8"))}catch(n){throw wt(n)?Hh(t):n}}async function Dh(e,t,n){try{await Vc(e,{recursive:n})}catch(r){throw wt(r)?Hh(t):r}}async function AI(e,t,n=qh){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 CI(e,t,n,r,s){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await s?.()}catch(o){throw await r.renameEntry(n,t),await r.removeEntry(e),o}await r.removeEntry(n)}async function RI(e,t){return Wc(t),/^[a-f0-9]{64}$/.test(t)?t:(await Vh(L.join(an(e),"refs",`${t}.json`),t)).fingerprint}async function Yc(e,t={}){if(t.name!==void 0&&(Wc(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new l("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",d.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 zh(e),s=an(e),o=L.join(s,"objects",n.fingerprint),i=!1;try{i=(await kI(o)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&wt(a)))throw a}if(!i){let a=L.join(s,"objects",`.create-${process.pid}-${yr.randomUUID()}`);await Bh("create_object",async()=>{await on(L.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=L.join(a,"files",m);await on(L.dirname(u),{recursive:!0}),await Yo(u,r[c])}await Yo(L.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
|
|
44
|
+
`,"utf8"),await on(L.dirname(o),{recursive:!0})}),i=await AI(a,o)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=L.join(s,"refs");await on(c,{recursive:!0});let m=L.join(c,`.ref-${process.pid}-${yr.randomUUID()}`);await Yo(m,`${JSON.stringify(a,null,2)}
|
|
45
|
+
`,"utf8"),await Uh(m,L.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function br(e,t){let n=await RI(e,t),r=await Vh(L.join(an(e),"objects",n,"manifest.json"),t);if(r.schema!==Gh||r.fingerprint!==n)throw new l(`Snapshot manifest identity mismatch: ${t}`,d.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 Jc(e){let t=an(e),n=await Bc(L.join(t,"objects")).catch(s=>{if(s instanceof Error&&"code"in s&&wt(s))return[];throw s}),r=await Bc(L.join(t,"refs")).catch(s=>{if(s instanceof Error&&"code"in s&&wt(s))return[];throw s});return{objects:await Promise.all(n.filter(s=>/^[a-f0-9]{64}$/.test(s)).sort().map(s=>br(e,s))),references:await Promise.all(r.filter(s=>s.endsWith(".json")).sort().map(async s=>JSON.parse(await $n(L.join(t,"refs",s),"utf8"))))}}async function Xc(e,t){let n=await br(e,t),{manifest:r,contents:s}=await zh(e),o=new Map(r.files.map((p,f)=>[p,s[f]])),i=await TI(L.join(an(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=o.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=Mh(o.get(p)),_=Mh(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 Wh(e,t,n={}){if(n.force!==!0)throw new l("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",d.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",s=n.lockTtlSeconds??60,o=n.lockWaitMs??5e3,i=await Pe(e,gr,s,r,!1,!1,o),a=new Hc(Fr(e,gr),r,s);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await Xc(e,t),f=await br(e,t),_=await Yc(e),h=f.fingerprint,y=an(e),g=L.join(y,"objects",h,"files"),b=L.dirname(e),v=L.basename(e);c=L.join(b,`.${v}.restore-${yr.randomUUID()}`);let E=L.join(b,`.${v}.backup-${yr.randomUUID()}`);await Bh("restore_stage",async()=>{await on(c,{recursive:!0}),await $h(g,c,{recursive:!0,force:!1}),await on(L.join(c,"runtime"),{recursive:!0}),await $h(y,L.join(c,jh),{recursive:!0,force:!1})});let N=await Eu({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${h}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:h,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:s,lockWaitMs:o}),O=L.relative(c,N.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let j=Fr(c,gr);return await on(L.dirname(j),{recursive:!0}),await Yo(j,await $n(Fr(e,gr)),{flag:"wx"}),m=!0,await CI(c,e,E,qh,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:O,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([Vc(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function Yh(e,t){Wc(t);let n=an(e);if(!/^[a-f0-9]{64}$/.test(t))return await Dh(L.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Jc(e);if(r.some(s=>s.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Dh(L.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]="0492d773-2af2-5072-8164-9f8aab536191")}catch{}})();function wr(e){return{...e.args,...e.options}}function lt(e,t){let n=w(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Mn(e){return typeof e=="string"?[e]:ye(e)}function Jh(e){return mh(wr(e),e.global)}function Xh(e){let t=wr(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new l("Mutation event cursor mode must be batch or row.",d.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Vo({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Mn(t.type),author:Mn(t.author),item:Mn(t.item),limit:t.limit===void 0?void 0:Fe(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:Mn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Mn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Mn(t.provenanceFilter)}})}function Qh(e){let t=wr(e),n=lt(t,"subcommand");if(n==="install")return fp({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return Th({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return Dp({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return wh({artifact:lt(t,"artifact"),basePath:lt(t,"basePath"),oursPath:lt(t,"oursPath"),theirsPath:lt(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw Te({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Zh(e){let t=wr(e),n=lt(t,"subcommand");if(n!=="snapshot")throw Te({command_path:"workspace",token:n,allowed:["snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??lt(t,"snapshot_action"),s=T(process.cwd(),e.global.path);if(r==="create")return Yc(s,{name:w(t,"name")});if(r==="list")return Jc(s);let o=lt(t,"target");if(r==="inspect")return br(s,o);if(r==="delete")return Yh(s,o);if(r==="restore")return t.dryRun===!0?Xc(s,o):Wh(s,o,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Fe(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Fe(t.lockWaitMs,"lockWaitMs")});throw Te({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function Jo(e){let t=wr(e),n=lt(t,"title");return e.action==="meet"?Ph(n,t,e.global):e.action==="event"?Nh(n,t,e.global):Lh(n,t,e.global)}import jI from"node:path";import II from"node:fs/promises";import eg 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]="f232e106-54f4-572e-8f6e-054f52290267")}catch{}})();var xI="templates",OI=".json",PI=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,NI=ys.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),LI=new Set(NI);function FI(e){let t=e.trim();if(!PI.test(t))throw new l(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,d.USAGE);return t}function tg(e){return eg.join(e,xI)}function ng(e,t){return eg.join(tg(e),`${t}${OI}`)}async function $I(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function rg(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function MI(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(LI.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let s=r.filter(o=>typeof o=="string");s.length>0&&(t[n]=s);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(s=>typeof s=="string")&&(t[n]=[...r])}return rg(t)}function DI(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new l(`Template "${t}" has invalid options payload.`,d.GENERIC_FAILURE);let n=e,r={};for(let[s,o]of Object.entries(n)){let i=s.trim();if(i.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof o=="string"){r[i]=o;continue}if(Array.isArray(o)&&o.every(a=>typeof a=="string")){r[i]=[...o];continue}throw new l(`Template "${t}" contains invalid value for option "${i}".`,d.GENERIC_FAILURE)}return rg(r)}function UI(e,t){let n;try{n=JSON.parse(e)}catch{throw new l(`Template "${t}" contains invalid JSON.`,d.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new l(`Template "${t}" has invalid document shape.`,d.GENERIC_FAILURE);let r=n,s=DI(r.options,t),o=S();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:o,updated_at:typeof r.updated_at=="string"?r.updated_at:o,options:s}}async function GI(e,t){let n=await q(ng(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return UI(n,t)}async function Qc(e,t,n){let r=T(process.cwd(),n.path);await $I(r);let s=FI(e),o=MI(t);if(Object.keys(o).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let i=S(),a=ng(r,s),c=i;await k(a)&&(c=(await GI(r,s)).created_at);let m={name:s,created_at:c,updated_at:i,options:o},u=await A(r);return await II.mkdir(tg(r),{recursive:!0}),await At({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
|
|
46
|
+
`,op:"templates:save",author:R(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]="a1e34cfb-3d4e-5b79-8585-3162e71e574c")}catch{}})();var ag=["list","show","apply","lint"],qI="schema-types",KI="schema-statuses",zI="schema-fields";function Xo(){let e=I();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function cg(){let{profiles:e,warnings:t}=ym(Xo());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:Sm(n.definition)})),warnings:t,generated_at:S()}}function dg(e){let t;try{t=ps(e,Xo())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...Em(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function lg(e){let t;try{t=ps(e,Xo())}catch(s){throw new l(s instanceof Error?s.message:String(s),d.USAGE)}let{resolved:n}=t,r=jm(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:S()}}function BI(e,t){return jI.join(e,"templates",`${t}.json`)}async function HI(e,t){let n=await q(BI(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let s=r.options;if(s!==null&&typeof s=="object"&&!Array.isArray(s))return s}}catch{}}async function sg(e,t,n,r){let s=new Map;for(let o of r.templates){let i=await HI(e,o.name);i!==void 0&&s.set(o.name,i)}return{typesRaw:await q(rt(e,t.files.types,nt.types)),statusesRaw:await q(rt(e,t.files.statuses,nt.statuses)),fieldsRaw:await q(rt(e,t.files.fields,nt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:s,installedPackages:new Set}}function Dn(e){let t=[],n=[],r=[];for(let s of e)(s.status==="add"?t:s.status==="update"?n:r).push(s.key);return{added:t,updated:n,unchanged:r}}function og(e,t,n,r,s){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Dn(t.types.changes),statuses:Dn(t.statuses.changes),fields:Dn(t.fields.changes),workflows:Dn(t.workflows.changes.map(o=>({key:o.type,status:o.status}))),config:Dn(t.config.changes),templates:Dn(t.templates.changes.map(o=>({key:o.name,status:o.status}))),packages:t.packages,warnings:[...new Set(s)].sort((o,i)=>o.localeCompare(i)),generated_at:S()}}async function VI(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function WI(e){try{let t=ps(e,Xo());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function mg(e,t,n){let r=T(process.cwd(),n.path);await VI(r);let s=WI(e),o=s.profile,i=s.warnings,a=t.dryRun===!0,c=await A(r),m=fs(c.schema);if(a){let b=await sg(r,m,c,o),v=ig(o,b);return og(o,v,!1,!0,[...i])}let u=R(t.author,c.author_default),p=Au(c),f=!!t.force,_=[...i],h=[],y=async b=>{h.push(await Pe(r,b,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await y(qI),await y(KI),await y(zI);let b=await sg(r,m,c,o);if(g=ig(o,b),g.types.changed){let v=rt(r,m.files.types,nt.types);await At({pmRoot:r,filePath:v,raw:us(g.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let E=new Set(o.types.map(O=>um(O).name)),N=g.types.file.definitions.filter(O=>E.has(O.name));await wp(r,N,_,"profile:apply-type-folder"),_.push(...await z({path:v,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let v=rt(r,m.files.statuses,nt.statuses);await At({pmRoot:r,filePath:v,raw:km(g.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let v=rt(r,m.files.fields,nt.fields);await At({pmRoot:r,filePath:v,raw:bm(g.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await z({path:v,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let v of g.config.changes){if(v.status==="unchanged")continue;let E=hs(v.key);E!==void 0&&gs(c,E,v.value)}c.schema.type_workflows=g.workflows.result,await Ee(r,c,"profile:apply-config")}for(let v of g.templates.changes)v.status!=="unchanged"&&await Qc(v.name,{...v.options},n)}finally{for(let b of h.reverse())try{await b()}catch{}}return og(o,g,g.changed,!1,_)}function ig(e,t){try{return qm(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import pg from"node:fs/promises";import fg 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]="7e0f84f6-9528-55c5-8976-6f85cd920486")}catch{}})();function YI(e,t,n){let r=new Set,s=[];for(let o of e){let i=o.trim();if(i.length===0||r.has(i))continue;r.add(i);let a=t.get(i);if(a===void 0){s.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){s.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}s.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return s}function JI(e,t){let n=[...e].sort((s,o)=>o.entries-s.entries||s.id.localeCompare(o.id)),r=[];for(let s of n){if(t.scope==="closed"&&s.bucket!=="closed"){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(s.entries<=t.minEntries){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&s.entries<=t.allOver){r.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:s.id,entries:s.entries,selected:!0,skip_reason:null})}return r}function ug(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return YI(t.ids,n,t.minEntries)}return JI(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]="c6609492-75a9-5111-b9b3-1b81908f3084")}catch{}})();function XI(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(n)){let o=Number.parseInt(n,10);if(!Number.isSafeInteger(o)||o<1||o>t.length+1)throw new l(`history-compact --before version must be between 1 and ${t.length+1}.`,d.USAGE);let i=Math.max(0,Math.min(t.length,o-1));return{kind:"version",raw:n,compactCount:i,retainedCount:t.length-i}}let r=Date.parse(n);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let s=0;for(let[o,i]of t.entries()){let a=Date.parse(i.ts);if(!Number.isFinite(a))throw new l(`History for this item contains invalid timestamp at entry ${o+1}.`,d.GENERIC_FAILURE);if(a>=r)break;s+=1}return{kind:"timestamp",raw:n,compactCount:s,retainedCount:t.length-s}}function QI(e,t){let n=As(),r=As();for(let s=0;s<e.length;s+=1){let o=e[s];if(Ne(n)!==o.before_hash)throw new l(`history-compact detected before-hash drift at entry ${s+1}; run pm history-repair first.`,d.CONFLICT);if(n=xs(n,o.patch,s+1,o.op),Ne(n)!==o.after_hash)throw new l(`history-compact detected after-hash drift at entry ${s+1}; run pm history-repair first.`,d.CONFLICT);s+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function ZI(e,t,n){let r=structuredClone(t),s=[];for(let[o,i]of e.entries()){let a=Ne(r);r=xs(r,i.patch,n+o+1,i.op),s.push({...i,before_hash:a,after_hash:Ne(r)})}return{entries:s,finalReplay:r}}async function ex(e,t,n){let r=e.located?await K(e.located,{schema:t.schema}):null;return r?{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:Ne(Bt(r.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function tx(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 nx(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 rx(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=QI(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),s=ZI(r,t,e.boundary.compactCount),i=[qe({nowIso:S(),author:e.author,op:"history_compact_baseline",before:zt(As()),after:zt(t),message:nx(e.boundary)}),...s.entries];return e.dryRun||i.push(qe({nowIso:S(),author:e.author,op:"history_compact",before:zt(n),after:zt(n),message:tx(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function sx(e){return Ps({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-compact",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Os({historyPath:e.historyPath,nextHistoryRaw:st(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>z({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function Zc(e,t,n){let r=T(process.cwd(),n.path);if(!await k(C(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,d.NOT_FOUND);let s=await A(r),o=x(s,I()),i=await Ns(r,e,s,o.type_to_folder),a=i.historyPath,c=await q(a);if(c===null)throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let m=await Et(a,i.id);if(m.length===0)throw new l(`No history entries exist for ${i.id}; nothing to compact.`,d.USAGE);let u=bn(m);if(!u.ok)throw new l(`history-compact requires a valid history chain (${u.errors.join(", ")}). Run pm history-repair ${i.id} first.`,d.CONFLICT);let p=XI(t.before,m),f=p.compactCount>0,_=!!t.dryRun,h=R(t.author,s.author_default),y=[];f||y.push("history_compact_noop_before_boundary");let g=await ex(i,s,m);g.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:E}=rx({historyEntries:m,boundary:p,changed:f,dryRun:_,author:h,options:t}),N=bn(b);if(!N.ok)throw new l(`history-compact produced an invalid rewritten chain (${N.errors.join(", ")}).`,d.GENERIC_FAILURE);f&&!_&&y.push(...await sx({pmRoot:r,subject:i,settings:s,typeRegistry:o,historyRawBeforeLock:c,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:h,force:t.force,loadedItem:g.loadedItem,historyPath:a,rewrittenEntries:b}));let O=p.retainedCount>0?p.compactCount+1:null;return{id:i.id,dry_run:_,changed:f,compact_boundary:{kind:p.kind,before:p.raw,entries_compacted:p.compactCount,entries_retained:p.retainedCount,first_retained_entry:O},history:{path:a,entries_scanned:m.length,entries_after:b.length,baseline_entry_added:v,audit_entry_added:E,verify_ok:N.ok,verify_errors:N.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:g.matchedChainBefore},warnings:[...new Set(y)].sort((j,$)=>j.localeCompare($)),generated_at:S()}}var ox=3;function _g(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)===0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(n||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(n&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function ix(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function ax(e){let t=M(e.settings.schema),n=Zs(t),r=await oe(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),s=new Map(r.map(m=>[m.id,n.classify(m.status)])),o=fg.join(e.pmRoot,"history"),i=[],a=[];if(!await k(o))return{candidates:i,preselectionErrors:a};let c=(await pg.readdir(o)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=fg.join(o,m),p=m.slice(0,-6);try{let f=await pg.readFile(u,"utf8");await _n({path:u,scope:"project"}),i.push({id:p,entries:ix(f),bucket:s.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 cx(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 Zc(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 hg(e,t){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=x(r,I()),{candidates:o,preselectionErrors:i}=await ax({pmRoot:n,settings:r,typeToFolder:s.type_to_folder}),a=e.ids!==void 0&&e.ids.length>0?"ids":"scan",c=e.minEntries??ox,m=r.history.compact_policy,u=a==="scan"&&e.allOver===void 0&&m.enabled,p=e.allOver??(u?m.max_entries:void 0),f=ug(o,{ids:e.ids,scope:e.scope,minEntries:c,allOver:p}),_=!!e.dryRun,h=[...i],y={streams_considered:o.length+i.length,selected:0,items_compacted:0,items_skipped:0,items_errored:i.length};for(let g of f){let b=await cx({row:g,options:e,dryRun:_,global:t});if(h.push(b.result),!b.selected){y.items_skipped+=1;continue}y.selected+=1,b.compacted&&(y.items_compacted+=1),b.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:_,mode:a,scope:e.scope??null,criteria:{min_entries:c,all_over:p??null,policy_threshold_applied:u},totals:y,results:h,generated_at: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]="f762b5e6-8224-531f-9dd1-f71dc18c3ddf")}catch{}})();function gg(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return Eh(n,t),t?Ho(e.options,e.global):hr(n,e.options,e.global)}function yg(e){let t=e.options.ids,n=Array.isArray(t)?t.map(String).filter(m=>m.trim().length>0):typeof t=="string"?t.split(",").map(m=>m.trim()).filter(Boolean):void 0,r=Fe(e.options.allOver??e.options.all_over,"history-compact allOver"),s=Fe(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),o=w(e.options,"scope"),i=[];e.options.closed===!0&&i.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&i.push("all-streams"),(o==="closed"||o==="all-streams")&&i.push(o);let a=[...new Set(i)];if(a.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let c=a[0];return _g(e.id,{ids:n,allOver:r,scope:c}),e.id!==void 0?Zc(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):hg({ids:n,scope:c,allOver:r,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]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function Qo(e){return _s("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]="08dcee99-5572-5133-b76a-6a50e4e292e7")}catch{}})();async function ed(e,t,n,r){let s=t.trim();if(s.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",d.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 o=T(process.cwd(),r.path),i=M((await A(o)).schema),a=i.open_status,c=Qo(i),m=n.status??a,u=W(m,i)??m;if(u!==a&&u!==c)throw new l(`Reopen target status must be ${a} or ${c}; received ${m}.`,d.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} "${s}" --status ${a}`,suggested_retry_args:["item","reopen",e,s,"--status",a]}});let p=await l_(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,s);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]="55869854-565d-52d2-8dca-b66aade074bb")}catch{}})();function bg(e,t){let n=e.id??w(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function wg(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function vg(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await it(bg(e,r),wg(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function kg(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await ed(bg(e,r),wg(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]="c2ef0de1-bc44-5550-862c-f3929334fbef")}catch{}})();function Sg(e,t,n){let r;if(typeof e.lines=="string")r=Ys(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=Ys(`${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]="90896fb6-ee3e-575d-b103-bbc1a83c6672")}catch{}})();var dx=Bi("list").properties.outputSession,lx={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:{...dx},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Eg={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},ee={type:"string",description:"pm item id, for example pm-abc1."},mx=`Operation name (one of): ${ji.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,ux={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."}},px={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{...Eg,properties:{...Eg.properties,...e},required:t}}var fx=[{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:[...ji],description:mx},id:ee,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."},...lx},["action"])},{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"},...px},["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"},...ux})},{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:ee,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:ee,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:ee,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:ee,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:ee,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:ee,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:ee,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:U({id:ee,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:ee,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. 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:ee,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:U({id:ee,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:U({id:ee,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List or add structured notes on a pm item. Use options.add to append a note; omit it to list existing notes.",inputSchema:U({id:ee,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List or add learnings on a pm item. Use options.add to capture a learning/insight; omit it to list existing learnings.",inputSchema:U({id:ee,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:ee,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:[...Fm]},id:ee,target:ee,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:U({id:ee,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:[...Ei]},description:`Lifecycle roles for add-status: ${Ei.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."}})}],_x={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"},hx=fx.map(e=>{let t=_x[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Bi(t,{properties:n,required:r})}});function Tg(){return hx.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,s)=>r.localeCompare(s)):[];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]="b07d8f62-6c75-52fd-9956-52cec211303c")}catch{}})();var Ag=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"]]]),gx=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],$g=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ei=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"]),vr=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"]),Mg=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"]]),Dg=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"]]),Ug=new Map([...Dg.entries()].flatMap(([e,t])=>mt(t).map(n=>[n,e]))),Gg=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],jg=new Map(Gg.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),yx=10,bx=20,Cg=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["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 work through typed operations."],["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 portable workspace primitives."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),qg=[["init",Tl],["install",Cl],["uninstall",Rl],["explore",Il],["manage",Fl],["describe",xl],["reload",$l],["doctor",Ml],["catalog",Dl],["adopt",Ul],["adopt-all",Ol],["activate",Pl],["deactivate",Nl],["migrate",Ll]],wx=qg.map(([e,t])=>e==="init"?[e,Al]:[e,t]),vx=[...qg.map(([e,t])=>[`extension ${e}`,t]),...wx.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Br],["config",El],["extension",Hr],["package",Bn],["packages",Bn],["install",Gl],["create",Qr],["item mutate",im],["item complete",am],["item reopen",cm],["copy",Zr],["focus",es],["update",ts],["update-many",ns],["upgrade",jl],["calendar",Hn],["cal",Hn],["context",Vn],["ctx",Vn],["get",ss],["search",ds],["eval",lm],["workspace",vt],["workspace snapshot",vt],["workspace snapshot create",vt],["workspace snapshot list",vt],["workspace snapshot inspect",vt],["workspace snapshot restore",vt],["workspace snapshot delete",vt],["next",cs],["aggregate",jr],["deps",is],["graph",as],["guide",os],["reindex",ql],["history",qr],["history-compact",vl],["history-redact",bl],["history-repair",wl],["history-author-acknowledge",Kr],["merge",yl],["schema",kl],["profile",Sl],["plan",zr],["restore",Bl],["delete",Hl],["close",Kl],["close-many",Vr],["append",Wr],["claim",zl],["release",Vl],["start-task",Wl],["pause-task",Yl],["close-task",Jl],["comments",pl],["notes",fl],["learnings",_l],["files",hl],["docs",gl],["test",Zl],["test-all",em],["telemetry",tm],["test-runs",nm],["gc",rm],["stats",Yr],["duplicates",Jr],["validate",sm],["health",Xr],["assurance",om],...mm,["contracts",ls],["completion",ms],["activity",rs],...[...$g].map(e=>[e,Gr])],sd=new Map(vx);function kx(e){let t=Ug.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Rg(e){return Ui.includes(e)?fe(e):e.startsWith("extension-")?fe(`extension ${e.slice(10)}`):e.startsWith("package-")?fe(`package ${e.slice(8)}`):e.startsWith("item-")?fe(`item ${e.slice(5)}`):e.startsWith("test-runs-")?fe(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?fe(`templates ${e.slice(10)}`):ei.has(e)?Dg.get(e)??fe(e):null}function Sx(e,t){return e.command_path===null?!1:mt(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `)||t.startsWith(`${n} `))}function mt(e){return e.split("|").map(t=>fe(t)).filter(t=>t.length>0)}function Ex(e,t){let n=new Set(t),r=new Set;for(let s of e)if(s.command_path)for(let o of mt(s.command_path)){let i=o.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((s,o)=>s.localeCompare(o))}function Zo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function kr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function Tx(e,t){if(!t)return{...e};let r=kr(e).filter(s=>{let o=s.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:r}}function td(e,t){let r=kr(e).filter(s=>{let o=s.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function fe(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Kg(e){return e.replace(/\s+/g,"-")}function Je(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ig(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=Je(r);!s||n.has(s)||(n.add(s),t.push(s))}return t}function nd(e,t,n){n&&(e[t]=!0)}function xg(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 Ax(e){let t=xg(e.long,"long"),n=xg(e.short,"short"),r=t??n;if(!r)return null;let s={flag:r};n&&t&&(s.short=n),nd(s,"required",e.required===!0),nd(s,"repeatable",e.repeatable===!0),nd(s,"list",e.list===!0);let o=Je(e.description);o&&(s.description=o);let i=Je(e.value_name);i&&(s.value_name=i);let a=[Je(e.value_type),Je(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(s.value_type=a),s}function zg(e){let t=new Map;for(let r of e){let s=fe(r.target_command);if(s.length===0)continue;let o=t.get(s)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;o.sourceDedupe.has(i)||(o.sourceDedupe.add(i),o.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=Ax(a);if(!c)continue;let m=`${c.flag}|${c.short??""}`;o.dedupe.has(m)||(o.dedupe.add(m),o.flags.push(c))}t.set(s,o)}let n=new Map;for(let[r,s]of t.entries())n.set(r,{flags:s.flags,sources:s.sources.sort((o,i)=>{let a=o.layer.localeCompare(i.layer);return a!==0?a:(o.name??"").localeCompare(i.name??"")})});return n}function Cx(e){let t=zg(e.flagRegistrations),n=new Map;for(let o of e.commandDefinitions){let i=fe(o.command);if(i.length===0)continue;let a=Je(o.action)??Kg(i),c=Array.isArray(o.arguments)?o.arguments.map(m=>{let u=Je(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:Je(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{command:i,action:a,source:{layer:o.layer,name:o.name},description:Je(o.description),intent:Je(o.intent),arguments:c,flags:t.get(i)?.flags??[],examples:Ig(o.examples),failure_hints:Ig(o.failure_hints)})}let r=new Set;for(let o of e.handlers)r.add(fe(o));for(let o of n.keys())r.add(o);for(let o of t.keys())r.add(o);let s=[];for(let o of[...r].sort((i,a)=>i.localeCompare(a))){let i=n.get(o);s.push(Rx(o,i,t.get(o)?.flags??[]))}return s}function Rx(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Kg(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function Ix(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(s,o)=>o.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function xx(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 Ox(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",s=e.repeatable===!0||e.list===!0;return{type:s?"array":r,...s?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function Px(e){let t=e.command.split("|").map(s=>s.trim()).filter(s=>s.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let s of e.arguments)n[s.name]=xx(s,e.action),s.required&&r.push(s.name);for(let s of e.flags){let o=Ix(s);!o||n[o]!==void 0||(n[o]=Ox(s,e.action),s.required===!0&&r.push(o))}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 Lx(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((o,i)=>o.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let s=new Set(r.flags.map(o=>`${o.flag}|${o.short??""}`));for(let o of n.flags){let i=`${o.flag}|${o.short??""}`;if(!s.has(i))s.add(i),r.flags.push(o);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);a&&Nx(a,o)}}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 Fx(e,t=A){let n={mode:yt.extensions.policy.mode,trust_mode:yt.extensions.policy.trust_mode,default_sandbox_profile:yt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=T(process.cwd(),e.path);if(!await k(C(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let s=await t(r),o=await Mr({pmRoot:r,settings:s,cwd:process.cwd(),noExtensions:!1}),i=await Dr({...o,loaded:o.loaded});return{handlers:new Set(i.commands.handlers.map(c=>fe(c.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:o.policy.mode,trust_mode:o.policy.trust_mode,default_sandbox_profile:o.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function $x(e,t={}){let n=new Map;for(let r of Gi){let s=ei.has(r);if(s&&!t.includePackageOwnedActions)continue;let o=Rg(r);n.set(r,{action:r,provider:s?"extension":"core",requires_extension:s,command_path:o})}if(t.includePackageOwnedActions)for(let r of ei)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Rg(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:fe(r.command)});return[...n.values()].sort((r,s)=>(r.action??"").localeCompare(s.action??""))}function Mx(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?mt(e.command_path):[],r=n.some(i=>t.handlers.has(i)),s=n.map(i=>Mg.get(i)).find(i=>typeof i=="string"),o=t.disabledReason===null&&r;return{action:e.action,invocable:o,available:o,requires_extension:!0,provider:"extension",disabled_reason:o?null:t.disabledReason??(s?`optional_package_not_installed:${s}`:"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 Bg(e){return sd.get(e)??Ur}function Dx(e){return vr.has(e)?!1:sd.has(e)}function Ux(e){return $g.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function Og(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function Gx(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function jx(e){let t=new Map;for(let r of e.definitions){let s=Og(r.cli_flag);if(!s)continue;let o=r.cli_aliases.map(a=>Gx(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>Og(a)).filter(a=>a!==null&&a!==s);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=o?{flag:s,short:o}:{flag:s},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,s]of t.entries())n.set(r,$i(s.flags));return n}function Pg(e,t){let n=[],r=new Set;for(let s of[...e,...t]){let o=`${s.flag}|${s.short??""}`;r.has(o)||(r.add(o),n.push(s))}return $i(n)}function qx(e,t,n,r){return e.map(s=>{let o=Dx(s),i=o?Bg(s):[],a=n.get(Ux(s))??[],c=t.get(s),m=Pg(i,a),u=Pg(m,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":o?"core":"extension";return{command:s,flags:u,...r?{canonical_command:rd(s),visibility:Zm(rd(s)),positionals:ll(s)?.slots??[],flag_invocations:Qm(s,u)}:{},provider:p,extension_sources:c?.sources}}).sort((s,o)=>s.command.localeCompare(o.command))}function Kx(e,t=Wn){let n=new Set(e),r=new Map;for(let s of Gg){let o=s.aliases.filter(i=>n.has(i));r.set(s.canonical,{canonical:s.canonical,aliases:o,contracts:[]})}for(let s of t){if(!n.has(s.canonical)||s.registration==="commander"&&!n.has(s.alias))continue;let o=r.get(s.canonical)??{canonical:s.canonical,aliases:[],contracts:[]};o.aliases.includes(s.alias)||o.aliases.push(s.alias),o.contracts.push(s),r.set(s.canonical,o)}return[...r.values()].map(({contracts:s,...o})=>s.length===0?o:{...o,contracts:s}).sort((s,o)=>s.canonical.localeCompare(o.canonical))}function zx(){return{create_string_options:Km,create_repeatable_options:ys,update_string_options:zm,update_repeatable_options:Bm,list_string_options:ol,search_string_options:il,calendar_string_options:al,context_string_options:cl,activity_string_options:dl}}function Ng(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=mn(e,"create",n),s=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),o=[...new Set(s.map(a=>he("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:s,required_flags:o,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function Bx(e){let t={},n={};for(let r of[...e.types].sort((s,o)=>s.localeCompare(o))){let s=e.by_type[r];t[r]=Ng(s,"strict"),n[r]=Ng(s,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Hx(e,t){let n=kr(e);if(n.length===0)return e;let r=!1,s=n.map(o=>{let i=o.properties;if(typeof i!="object"||i===null)return o;let a=i.action;return typeof a!="object"||a===null||a.const!=="create"?o:(r=!0,{...o,"x-create-required-options":t})});return r?{...e,oneOf:s}:e}function Vx(e){let t=Zo(e.action)!==void 0||Zo(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,s=e.schemaOnly===!0,o=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=Zo(e.action),u=Zo(e.command),p=!r&&!c&&!s&&!o&&!i&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:s,flagsOnly:o,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function Wx(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new l("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",d.USAGE)}async function Yx(e,t=A){try{return await t(e)}catch{return structuredClone(yt)}}async function Jx(e,t){let n=await Yx(t),r=await Fx(e),s=x(n,r.registrations??I()),o=Ve(n.schema),i=Cx(r);return{settings:n,runtimeProbe:r,typeRegistry:s,statusRegistry:M(n.schema),runtimeFieldRegistry:o,runtimeFieldFlagMap:jx(o),createRequiredOptionContracts:Bx(s),extensionContracts:i,mergedExtensionContracts:Lx(i),extensionFlagMap:zg(r.flagRegistrations)}}function Lg(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ei.has(e.selectedAction)||e.selectedCommand!==void 0&&vr.has(e.selectedCommand))}function Xx(e,t){let n=$x(t,{includePackageOwnedActions:Lg(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Mm);return n.filter(s=>!r.has(s.action))}return Lg(e)&&e.selectedCommand!==void 0&&vr.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:kx(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function Qx(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new l(`Unknown action: "${e.selectedAction}".`,d.USAGE)}function Zx(e,t){return[...new Set([...Ui.filter(n=>!vr.has(n)),...[...sd.keys()].filter(n=>!vr.has(n)),...e.flatMap(n=>n.command_path?mt(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>fe(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function eO(e,t){let n=t.slice(0,yx),r=t.length-n.length,s=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),o=t.slice(0,bx),i=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new l(`Command "${e}" is a command namespace. Choose a concrete child command: ${s}.`,d.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:o.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function tO(e,t){return new l(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,d.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 nO(e){return new l(`Unknown command: "${e}".`,d.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 rO(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(o=>o.startsWith(`${e.selectedCommand} `));if(r.length>0)throw eO(e.selectedCommand,r);let s=Mg.get(e.selectedCommand);throw s?tO(e.selectedCommand,s):nO(e.selectedCommand)}function sO(e,t){let n=Xx(e,t.mergedExtensionContracts);Qx(e,n);let r=Zx(n,t.mergedExtensionContracts);rO(e,r);let s=e.selectedCommand?Ug.get(e.selectedCommand):void 0,o=e.selectedCommand?n.filter(m=>s?m.action===s:Sx(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!o.some(m=>m.action===e.selectedAction))throw new l(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,d.USAGE);let i=e.selectedAction?o.filter(m=>m.action===e.selectedAction):o,a=[...new Map(i.map(m=>Mx(m,t.runtimeProbe)).map(m=>[s?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:o,scopedActionDescriptors:i,selectedPackageOwnedAction:s,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function oO(e){return new Set(kr(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 s=r.const;return typeof s=="string"?s:null}).filter(t=>t!==null))}function iO(e){let t=Gm,n=kr(t),r=oO(t),s=e.filter(o=>!r.has(o.action)).map(o=>Px(o));return s.length>0?{...t,oneOf:[...n,...s]}:t}function Fg(e,t,n){let r=new Set(t.actionDescriptors.map(o=>o.action)),s=e.selectedAction?Tx(n,e.selectedAction):e.selectedCommand?td(n,new Set(t.scopedActionDescriptors.map(o=>o.action))):td(n,r);return e.runtimeOnly&&!e.selectedAction?td(s,new Set(t.actions)):s}function aO(e,t,n){let r=iO(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?Hx(Fg(e,n,r),t.createRequiredOptionContracts):Fg(e,n,r);return{mergedSchema:r,filteredSchema:o}}function cO(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?Ex(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function dO(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Wn.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function rd(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":jg.get(t)??t}var lO=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"]]),mO=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function uO(e,t){let n=Cg.get(e)??(e.includes(" ")?void 0:Cg.get(rd(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>mt(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 s=e.split(" "),o=s.at(-1),i=s.slice(0,-1).join(" "),a=lO.get(o),c=mO.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function pO(e,t=[],n={}){let r=n.includeFormatBudgets??!0,s=n.includeIntentProvenance??!0;return[...new Set(e.map(fe))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i)).map(o=>{let i=qi(o,{generateFallback:!0}),a=o.split(" ")[0],c=jg.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),m=new Set([...Bg(o).map(f=>f.flag),...t.filter(f=>mt(f.command).includes(o)).flatMap(f=>f.flags.map(_=>_.flag))]),u=(Ag.get(o)??Ag.get(c)??gx).filter(f=>m.has(f)),p=uO(o,t);return{command:o,intent:p.intent,...s||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 fO(e){return e.map(t=>({budget:qi(t,{generateFallback:!0}),envelope:tu(t)}))}function _O(e){let t=new Map;for(let n of e){let r=Vm(n),s=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,o=s.join(","),i=t.get(o)??{commands:[],exit_codes:s};i.commands.push(n),t.set(o,i)}return[...t.values()]}function hO(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>mt(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(s=>mt(s.command).some(o=>r.has(o)))}return t.extensionContracts}function gO(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 yO(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(s=>s.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(([s])=>r===void 0||s===r).map(([s,o])=>[s,[...new Set(o.map(i=>`--${i.cli_flag}`))].sort((i,a)=>i.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Im],services:[...xm],policy_modes:[...Om],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Lm],trust_modes:[...Pm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Nm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Md],create_modes:[...Dd],close_validation_modes:[...Ud],workflow_enforcement_modes:[...Gd]},e.relationship_kind_contracts=[...Vd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(s=>s.definitions)].sort((s,o)=>s.kind.localeCompare(o.kind)).map(s=>({canonical:s.kind,aliases:[...s.aliases??[]],...s.inverse===void 0?{}:{inverse:s.inverse},ordering:s.ordering,hierarchy:s.hierarchy})))}function bO(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 wO(e,t,n,r,s){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=qx(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let o=new Set(r);e.list_projections=Object.entries(su).filter(([i])=>o.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...ru],compact_fields:[...nu]}))}e.command_aliases=s}}function vO(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=zx();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function kO(e,t,n,r){e.command_summaries=pO(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Dm],allows_unbounded_opt_out:!0},e.grammar_contracts={nouns:jt.nouns,shared_verbs:jt.shared_verbs,scope_before_verb:jt.scope_before_verb,visible_top_level_ceiling:jt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:jt.ceiling_raise_requires_pm_item,positional_shape_budget:jt.positional_shape_budget,positional_shape_count:new Set(Fi.map(({slots:s})=>ul(s))).size,positional_action_count:Li.length,positional_action_parents:[...new Set(Li.map(({parent:s})=>s))].sort((s,o)=>s.localeCompare(o)),...r.includePositionalSignatures?{positional_signatures:Fi}:{}}}async function Hg(e,t){let n=Vx(e);Wx(n);let r=T(process.cwd(),t.path),s=await Jx(t,r),o=sO(n,s),i=aO(n,s,o),a=cO(n,o),c=dO(n,a),m=gO(n,i,o,c),u=hO(n,s,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&kO(m,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p}),n.summary)return m;let f=Kx(o.commandCatalog);return n.flagsOnly&&!n.fullOutput||yO(m,s,n),bO(m,n,i,u),wO(m,n,s,c,f),vO(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...Zu],gate_triggers:[...Qu]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=ml),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=Tg(),m.context_intents=Wm(),m.read_output_dimensions=Ki,m.error_codes=Xm,m.command_output_contracts=fO(c),m.command_exit_contracts={vocabulary:Hm,command_sets:_O(c)}),m}import oP from"node:fs/promises";import ly 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]="ed44fc89-8b6e-5c83-a4f4-ced4e9031dac")}catch{}})();function ti(e,t,n,r,s,o="min"){let i=s==="min"?e-t:t-e,a=o==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&a<0}function SO(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,s=null,o=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)||(ti(f,i,p,s,"min")&&(i=f,s=p),ti(f,a,p,o,"max","max")&&(a=f,o=p))}return{id:e,bytes:n,lines:r,oldest_ts:s,newest_ts:o}}function Vg(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),s=e.map(({id:_,raw:h})=>SO(_,h)),o=0,i=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of s){if(o+=_.lines,i+=_.bytes,_.oldest_ts!==null){let h=Date.parse(_.oldest_ts);ti(h,m,_.id,a?.id??null,"min")&&(m=h,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let h=Date.parse(_.newest_ts);ti(h,u,_.id,c?.id??null,"max")&&(u=h,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...s].sort((_,h)=>h.bytes-_.bytes||_.id.localeCompare(h.id)).slice(0,r),f=r===0?[]:[...s].sort((_,h)=>h.lines-_.lines||_.id.localeCompare(h.id)).slice(0,r);return{total_streams:e.length,total_lines:o,total_bytes:i,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as TO}from"node:crypto";import{execFile as AO}from"node:child_process";import Jg from"node:path";import{promisify as CO}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]="939d5f93-d287-5c1c-bc78-d013f76735f2")}catch{}})();var Wg=1;function EO(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 od(e){if(e===null)return{format_version:Wg,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new l("Improvement ledger contains invalid JSON.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Wg||!Array.isArray(t.observations))throw new l("Improvement ledger has an unsupported shape or format version.",d.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!EO(r))throw new l("Improvement ledger contains an invalid observation.",d.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]="aaa927b3-4bc4-561f-aff1-85dc95c12ea1")}catch{}})();var RO=CO(AO),IO=50,Yg=1e3,xO=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Xg(e){let t=e.trim().toLowerCase();if(!xO.test(t))throw new l(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,d.USAGE,{code:"invalid_improvement_metric"});return t}function OO(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new l("Improvement direction must be higher, lower, or target.",d.USAGE,{code:"invalid_improvement_observation"});return t}function Sr(e,t){let n=e?.trim();if(n){if(n.length>256)throw new l(`${t} must not exceed 256 characters.`,d.USAGE,{code:"invalid_improvement_observation"});return n}}function PO(e){let t=e??IO;if(!Number.isSafeInteger(t)||t<0||t>Yg)throw new l(`Improvement observation limit must be an integer from 0 to ${Yg}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Qg(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new l(`${t} must be an ISO timestamp.`,d.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function NO(e,t,n){if(!Number.isFinite(n.value))throw new l("Improvement observation value must be finite.",d.USAGE,{code:"invalid_improvement_observation"});let r=Xg(n.metric),s=OO(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||s==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let o=await FO(e,n.revision),i=Sr(n.source,"source"),a=Sr(n.itemId,"itemId"),c=Sr(n.unit,"unit"),m=Sr(n.idempotencyKey,"idempotencyKey")??(o.revision_source==="unversioned"?void 0:[o.revision,r,i??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:s,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Qg(n.observedAt??S(),"observedAt"),...o,author:R(n.author,t.author_default),...a===void 0?{}:{item_id:a},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:TO("sha256").update(J(u)).digest("hex").slice(0,24),...u}}function LO(e,t){let n=t.idempotency_key?e.observations.find(s=>s.idempotency_key===t.idempotency_key):e.observations.find(s=>s.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(s=>s.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function FO(e,t){let n=Sr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await RO("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Bd(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function $O(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,s=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:s,sample_count:e.length}}async function Zg(e,t={}){let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await NO(n,r,e),o=Jg.join(n,"improvement-ledger.json"),i=await Tu({pmRoot:n,filePath:o,op:"improvement_observe",author:s.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${s.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=od(a),m=LO(c,s);return m?{raw:a,result:m}:(c.observations.push(s),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${J(c)}
|
|
47
|
+
`,result:s})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function ey(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);if(!await k(C(t)))throw new l(`Tracker is not initialized at ${t}. Run pm init first.`,d.NOT_FOUND);let n=e.metric===void 0?void 0:Xg(e.metric),r=e.since===void 0?void 0:Qg(e.since,"since"),s=PO(e.limit),i=od(await q(Jg.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,s),total:i.length,truncated:i.length>s,trends:[...a].map(([,c])=>$O(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]="6162845d-f4b4-5d1f-a210-ddef1a5c38f6")}catch{}})();function ty(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 MO(e,t,n){let r=t,s=new Set([e.id]);for(;r!==void 0&&!s.has(r.id);)s.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function DO(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,s)=>r.entries[0].ts.localeCompare(s.entries[0].ts)||r.id.localeCompare(s.id)),t.push(...n.map(r=>r.children))}}function id(e=Yn,t=hn){return t.map(n=>{let r=e.filter(s=>((n==="model"?s.model_environment_keys:s.provenance_environment_keys?.[n])?.length??0)>0||s.provenance_resolvers?.[n]!==void 0).map(s=>s.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function UO(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let s=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?s.observed+=1:r.agent_provenance?.model===null?s.unavailable+=1:s.legacy_missing+=1,n.set(r.agent_harness,s)}return[...n.values()].map(r=>{let s=r.observed+r.unavailable;return{...r,coverage:s===0?null:r.observed/s,inert:s>=t&&r.observed===0}}).sort((r,s)=>r.harness.localeCompare(s.harness))}function ad(e,t=hn,n=1){let r=new Map;for(let s of e)if(s.agent_harness)for(let o of t){let i=`${s.agent_harness}\0${o}`,a=r.get(i)??{harness:s.agent_harness,dimension:o,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=s.agent_provenance?.[o];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(s=>{let o=s.observed+s.unavailable;return{...s,coverage:o===0?null:s.observed/o,inert:o>=n&&s.observed===0}}).sort((s,o)=>s.harness.localeCompare(o.harness)||s.dimension.localeCompare(o.dimension))}function GO(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 s=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=s.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),s.set(u,p)}let o=[...s.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=o.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:o,failures:a}}function jO(e){let t=[...e].sort((o,i)=>o.ts.localeCompare(i.ts)||o.author.localeCompare(i.author)||o.op.localeCompare(i.op)||o.before_hash.localeCompare(i.before_hash)||o.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let o of t){let i=o.agent_episode,a=ty(o),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(o);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:[o],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let s=[];for(let o of n.values()){let i=o.parent_id?r.get(o.parent_id):void 0;i&&MO(o,i,r)?i.children.push(o):s.push(o)}return DO(s),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]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var qO=1e4,ny=1e5,KO=1e3,zO=30,BO=["append","comment","docs","file","learning","note","test_run"];function HO(e){let t=e??qO;if(!Number.isSafeInteger(t)||t<1||t>ny)throw new l(`History analytics event limit must be an integer from 1 to ${ny}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function ry(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new l("History analytics minimum sample must be an integer from 1 to 10000.",d.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function VO(e){let t=e?.trim();if(!t)return new Date(Date.now()-zO*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let s=Number(n[1]),o=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(s)||s<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-s*o).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new l("History analytics --since must be an ISO timestamp or negative duration such as -30d.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function sy(e,t){let n=HO(t.eventLimit),r=VO(t.since),s=[],o=r,i=!1;for(;s.length<n;){let a=await Vo({pmRoot:e,since:o,limit:Math.min(KO,n-s.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(s.push(...c),i=a.has_more,o=a.next_cursor,!a.has_more)break}return{events:s,receipt:{since:r,events:s.length,truncated:i,...i?{next_cursor:o}:{},source:"history_event_index"}}}function WO(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function YO(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 JO(e){return BO.some(t=>e.startsWith(t))}function oy(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 XO(e,t,n){let r=new Map,s=new Map,o=new Map;for(let i of t){let a=WO(i.entry,e),c=YO(i.entry),m=s.get(i.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&s.set(i.item_id,u),!a)continue;let p=oy(r,a);p.events+=1,JO(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,o.set(i.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:o}}function QO(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let s=new Set((r.dependencies??[]).filter(o=>o.kind==="discovered_from").map(o=>o.id));for(let o of s){let i=t.get(o);i&&(oy(e,i).defectEscapes+=1)}}}function ZO(e,t,n,r){let s=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:s==="available"?t.closes/r:null,rework_rate:s==="available"?t.reopens/t.closes:null,defect_escape_rate:s==="available"?t.defectEscapes/t.closes:null,sample_status:s}}function eP(e,t,n,r,s,o){let{buckets:i,lastCloseValue:a}=XO(e,t,r);return QO(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>ZO(c,m,s,o)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function tP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,s=Date.parse(n),o=Date.parse(r);return!Number.isFinite(s)||!Number.isFinite(o)?1:Math.max(1,(o-s)/864e5)}function nP(e,t,n){let r=id(t),s=ad(e,hn,n),o=s.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:s,inert:o,undeclared:i,warnings:[...o.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...i.map(a=>`provenance_dimension_undeclared:${a}`)]}}function iy(e,t=Yn,n={}){let r=ry(n.minimumSample);return{...nP(e.events.map(s=>s.entry),t,r),window:e.receipt}}function ay(e,t,n,r={}){let s=ry(r.minimumSample),o=tP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>eP(i,e.events,t,n,s,o)),minimum_sample:s,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]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var rP=32;function sP(e){let t=[];for(let n of e??[]){let r=[];for(let s of n.split(",")){let o=s.slice(0,s.indexOf("=")).trim();r.length>0&&o!=="unit"&&o!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(s)}t.push(r.join(","))}return t}function Er(e,t){let n=sP(e).map(s=>{let[o,...i]=s.split(","),a=o.indexOf("="),c=o.slice(0,a).trim(),m=o.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${s}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,f;for(let _ of i){let h=_.indexOf("="),y=_.slice(0,h).trim(),g=_.slice(h+1).trim();if(y==="unit"&&g.length>0)p=g;else if(y==="threshold"&&g.length>0&&Number.isFinite(Number(g)))f=Number(g);else throw new l(`Invalid --measure attribute "${_}"`,d.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(s=>[s.name,s])).values()].sort((s,o)=>s.name.localeCompare(o.name)).slice(0,rP)}function cy(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(s=>s.name===t&&s.value<n).map(s=>({...s,run_id:r.run_id})))}function dy(e,t){let n=e.flatMap(o=>o.measurements??[]).filter(o=>o.name===t).sort((o,i)=>i.recorded_at.localeCompare(o.recorded_at)),r=n[0],s=n[1];return{name:t,latest:r?.value??null,previous:s?.value??null,delta:r!==void 0&&s!==void 0?r.value-s.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]="d28c7ac7-9801-5b0c-84c9-51deede398be")}catch{}})();function iP(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function aP(e,t,n,r,s){let o=rr(e,"type",r),i=new Set(o.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),m=(s?[...o.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}}))]:o.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])=>s||f>0));return{byType:m,byStatus:p,omitted:s?0:a.length+Object.values(u).filter(f=>f===0).length}}function cP(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function dP(e){let t=ly.join(e,"history");if(!await k(t))return[];await _n({path:t,scope:"project"});let n=(await oP.readdir(t)).filter(s=>s.endsWith(".jsonl")).sort((s,o)=>s.localeCompare(o)),r=[];for(let s of n){let o=ly.join(t,s),i=await q(o);i!==null&&(await _n({path:o,scope:"project"}),r.push({id:s.slice(0,-6),raw:i}))}return r}async function lP(e,t){let n=[],r=S();for(let s of Er(t.observe,r))n.push(await Zg({metric:s.name,value:s.value,direction:t.direction,unit:s.unit,threshold:s.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function mP(e,t,n){let r={};return t.byAssignee&&(r.assignee=rr(e,"assignee",n)),t.byTag&&(r.tag=rr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=rr(e,"priority",n)),r}async function uP(e,t,n,r,s){let o={since:s.since,eventLimit:s.eventLimit,minimumSample:s.minimumSample},i=s.provenanceCoverage||s.fleetAttribution?await sy(e,o):void 0;return{provenanceCoverage:s.provenanceCoverage&&i?iy(i,n.agent_identity?.harness_signals,o):void 0,fleetAttribution:s.fleetAttribution&&i?ay(i,t,r,o):void 0}}function pP(e,t,n,r,s){let o=Object.keys(s.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...s.metadataCoverage?{metadata_coverage:s.metadataCoverage}:{},...o?{breakdowns:s.breakdowns}:{},...s.storage?{storage:s.storage}:{},...s.fieldUtilization?{field_utilization:s.fieldUtilization}:{},...s.improvementLedger?{improvement_ledger:s.improvementLedger}:{},...s.recordedObservations.length>0?{recorded_observations:s.recordedObservations}:{},...s.provenanceCoverage?{provenance_coverage:s.provenanceCoverage}:{},...s.fleetAttribution?{fleet_attribution:s.fleetAttribution}:{},generated_at:S()}}async function cd(e,t={}){let n=T(process.cwd(),e.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await lP(e,t),o=x(r,I()),i=M(r.schema),a=t.fieldUtilization?await Rs(n,r.item_format,o.type_to_folder,void 0,r.schema):await oe(n,r.item_format,o.type_to_folder,void 0,r.schema);await Iu({pmRoot:n,settings:r,itemIds:a.map(E=>E.id),commandLabel:"stats"});let c=Zs(i),m=aP(a,o.types,i.definitions.map(E=>E.id),c,t.includeEmpty===!0),u=await dP(n),p=0;for(let E of u)p+=cP(E.raw);let f=t.storage?Vg(u):void 0,_=t.metadataCoverage?Zp(a,c):void 0,h=mP(a,t,c),y=t.fieldUtilization?ef(a):void 0,g=t.measurements===!0||s.length>0?await ey({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:b,fleetAttribution:v}=await uP(n,a,r,i.terminal_statuses,t);return pP({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:h,storage:f,fieldUtilization:y,improvementLedger:g,recordedObservations:s,provenanceCoverage:b,fleetAttribution: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]="0e63298a-d2d7-5217-af50-a206348b4cd4")}catch{}})();function my(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:ye(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 fP from"node:fs/promises";import Ft 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]="ad3110ca-e85b-5a7e-b0a1-591796c298eb")}catch{}})();var hy=Ft.join("runtime","telemetry","events.jsonl"),gy=Ft.join("runtime","telemetry","state.json"),_P=Ft.join("runtime","telemetry"),hP=20,uy=["status","flush","stats","clear"],py=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},dd=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,fy=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},gP=e=>({command:dd(e.event.command,"<unknown>"),eventType:dd(e.event.event_type,"unknown"),eventSchemaVersion:fy(e.event.schema_version),clientSchemaVersion:fy(e.client_schema_version)}),yP=()=>({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:{}}),bP=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},wP=e=>{let t=e?.command_resolution;return dd(t,"")||void 0},yy=(e,t)=>{e[t]=(e[t]??0)+1},vP=(e,t)=>{let n=bP(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=wP(t);r!==void 0&&yy(e.resolution_counts,r)},kP=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,_y=(e,t)=>{t!==void 0&&e.add(t)},SP=(e,t)=>{let n=gP(t),r=e.get(n.command)??yP();r.count+=1,r.max_attempts=Math.max(r.max_attempts,kP(t.attempts)),yy(r.event_type_counts,n.eventType),_y(r.event_schema_versions,n.eventSchemaVersion),_y(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&vP(r,t.event.payload),e.set(n.command,r)},EP=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((o,i)=>o-i),s=Object.entries(t.resolution_counts).sort((o,i)=>o[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((o,i)=>o[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((o,i)=>o-i),client_schema_versions:[...t.client_schema_versions].sort((o,i)=>o-i),...r.length>0?{duration_p50_ms:py(r,.5),duration_p95_ms:py(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}:{},...s.length>0?{command_resolution_counts:Object.fromEntries(s)}:{}}},TP=e=>{let t=(e??"status").trim().toLowerCase();if(uy.includes(t))return t;throw Te({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:uy,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},ld=()=>{throw new l("--limit must be a positive integer",d.USAGE)},by=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?ld():e,AP=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?ld():by(Number.parseInt(t,10))},CP=e=>e===void 0?hP:typeof e=="number"?by(e):typeof e=="string"?AP(e):ld(),RP=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},IP=e=>{try{let t=JSON.parse(e);return RP(t)?t:void 0}catch{return}},xP=e=>e===null?[]:e.split(`
|
|
48
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),wy=e=>{let t=xP(e),n=[],r=0;for(let s of t){let o=IP(s);o===void 0?r+=1:n.push(o)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},OP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),PP=e=>{try{let t=JSON.parse(e);return OP(t)?t:{}}catch{return{}}},NP=async e=>{let t=await q(e);return t===null||t.trim().length===0?{}:PP(t)},ni=e=>e??null,ri=async e=>{let t=await A(e),n=Ft.join(e,hy),r=Ft.join(e,gy),s=await q(n),o=wy(s),i=await NP(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:o.rows_total,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_size_bytes:Buffer.byteLength(s??"","utf8"),last_attempted_flush_at:ni(i.last_attempted_flush_at),last_successful_flush_at:ni(i.last_successful_flush_at),last_failed_flush_at:ni(i.last_failed_flush_at),last_failed_flush_error:ni(i.last_failed_flush_error)}},LP=e=>{let t=new Map;for(let n of e)SP(t,n);return[...t.entries()].map(([n,r])=>EP(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},FP=async(e,t)=>({action:"telemetry",subcommand:"status",status:await ri(t.globalPmRoot),generated_at:S()}),$P=async(e,t)=>{let n=await ri(t.globalPmRoot);await Bu(t.globalPmRoot);let r=await ri(t.globalPmRoot),s=Math.max(0,n.queue_entries-r.queue_entries),o=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:s,queue_progressed:s>0,queue_empty:o,queue_drained:o,status:r,generated_at:S()}},MP=async(e,t)=>{let n=CP(e.limit),r=await q(t.queuePath),s=wy(r),o=LP(s.entries),i=o.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:o.length,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_rows_total:s.rows_total,truncated:o.length>i.length,stats:i,generated_at:S()}},DP=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 Ee(t.globalPmRoot,n,"telemetry:clear");let s=Ft.join(t.globalPmRoot,_P),o=await k(s);return await fP.rm(s,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:o&&!await k(s),queue_exists_after:await k(t.queuePath),state_exists_after:await k(t.statePath),status:await ri(t.globalPmRoot),generated_at:S()}},UP={status:FP,flush:$P,stats:MP,clear:DP};async function vy(e,t){let n=TP(e.subcommand),r=et(process.cwd());return UP[n](e,{globalPmRoot:r,queuePath:Ft.join(r,hy),statePath:Ft.join(r,gy)})}import{spawn as Gy}from"node:child_process";import{cp as Ay,mkdir as zP,mkdtemp as jy,open as fd,readdir as _d,rm as qy}from"node:fs/promises";import{tmpdir as Ky}from"node:os";import me 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]="62af7c1e-c1c7-529e-ab30-117103ac4607")}catch{}})();var ky=20;function GP(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return ky;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?ky:t}function md(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,s)=>{let o=yn(r.recorded_at,s.recorded_at);if(o!==0)return o;let i=r.run_id.localeCompare(s.run_id);return i!==0?i:r.kind.localeCompare(s.kind)}),n=GP();return t.length>n?t.slice(t.length-n):t}async function si(e){await Z({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=md([...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]="8a6a3402-dae3-56f8-b9ba-a4f6f8a47cda")}catch{}})();var Sy=100;function ud(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,d.USAGE);return n}function jP(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Sy?n:`${n.slice(0,Sy-3)}...`}function Ey(e){return e.map((t,n)=>`${n+1}. ${jP(t)}`).join("; ")}function qP(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 KP(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Ty(e,t){let n=qP(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((s,o)=>o+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(s=>`--${s}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,d.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,d.USAGE);if(r==="match"){let s=t.match.trim().toLowerCase();if(s.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let o=[],i=[];for(let a=0;a<e.length;a+=1)KP(e[a],s)&&(i.push(e[a]),o.push(a+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Ey(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:o,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let s=ud(t.onlyIndex);if(s>e.length)throw new l(`--only-index ${s} is out of range: this item has ${e.length} linked test(s). Available entries: ${Ey(e)}`,d.USAGE);return{selector:"only-index",requested:String(s),selected:[e[s-1]],selected_indexes:[s],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]="4322c352-6b95-5796-94eb-5a68745d53bc")}catch{}})();var ii=20*1024*1024,BP=3e3,HP=1e4,VP=5e3,Cy=120,WP=new Set(["locks","extensions","runtime"]),YP=new Set(["history","index","search","extensions","locks","runtime"]),JP=[/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],XP=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,QP=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,ZP=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 yd(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 eN(){return yd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",BP)}function tN(){return yd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",HP)}function nN(){return yd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",VP)}function rN(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 sN(e){let t=0,n=0,r=0;for(let s of e){if(s.status==="passed"){t+=1;continue}if(s.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function bd(e){let t=0,n=0,r=0,s=0;for(let o of e){let i=o.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&&(s+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:s}}function oN(e){let t=e??"project";if(!Ze.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function ai(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Xt.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${Xt.join(", ")}`,d.USAGE)}function zy(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:ai(e.pm_context_mode)}function By(e,t){return e==="auto"?t?"tracker":"schema":e}function iN(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 aN(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 cN(e,t){let n={};if(!e)return n;for(let r of e){let s=dr(r,t);if(s)for(let[o,i]of Object.entries(s))n[o]=i}return n}function dN(e,t){if(!e)return[];let n=[];for(let r of e){let s=lr(r,t);s&&n.push(...s)}return[...new Set(n)]}function lN(e){let t=ci(e);return tr(t).some(n=>ga(n)!==null)}function Hy(e){let t=ci(e);return tr(t).some(n=>{let r=ga(n);if(!r)return!1;let s=Jp(r);return s?ZP.has(s.subcommand):!1})}function oi(e){if(e)return Vp.has(e.subcommand)?Rn(e.args,Wp)?.subcommand:e.subcommand}function Ry(e,t){if(e==="npx"||e==="bunx")return Xs(t)?.command;if(e==="pnpm")return oi(Rn(t,Kp));if(e==="npm")return oi(Rn(t,zp));if(e==="yarn")return oi(Rn(t,Bp));if(e==="bun")return oi(Rn(t,Hp))}function Iy(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function pd(e){return!e||!ba(e.command)&&!Yp(e.command)?!1:Js(e.args)==="test-all"}var mN=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])]),uN=new Set(["npx","bunx"]);function Vy(e){let t=e.split(" ").filter(i=>i.length>0),n=ya(t);if(n.length===0)return!1;let[r,...s]=n,o=mN.get(r);if(o){let i=s.findIndex(a=>o.test(a));return i>=0?Vy(s.slice(i+1).join(" ")):!1}return ba(r)||wa(r)?Js(s)==="test-all":r==="node"&&s.length>0&&wa(s[0])?Js(s.slice(1))==="test-all":uN.has(r)?pd(Xs(s)):r==="pnpm"?pd(va(s)):r==="npm"?pd(ka(s)):!1}function Wy(e){let t=ci(e);return tr(t).some(n=>Vy(n))}function Yy(e){if(Wy(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function ci(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function pN(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function fN(e){let t=/\bpm_path\s*=/.test(e)||/\$env:pm_path\s*=/.test(e),n=/\bpm_global_path\s*=/.test(e)||/\$env:pm_global_path\s*=/.test(e);return t&&n}function _N(e){let t=e.split(" ").filter(o=>o.length>0),n=ya(t);if(n.length===0)return!1;let[r,...s]=n;return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?hN(s):gN(r,s)}function hN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function gN(e,t){return e==="npx"||e==="bunx"?Iy(Xs(t)?.command):e==="pnpm"||e==="npm"?Iy((e==="pnpm"?va(t):ka(t))?.command)||Ry(e,t)==="vitest":(e==="yarn"||e==="bun")&&Ry(e,t)==="vitest"}function Jy(e){let t=ci(e);if(tr(t).some(s=>!pN(s)&&_N(s)&&!fN(s)))throw new l('Linked test runner commands must be sandbox-safe: use "node scripts/run-tests.mjs <test|coverage>", use a package-manager script such as "pnpm test", or include PM_PATH=... PM_GLOBAL_PATH=... INLINE in the command string (exporting them in your shell environment is not checked). Example: "PM_PATH=/tmp/pm-x PM_GLOBAL_PATH=/tmp/pm-x-g vitest run".',d.USAGE)}function yN(e){if(Wy(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function bN(e){return e?e.map(wN):[]}function wN(e){let t=e.trim(),n=ko(t)?So(ne(e,"--add"),"--add"):{command:t},r=le(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return Yy(r),Jy(r),{command:r,path:le(n.path),scope:oN(n.scope),timeout_seconds:vN(le(n.timeout_seconds),le(n.timeout)),pm_context_mode:Ro(le(n.pm_context_mode),"--add"),env_set:dr(le(n.env_set),"--add"),env_clear:lr(le(n.env_clear),"--add"),shared_host_safe:Co(le(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Zt(le(n.assert_stdout_contains)),assert_stdout_regex:Nn(le(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Zt(le(n.assert_stderr_contains)),assert_stderr_regex:Nn(le(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Io(le(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:xo(le(n.assert_json_field_equals),"--add"),assert_json_field_gte:Oo(le(n.assert_json_field_gte),"--add"),note:le(n.note)}}function le(e){let t=e?.trim();return t&&t.length>0?t:void 0}function vN(e,t){if(e&&t&&e!==t)throw new l("--add timeout and timeout_seconds must match when both are provided",d.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(ie(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function kN(e){return e?e.flatMap(t=>{let n=jf(t,"--add-json");for(let r of n){let s=r.command;if(!s)throw new l("--add-json requires a non-empty command string",d.USAGE);Yy(s),Jy(s)}return n}):[]}function SN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires command or path value",d.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let s=n.slice(r[0].length).trim();if(!s)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:s}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let s=ne(n,"--remove"),o=s.path!==void 0?"path":"command",i=s.path??s.command;if(!i?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:o,value:i.trim()}}return{kind:"either",value:n}}):[]}function EN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new l("--remove-index must be a positive integer",d.USAGE);return n}))]:[]}function TN(e){try{e.stdin?.end()}catch{}}function Xy(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=Cy?t:`${t.slice(0,Cy-3)}...`}function Qy(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function hd(e){try{process.stderr.write(`${e}
|
|
49
|
+
`)}catch{}}function AN(e,t){if(!Qy(t))return null;let n=Xy(e.command),r=Date.now();hd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let s=setInterval(()=>{let o=Date.now()-r;hd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${o} command="${n}"`)},tN());return s.unref?.(),s}function CN(e,t,n,r){if(!Qy(r))return;let s=Xy(e.command),o=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(" ")}`:"";hd(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${o}${u} command="${s}"`)}async function xy(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Gy("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 RN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function IN(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 xy(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{xy(r)},eN()),t.forceKillTimer.unref?.()}}function xN(e){return new Promise(t=>{let n=!1,r=null,s=(o,i=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(o))};e.on("exit",(o,i)=>{n||(r=setTimeout(()=>{s({code:o,signal:i},!0)},nN()),r.unref?.())}),e.on("close",(o,i)=>{s({code:o,signal:i})})})}function ON(e,t,n,r){return Gy(e,{cwd:process.cwd(),env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function Oy(e){let t=await fd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,ii),s=Buffer.alloc(r);return r>0&&await t.read(s,0,r,0),{text:s.toString("utf8"),truncated:n>ii}}finally{await t.close()}}async function PN(e,t,n,r,s){let o=Date.now(),i=await jy(me.join(Ky(),"pm-linked-test-output-"));try{let a=me.join(i,"stdout.log"),c=me.join(i,"stderr.log"),[m,u]=await Promise.all([fd(a,"w"),fd(c,"w")]),p;try{p=ON(e,n,m.fd,u.fd)}finally{await Promise.all([m.close(),u.close()])}TN(p);let f={heartbeat:AN(r,s),forceKillTimer:null,timedOutTimer:null},_=IN(p,f),h=!1,y;p.on("error",$=>{y=$.message}),f.timedOutTimer=setTimeout(()=>{h=!0,_()},t),f.timedOutTimer.unref?.();let{code:g,signal:b}=await xN(p);RN(f);let[v,E]=await Promise.all([Oy(a),Oy(c)]),N=v.truncated||E.truncated,O=N?`
|
|
50
|
+
[pm linked-test output truncated at ${ii} bytes per stream; the child process continued to completion]
|
|
51
|
+
`:"",j={stdout:`${v.text}${O}`,stderr:E.text,exitCode:g,signal:b,timedOut:h,maxBufferExceeded:!1,outputTruncated:N,spawnError:y};return CN(r,j,o,s),j}finally{await qy(i,{recursive:!0,force:!0})}}function NN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${ii} 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,s=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?s:`${s} ${n.join(" ")}`}function LN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
52
|
+
`);return JP.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>XP.test(n)&&QP.test(n))}function FN(e){return LN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function $N(){return{infra_collision:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function di(e){let t=$N();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function Py(e,t){for(let[n,r]of Object.entries(t.env_set))Qt.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)Qt.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 DN(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],s=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:s}}function UN(e,t,n){return{env_set:cN(e,"--env-set"),env_clear:dN(t,"--env-clear"),shared_host_safe:n===!0}}async function Gn(e,t,n=!1,r=zP){if(await k(e))try{await Wo("seed_linked_test",async()=>{if(await r(me.dirname(t),{recursive:!0}),n){await Ay(e,t,{recursive:!0,force:!0});return}await Ay(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(s){if(typeof s=="object"&&s!==null&&"code"in s&&wt(s))return;throw s}}async function Ny(e,t,n){await Gn(C(n.projectPmRoot),C(e)),await Gn(me.join(n.projectPmRoot,"extensions"),me.join(e,"extensions"),!0),await Gn(C(n.globalPmRoot),C(t)),await Gn(me.join(n.globalPmRoot,"extensions"),me.join(t,"extensions"),!0)}async function Ly(e,t){if(!await k(e))return;let n=await _d(e,{withFileTypes:!0});for(let r of n){if(WP.has(r.name))continue;let s=me.join(e,r.name),o=me.join(t,r.name);if(r.isDirectory()){await Gn(s,o,!0);continue}r.isFile()&&await Gn(s,o)}}async function Un(e){if(!await k(e))return 0;let t=0,n=await _d(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||YP.has(r.name))continue;let s=me.join(e,r.name),o;try{o=await _d(s,{withFileTypes:!0})}catch{continue}for(let i of o)i.isFile()&&zd.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function GN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function jN(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let r of n){if(r.startsWith("[")&&r.endsWith("]")){let s=Number.parseInt(r.slice(1,-1),10);if(!Number.isInteger(s)||s<0)return[];t.push(s);continue}t.push(r)}return t}function Fy(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=jN(n);if(r.length===0)return{found:!1,value:void 0};let s=e;for(let o of r){if(typeof o=="number"){if(!Array.isArray(s)||o>=s.length)return{found:!1,value:void 0};s=s[o];continue}if(typeof s!="object"||s===null||!Object.prototype.hasOwnProperty.call(s,o))return{found:!1,value:void 0};s=s[o]}return{found:!0,value:s}}function qN(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 KN(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?tt(e,t):Object.is(e,t)}function zN(e,t,n){let r=[];r.push(...$y("stdout",t,e.assert_stdout_contains)),r.push(...My("stdout",t,e.assert_stdout_regex)),r.push(...$y("stderr",n,e.assert_stderr_contains)),r.push(...My("stderr",n,e.assert_stderr_regex)),r.push(...BN(t,e.assert_stdout_min_lines));let s=e.assert_json_field_equals??{},o=e.assert_json_field_gte??{};if(!(Object.keys(s).length>0||Object.keys(o).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(s)){let u=Fy(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=qN(m);KN(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(o)){let u=Fy(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 $y(e,t,n){let r=[];for(let s of n??[])t.includes(s)||r.push(`${e} missing required text: "${s}"`);return r}function My(e,t,n){let r=[];for(let s of n??[])try{new RegExp(s,"m").test(t)||r.push(`${e} failed regex assertion: /${s}/m`)}catch(o){r.push(`${e} regex assertion is invalid: /${s}/ (${o instanceof Error?o.message:String(o)})`)}return r}function BN(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 HN=[{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}];function VN(e,t){let n=`${e}
|
|
53
|
+
${t}`;for(let r of HN)if(r.regex.test(n))return r.code;return null}function WN(e){return{root:e,schemaProjectPmPath:me.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:me.join(e,"schema","global"),trackerProjectPmPath:me.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:me.join(e,"tracker","global")}}async function YN(e,t=_r,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 JN(e,t,n){t&&(await Ny(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await Ny(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Ly(t.projectPmRoot,e.trackerProjectPmPath),await Ly(t.globalPmRoot,e.trackerGlobalPmPath)))}function XN(e,t,n){return e.some(r=>{let s=r.command??"",o=s.length>0&&Hy(s),i=n?.autoPmContext===!0&&o?"auto":zy(r,t,n?.overrideLinkedPmContext===!0);return By(i,o)==="tracker"})}async function QN(e,t){return{sourceProjectItemCount:t?await Un(t.projectPmRoot):0,sourceGlobalItemCount:t?await Un(t.globalPmRoot):0,schemaProjectItemCount:await Un(e.schemaProjectPmPath),schemaGlobalItemCount:await Un(e.schemaGlobalPmPath),trackerProjectItemCount:await Un(e.trackerProjectPmPath),trackerGlobalItemCount:await Un(e.trackerGlobalPmPath)}}function ZN(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,s=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,o=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount;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:s,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:o,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==s||e.counts.sourceGlobalItemCount!==o),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots}}function eL(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?ai(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?lN(n):!1,s=r&&n?Hy(n):!1,o=e.options?.autoPmContext===!0&&s,i=o?"auto":zy(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=By(i,s);return{linkedOverridePmContextMode:t,executionContext:ZN({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:s,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:o})}}function Dy(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function gd(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 tL(e){if(!e.linkedTest.command)return Dy(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=yN(e.linkedTest.command);if(t)return Dy(e.linkedTest,e.executionContext,t);let n=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,r=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(n||r){let s=aN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return gd(e.linkedTest,e.executionContext,`${o} (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&&!iN(e.linkedTest)?gd(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function nL(e){let t=DN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return Py(n,e.runtimeDirectives),Py(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,n.PM_SOURCE_WORKSPACE_ROOT=process.env.PM_SOURCE_WORKSPACE_ROOT??process.cwd(),n.PM_SOURCE_PM_PATH=e.executionContext.source_project_pm_path,n[Ws]="read_only",n}function rL(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 sL(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}) while --fail-on-empty-test-run is enabled. Update test selection or disable --fail-on-empty-test-run for this run.`}}function oL(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:GN(e.execution),failure_category:FN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:NN(e.execution,e.timeoutMs)}}function iL(e){if(e.options?.failOnEmptyTestRun===!0){let n=VN(e.execution.stdout,e.execution.stderr);if(n)return sL({...e,emptyRunSignal:n})}let t=zN(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?gd(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):rL(e.linkedTest,e.executionContext,e.execution)}async function aL(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await PN(t,n,nL(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?iL({...e,execution:r}):oL({...e,execution:r,timeoutMs:n})}async function wd(e,t,n){let r=[],s=await jy(me.join(Ky(),"pm-linked-test-")),o=WN(s),i=ai(n?.pmContext),a=n?.progress===!0?"always":"auto",c=UN(n?.envSet,n?.envClear,n?.sharedHostSafe),m=n?.sourceRoots,u=XN(e,i,n);try{await YN(o,_r,u),await JN(o,m,u);let p=await QN(o,m);for(let f=0;f<e.length;f+=1){let _=e[f],h=eL({linkedTest:_,layout:o,counts:p,sourceRoots:m,runLevelPmContextMode:i,options:n}),y=tL({linkedTest:_,executionContext:h.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:h.linkedOverridePmContextMode,options:n});if(y){r.push(y);continue}r.push(await aL({linkedTest:_,index:f,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:c,progressMode:a,executionContext:h.executionContext,options:n}))}}finally{await qy(o.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function cL(e){let{id:t,pmRoot:n,settings:r,typeToFolder:s}=e,o=await D(n,t,r.id_prefix,r.item_format,s);if(!o)throw new l(`Item ${t} not found`,d.NOT_FOUND);let i=await K(o,{schema:r.schema});return{itemId:o.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function dL(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode}function lL(e,t){let n=[...e];for(let r of t)n.some(s=>dL(s,r))||n.push(r);return n}function mL(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),s=e.filter((o,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?o.command===a.value:a.kind==="path"?o.path===a.value:o.command===a.value||o.path===a.value));return{tests:s,removed:e.length-s.length}}function uL(e,t,n,r){return mL(lL(e,t),n,r)}function pL(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}function fL(e){if(pL(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",d.USAGE)}async function _L(e){let{id:t,options:n,pmRoot:r,settings:s,typeToFolder:o,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return cL({id:t,pmRoot:r,settings:s,typeToFolder:o});let m=0,u=await Z({pmRoot:r,settings:s,id:t,op:i.length>0?"tests_add":"tests_remove",author:R(n.author,s.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=uL(f,i,a,c);if(m=_.removed,(a.length>0||c.length>0)&&m===0)throw new l("No linked tests matched the requested removal selector",d.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(h=>`${h.kind}=${h.value}`),...c.map(h=>`index=${h}`)],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:tt(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 hL(e,t){fL(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:ud(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?Ty(t,n):void 0,s=e.timeout===void 0?void 0:ie(e.timeout,"timeout");if(s!==void 0&&s<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:s,pmContextMode:ai(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function gL(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await wd(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,sourceRoots:{projectPmRoot:r,globalPmRoot:et(process.cwd())}})}function yL(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 s=bd(n);r.push(`context_preflight:checked_pm_commands=${s.checked_pm_commands};tracker_read_commands=${s.tracker_read_commands};mismatches=${s.mismatches};auto_remediated=${s.auto_remediated}`)}return r}function bL(e){let t=sN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),s=S(),o=Er(e.options.measure,s);return{run_id:rN("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:s,recorded_at:s,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:o.length>0?o:void 0}}async function wL(e){let{options:t,pmRoot:n,settings:r,itemId:s,runStartedAt:o,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!o)return;let m=bL({options:t,runStartedAt:o,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return m;try{return await si({pmRoot:n,settings:r,itemId:s,author:R(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:${s}:${u instanceof Error?u.message:String(u)}`),m}}function Uy(e,t,n){let r;if(e.metricBelow!==void 0){let s=e.metricBelow.indexOf("="),o=e.metricBelow.slice(0,s).trim(),i=e.metricBelow.slice(s+1).trim(),a=Number(i);if(s<=0||o.length===0||i.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",d.USAGE);r=cy(t,o,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:dy(t,e.metricDiff)}}async function li(e,t,n){let r=Le(),s=T(process.cwd(),n.path);if(!await k(C(s)))throw new l(`Tracker is not initialized at ${s}. Run pm init first.`,d.NOT_FOUND);let o=await A(s);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);Er(t.measure,"validation"),Uy(t,[],void 0);let i=x(o,I()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...bN(a),...kN(c)],p=SN(m),f=EN(t.removeIndex),_=await _L({id:e,options:t,pmRoot:s,settings:o,typeToFolder:i.type_to_folder,adds:u,removes:p,removeIndexes:f}),h=hL(t,_.tests),y=t.run===!0?S():void 0,g=await gL({options:t,runOptions:h,pmRoot:s}),b=di(g),v=t.run===!0&&t.failOnSkipped===!0&&g.some($=>$.status==="skipped"),E=yL(t,h.runSelection,g),N=await wL({options:t,pmRoot:s,settings:o,itemId:_.itemId,runStartedAt:y,runResults:g,failOnSkippedTriggered:v,warnings:E}),O=N?md([..._.testRuns,N]):_.testRuns,j=Uy(t,O,N);return{ok:g.every($=>$.status!=="failed")&&v!==!0,id:_.itemId,tests:_.tests,run_results:g,failure_categories:b,selection:h.runSelection?{selector:h.runSelection.selector,requested:h.runSelection.requested,selected_indexes:h.runSelection.selected_indexes,selected_count:h.runSelection.selected_count,skipped_count:h.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:v?!0:void 0,warnings:E.length>0?E:void 0,changed:_.changed,count:_.tests.length,..._.removed>0?{removed:_.removed}:{},...j}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7fea0ecb-35e2-5d40-931f-ffdd1a465fdc")}catch{}})();var vL=(e,t)=>{if(e===void 0)return;let n=W(e,t);if(!n){let r=t.definitions.map(s=>s.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},kL=e=>{if(e===void 0)return;let t=ie(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},Zy=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new l(`${t} must be a non-negative integer`,d.USAGE);return n},SL=e=>e instanceof Error?e.message:String(e),EL=()=>{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)}`},TL=e=>e.trim().replaceAll(/\s+/g," "),AL=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),CL=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),RL=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},mi=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),eb=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),IL=e=>typeof e=="number"?e:void 0,xL=e=>{let t={assert_stdout_contains:mi(e.assert_stdout_contains),assert_stdout_regex:mi(e.assert_stdout_regex),assert_stderr_contains:mi(e.assert_stderr_contains),assert_stderr_regex:mi(e.assert_stderr_regex),assert_stdout_min_lines:IL(e.assert_stdout_min_lines),assert_json_field_equals:eb(e.assert_json_field_equals),assert_json_field_gte:eb(e.assert_json_field_gte)};return JSON.stringify(t)},OL=e=>{let t=vd(e.command);return t!==void 0?`command:${e.scope}:${TL(t)}`:`path:${e.scope}:${vd(e.path)??""}`},tb=e=>{let t=AL(e.env_set),n=CL(e.env_clear),r=RL(e.pm_context_mode),s=e.shared_host_safe===!0?"true":"false",o=xL(e);return`${OL(e)}:${t}:${n}:${r}:${s}:${o}`},PL=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,NL=e=>{let t=0,n=0,r=0;for(let s of e){if(s.status==="passed"){t+=1;continue}if(s.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},LL=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},ui=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
54
|
+
`)}catch{}},FL=async(e,t,n)=>{let r=[],s=0;for(let o of e){let i=await li(o.id,{run:!1},{...t,path:n});s+=i.tests.length,r.push({item:o,tests:i.tests})}return{itemTests:r,linkedTests:s}},$L=async e=>{let t=M(e.settings.schema),n=x(e.settings,I()),r=vL(e.options.status,t),s=Zy(e.options.limit,"--limit"),o=Zy(e.options.offset,"--offset")??0,a=(await oe(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:s===void 0?a.slice(o):a.slice(o,o+s),statusFilter:r,limitFilter:s,offsetFilter:o}},ML=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let s=tb(r);if(!t.has(s)){t.set(s,r.timeout_seconds);continue}t.set(s,PL(t.get(s),r.timeout_seconds))}return t},DL=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=tb(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}}),s=n.length>0?await wd(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}):[],o=0,i=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=s[o];return o+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=NL(i),c=di(i),m=await jL(e,a,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}}},UL=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),GL=e=>e?!0:void 0,jL=async(e,t,n)=>{if(!n.trackingEnabled)return[];try{let r=UL(t,n.options);await si({pmRoot:n.pmRoot,settings:n.settings,itemId:e.item.id,author:n.trackingAuthor,message:`Track test-all run summary (${n.trackingRunId})`,entry:{run_id:n.trackingRunId,kind:"test-all",status:r?"failed":"passed",started_at:n.runStartedAt,finished_at:S(),recorded_at:S(),attempt:n.trackingAttempt,resumed_from:n.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:GL(n.options.failOnSkipped===!0&&t.skipped>0)}})}catch(r){return[`test_result_tracking_failed:${e.item.id}:${SL(r)}`]}return[]},qL=()=>{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},vd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},KL=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:et(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:ML(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:R(e.options.author,e.settings.author_default),trackingRunId:EL(),trackingAttempt:qL(),trackingResumedFrom:vd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),zL=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:di([]),trackingWarnings:[]},s=e.failOnEmptyTestRun===!0&&t===0;return s&&(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:s}},BL=async(e,t,n)=>{for(let[r,s]of e.entries()){ui(t.options,`item ${r+1}/${e.length} start id=${s.item.id} linked_tests=${s.tests.length}`);let o=await DL(s,t);LL(n.failureCategories,o.failureCategories),n.passed+=o.passed,n.failed+=o.failed,n.skipped+=o.skipped,n.trackingWarnings.push(...o.trackingWarnings),n.results.push(o.result),ui(t.options,`item ${r+1}/${e.length} end id=${s.item.id} status=${o.failed===0?"passed":"failed"} passed=${o.passed} failed=${o.failed} skipped=${o.skipped}`)}},HL=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(s=>s.run_results),r=bd(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}`)},VL=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}),WL=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(" "),YL=async(e,t)=>{let n=T(process.cwd(),t.path);if(!await k(C(n)))throw new l(`Tracker is not initialized at ${n}. Run pm init first.`,d.NOT_FOUND);let r=await A(n),s=await $L({pmRoot:n,settings:r,options:e}),o=kL(e.timeout),i=S(),a=await FL(s.filteredItems,t,n);return ui(e,WL({...s,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:s.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:o,runStartedAt:i}},JL=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}},nb=async(e,t)=>{let n=await YL(e,t),{accumulation:r,failOnEmptyTestRunTriggered:s}=zL(e,n.linkedTests,n.filteredItems),o=KL({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await BL(n.itemTests,o,r),HL(e,r);let i=JL({options:e,accumulation:r,failOnEmptyTestRunTriggered:s});return ui(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),VL({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered: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]="2643d11d-befc-5a87-8bec-760951eec4d0")}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]="c2567f6a-cd1c-56b5-a93d-41e92ed574bf")}catch{}})();function rb(){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]="7be35c3f-df6f-5ed6-b887-a7d8d53910a7")}catch{}})();var ob=[{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 install <target> --project","pm 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 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 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:"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"]}],sb=new Map;for(let e of ob){sb.set(e.id,e);for(let t of e.aliases)sb.set(t,e)}function kd(){return ob.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]="27be0fa5-1c6a-53de-a0e8-179aab7c795a")}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]="48da3e98-ab96-54de-8993-7de0c4edf19b")}catch{}})();var eB=[...Rr],tB=[...Ir],XL=new Set(Wn.filter(e=>e.hidden).map(e=>e.alias)),nB=eu("full").filter(e=>!XL.has(e)),rB=F(Gr),sB=F(jr),oB=F(Wr),iB=F(Zr),aB=F(es),cB=F(Xl),dB=F(Ql),lB=F(Qr),mB=F(ss),uB=F(ts),pB=F(ns),fB=F(Vr),_B=F(rs),hB=F(qr),gB=F(Kr,!1),yB=F(dm),bB=F(Hn),wB=F(Vn),vB=F(cs),kB=F(is),SB=F(Jr),EB=F(as),TB=F(os),AB=F(ds),CB=F(Yr),RB=F(Xr),IB=F(Br),xB=F(ls),OB=F(zr);var QL=F(ms),PB=`${QL} bash zsh fish`,NB=ZL(kd());var LB=F(Hr),FB=F(Bn);var $B=Ur.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function ZL(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]="0224a672-e326-5555-a4b4-1fa3550d9e61")}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]="8f02f498-5cee-59fa-9f4e-fd882c58d401")}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]="c770afea-3eb6-5476-ba07-8ec1c5d9c699")}catch{}})();var db=Symbol("pm.active-extension-host-context");function Ie(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[db]=!0,n}run(t,n={}){return lb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return of(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return sa(await this.list(ra(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,...Ie({...r,body:n})})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,s,o={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...s===void 0?{}:{value:s},options:o})}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,s){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...s?{fieldTypeScope:s}:{}}})}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={},s,o){return this.runTyped("plan",{...n===void 0?{}:{id:n},...s===void 0?{}:{stepRef:s},...o===void 0?{}:{reorderTo:o},options:{...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,s={}){return this.plan("reorder-step",t,s,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",Ie(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ie(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,...Ie(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ie(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ie(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ie(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ie(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ie(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},...Ie(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ie(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ie(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ie(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 tF(e={},t={}){return new G(t).context(e)}function nF(e={},t={}){return new G(t).list(e)}function rF(e={},t={}){return new G(t).listAllComplete(e)}function sF(e,t={},n={}){return new G(n).search(e,t)}function oF(e,t={},n={}){return new G(n).get(e,t)}function iF(e={},t={}){return new G(t).next(e)}function aF(e={},t={}){return new G(t).aggregate(e)}function cF(e,t={},n={}){return new G(n).comments(e,t)}function dF(e,t={},n={}){return new G(n).notes(e,t)}function lF(e,t={},n={}){return new G(n).learnings(e,t)}function mF(e,t={},n={}){return new G(n).files(e,t)}function uF(e,t={},n={}){return new G(n).filesDiscover(e,t)}function pF(e,t={},n={}){return new G(n).docs(e,t)}function fF(e,t={},n={}){return new G(n).deps(e,t)}function _F(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 gF(e={},t={}){return new G(t).create(e)}function yF(e,t={},n={}){return new G(n).update(e,t)}function bF(e,t,n={},r={}){return new G(r).reopen(e,t,n)}function wF(e,t,n={},r={}){return new G(r).close(e,t,n)}function vF(e,t={},n={}){return new G(n).claim(e,t)}function kF(e={},t={}){return new G(t).claimNext(e)}function SF(e,t={},n={}){return new G(n).release(e,t)}function EF(e,t={},n={}){return new G(n).copy(e,t)}function TF(e,t={},n={}){return new G(n).delete(e,t)}function AF(e,t,n={},r={}){return new G(r).restore(e,t,n)}function CF(e,t={},n={}){return new G(n).focus(e,t)}function Xe(e,t){let n=w(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}var ib=ou(),RF=new eF;function pi(){Vi(Xd()),Wi(Qd()),Yi(Zd()),Ji(el()),Xi(tl()),Qi(nl()),Zi(rl())}async function IF(e,t,n,r){return iu(()=>t===void 0?ib.read(()=>ab(e,n,r)):ib.write(()=>OF(t,()=>ab(e,n,r))))}async function ab(e,t,n){let r=T(t,e.path);if(e.noExtensions)return pi(),La({pmRoot:r},()=>n(null));if(!await k(C(r)))return pi(),n(null);let s=null,o;try{let i=await A(r),a=await Mr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Dr({...a,loaded:a.loaded});o={loadResult:a,activationResult:c},Vi(c.hooks),Wi(c.commands),Yi(c.parsers),Ji(c.preflight),Xi(c.services),Qi(c.renderers),Zi(c.registrations),s={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){pi(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await La({pmRoot:r,packages:s?.packages},()=>n(s))}finally{pi(),o&&await sl(o.loadResult,o.activationResult).catch(()=>{})}}async function xF(e,t,n,r,s){if(!s)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let o=Ht(e),a=s.registrations.commands.find(m=>Ht(m.action)===o)?.command??s.commands.handlers.find(m=>Ht(m.command)===o)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=await vs({command:ua(a),args:ye(n.args??t.args),options:pa(t,n),global:r,pm_root:s.pmRoot,sdk:lf(s.pmRoot,G.forActiveExtensionHost({pmRoot:s.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 l(`Unsupported native pm action: ${e}${m}`,d.USAGE)}return c.result}async function OF(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var PF=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function NF(e){let t=Xe(e,"action"),n=Ht(t),r=_i(cf,n),s=r?.action??n,o={...e,action:s};return r?.options!==void 0&&(o.options={...r.options,...Ni(e.options)}),s==="package"&&(o.options={...Ni(o.options),vocabulary:"package"}),{action:s,args:o}}function LF(e){return!PF.has(Ht(e))}async function lb(e){let t=NF(e),n=da(t.args),r=LF(t.action),s=w(t.args,"cwd"),o=s??process.cwd();try{return e[db]===!0||RF.getStore()===!0?await cb(t.action,t.args,n,null):await IF(n,s,o,i=>cb(t.action,t.args,n,i))}finally{r&&xa()}}function _i(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function fi(e){return w(e.args,"target")??w(e.options,"target")}function Y(e,t=e.options){return e.id??Xe(t,"id")}async function FF(e){let t=pn("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),Ia(await It(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function $F(e){let t=Xe(e.args,"query"),n=pn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Ia(await or(t,n,e.global),n)}async function MF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await xt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function DF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options),s={...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 Ge(await vc(Y(e,s),s,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function UF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await at(Y(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function GF(e){let t=io(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")),Af(Y(e),t,e.global)}function mb(e,t){return qp(Sg(e.options,t,Fe),e.global)}function jF(e){let t=ye(e.options.lookupPath);if(t&&t.length>0)return mb(e,t);let n=Y(e);return e.options.discover===!0?ha(n,ma(e.options),e.global):jp(n,Vs(e.options),e.global)}function qF(e){return vy({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:ip(e.args,e.options)},e.global)}function KF(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Up(e.global,t)}function zF(e){let t=w(e.args,"configAction")??w(e.options,"configAction")??w(e.options,"action");if(t===void 0)throw new l("Missing required argument: configAction",64);return Y_(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),e.options,e.global,w(e.args,"value")??w(e.options,"value"))}function BF(e){let t=e.options;return Xu(Ju(t),e.global)}function HF(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new l(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new l(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new l(`${t} must be a finite integer.`,64);return r}}function VF(e){let t=w(e.args,"subcommand")??Xe(e.options,"subcommand"),n=e.options;return C_({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:WF(e),reorderTo:HF(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function WF(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function YF(e){let t=w(e.args,"subcommand")??Xe(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:ye(n)}}function JF(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,a=_i({list:()=>Sp(t.global),show:()=>Ep(r,t.global),"show-status":()=>Tp(r,t.global),"list-fields":()=>Rp(t.global),"show-field":()=>Ip(r,t.global),"remove-type":()=>bp(r,{author:s,force:o},t.global),"remove-field":()=>Cp(r,{author:s,force:o},t.global),"remove-status":()=>kp(r,{author:s,force:o},t.global),"apply-preset":()=>xp(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:s,force:o},t.global)},n);return a?a():null}function XF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return Ap(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:ye(i),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:o,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:ye(a),author:r,force:s},t.global)}function QF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e,i=t.args.role??t.options.role;return vp(n,{role:i===void 0?void 0:ye(i),alias:o,description:w(t.args,"description")??w(t.options,"description"),order:Fe(t.args.order??t.options.order,"schema add-status order"),author:r,force:s},t.global)}function ZF(e){let{ctx:t,name:n,author:r,force:s,aliases:o}=e;return yp(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:o,author:r,force:s},t.global)}function e$(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,i=w(t.args,"to")??Xe(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 hp(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:s,force:o},t.global)}function t$(e){let t=YF(e),n=JF(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return e$(t);if(t.subcommand==="add-field")return XF(t);if(t.subcommand==="add-status")return QF(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?Op({minCount:Fe(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):ZF(t);throw Te({command_path:"schema",token:t.subcommand,allowed:gp,exit_code:64})}function n$(e){let t=w(e.args,"subcommand")??Xe(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),o=_i({list:()=>cg(),show:()=>dg(r),lint:()=>lg(r),apply:()=>mg(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(!o)throw Te({command_path:"profile",token:t,allowed:ag,exit_code:64});return o()}async function r$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await uf(Y(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function s$(e){let{changedFields:t,runnerOptions:n}=$e(e.args,e.options);return Ge(await __(_a(n),e.global),{changedFields:t})}async function o$(e){let{changedFields:t,runnerOptions:n}=$e(e.args,e.options),r=w(e.args,"reason"),s=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&s.force===void 0&&(s.force=!0),Ge(await Tf(fa(s),e.global),{changedFields:t})}async function i$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options),s=w(r,"target")??Xe(e.args,"target");return Ge(await Wt(Y(e,r),s,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function ub(e){let t={...e};return delete t.assignee,t}async function a$(e){let t=T(process.cwd(),e.global.path),n=await A(t),r=Qo(M(n.schema)),s=Y(e),o=await co(s,e.force,e.global,e.options),i=await at(s,{...ub(e.options),status:r,force:e.force},e.global);return{id:s,action:"start_task",claim:o,update:i}}async function c$(e){let t=T(process.cwd(),e.global.path),n=await A(t),r=Y(e),s=M(n.schema).open_status,o=await at(r,{...ub(e.options),status:s,force:e.force},e.global),i=await lo(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:o,release:i}}async function d$(e){let t=Y(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await it(t,n,{...e.options,force:e.force},e.global),s=await lo(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:s}}function l$(e){let t={...e.args,...e.options};return np(Xe(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),dp(t),e.global)}function m$(e){return mp(T(process.cwd(),e.global.path),{...e.args,...e.options})}var u$={init:e=>_r(w(e.args,"prefix"),e.global,e.options),context:e=>Aa(pn("context",e.options),e.global),next:e=>sr(pn("next",e.options),e.global),eval:Jh,events:Xh,merge:Qh,workspace:Zh,meet:Jo,event:Jo,remind:Jo,list:FF,get:e=>{let t=Y(e);return Ca(t,e.global,pn("get",e.options,[t]))},search:$F,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ye(e.options.status);return Ra(e.global,{...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:Fe(e.options.limit,"limit")})},create:MF,copy:DF,focus:e=>Sc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:UF,"item-reopen":kg,restore:i$,claim:e=>e.options.next===!0||e.args.next===!0?bf(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):co(Y(e),e.force,e.global,e.options),release:e=>lo(Y(e),e.force,e.global,e.options),"start-task":a$,"pause-task":c$,"close-task":d$,close:vg,comments:GF,notes:e=>Rf(Y(e),io(e.options),e.global),learnings:e=>Cf(Y(e),io(e.options),e.global),files:jF,docs:e=>Gp(Y(e),Vs(e.options),e.global),test:e=>li(Y(e),e.options,e.global),"test-all":e=>nb(e.options,e.global),telemetry:qF,validate:e=>Qs(e.options,e.global,{runUpdate:(t,n,r)=>at(t,n,r)}),health:KF,assurance:e=>Xp(e.args,e.options,e.global),contracts:e=>Hg(e.options,e.global),config:zF,activity:BF,aggregate:e=>Sa(e.options,e.global),extension:e=>Cn(fi(e),e.options,e.global),package:e=>Cn(fi(e),e.options,e.global),install:e=>Cn(fi(e),{...e.options,install:!0},e.global),upgrade:e=>nf(fi(e),e.options,e.global),delete:e=>kc(Y(e),e.options,e.global),deps:e=>tp(Y(e),e.options,e.global),graph:l$,"files-discover":e=>ha(Y(e),e.options,e.global),"files-lookup":e=>mb(e,ye(e.options.paths)),history:e=>tf(Y(e),e.options,e.global),"history-redact":e=>Lu(Y(e),e.options,e.global),"history-repair":gg,"history-compact":yg,"history-author-acknowledge":m$,plan:VF,schema:t$,profile:n$,stats:e=>cd(e.global,my(e.options)),append:r$,"update-many":s$,"close-many":o$,gc:e=>rf(e.global,e.options)};async function cb(e,t,n,r){let s=la(t,e);zi(e,s),Um(e,s);let o={action:e,args:t,options:s,id:w(t,"id"),force:t.force===!0||s.force===!0,global:n,activeExtensions:r},i=_i(u$,e),a=i?await i(o):await xF(e,t,s,n,r);return s.resolvedOutputFormat="json",Jm(e,s,a)}var p$={closeManyOptionsFromFlat:fa,extensionOptionsFromArgs:pa,globalOptions:da,mutationListOptions:cp,normalizeActionName:Ht,normalizeCommandPath:ua,normalizeMcpUpdateOptions:lp,normalizeMcpOptionsArrays:ap,optionsWithAuthor:la,readRequiredString:Xe,readScalarString:sp,readScalarStringAllowBlank:op,readStringArray:ye,updateManyOptionsFromFlat:_a,withAddNoteOption:Vs,withFilesDiscoveryOptions:ma,withMutationCompaction:$e};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=p$);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d19cfa31-a02f-53a7-8685-5d169d6e051d")}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]="cc0d4dd1-20e8-59d4-acb5-9f8ed639d35f")}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]="f44898af-0809-51e1-a6fb-74716c0971f5")}catch{}})();export{hn as AGENT_PROVENANCE_DIMENSIONS,lu as BASELINE_ITEM_FORMAT_VERSION,Yn as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,Rr as BUILTIN_ITEM_TYPE_VALUES,xr as CONFIDENCE_TEXT_VALUES,mu as CURRENT_ITEM_FORMAT_VERSION,Dt as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,dn as ISSUE_SEVERITY_VALUES,$d as ITEM_TYPE_VALUES,Oa as PM_CLI_EXPECTED_ERROR_NAME,iw as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,sw as PM_READ_OUTPUT_DIMENSIONS,ow as PM_READ_OUTPUT_OPTION_FLAGS,Ki as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,G as PmClient,cn as RISK_VALUES,Cw as SEMANTIC_ATTRIBUTION_LIMITS,Ir as STATUS_VALUES,hw as agentSessionEnvironment,aF as aggregate,id as analyzeAgentProvenanceDescriptorCoverage,uw as analyzeSdkCliParameterCompleteness,hF as append,dw as applyReadOutputDimensions,Zb as applyReadOutputSessionReferences,ew as attachReadOutputSessionReceipt,pw as boundAgentEpisodeIdentity,We as canonicalDocument,vF as claim,kF as claimNext,fu as classifyItemFormatVersion,wF as close,cF as comments,tF as context,EF as copy,gF as create,df as createPmCliExpectedError,rw as decodeReadOutputContinuationCursor,TF as deleteItem,fF as deps,ww as detectAgentIdentity,Sw as detectHarnessIdentity,vw as diagnoseAgentIdentity,pF as docs,uu as effectiveItemFormatVersion,rb as emptyImportedDocument,nw as encodeReadOutputContinuationCursor,GO as evaluateSemanticAttributionCoverage,Tw as explainSourceTraceability,mF as files,uF as filesDiscover,CF as focus,oF as get,_F as graph,jO as groupHistoryByEpisode,yf as isAlreadyClaimedError,ro as isPmCliExpectedError,lw as isReadOutputBudgetExceeded,lF as learnings,nF as list,rF as listAllComplete,iF as next,pu as normalizeItemFormatVersion,ge as normalizeItemId,W as normalizeStatusInput,dF as notes,S as nowIso,Qb as parseReadOutputSession,Ys as parseSourceLineRange,Ss as readAuthorEnvironment,tw as readOutputSessionRemainingTokens,Ea as recordClaimSemanticAttribution,eo as recordFocusSemanticAttribution,Ta as recordReleaseSemanticAttribution,gw as registerHarnessSignalDescriptors,SF as release,bF as reopen,fw as resolveAgentSessionContextFromSignals,Ew as resolveAuthorIdentity,ty as resolveHistoryEpisodeGroupIdentity,cw as resolveReadOutputDimensions,mw as resolveReadOutputEncoding,aw as resolveReadOutputSurface,Aw as resolveSemanticLineageIds,AF as restore,lb as runAction,_w as runWithAgentSessionContext,yw as runWithHarnessDetectionSignals,bw as runWithWorkspaceHarnessSignalDescriptors,sF as search,Rw as semanticAttributionAffinity,je as serializeItemDocument,UO as summarizeAgentModelProvenance,ad as summarizeAgentProvenance,yF as update,zi as validateReadOutputOptions,kw as writeAuthorEnvironment};
|
|
55
55
|
//# sourceMappingURL=sdk-core.js.map
|