@unbrained/pm-cli 2026.8.18 → 2026.8.19
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 +16 -2
- package/dist/cli/error-guidance.js +3 -2
- package/dist/cli/help-content.js +32 -13
- package/dist/cli/help-json-payload.d.ts +15 -0
- package/dist/cli/help-json-payload.js +101 -23
- package/dist/cli/main.js +6 -2
- package/dist/cli/register-list-query.js +8 -5
- package/dist/cli/register-mutation.js +8 -8
- package/dist/cli/register-operations.js +6 -6
- package/dist/cli-bundle/bundle-manifest.json +139 -139
- package/dist/cli-bundle/chunks/chunk-4NRRH7AM.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-UYCLQVL2.js → chunk-4THEB6PD.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BSK2IN3C.js → chunk-BHYMXLAE.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GWMXAQOD.js +197 -0
- package/dist/cli-bundle/chunks/chunk-HVFQTLYM.js +35 -0
- package/dist/cli-bundle/chunks/chunk-OI4XI562.js +5 -0
- package/dist/cli-bundle/chunks/{chunk-YRGOLZA7.js → chunk-OIOKV6NO.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-5UZZAJKR.js → chunk-QXSH7BLM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-RZQTVMRQ.js → chunk-TOXJM4WA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GNFAFIJI.js → chunk-YBMRWW4E.js} +44 -44
- package/dist/cli-bundle/chunks/{register-list-query-I23LALEE.js → register-list-query-Y56KINDU.js} +11 -11
- package/dist/cli-bundle/chunks/register-mutation-AUWVCW4M.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-PZQPHXW5.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-PPPEF3SN.js → register-setup-I4LUHGVW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5AF3ZBNB.js → chunk-34QBIYZI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-V5XTGLK7.js → chunk-BJRYFVSH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-DKPLYW3L.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ODOVCP45.js → chunk-EF6ZS5GH.js} +44 -44
- package/dist/cli-bundle/focused-chunks/{chunk-EX6MKP2X.js → chunk-ESISGDAY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EUEGXZ2A.js → chunk-EXBCLIBU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UI6AJ5TD.js → chunk-JDOMQ7VQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-L623ZPNK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-MCZXYZAF.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-ODHQEECS.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3TKWMNKF.js → chunk-PRHY2IMX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-RZU5U6Q7.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-M62NO7EI.js → chunk-US7VEYZG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TN4AE665.js → chunk-VXDSU5MC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-YBMGXBFV.js +16 -0
- package/dist/cli-bundle/focused-chunks/chunk-YLVBJ6GF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-K43KKAFS.js → chunk-ZBIQQYMI.js} +2 -2
- package/dist/cli-bundle/main.js +13 -13
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -1
- package/dist/cli-bundle/sdk-core.js +31 -31
- 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 +32 -32
- 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 -4
- package/dist/core/shared/errors.d.ts +2 -0
- package/dist/core/shared/errors.js +2 -2
- package/dist/sdk/agent/refusal-closure.d.ts +41 -0
- package/dist/sdk/agent/refusal-closure.js +92 -0
- package/dist/sdk/agent/refusal-reachability.d.ts +1 -1
- package/dist/sdk/agent-capability-contracts.d.ts +13 -0
- package/dist/sdk/agent-capability-contracts.js +104 -7
- package/dist/sdk/cli-contracts/command-aliases.js +18 -2
- package/dist/sdk/cli-contracts/commander-mutation-options.js +30 -6
- package/dist/sdk/cli-contracts/commander-types.js +5 -4
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +5 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +75 -8
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.d.ts +55 -0
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +240 -0
- package/dist/sdk/cli-contracts/grammar-contracts.d.ts +81 -0
- package/dist/sdk/cli-contracts/grammar-contracts.js +615 -2
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +15 -4
- package/dist/sdk/cli-contracts/runtime-contracts.js +42 -12
- package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +28 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.js +38 -3
- package/dist/sdk/cli-contracts.d.ts +3 -2
- package/dist/sdk/cli-contracts.js +5 -4
- package/dist/sdk/context-intent-contracts.d.ts +2 -2
- package/dist/sdk/context-intent-contracts.js +22 -7
- package/dist/sdk/contracts.d.ts +2 -0
- package/dist/sdk/contracts.js +4 -2
- package/dist/sdk/flag-invocation-contracts.d.ts +37 -0
- package/dist/sdk/flag-invocation-contracts.js +218 -9
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +134 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +154 -22
- package/dist/sdk/index.d.ts +7 -5
- package/dist/sdk/index.js +7 -5
- package/dist/sdk/output-projection.d.ts +2 -0
- package/dist/sdk/output-projection.js +11 -5
- package/dist/sdk/query/get.js +25 -6
- package/dist/sdk/query/list.js +16 -2
- package/dist/sdk/query/search-contracts.d.ts +1 -1
- package/dist/sdk/query/search-contracts.js +23 -9
- package/dist/sdk/query/search.js +3 -3
- package/dist/sdk/read-output/continuation.d.ts +1 -1
- package/dist/sdk/read-output/continuation.js +7 -24
- package/dist/sdk/read-output-contracts.js +55 -6
- package/dist/sdk/read-output-rows.d.ts +4 -0
- package/dist/sdk/read-output-rows.js +47 -18
- package/dist/sdk/runtime.js +9 -5
- package/dist/sdk/workspace-snapshot.d.ts +2 -0
- package/dist/sdk/workspace-snapshot.js +10 -2
- package/docs/COMMANDS.md +16 -4
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +11 -2
- package/docs/READ_OUTPUT_CONTRACTS.md +10 -6
- package/docs/SDK.md +6 -0
- package/docs/TESTING.md +14 -1
- package/docs/generated/AGENT_COMMAND_SURFACE.md +78 -78
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +76 -0
- package/marketplace.json +2 -2
- package/package.json +5 -3
- 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/scripts/generate-agent-capability-surfaces.mjs +20 -14
- package/sdk/public-surface.json +576 -12
- package/dist/cli-bundle/chunks/chunk-ALDJGKAK.js +0 -2
- package/dist/cli-bundle/chunks/chunk-DY4DMUMC.js +0 -197
- package/dist/cli-bundle/chunks/chunk-L5Q2CLPE.js +0 -35
- package/dist/cli-bundle/chunks/chunk-PVRUN5ZS.js +0 -5
- package/dist/cli-bundle/chunks/register-mutation-6YGU3GPH.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-4HTFC6J7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2PN4TJXH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-C5IW2NDA.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-RNDNMARJ.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-TVV2DONO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-WGHQVU6P.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-XYNBXTDQ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-Z56ECT7I.js +0 -2
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
import{n as im,o as ms,p as mm,q as um,r as Ni,s as fs,t as pm,u as Li,v as _s,y as Im,z as xm}from"./focused-chunks/chunk-TN4AE665.js";import{c as Lm,d as dn,f as Fm,k as Mm,m as Dt,r as Gm,t as jm,x as qm}from"./focused-chunks/chunk-Z56ECT7I.js";import{$ as la,$a as Ip,Aa as lp,Ba as mp,Ca as up,Cb as Lp,Da as pp,Db as qp,Ea as fp,Eb as Kp,Fa as En,G as Gu,Ga as _p,Ha as hp,I as w,J as ju,Ja as Jn,K as qu,Ka as gp,L as Le,La as yp,M as Ku,Ma as bp,N as sa,Na as wp,O as zu,Oa as vp,P as oa,Pa as kp,Q as zs,R as ia,S as qt,Sa as Sp,T as aa,Ta as Vs,U as he,Ua as pw,V as ca,Va as Ep,W as Ve,Wa as Tp,X as Bu,Xa as ma,Y as Hu,Ya as Ap,Z as da,Za as Cp,_ as Vu,_a as Rp,a as ji,ab as xp,b as ku,bb as Op,cb as Xn,db as ua,eb as pa,fb as Ws,gb as fa,ha as Wu,hb as Pp,i as Fu,ib as _a,j as Mu,ja as Bs,jb as Ys,ka as Hs,kb as Tn,la as Yu,lb as ha,ma as Ju,mb as ga,na as Xu,nb as Np,oa as Qu,pa as Zu,qa as ep,qb as Js,ra as tp,sa as np,ta as rp,ua as sp,va as op,wa as ip,xa as ap,ya as cp,za as dp}from"./focused-chunks/chunk-ODOVCP45.js";import{e as rm,g as sm,h as om,k as am,q as lm}from"./focused-chunks/chunk-EUEGXZ2A.js";import{b as Om,c as hs,e as Pm,f as Nm,g as ew}from"./focused-chunks/chunk-XYNBXTDQ.js";import{G as Gi,K as Rm,a as Qd,b as Zd,c as el,d as tl,f as nl}from"./focused-chunks/chunk-C5IW2NDA.js";import{a as bu,b as wu,c as Zs}from"./focused-chunks/chunk-K43KKAFS.js";import{Z as Uu,b as vu,e as $u,f as Wn,g as Yn,i as ra,t as Du}from"./focused-chunks/chunk-V5XTGLK7.js";import{$a as va,D as Xs,E as Mp,Ea as fw,F as Zn,Fa as ba,G as $p,Ga as wa,Ha as Qs,Ia as _w,Ja as hw,L as Dp,M as Up,N as Gp,R as Et,T as ya,c as Qi,e as Zi,eb as er,g as _u,gb as jp,h as Cs,i as ea,j as hu,k as Rs,kb as ka,l as Is,m as xs,n as gu,o as yu,s as Iu,t as xu,u as Ou,v as Pu,w as Nu,x as Lu,xb as tr,y as Qn,yb as Sa}from"./focused-chunks/chunk-RNDNMARJ.js";import{A as ta,B as Ks,Ca as Ru,D as Eu,E as Tu,Ea as eo,F as Vn,Ia as An,a as Os,b as Ps,c as Ns,d as Ls,h as Fs,j as Ms,k as $s,l as Su,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 Au,x as se,xa as na,y as vn,ya as Cu,z as kn}from"./focused-chunks/chunk-3TKWMNKF.js";import{c as em,f as tm,g as nm,i as ls,j as gt,k as fm,l as _m,m as hm}from"./focused-chunks/chunk-EX6MKP2X.js";import{$ as Gl,A as Gn,Aa as ss,B as hl,Ba as os,C as gl,Ca as Zl,D as yl,Da as ht,E as bl,Ea as is,F as wl,Fa as as,G as vl,Ga as cs,H as kl,Ha as ds,I as Sl,J as El,K as Tl,L as Al,La as F,M as Cl,N as Rl,O as Il,P as xl,Q as Ol,R as Pl,S as Nl,T as Br,U as Hr,V as Ll,W as Fl,X as Ml,Y as $l,Z as Dl,_ as Ul,aa as jl,c as Pi,ca as ql,da as Kl,e as $r,ea as zl,f as Dr,fa as Bl,g as Ur,ga as Hl,h as rl,ha as Vl,i as sl,ia as Vr,j as ol,ja as Wr,k as il,ka as Yr,l as al,la as Wl,m as Gr,ma as Yl,n as cl,na as Jr,o as dl,oa as Jl,p as ll,pa as Xl,q as jr,qa as Xr,r as ml,ra as Qr,s as ul,sa as Zr,t as pl,ta as es,u as qr,ua as jn,v as Kr,va as ts,w as fl,wa as Ql,x as zr,xa as qn,ya as ns,z as _l,za as rs}from"./focused-chunks/chunk-TVV2DONO.js";import{c as Fp}from"./focused-chunks/chunk-M62NO7EI.js";import{$a as mu,Ab as Ee,Da as De,Ea as wt,F as bs,G as Bm,Ga as Ss,H as Hm,Ha as Pe,I as pn,Ia as Gt,J as Bn,Ja as su,K as ow,Ka as jt,L as iw,La as ou,M as aw,N as cw,Na as iu,O as dw,Oa as hn,P as ws,Pa as au,Q as lw,Qa as Es,R as mw,Ra as ot,S as uw,T as fn,U as R,V as S,Wa as cu,X as _n,Xa as du,Ya as vt,Z as Q,_ as xe,_a as lu,a as Km,ab as A,ba as Vm,bb as Se,c as zm,ca as vs,cb as uu,da as Wm,db as pu,e as qi,ea as Ym,eb as kt,f as Ki,fa as Jm,fb as Xi,g as zi,ga as Xm,gb as _e,h as Bi,ha as Qm,hb as Hn,i as Hi,j as Vi,ja as ne,k as Wi,l as I,la as Oe,m as mn,ma as ks,n as Ut,na as Yi,nb as gn,o as z,oa as Zm,p as gs,pa as $e,pb as yn,q as un,qa as He,ra as bt,rb as $,sa as eu,sb as K,t as ys,ta as tu,ua as Ji,ub as re,v as st,vb as Ts,w as tw,wa as nu,wb as As,x as nw,xa as ru,xb as it,y as rw,yb as Y,z as sw,zb as fu}from"./focused-chunks/chunk-5AF3ZBNB.js";import{$ as Ud,B as xi,C as Dn,D as fe,G as x,Ga as Fr,H as ue,Ha as Xd,I as Pr,Ia as Mr,J as an,K as Un,L as $d,La as nt,M as T,N as Dd,Na as us,O as et,Oa as rt,P as C,Pa as yt,Q as $t,Qa as cm,S as ke,Sa as j,T as Nr,Ta as ps,Ua as Be,Wa as dm,Z as cn,ba as Oi,ca as Gd,ea as jd,ga as Lr,h as ft,i as xr,ia as qd,j as Or,ja as Kd,la as zd,ma as Bd,na as Hd,oa as Vd,pa as Wd,q as k,qa as Yd,r as Mt,ra as Jd,s as _t,t as q,u as me,w as on}from"./focused-chunks/chunk-UI6AJ5TD.js";import{f as $m,g as Dm,j as ln,n as Um}from"./focused-chunks/chunk-WGHQVU6P.js";import{$a as Vb,A as Pd,B as Nd,C as Ld,Ca as Gb,D as Fd,Da as jb,E as Si,Ea as qb,F as Ei,Fa as Kb,G as Ti,Ga as Am,H as Ai,I as Ci,J as Ri,Ma as $i,Oa as zb,Pa as Bb,Q as Ii,S as Ir,T as Md,W as pt,Y as d,Z as l,Za as Hb,aa as J,ab as Wb,ba as tt,bb as Di,cb as Yb,db as Ui,ea as Kn,gb as Cm,hb as Jb,ia as gm,ja as ym,jb as Xb,ka as bm,kb as Qb,l as Ar,la as wm,lb as Zb,m as Id,ma as vm,n as Cr,na as km,o as ki,oa as zn,pa as Sm,qa as Em,s as Ft,sa as Fi,t as Ze,ta as Tm,u as rn,ua as Mi,v as sn,w as Rr,y as xd,z as Od}from"./focused-chunks/chunk-2PN4TJXH.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 zp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function gw(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 Ea(e,t){let n=gw(t),r=n==="brief"?n:zp(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:zp(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 Bp(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 yw=new Map;function Ta(){yw.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 bw={"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 Hp(e){return Object.fromEntries(Em.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Vp={ctx:{action:"context"},...bw,...Hp("extension"),...Hp("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 Aa="PmCliError";function ww(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 Wp(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,ww(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 to(e){if(!(e instanceof Error)||e.name!==Aa)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 Ca(e){let t=jd();for(let n of e)t.register(n);return t}function Yp(e,t){return{client:t,isItemNotFoundError:n=>to(n)&&n.exitCode===d.NOT_FOUND,getItemAt:(n,r)=>yu(n,r,{pmRoot:e}),openRelationshipEventStore:n=>wu.open({pmRoot:e,nodes:n.nodes,registry:Ca(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new Kd(n.nodes,n.edges,Ca(n.definitions)),analyzeRelationshipImpact:(n,r,s)=>vu(n,r,s),validateRelationshipEvents:n=>{let r=new bu(n.nodes,{registry:Ca(n.definitions)});return n.events.map(s=>r.append({...s,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>ku({...n,pmRoot:e})}}import{readFile as vw}from"node:fs/promises";import kw 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 Ra="context-intents.json";function no(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sw(e,t,n){if(!no(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 Jp(e,t){let n=Array.isArray(e)?e:no(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)=>Sw(r,t,s))}async function Ew(e){let t=kw.join(e,Ra),n;try{n=await vw(t,"utf8")}catch(s){if(Mt(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 ${Ra}: ${o}`,{cause:s})}return Jp(r,Ra)}function Tw(e){if(!no(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return no(n)?n.contextIntents??n.context_intents:void 0}function Aw(e){return e.flatMap(t=>{let n=Tw(t.module);return n===void 0?[]:Jp(n,`package ${t.name}`)})}async function Cw(e){let t=await Ew(e.pmRoot),n=Aw(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Ia(e,t){let n=await Cw(e);return await Dm(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 Xp(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 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?`
|
|
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 Rw}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 so(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,t}function Qp(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 xa(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Kt(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 Oa(e){return typeof e=="object"&&e!==null&&"code"in e}async function Iw(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 Rw(s,"utf8"),emptyFlag:"--file"}}catch(o){if(Oa(o)&&Mt(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 oo(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 Iw(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 rr(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 ef(e){return e==="comments"?"--stdin":"--add -"}function xw(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=ef(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 Ow(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> ${ef(e.collectionKey)}`]})}async function Rn(e,t,n,r){Ow(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=Vn(t.limit);if(r.input.mode==="list"){let _=await $(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=Kt(h.document.metadata,r.collectionKey);return ro(_.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=Kt(g.metadata,r.collectionKey),v=Zp(r.input.index,b.length,r.collectionKey);return Qp(b[v],"deleted"),b.splice(v,1),g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){rr(g,r.conflictGuidance)}let y=Kt(h.item,r.collectionKey);return ro(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??"";xw(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=Kt(g.metadata,r.collectionKey),v=Zp(r.input.index,b.length,r.collectionKey),E=b[v];return Qp(E,"edited"),b[v]={...E,text:u,edited_at:S()},g.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(g){rr(g,r.conflictGuidance)}let y=Kt(h.item,r.collectionKey);return ro(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=Kt(_.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(_){rr(_,r.conflictGuidance)}let f=Kt(p.item,r.collectionKey);return ro(p.item.id,r.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:f.length,entry:f.at(-1)},t.fullHistory===!0)}function Zp(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 ro(e,t,n,r,s,o,i=!1){let a=o===void 0||i?xa(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 tf(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 nf="no_available_next_item";function rf(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 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=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,dm(_.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 tf(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 ba({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 sf(e,t,n={},r={}){let s=Pw(n.maxAttempts),o=await A(T(process.cwd(),t.path)),i={...n,author:R(n.author,o.author_default)},a=await er({...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 Nw(c.slice(0,s),e,t,i)}function Pw(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 Nw(e,t,n,r={},s=io){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(!rf(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:[nf]};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:nf,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 ao(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){rr(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 wa({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 Lw=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function of(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 Pa(e,t){return Na(e,t,{operation:"close"})}function Na(e,t,n){let r=of(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 La(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 Fw=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function Mw(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 $w(e){let t=[];for(let n of Fw){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function Dw(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 Uw(e){return typeof e!="string"||e.trim().length===0}async function Gw(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 $(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 Dw(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 jw(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 qw(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),s=Fp(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 Kw(e,t,n,r,s,o){let i=qw(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 zw(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 Bw(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)Uw(e[s])&&(e[s]=o,n.push(s));return n}function Hw(e,t,n,r){let s=[];if(t!=="off"){let o=$w(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 Vw(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function Ww(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function Yw(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=zw(e,t.options),r=Bw(e,t.duplicateOf),s=Hw(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"]:[],...Vw(e,t.closeReason),...n];if(Cu(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(...Ww(e));let a=La(e,t.lifecyclePolicy);return i.push(...a.changedFields),s.push(...a.warnings),{changedFields:i,...s.length>0?{warnings:s}:{}}}async function af(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 $(s,e,o.id_prefix,o.item_format,c);if(!m)throw await it(s,e,o.id_prefix,c);let u=await Gw(s,o,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??o.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=Pa({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=Mw(n.validateClose)??o.governance.close_validation_default,h=await re(s,o.item_format,c,void 0,o.schema),y=jw(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 Yw(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 Kw(s,o,h,m.id,a,i)]}}function Tt(e,t,n,r){return af(e,t,n,r)}import Jw from"fast-json-patch";import Fa 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 Xw(e,t){return _u(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Qw(e){let t=ea(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:He(Gt(t))}async function Zw(e,t,n,r){let s=await $(e,t,n.id_prefix,n.item_format,r);if(s){let c=ke(e,s.id),m=await uu({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=Xi(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 ev(e,t){let n=jt(e),r=jt(t),s=Jw.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 tv(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 $(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 nv(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Qw(t),originalRaw:null}}function rv(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 sv(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await me(e.existingItemPath,e.resolvedOriginalRaw),await Fa.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await me(e.existingItemPath,e.resolvedOriginalRaw);return}await Fa.rm(e.restoredItemPath,{force:!0})}async function ov(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 zt(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 Zw(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=Xw(t,u),f=hu(ea(u,p.historyIndex),p),_=su(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 tv({pmRoot:s,resolvedId:c,subject:a,settings:o,typeToFolder:i.type_to_folder,historyRawBeforeLock:m,currentItemRawBeforeLock:y}),N="toon",P=nv(v,u),M=rv({document:P.document,author:g,force:n.force,enforcement:o.governance.ownership_enforcement,resolvedId:c}),G=ev(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=$e(_,{format:N,schema:o.schema}),ee=$t(s,_.metadata.type,c,N,i.type_to_folder),pe=await gn(s,g),ie=[];try{await me(ee,Ie),E&&ee!==E&&await Fa.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 sv({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 ov({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:Ut(P.document.metadata,G),current:Ut(_.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,...M,...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 df=1,Ma="close-many",iv=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function av(e,t){return Qn(e,t,{includePagination:!1})}function cv(e,t){return Qn(e,t)}function dv(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 lv(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 mv(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 uv(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 cf(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 pv(e){let t=await Ns(e.pmRoot,Ma,e.rollbackId,df),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Ls(t.items,(s,o)=>zt(s,o,{author:e.options.author,message:n,force:!0},e.global));return{...Dt({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 fv(e,t,n,r,s){return e.map(o=>{let i=(t.get(o.id)??[]).filter(c=>!n.has(c)),a=!lf(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 _v(e){let t=await Ps(e.pmRoot,Ma,e.checkpointId,{schema_version:df,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 hv(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:cn(s)})}}return{rows:t,closedIds:n}}function gv(e){return typeof e.rollback=="string"?e.rollback:void 0}function yv(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(cv(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function bv(e){if(!av(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${iv}). Refusing to match every item.`,d.USAGE)}function wv(e,t){let n=new Map;return[...e].sort((r,s)=>{let o=cf(s.id,t,n)-cf(r.id,t,n);return o!==0?o:r.id.localeCompare(s.id)})}function lf(e,t,n){return n||!Oe(e.status,t)}function vv(e,t,n){return new Set(e.filter(r=>lf(r,t,n)).map(r=>r.id))}async function kv(e){bv(e.options);let t=j(e.settings.schema),n=mv(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,s=await Et(e.options.status,lv(e.options.list),e.global),{childrenByParent:o,parentByChild:i}=await uv(e.pmRoot,e.settings),a=wv(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=vv(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:fv(a,o,u,t,r)}}function Sv(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 Ev(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 _v({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 mf(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=gv(e);if(dv(e.list),o!==void 0)return yv(e,o),pv({pmRoot:n,rollbackId:o,options:e,global:t});let i=await kv({pmRoot:n,settings:r,options:e,global:t});if(s)return Sv(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=S(),m=Os(Ma,c),u=await Ev({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 hv({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{...Dt({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 Tv}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 $a(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 Tv(i,"utf8"),emptyFlag:"--file"}}catch(a){if(Oa(a)&&Mt(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 Av(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 $a(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 $a(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 $a(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 uf(e,t,n){let r=Ne(),s=await Av(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 pf(e,t,n){return Rn(e,t,n,{input:await oo(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 Cv(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 Rv(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 Iv(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 ff(e,t,n){let r=Cv(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=Iv(t.since),c=Vn(t.limit),m=await Rn(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await oo(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:Rv(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?xa(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 co(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 sr(e,t,n=ra()){for(let r of t??[])try{qd(e,r.id,r.kind,n)}catch(s){throw new l(cn(s),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function _f(e,t){return(await K(e,{schema:t})).document.metadata.created_at}async function xv(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await $(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:_f(n,t.schema)}function Ov(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 Pv(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 _f(n.get(s),e.context.schema)])));for(let s of e.holders){let o=await xv(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 Ov({holder:s,dependency:i,sourceCreatedAt:o,targetCreatedAt:a,registry:e.registry})}}}async function Bt(e){let t=e.registry??ra(),n=(e.dependencies??[]).filter(i=>!$u(i.source_kind)),r=[...new Set(n.map(i=>i.id))],s=await Promise.all(r.map(async i=>({target:i,located:await $(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 Pv({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 lo(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function mo(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function uo(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Rr.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 po(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 Nv=new Set(["none","null"]);function fo(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:Nv.has(e.trim().toLowerCase())}function _o(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 ho(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 gf(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 Da(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 yf=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Lv(e,t){return t==="defined"?e!==void 0:!!e}function hf(e,t,n){if(!Lv(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 Fv(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 Mv(e){return Array.from(new Set(Da(e).map(t=>ye(t.toLowerCase(),Fd,"event weekday")))).sort((t,n)=>Si(t)-Si(n))}function $v(e){return Array.from(new Set(Da(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 Dv(e,t){return Array.from(new Set(Da(e).map(n=>Q(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function bf(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(),Ld,"event recurrence frequency"),_=hf(o,"recur_interval",r),h=hf(i,"recur_count",r),y=Fv(a,t,n),g=Mv(c),b=$v(m),v=Dv(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 wf="--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.",Uv="--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).",Gv=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,jv=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,kf=1e3,Ua=60*kf,qv=60*Ua;function vf(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 Kv(e,t){let n=new Date(e),r=t.trim(),s=Gv.exec(r);if(s){let a=s[1]==="-"?-1:1,c=Number.parseInt(s[2],10)*a;return vf(n.getTime()+c*Ua,r)}let o=jv.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=_*qv+h*Ua+y*kf;return vf(n.getTime()+f*g,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return Q(i,n,"event.duration")}function Sf(e,t,n,r){if(t&&n)throw new l(Uv,d.USAGE);if(n){let o=Kv(e,n);if(o<e)throw new l(wf,d.USAGE);return o===e?void 0:o}if(!t)return;let s=Q(t,r,"event.end");if(s<e)throw new l(wf,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 zv=["at","date","text","title"],Bv=["start","date","end","duration","title","description","location","timezone","all_day",...yf],Hv=["key","value"];function Ef(e,t){return t==="trimmed"?e?.trim():e}function Vv(e,t){return t==="defined"?e!==void 0:!!e}function go(e,t,n){return e.map(r=>{let s=te(r,"--reminder");Ue(s,"--reminder",zv);let o=Ef(s.at??s.date,n.valueMode),i=Ef(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 yo(e,t,n){return e.map(r=>{let s=te(r,"--event");Ue(s,"--event",Bv);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=Sf(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[M,G,Ie]of v)if(G!==void 0&&!Ie)throw new l(`--event ${M} must not be empty`,d.USAGE);let E=s.all_day?.trim(),N=bf(s,i,t,n.recurrenceEmptyNumericGuard),P=Vv(E,n.allDayEmptyGuard)?gf(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 bo(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=te(r,"--type-option");Ue(a,"--type-option",
|
|
6
|
-
`)?!0:Xv.test(e)}function vo(e,t){let n={},r=[];for(let[s,o]of Object.entries(e)){let i=s.toLowerCase();if(!Yv.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: ${Ht.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 Wt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",Hs,Yu,"FORCE_COLOR"]),Eo=/^[A-Za-z_][A-Za-z0-9_]*$/,Vt=["schema","tracker","auto"];function or(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(!Eo.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(Wt.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 ir(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(!Eo.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(Wt.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function To(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 Ao(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Vt.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${Vt.join(", ")}`,d.USAGE)}function Yt(e){if(!e)return;let t=Sn(e,{separators:/[;\n]/});return t.length>0?t:void 0}function xn(e,t,n){let r=Yt(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 Co(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 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_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 Io(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 Qv=new Set(Ht);function xo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zv(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 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: ${Ht.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 ko(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 Af(e,t,n){let r=ko(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 So(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 ek(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:So(n,"timeout_seconds",t),o=r===void 0?void 0:So(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 tk(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 nk(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!xo(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(!Eo.test(s))throw t(`field "env_set" key "${s}" is invalid`);if(Wt.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 rk(e,t){let n=ko(e,"env_clear",t);if(n){for(let r of n){if(!Eo.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(Wt.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function sk(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 ok(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=So(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 ik(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!xo(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 ak(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!xo(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]=So(o,`assert_json_field_gte.${s}`,t)}return Object.keys(r).length>0?r:void 0}function ck(e,t,n){let r=p=>new l(`${n} ${t} ${p}`,d.USAGE);if(!xo(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Ht.join(", ")}.`);let s=Zv(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&&!Vt.includes(m))throw r(`field "pm_context_mode" must be one of: ${Vt.join(", ")}`);let u=In(s,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:tk(s,r),timeout_seconds:ek(s,r),pm_context_mode:m,env_set:nk(s,r),env_clear:rk(s,r),shared_host_safe:sk(s,"shared_host_safe",r),assert_stdout_contains:ko(s,"assert_stdout_contains",r),assert_stdout_regex:Af(s,"assert_stdout_regex",r),assert_stderr_contains:ko(s,"assert_stderr_contains",r),assert_stderr_regex:Af(s,"assert_stderr_regex",r),assert_stdout_min_lines:ok(s,r),assert_json_field_equals:ik(s,r),assert_json_field_gte:ak(s,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function Cf(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)=>ck(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 Ga=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],ja=[{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"}],Rf=[...Ga,...ja],Oo=[{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 Po(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 No(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 dk={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 lk(e){return dk[e]}function qa(e){return lk(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 mk=["strict","progressive"],uk=["lightweight"],Pf=new Set(["Reminder","Meeting","Event"]),pk=new Set(["author","created_at","text"]),za=[...Rf,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...Oo],fk=(()=>{let e=new Map;for(let t of za)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Lo=new Map(za.map(e=>[e.optionKey,e.canonical])),_k=za.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function hk(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 gk(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 Ka(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 yk=fo();function Nf(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([...Lo.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Ge(o))continue;let i=s==="rank"?"order":Lo.get(s)??s;n(i),t[s]=void 0}return ho(t,yk)}function ce(e){if(e!==void 0)return e}function bk(e,t){return Po({raw:e,supportedFields:_k,resolveDefinition:n=>fk.get(n)??No(n,"create",t)})}var If=["id","kind","type","author","created_at","source_kind"],Fo=["path","scope","note"];function wk(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=Ba(i,If);co(i,a);let c=a?te(o,"--dep"):{id:i,kind:"related"};a&&Ue(c,"--dep",If);let m=ce(c.id),u=vk(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=Wn(ce(c.source_kind)),f=ce(c.author);return{id:Yn(m,n,p),kind:ye(u,Ft,"dependency kind"),created_at:Ka(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function vk(e){return typeof e=="string"?Lr(e)??e.trim():e}function Ba(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 Xt(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=>!pk.has(f)).length>0)return{created_at:Ka(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:Ka(m.created_at,n),author:ce(m.author)??r,text:p}}),explicitEmpty:!1})}function Ha(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=Ba(r,Fo),o=s?te(n,"--file"):{path:r};if(s&&Ue(o,"--file",Fo),!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 Va(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=wo(r)?vo(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:Ao(s.pm_context_mode,"--test"),env_set:or(s.env_set,"--test"),env_clear:ir(s.env_clear,"--test"),shared_host_safe:To(s.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Yt(s.assert_stdout_contains),assert_stdout_regex:xn(s.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Yt(s.assert_stderr_contains),assert_stderr_regex:xn(s.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Co(s.assert_stdout_min_lines,"--test"),assert_json_field_equals:Ro(s.assert_json_field_equals,"--test"),assert_json_field_gte:Io(s.assert_json_field_gte,"--test"),note:ce(s.note)}}),explicitEmpty:!1})}function Wa(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=Ba(r,Fo),o=s?te(n,"--doc"):{path:r};if(s&&Ue(o,"--doc",Fo),!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 kk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--reminder","Use --clear-reminders to clear reminders."),{values:go(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function Sk(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(ge(e,"--event","Use --clear-events to clear linked events."),{values:yo(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function Ek(e,t,n,r=[]){let s=[...Ir.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 Tk(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function xf(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 Ak(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 Lf(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 Ck(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(xf(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(xf(r,e.name,"required_create_repeatables"));return n}function Rk(e,t,n,r){for(let s of e)if(!(!Lf(t,s)&&!n.has(s)))throw new l(`Option ${fe("create",s)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function Ik(e,t,n){if(t!=="strict")return;let r=e.filter(o=>n.has(o)&&!qa(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 xk(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:bo(e),explicitEmpty:!1})}async function Ok(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 Pk(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: ${mk.join(", ")}`,d.USAGE)}function Nk(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: ${uk.join(", ")}`,d.USAGE)}function Lk(e,t,n){let r=Pk(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 Fk(e,t,n,r){let s=e.name,o=Ak(t),i=Ck(e,n),a=an(e,"create",i);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);Rk(a.disabled,o,r,s),Ik(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&qa(u)?!0:Lf(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 Ff=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function Mk(e,t){let n=[];for(let r of e){let s=r.match(Ff);s&&s[2]===t&&n.push(s[1])}return[...new Set(n)].sort((r,s)=>r.localeCompare(s))}function $k(e,t){return e.filter(n=>{let r=n.match(Ff);return!r||r[2]!==t})}function Dk(e,t,n,r){let s=$k(e,t);if(s.length===0)return;let o=Mf(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 Uk(e,t){let r=e.options.find(s=>s.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function Gk(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 Mf(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(...Gk(c,e.name,r)),a.add(c));for(let c of n){let m=Uk(e,c);s.push("--type-option",`${c}=${m}`)}return s.join(" ")}function Ya(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 jk(e){return kn(e)}function qk(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 Kk(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function zk(){let e=I();return e?e.commands.some(t=>t.action==="templates-show"||Kk(t.command)==="templates show"):!1}function Bk(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 Hk(e,t,n){if(!zk())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 Bk(r.result,e)}function Vk(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 Jt(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var Wk=new Set(["milestone","meeting","reminder","event"]);function $f(e,t,n,r){let s=t!==void 0,o=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return Wk.has(e.toLowerCase())&&!s&&!o&&!i}function Yk(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`),$f(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 Jk(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 Xk(e,t,n,r,s,o){let i=$s(s);if(Us(r,i,t.id_prefix),await $(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 Qk(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await Xk(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function Zk(e){if(e.explicitId===void 0)return Hn(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||Su(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 Of(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 eS(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 $(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 tS(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 nS(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 rS(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 Hk(h,t,n);o=Nf(qk(y,o))}if(o.type===void 0&&tS(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=Tu(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=Pr(a,s);if(!c)throw new l(`Invalid type value "${o.type}"`,d.USAGE);let m=c.name,u=nS(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=Nk(o.schedulePreset);if(f!==void 0&&!Pf.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=Lk(o.createMode,f,r.governance.create_mode_default);return{resolvedOptions:o,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function sS(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 oS(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=Lo.get(r)??r;throw new l(`Cannot combine --unset ${o} with ${fe("create",r)}`,d.USAGE)}}function iS(e){let t=(n,r)=>{let s=Lo.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;_o(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 aS(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 cS(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=[Mf(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".'),Pf.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 dS(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 lS(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=Jt(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 mS(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:Na(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function uS(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=$t(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 $(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}),M=[];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,$e(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 on(y),G}M=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?Zs(E,[...E,c.metadata],r):[],...M,...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:Ut(c.metadata,p),changed_fields:p})}finally{await b()}return v}async function At(e,t){let n=Nf(await Ok(e)),r=T(process.cwd(),t.path);await Vk(r);let s=await A(r),o=j(s.schema),i=Be(s.schema),a=x(s,I()),c=await rS(n,t,r,s,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=bk(n.unset,i),{explicitUnsets:_,clearOptionKeys:h}=sS(n,f);oS(n,f),iS(n);let y=Fk(m,n,p,h),g=S(),b=R(ce(n.author),s.author_default),v=wk(n.dep,g,s.id_prefix,b),E=Xt("--comment",n.comment,g,b),N=Xt("--note",n.note,g,b),P=Xt("--learning",n.learning,g,b),M=Ha(n.file),G=Va(n.test),Ie=Wa(n.doc),ee=kk(n.reminder,g),pe=Sk(n.event,g),ie=xk(n.typeOption),Xe=Un(u,ie.values,a),ze=I(),Pt=ft(ze),ut=xr(n.field,ze),Nt=Vm(n,i,u),pi=new Set(Nt.missing_required_flags),vr=i.definitions.filter(H=>pi.has(`--${H.cli_flag}`));aS(ut,Nt,f);let Qe=Mk(Xe.errors,u),hd=Qe.map(H=>`--type-option ${H}=<value>`),kr=[...new Set([...y,...hd,...Nt.missing_required_flags])].sort((H,vi)=>H.localeCompare(vi));cS({combinedMissingFlags:kr,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:Qe,openStatus:o.open_status,type:u,createMode:p,missingRequiredRuntimeFields:vr}),Dk(Xe.errors,u,m,o);let ae=await Zk({pmRoot:r,settings:s,typeRegistry:a,explicitId:n.id}),ve=n.status!==void 0?hk(n.status,o):gk(m,o),fi=n.priority!==void 0?jk(n.priority):2,O=f.metadataKeys,Sr=dS(O,n),_i=Jt(O,"deadline",n.deadline,H=>Q(H,new Date(g),"deadline")),Zy=Jt(O,"estimated_minutes",n.estimatedMinutes,H=>vn(H,"estimated-minutes")),eb=B(O,"acceptance_criteria",n.acceptanceCriteria),tb=B(O,"definition_of_ready",n.definitionOfReady),nb=lS(O,n),rb=B(O,"goal",n.goal),sb=B(O,"objective",n.objective),ob=B(O,"value",n.value),ib=B(O,"impact",n.impact),ab=B(O,"outcome",n.outcome),cb=B(O,"why_now",n.whyNow),db=B(O,"assignee",n.assignee),lb=O.has("author")?void 0:ce(n.author)??b,mb=B(O,"parent",n.parent),gd=await Jk(mb,n,O,r),hi=gd.parent,ub=gd.parentSource,pb=B(O,"reviewer",n.reviewer),fb=Jt(O,"risk",n.risk,H=>ye(lo(H),rn,"risk")),_b=Jt(O,"confidence",n.confidence,H=>uo(H)),hb=n.allowMissingParent===!0&&s.validation.parent_reference==="strict_error"?"warn":s.validation.parent_reference,yd=s.validation.sprint_release_format,Lt=[...c.warnings,...Yk(u,ae,_i,ee.values,pe.values)],bd=await Qk({itemId:ae,parent:hi,pmRoot:r,settings:s,typeRegistry:a,policy:hb});hi=bd.parent,Lt.push(...bd.warnings);let wd=Of(O,"sprint",n.sprint,"sprint",yd),gb=wd.value;Lt.push(...wd.warnings);let vd=Of(O,"release",n.release,"release",yd),yb=vd.value;Lt.push(...vd.warnings);let kd=B(O,"blocked_by",n.blockedBy),Sd=await eS({pmRoot:r,settings:s,typeRegistry:a,statusRegistry:o,blockedBy:kd,dependencyValues:v.values,status:ve,statusExplicit:n.status!==void 0,nowValue:g,author:b}),gi=Sd.dependencyValues;sr(ae,gi),Lt.push(...await Bt({pmRoot:r,dependencies:gi,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=Sd.status;let bb=B(O,"blocked_reason",n.blockedReason),wb=B(O,"unblock_note",n.unblockNote),vb=B(O,"reporter",n.reporter),kb=Jt(O,"severity",n.severity,H=>ye(mo(H),sn,"severity")),Sb=B(O,"environment",n.environment),Eb=B(O,"repro_steps",n.reproSteps),Ed=B(O,"resolution",n.resolution),Tb=B(O,"expected_result",n.expectedResult),Ab=B(O,"actual_result",n.actualResult),Cb=B(O,"affected_version",n.affectedVersion),Rb=B(O,"fixed_version",n.fixedVersion),Ib=B(O,"component",n.component),xb=Jt(O,"regression",n.regression,H=>po(H)),Ob=B(O,"customer_impact",n.customerImpact),yi=Ya(n.title,"--title"),bi=n.description??"",Er=n.body??"",Td=await An({title:yi,description:bi,body:Er},{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(...eo(Td));let wi=mS(ve,o,s,n,Ed,g),Pb=wi.closeReason,Nb=ve===o.close_status?g:void 0,Lb=wi.completedAt;Lt.push(...wi.warnings);let Tr=Yi({id:ae,title:yi,description:bi,type:u,type_options:Xe.normalized,status:ve,closed_at:Nb,completed_at:Lb,close_reason:Pb,priority:fi,tags:Sr,created_at:g,updated_at:g,deadline:_i,assignee:db,author:lb,estimated_minutes:Zy,acceptance_criteria:eb,definition_of_ready:tb,order:nb,goal:rb,objective:sb,value:ob,impact:ib,outcome:ab,why_now:cb,parent:hi,reviewer:pb,risk:fb,confidence:_b,sprint:gb,release:yb,blocked_by:kd,blocked_reason:bb,unblock_note:wb,reporter:vb,severity:kb,environment:Sb,repro_steps:Eb,resolution:Ed,expected_result:Tb,actual_result:Ab,affected_version:Cb,fixed_version:Rb,component:Ib,regression:xb,customer_impact:Ob,dependencies:gi,comments:E.values,notes:N.values,learnings:P.values,files:M.values,tests:G.values,docs:Ie.values,reminders:ee.values,events:pe.values,...ut,...Nt.values});try{Or(Tr,ze)}catch(H){throw new l(H instanceof Error?H.message:"Invalid extension item field values",d.USAGE)}let Fb=He({metadata:Tr,body:Er},{schema:s.schema,extensionFieldNames:Pt}),Mb={metadata:{},body:""},Ad=[..._].sort((H,vi)=>H.localeCompare(vi)),$b=Tk(n.message,Ad),Cd=Ek(Tr,Er,Ad,[...Object.keys(ut),...Object.keys(Nt.values??{})]),Db=await uS({pmRoot:r,type:u,id:ae,settings:s,typeRegistry:a,author:b,extensionFieldNames:Pt,afterDocument:Fb,beforeDocument:Mb,historyMessage:$b,changedFields:Cd,nowValue:g,similarityCandidate:{title:yi,description:bi,body:Er},allowDuplicate:n.allowDuplicate}),Rd=structuredClone(Tr);p==="strict"&&_.has("dependencies")&&(Rd.dependencies=[]);let Ub=Tf(ae,u,ve,o);return $f(u,_i,ee.values,pe.values)&&nu(`[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:Rd,changed_fields:Cd,warnings:[...Lt,...Db],...Object.fromEntries([["parent_source",ub],["next_transition",Ub],["similarity_advisory",Td]].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 Za=[...Ga,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...ja,...Oo],pS=(()=>{let e=new Map;for(let t of Za)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Mo=new Map(Za.map(e=>[e.optionKey,e.canonical])),fS=Za.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),_S=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),hS=fo({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function gS(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([...Mo.keys(),"rank"]);for(let s of r){let o=t[s];if(typeof o!="string"||!Ge(o))continue;let i=s==="rank"?"order":Mo.get(s)??s;n(i),t[s]=void 0}return ho(t,hS)}function Hf(e,t,n=[]){return Po({raw:e,supportedFields:fS,resolveDefinition:r=>{let s=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return pS.get(r)??No(r,"update",t)??(s?{optionKey:"field",metadataKey:s}:void 0)}})}var Df=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 Uf(e){let t=e.disallowedFlags.flatMap(r=>{let s=Df.get(r);return s?[s(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let s=Df.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 yS(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 Uf({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=>_S.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw Uf({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 bS(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 wS(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=_m({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: ${hm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(s,d.USAGE);return`workflow_transition_not_allowed: ${s}`}function vS(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 kS=["id","kind","type","author","created_at","source_kind"],SS=["id","kind","type","source_kind"];function ES(e){return e.startsWith("```")||e.includes(`
|
|
8
|
-
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:qs(e)}function Vf(e){return typeof e=="string"?Lr(e)??e.trim():e}function Do(e,t,n,r){return e?(ge(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=ES(i);co(i,a);let c=a?te(o,"--dep"):{id:i,kind:"related"};a&&Ue(c,"--dep",kS);let m=c.id?.trim(),u=Vf((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=Wn($o(c.source_kind)),f=$o(c.author);return{id:Yn(m,t,p),kind:ye(u,Ft,"dependency kind"),created_at:vS(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function TS(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",SS);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=Vf($o(s.kind??s.type)),a=Wn($o(s.source_kind));return{id:Yn(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 Gf(e){let t=e.source_kind?.trim().toLowerCase()??"";return`${e.id.trim().toLowerCase()}::${e.kind}::${t}`}function AS(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 CS(e,t,n,r,s,o){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await $(n,_e(i,r),r,s,o);return a?{id:a.id}:{unresolved:i}}function RS(e,t,n,r,s){let o=AS(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 IS(e){return`${e.path}::${e.scope}`}function xS(e){return`${e.path}::${e.scope}`}function OS(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}`}function PS(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 NS(e){return kn(e)}function jf(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 LS(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=Hf(e.unset,t,n);for(let i of o.optionKeys)s(i,!0)}return r}function FS(e,t,n,r,s){let o=Pr(e,n);if(!o)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=an(o,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let a=LS(t,r,s);for(let c of i.disabled)if(a.has(jf(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(jf(c,e)))throw new l(`Missing required option ${fe("update",c)} for type "${e}"`,d.USAGE)}var MS=new Set(["order","rank"]),$S=xi.filter(e=>!MS.has(e)),Wf=["tags","closeReason",...$S],DS=["title","description","body","status","closeReason","completedAt","priority","type",...xi,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],US=[{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"}],GS=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>ye(lo(e),rn,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>uo(e)}],jS=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>ye(mo(e),sn,"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=>po(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Qa(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 qS(e){let t=Ne();return gS({...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 KS(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 Ja(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 ec(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);Ja({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Ja({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Ja({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function zS(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 BS(e){let t={};for(let n of Wf)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function HS(e,t){let n=BS(e);for(let[r,s]of Object.entries(n)){if(!s||!t.optionKeys.has(r))continue;let o=Mo.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 VS(e){let t=(n,r)=>{let s=Mo.get(r),o=s?`Use --unset ${s} to clear this field.`:void 0;_o(n,fe("update",r),o)};for(let n of Wf)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 WS(e,t){let n={};for(let r of DS)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 YS(e){let t=await $(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 JS(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function XS(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 QS(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=$s(e.options.parent);if(Us(e.id,t,e.settings.id_prefix),await $(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 ZS(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function eE(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await $(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=wS({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return s?[s]:[]}async function tE(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 nE(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Ya(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 rE(e,t,n,r,s){let o=bS(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 sE(e,t,n,r){if(t.options.status!==void 0&&rE(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 oE(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 iE(e,t,n,r){sE(e,t,n,r),oE(e,t,n,r)}function aE(e,t,n){let r=ue(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=NS(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 FS(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),cE(e,t,r,n),r}function cE(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=bo(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 dE(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=>Gf(o)));for(let o of t.dependencyUpdates.additions){let i=Gf(o);s.has(i)||(r.push(o),s.add(i))}}t.dependencyRemovals.length>0&&(r=r.filter(s=>!t.dependencyRemovals.some(o=>PS(s,o)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function lE(e,t,n){Xa(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Xa(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Xa(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Xa(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 mE(e,t,n){qf(e,"files",t.options.file,t.fileUpdates.values,IS,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),uE(e,t,n),qf(e,"docs",t.options.doc,t.docUpdates.values,xS,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function qf(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 uE(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Kf(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Kf([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Kf(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let s=OS(r);n.has(s)||(t.push(r),n.add(s))}return t}function pE(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")}Qa(US,t.options,n),_E(e,t,n.changedFields)}function fE(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 _E(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 hE(e,t,n,r){gE(e,t,n.changedFields),yE(e,t,n.changedFields),Qa(GS,t.options,n),zf(e,t,"sprint",r,n.changedFields),zf(e,t,"release",r,n.changedFields),bE(e,t,n.changedFields),Qa(jS,t.options,n)}function gE(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 yE(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 zf(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 bE(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)&&RS(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function wE(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=go(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=yo(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function vE(e,t,n){Bf(e,t.runtimeFieldRegistry.definitions.map(s=>s.metadata_key),t.clearItemMetadataKeys,n),Bf(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=xr(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 Bf(e,t,n,r){for(let s of t)!n.has(s)||e[s]===void 0||(delete e[s],r.push(s))}function kE(e,t){let n=structuredClone(e.metadata),r=e.body,s=[],o=[],i=nE(e,t.options,t.statusRegistry,s),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:s,nowValue:t.nowValue};iE(e,t,i,s),aE(e,t,s),dE(e,t,s),lE(e,t,s),mE(e,t,s),pE(e,t,c),fE(e,t,c),hE(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"))&&sr(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")),wE(e,t,s),vE(a,t,s);try{Or(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 qS(t);let r=T(process.cwd(),n.path);await JS(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"?[]:fm(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],_=Hf(t.unset,i,c),h=new Set(_.optionKeys),y=new Set(_.metadataKeys);ec(t),zS({definitions:KS(t),options:t,clearOptionKeys:h,clearItemMetadataKeys:y}),yS(e,t,y),HS(t,_),VS(t);let g=R(t.author,s.author_default),b=new Date,v=b.toISOString(),E=Do(t.dep,s.id_prefix,v,g);sr(e,E.additions);let N=await Bt({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=TS(t.depRemove,s.id_prefix),M=Xt("--comment",t.comment,v,g),G=t.ownershipMetadataBypass===!0&&M.values?{...M,values:M.values.map(O=>({...O,author:g}))}:M,Ie=Xt("--note",t.note,v,g),ee=Xt("--learning",t.learning,v,g),pe=Ha(t.file),ie=Va(t.test),Xe=Wa(t.doc),ze=[],Pt=await QS({id:e,options:t,unsetTargets:_,pmRoot:r,settings:s,typeRegistry:m,parentReferencePolicy:f}),ut=await CS(t.blockedBy,y.has("blocked_by"),r,s.id_prefix,s.item_format,m.type_to_folder),Nt=ut.id,pi=[...Pt.warnings,...ZS(ut)],vr=vs(t,i,t.runtimeFieldCommands),Qe=WS(t,vr);if(!Object.values(Qe).some(Boolean))return YS({pmRoot:r,id:e,settings:s,typeRegistry:m});ze.push(...await eE({options:t,fieldFlags:Qe,workflowEnforcement:u,typeWorkflows:p,statusRegistry:o,typeRegistry:m,pmRoot:r,id:e,settings:s}));let kr=await tE({options:t,fieldFlags:Qe,statusRegistry:o,workflowTransitionWarnings:ze,global:n,id:e});if(kr)return kr;XS(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(Sr=>Sr.id===O.metadata.id?structuredClone(O.metadata):Sr),kE(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:vr,nowValue:b,nowIso:v,author:g,pmRoot:r})}}),fi=ae?Zs(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,...pi,...N,...fi,...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 Jf=1,nc="update-many",SE=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),EE=["--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(", "),TE={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"},AE=[{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"}],CE={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"},Xf=e=>{let t={};for(let[n,r]of Object.entries(e))SE.has(n)||r!==void 0&&(t[n]=r);return t},RE=e=>Object.keys(Xf(e)).length>0,Qf=e=>typeof e=="string"?e.trim():e,IE=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},tc=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},xE=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Qf(e)},OE={priority:IE,estimatedMinutes:tc,order:tc,rank:tc,regression:xE},PE=(e,t)=>{if(t!==void 0)return(OE[e]??Qf)(t)},NE=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return CE[t]??t},Uo=(e,t)=>tt(e,t),LE=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],FE=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,ME=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",Yf=(e,t)=>t===void 0?void 0:e[t],On=e=>Array.isArray(e)?e.length:0,$E=(e,t,n)=>{let r=n[e.addKey],s=Yf(n,e.removeKey),o=On(r),i=On(s),a=n[e.clearKey]===!0,c=Yf(n,e.replaceKey)===!0;if(![a,c,o>0,i>0].includes(!0))return;let m=LE(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:ME({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:o,remove_count:i,before_count:FE(e.field,m)}}},DE=(e,t)=>{let n=[];for(let r of AE){let s=$E(r,e,t);s!==void 0&&n.push(s)}return n},UE=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],GE=(e,t)=>{if(![t.tags!==void 0,On(t.addTags)>0,On(t.removeTags)>0].includes(!0))return;let n=UE(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(!Uo(i,o))return{field:"tags",before:n,after:o}},jE=(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(!Uo(typeof n=="string"?n:"",s))return{field:"acceptance_criteria",before:n,after:s}},qE=(e,t,n)=>{for(let[r,s]of Object.entries(TE)){let o=n[r];if(o===void 0)continue;let i=t[s],a=PE(r,o);Uo(i,a)||e.push({field:s,before:i,after:a})}},KE=(e,t,n,r)=>{let s=vs(n,r,["update_many"]);for(let[o,i]of Object.entries(s)){let a=t[o];Uo(a,i)||e.push({field:o,before:a,after:i})}},zE=(e,t,n)=>{for(let r of n??[]){let s=NE(r),o=t[s];o!==void 0&&e.push({field:s,before:o,after:null})}},BE=(e,t,n={})=>{let r=e,s=[],o=GE(r,n);if(o&&s.push(o),qE(s,r,n),On(n.addAc)>0||On(n.removeAc)>0){let i=jE(r,n);i!==void 0&&s.push(i)}return s.push(...DE(r,n)),KE(s,r,n,t),zE(s,r,n.unset),{id:e.id,changes:s}},HE=(e,t)=>Eu(e,t,{strict:!0,flagLabel:"--filter-status"}),VE=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)},WE=[({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")}],YE=(e,t,n,r)=>{let s={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let o of WE)o(s)},JE=async e=>{let t=await Ns(e.pmRoot,nc,e.rollbackId,Jf),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Ls(t.items,(s,o)=>zt(s,o,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...Dt({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}},XE=async e=>{let t={schema_version:Jf,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,nc,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},QE=(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))},rc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},ZE=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)}},eT=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(Qn(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 JE({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},tT=async e=>{HE(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=BE(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:QE(e.options.list?.ids,r)}},nT=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:[],...rc(e)}),rT=e=>({...Dt({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:[],...rc(e)}),sT=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:cn(i)})}}return{rows:t,updatedIds:n}},oT=async e=>{if(e.plan.actionable.length===0)return rT(e.plan);let t=S(),n=Os(nc,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 XE({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 sT({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{...Dt({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,...rc(e.plan)}},Zf=async(e,t)=>{let n=await ZE(t),r=typeof e.rollback=="string"?e.rollback:void 0,s=Xf(e.update);if(VE(e.list),r!==void 0)return eT({runtime:n,rollbackId:r,options:e,global:t,updateSummary:s});if(!RE(e.update))throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${EE}).`,d.USAGE);YE(e.update,n.settings,n.statusRegistry,n.pmRoot),ec(e.update);let o=await Bt({pmRoot:n.pmRoot,dependencies:Do(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 tT({options:e,global:t,runtime:n,updateSummary:s,dependencyWarnings:o});return await Bt({pmRoot:n.pmRoot,dependencies:Do(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?nT(i):oT({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 iT=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],e_=["brief","standard","deep"],r_="plan-step-",dc="draft",cc=["bug-investigation","feature-implementation","refactoring-sprint"],t_={"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 aT(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(t_,t)?t_[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${cc.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${cc[0]}`]});return n.map(r=>({...r}))}function cT(e,t){return t>0?Math.round(e/t*100):0}function s_(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 o_(e,t=dc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ei.find(s=>s===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${Ei.join(", ")}`,d.USAGE);return r}function lc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ti.find(s=>s===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${Ti.join(", ")}`,d.USAGE);return r}function i_(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ci.find(s=>s===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${Ci.join(", ")}`,d.USAGE);return r}function dT(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ai.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${Ai.join(", ")}`,d.USAGE);return n}function lT(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=e_.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${e_.join(", ")}`,d.USAGE);return n}function mT(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 sc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function uT(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(!sc.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 ${[...sc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:s,suggested_retry:`pm plan show <id> --fields ${[...sc].join(",")}`}});return r}function mc(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 uc(e){let t=mc(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 pc(e){let t=mc(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 fc(e){let t=mc(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 pT(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=cT(t.completed,t.total),t}function fT(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${r_}${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 n_(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 _T(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=n_(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=n_(a);if(c){s.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:s}}function hT(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function gT(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function yT(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=pT(n),s=gT(n),o={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??dc,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:yT(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&&!na(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function a_(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 bT(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 c_(e,t){let n=x(e.settings,I()),r=await $(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 a_(s.document.metadata),{document:s.document,itemId:r.id}}function wT(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 vT(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function kT(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||Fe(e.dependsOn).length>0||Fe(e.link).length>0}function ST(e){let t=e.stepTitle?.trim()||void 0,n=s_(e.step),r=e.template?.trim()?aT(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(s=>s.title)],templateSteps:r}}function ET(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 ${cc[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 TT(e,t){let n=lc(e.stepStatus,"pending"),r=_c(e,"depends_on"),s=be(e.file).map(uc),o=be(e.test).map(pc),i=be(e.doc).map(fc),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 AT(e){let t=ST(e),n=kT(e);if(ET(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[TT(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=S();return{steps:t.stepTitles.map((s,o)=>({id:`${r_}${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 CT(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=o_(e.mode,dc),o=dT(e.harness),i=e.fromSearch?.trim(),a=vT(e),{steps:c,hasPerStepDetailOptions:m}=AT(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:wT(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 RT(e,t,n){let r=lT(t.depth),s=mT(t.fields),{document:o,itemId:i}=await c_(n,e),a=Te(o.metadata,s===null?r:"deep");return{action:"show",plan:s===null?a:uT(a,s),next_actions:Ae(i,a),warnings:[],generated_at:S()}}function IT(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){a_(s.metadata);let o=j(e.ctx.settings.schema);if(Oe(s.metadata.status,o)||na(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=IT(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 xT(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let s=lc(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;d_(u,void 0,s,o);let f=OT(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 d_(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 OT(e,t,n){let r=_c(t,"depends_on"),s=be(t.file).map(uc),o=be(t.test).map(pc),i=be(t.doc).map(fc),a=S();return{id:fT(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files: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 _c(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=i_(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 oc(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??lc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return d_(c,u.status==="in_progress"?u.id:void 0,f,_),PT(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 PT(e,t,n,r){NT(e,t,n),LT(e,t),e.status=n,e.updated_at=r,FT(e,n,r)}function NT(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 LT(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(uc),s=be(t.test).map(pc),o=be(t.doc).map(fc);r.length>0&&(e.files=ic(e.files,r)),s.length>0&&(e.tests=ic(e.tests,s)),o.length>0&&(e.docs=ic(e.docs,o))}function ic(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 FT(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function MT(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 $T(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 DT(e,t,n,r){let s=_c(t,i_(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 UT(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 ac(e,t,n,r){let s=hT(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 GT(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 jT(e,t,n){let r=o_(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 l_(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function qT(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:l_(t),generated_at:S()}}function KT(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 zT(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:KT(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 BT(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 HT(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 c_(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=_T(u,r);if(p.length===0){if(f.length>0)return qT(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await zT({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 BT(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:l_(f),generated_at:S()}}function VT(e){if(e.subcommand==="create")return e;let t=s_(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 Qt(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 WT(e){let t=Qt(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 YT={create:(e,t)=>CT(e.options,e.global,t),show:(e,t)=>RT(ct(e,"show"),e.options,t),"add-step":(e,t)=>xT(ct(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=Qt(e,"update-step");return oc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=Qt(e,"complete-step");return oc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=Qt(e,"block-step");return oc(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=WT(e);return MT(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=Qt(e,"remove-step");return $T(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=Qt(e,"link");return DT(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=Qt(e,"unlink");return UT(n.id,e.options,t,n.stepRef)},decision:(e,t)=>ac(ct(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>ac(ct(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>ac(ct(e,"validation"),e.options,t,"validation"),resume:(e,t)=>GT(ct(e,"resume"),e.options,t),approve:(e,t)=>jT(ct(e,"approve"),e.options,t),materialize:(e,t)=>HT(ct(e,"materialize"),e.options,t)};function JT(e){let t=YT[e];if(!t)throw Ee({command_path:"plan",token:e,allowed:iT});return t}async function m_(e){let t=await bT(e.global),n=VT(e);return JT(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 XT(e,t){return[...new Set([...Ir.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 QT(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function hc(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 $(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 Hn(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=XT(g.metadata,g.body),E=$t(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),M={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 $(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,$e(g,{format:s.item_format,schema:s.schema,extensionFieldNames:y}));try{let ie=De({nowIso:m,author:u,op:"create",before:M,after:g,message:QT(i.id,t.message)});await wt(N,ie)}catch(ie){throw await on(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:M,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:M,after:g,changed_fields:v})],mn({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:Ut(g.metadata,v),changed_fields:v})}finally{await P()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:v,warnings:[...eo(b),...Ie,...G],...b===void 0?{}:{similarity_advisory:b}}}import Go 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 gc(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 fu({pmRoot:r,settings:s,id:e,author:o,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?Go.relative(r,i.targetPath).split(Go.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:Go.relative(r,ke(r,i.item.id)).split(Go.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 ZT(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}async function yc(e,t,n){let r=T(process.cwd(),n.path);if(await ZT(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 Hm(r),await Qs({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 eA(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 $(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=u_(m.document.metadata.title);return await Bm(r,c),await Qs({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 eA(e,t){let n=await A(e),r=x(n,I()),s=await $(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 u_(o.document.metadata.title)}function u_(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 p_=new Set(["item_format"]),f_=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"]),tA=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"]),nA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","telemetry_tracking"]),rA={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function sA(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(p_.has(t)||f_.has(t)||tA.has(t)||t==="context")return t}function oA(e){let t=e.trim().toLowerCase();return rA[t]??e}function __(e,t){let n=sA(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."}:p_.has(n)?{routable:!0,flag:"format",value:t}:f_.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:nA.has(n)?oA(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 h_=["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"]},iA=Object.keys(dt).map(e=>dt[e][0]),aA=Object.fromEntries(Object.keys(dt).flatMap(e=>dt[e].map(t=>[t,e]))),cA={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)."},dA=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],lA=new Set(["metadata_required_fields",...dA]),mA=new Set(["test_result_tracking","telemetry_tracking"]),uA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),pA=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),fA=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),_A=new Set(["governance_preset","governance_create_default_type"]),v_=e=>lA.has(e),hA=e=>pA.has(e),gA=e=>fA.has(e),yA=e=>_A.has(e);function bc(e){return e==="definition_of_done"||v_(e)}function bA(e){if(h_.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${h_.join(", ")}`,d.USAGE)}function wA(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 vA(e){let t=aA[e];if(t)return t;let n=Ni.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${iA.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function kA(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 SA(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 k_(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 S_(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 E_(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 vc(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 T_(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 A_(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 C_(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 R_(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 I_(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 x_(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 O_(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 g_(e,t){switch(e){case"history_missing_stream_policy":return k_(t);case"sprint_release_format_policy":return ta(t);case"parent_reference_policy":case"governance_parent_reference_policy":return Ms(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return vc(t);case"governance_preset":return T_(t);case"governance_ownership_enforcement":return A_(t);case"governance_create_mode_default":return C_(t);case"governance_close_validation_default":return R_(t);case"governance_require_close_reason":return O_(t);case"governance_workflow_enforcement":return I_(t);case"governance_force_required_for_stale_lock":return x_(t);case"test_result_tracking":return S_(t);case"telemetry_tracking":return E_(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var y_={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"},EA=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function TA(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=>y_[o]===void 0);if(s.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${s.join(", ")}. Supported values: ${EA.join(", ")}`,d.USAGE);return[...new Set(r.map(o=>y_[o]))].sort((o,i)=>o.localeCompare(i))}function AA(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 CA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function RA(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 vA(t)}function P_(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var IA={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 kc(e,t){return IA[t](e)}function Me(e,t){return t.length===0?e:{...e,warnings:t}}async function xA(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 OA(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 b_(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 PA(e,t,n,r,s){let o=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!Ri.includes(c))throw new l(`Context --default-depth must be one of ${Ri.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,o=!0)}if(t.activityLimit!==void 0){let c=b_(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,o=!0)}if(t.staleThresholdDays!==void 0){let c=b_(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=OA(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"),Me({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 NA(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 LA(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 NA(t,s,o);P_(n);let i=__(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&&g_(n,o.policy)!==g_(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 FA(e){let t=Object.keys(dt).map(r=>({key:r,aliases:dt[r],value_kind:r==="context"?"object":bc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:bc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:cA[r],value:kc(e.settings,r)})),n=Ni.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Li(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 Me({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function MA(e){let t=Object.fromEntries(Object.keys(dt).map(n=>[n,kc(e.settings,n)]));return Me({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function $A(e,t){let n=kc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Me({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Me({...r,context_settings:n},e.warnings):Array.isArray(n)?Me({...r,criteria:n},e.warnings):Me({...r,policy:n},e.warnings)}async function DA(e,t,n,r){if(t==="get"){let a=Li(e.settings,n);return Me({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=pm(n,s);if(!o.ok)throw new l(o.error.message,d.USAGE);let i=_s(e.settings,n,o.parsed.value);return i&&await Se(e.target.pmRoot,e.settings,`config:set:${n.path}`),Me({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 w_(e,t,n){return e!==n||t!==n}function oe(e,t,n,r){return Me({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function wc(e,t,n,r){return Me({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function UA(e,t){let n=SA(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 Au(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 Me({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 GA(e,t,n){if(t==="history_missing_stream_policy"){let o=k_(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=ta(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=Ms(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=vc(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 jA(e,t,n){if(t==="metadata_required_fields"){let a=TA(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"),wc(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=AA(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}`),wc(e,t,[...s],i)}async function qA(e,t,n){if(t==="governance_preset"){let c=T_(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 KA(e,t,n){if(t==="governance_ownership_enforcement"){let o=A_(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=C_(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=R_(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 zA(e,t,n){if(t==="governance_parent_reference_policy"){let o=Ms(n.policy),i=e.settings.governance.preset!=="custom"||w_(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=vc(n.policy),i=e.settings.governance.preset!=="custom"||w_(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=I_(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 BA(e,t,n){if(t==="governance_require_close_reason"){let a=O_(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=x_(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 HA(e,t,n){if(t==="test_result_tracking"){let a=S_(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=E_(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 VA(e,t,n){let r=kA(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"),wc(e,t,[...e.settings.workflow.definition_of_done],s)}async function WA(e,t,n){if(n.clearCriteria===!0&&!bc(t))throw new l("--clear-criteria is only supported with config set criteria-list keys",d.USAGE);return t==="item_format"?UA(e,n):t==="context"?PA(e.settings,n,e.target,e.scope,e.warnings):t==="definition_of_done"?VA(e,t,n):v_(t)?jA(e,t,n):mA.has(t)?HA(e,t,n):uA.has(t)?BA(e,t,n):hA(t)?KA(e,t,n):gA(t)?zA(e,t,n):yA(t)?qA(e,t,n):GA(e,t,n)}async function N_(e,t,n,r,s,o){let i=bA(e),a=wA(t),c=a==="get"||a==="set"?fs(n):void 0,m=c?void 0:RA(a,n),u=LA(a,n,m,c,o,r),p=await xA(i,s),{settings:f,metadata:_,warnings:h}=await mu(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:CA(h)};return c?DA(y,a,c,u):a==="list"?FA(y):a==="export"?MA(y):(P_(m),a==="get"?$A(y,m):WA(y,m,u))}import SC from"node:fs/promises";import V from"node:path";import EC from"node:readline/promises";import{stdin as TC,stdout as Ce}from"node:process";import F_ from"node:fs/promises";import je from"node:path";import YA from"node:readline/promises";import{stdin as JA,stdout as jo}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 M_=["ask","add","skip","status"],XA=["AGENTS.md","CLAUDE.md"],QA=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],ZA=8,Ec=1,eC="<!-- pm-cli:agent-guidance:start:",tC=`<!-- pm-cli:agent-guidance:start:v${Ec} -->`,Sc="<!-- pm-cli:agent-guidance:end -->",dr="Add workflow guidance later: pm init --agent-guidance add";var nC=()=>YA.createInterface({input:JA,output:jo});function ar(e,t){let n=je.relative(e,t);return n.length===0?je.basename(t):n.split(je.sep).join("/")}function L_(e){return e.endsWith(`
|
|
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=te(r,"--type-option");Ue(a,"--type-option",Yv),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 Xv=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Pf(e,t,n,r){if(Xv.has(t.trim().toLowerCase())||n!==r.open_status)return;let s=us("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 Vt=["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"],Qv=new Set(Vt),Zv=Vt.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),ek=new RegExp(`^(?:[-*+]\\s+)?(?:${Zv})\\s*[:=]`,"i");function bo(e){return e.startsWith("```")||e.includes(`
|
|
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(`
|
|
9
9
|
`)?e:`${e}
|
|
10
|
-
`}function
|
|
10
|
+
`}function iC(e){return e.includes(`\r
|
|
11
11
|
`)?`\r
|
|
12
12
|
`:`
|
|
13
|
-
`}function
|
|
13
|
+
`}function z_(e){let t=e.indexOf(rC);if(t===-1)return null;let n=e.indexOf(Tc,t);return n===-1?null:{start_index:t,end_index:n+Tc.length}}function aC(e){return z_(e)!==null}function cC(e){return[sC,"## 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="node scripts/run-tests.mjs test -- ..."`.','- 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.","",Tc,""].join(e)}function dC(e){let t=iC(e),n=cC(t),r=z_(e);if(r){let i=e.slice(r.end_index),a=i.startsWith(`\r
|
|
14
14
|
`)?i.slice(2):i.startsWith(`
|
|
15
|
-
`)?i.slice(1):i,c=
|
|
15
|
+
`)?i.slice(1):i,c=j_(`${e.slice(0,r.start_index)}${n}${a}`);return{next_content:c,changed:c!==e}}let s=e.length===0?"":e.endsWith(`
|
|
16
16
|
`)?`
|
|
17
17
|
`:`
|
|
18
18
|
|
|
19
|
-
`,o=
|
|
19
|
+
`,o=j_(`${e}${s}${n}`);return{next_content:o,changed:o!==e}}function lC(e,t){let n=je.dirname(e);return je.basename(e)==="pm"&&je.basename(n)===".agents"?je.dirname(n):je.resolve(t,e)}function mC(e,t){let n=e.find(s=>je.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:je.join(t,"AGENTS.md")}function uC(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 pC(e){let t=oC();try{Go.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
|
-
`),
|
|
21
|
+
`),Go.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 Go.write(`
|
|
23
|
+
`),uC(n,!0)}finally{t.close()}}function B_(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:Ac,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 H_(e){let t=[];for(let n of eC){let r=je.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 q_.readFile(r,"utf8"),i=o.toLowerCase(),a=tC.filter(m=>i.includes(m)),c=aC(o);t.push({file_path:r,exists:s,has_guidance:c||a.length>=nC,has_marker:c})}return t}function dr(e,t){e.includes(t)||e.push(t)}function fC(e,t){let n=B_(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function _C(e){let n=await k(e)?await q_.readFile(e,"utf8"):"",r=dC(n);return r.changed?(await me(e,r.next_content),{changed:!0,warnings:await z({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function hC(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=>ir(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>ir(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>ir(e.projectRoot,t.file_path))}}async function gC(e,t,n){return e?await H_(n):t}function ar(e,t,n){e.state={...e.state,...n,template_version:Ac,last_checked_files:t}}async function V_(e,t){if(t.presentBefore)return;let n=await _C(t.targetPath);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function yC(e,t){t||(e.warnings.push("agent_guidance:missing"),dr(e.nextSteps,cr))}function bC(e,t){e.skipped=!0,ar(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),dr(e.nextSteps,cr)}async function wC(e,t){await V_(e,t),ar(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function vC(e,t){e.state.declined&&ar(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function kC(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),dr(e.nextSteps,cr)}async function SC(e,t){if(e.prompted=!0,await pC(t.targetRelativePath)){await V_(e,t),ar(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,ar(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),dr(e.nextSteps,cr)}function EC(e){e.warnings.push("agent_guidance:missing_non_interactive"),dr(e.nextSteps,cr)}async function TC(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(yC(n,t.presentBefore),n):t.mode==="skip"?(bC(n,t.checkedFiles),n):t.mode==="add"?(await wC(n,t),n):t.presentBefore?(vC(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(kC(n),n):t.interactive?(await SC(n,t),n):(EC(n),n)}async function W_(e){let t=lC(e.pm_root,e.cwd),n=await H_(t),r=mC(n,t),s=ir(t,r),o=n.map(u=>ir(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await TC(B_(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:s,checkedFiles:o,presentBefore:i}),c=fC(e.settings,a.state);return n=await gC(a.applied,n,t),{summary:hC({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 IC=()=>CC.createInterface({input:RC,output:Ce});function xC(){return structuredClone(pt)}var OC=["minimal","default","strict"];function J_(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: ${OC.join(", ")}`,d.USAGE)}function PC(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return lm(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${dm.join(", ")}`,d.USAGE)}}}function NC(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 Cc(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 LC(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||Cc(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&&Cc(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 FC(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(Cc(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&&kt(e)!==kt(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 ${kt(e)}`,`pm init --id-prefix ${kt(t)}`]});return t}function $C(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: ${K_.join(", ")}`,d.USAGE)}function MC(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function X_(e,t){let n=Dd[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function DC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function UC(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(DC).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function GC(e,t,n){let r=ms(t.schema),s=rt(e,r.files.types,nt.types),i=am(await q(s)),a=[],c=[];for(let m of mm(n)){let u=cm(i,m);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await vt({pmRoot:e,filePath:s,raw:ds(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 jC(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 qC(e,t,n){if(!t||n||await k(V.join(e,"settings.json"))||!await jC(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 Q_(e,t){let n=[],r=[];for(let s of t){let o=s?V.join(e,s):e,i=await k(o);await AC.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 KC(e,t){let n=IC();try{Ce.write(`pm init setup wizard (agent-optimized)
|
|
24
24
|
`),Ce.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
|
|
25
25
|
|
|
26
26
|
`),Ce.write(`1/3 Item ID prefix
|
|
@@ -30,26 +30,26 @@ Agent guidance check
|
|
|
30
30
|
`),Ce.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
|
|
31
31
|
`),Ce.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
|
|
32
32
|
`),Ce.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=
|
|
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=J_(i)}catch{Ce.write(`Unrecognized governance preset "${i}"; using minimal.
|
|
34
34
|
`)}Ce.write(`
|
|
35
35
|
3/3 Project telemetry
|
|
36
36
|
`),Ce.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=
|
|
38
|
-
`),{prefix:s,preset:a,telemetry_enabled:u}}finally{n.close()}}function jC(e){return{presetFromOption:K_(e.preset),useDefaults:e.defaults===!0,authorFromOption:xC(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:NC(e.agentGuidance),typePreset:IC(e.typePreset)}}function qC(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 KC(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 zC(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&&(z_(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 BC(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=qC({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return KC(e.settingsPath,n,e.options.force===!0,e.target),zC({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 HC(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 GC(t,pt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,s=!0}let o=n??"minimal",i=CC();i.id_prefix=t,z_(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 q_(e){return e.settingsExists?await BC(e):await HC({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function VC(e){let t=await j_({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 WC(e,t){let n=[],r=[],s=await cm(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 YC(e){if(e.typePreset===void 0)return;let t=await $C(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 JC(e){let n=x(e.settings,I()).folders.filter(s=>!Ii.includes(s)),r=await B_(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function XC(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 QC(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=MC(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 ZC(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 eR(e,t,n,r=Qu){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 mr(e,t,n={}){let r=process.cwd(),s=OC(r,t,e,n.workspace),o=s.pmRoot;e=PC(s.prefixArg,n.idPrefix);let i=jC(n);await UC(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 q_({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:kt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target}));let f=await B_(o,Ii);a.push(...f.createdDirs),c.push(...f.warnings),p??=await q_({pmRoot:o,settingsPath:m,settingsExists:u,normalizedPrefix:kt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:s.target});let{settings:_}=p,h=XC(s.target),y=await Ju(h??V.dirname(o)),g=h??y,b=await VC({pmRoot:o,cwd:g??r,agentGuidanceMode:i.agentGuidanceMode,settings:_,warnings:c}),v=await WC(o,_);a.push(...v.createdDirs),c.push(...v.warnings);let E=await YC({pmRoot:o,settings:_,typePreset:i.typePreset,warnings:c});if(E&&(_=await A(o)),await JC({pmRoot:o,settings:_,createdDirs:a,warnings:c}),g&&i.agentGuidanceMode!=="status"){let M=await ji(g,{pmRoot:o});M.changed&&c.push(`updated:gitignore:${M.path}`)}!u&&n.mergeFence!==!1&&i.agentGuidanceMode!=="status"&&await eR(o,y,c);let N=await QC(i.installBundledPackages,t,o,c),P=ZC({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 aR from"node:fs/promises";import Rc 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 V_=10,Zt="https://schema.unbrained.dev/pm/eval-query-set/v1";var qo={schema:Zt,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},qe=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},tR=new Set(["keyword","semantic","hybrid"]);function H_(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 nR(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),s=H_(r,n),o=Array.from({length:t.size},()=>1),i=H_(o,n);return i===0?0:s/i}function rR(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 Ac(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 sR(e,t,n){return n<=0?0:Ac(e,t,n)/n}function oR(e,t,n){return t.size===0?0:Ac(e,t,n)/t.size}function W_(e,t,n){return{ndcg:nR(e,t,n),mrr:rR(e,t,n),precision:sR(e,t,n),recall:oR(e,t,n),relevant_total:t.size,retrieved_relevant:Ac(e,t,n)}}function Y_(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 iR(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"||!tR.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 Cc(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==Zt)throw new qe(`Unsupported eval query set schema; expected "${Zt}"`);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:Zt,queries:n.map((r,s)=>iR(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 cR=Rc.join("search","eval-queries.json"),Ic={schema:Zt,examples:[JSON.stringify(qo)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},dR=new Set(["keyword","semantic","hybrid"]),lR=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!dR.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},mR=e=>{if(e===void 0||e==="")return V_;let t=Ud(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},uR=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,pR=async e=>{try{return await aR.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...Ic,examples:[`echo '${JSON.stringify(qo)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},fR=(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,Ic)}},_R=e=>{try{return Cc(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,Ic)}},hR=async e=>_R(fR(await pR(e),e)),gR=(e,t)=>t?Rc.resolve(process.cwd(),t):Rc.join(e,cR),yR=async(e,t,n,r)=>{let s=e.mode??t,i=(await tr(e.query,{mode:s,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=W_(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)}}},bR=(e,t,n,r)=>{let s=Y_(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}},J_=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=mR(e.k),s=lR(e.mode),o=uR(e.failUnder),i=gR(n,e.queries),a=await hR(i),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await yR(u,s,r,t);m.push(f),c.push(p)}return bR(r,c,m,o)};import{readFile as xR,writeFile as OR}from"node:fs/promises";import PR 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 xc(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 wR(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 X_(e,t,n){xc(e,"base");let r=xc(t,"ours"),s=xc(n,"theirs"),o=wR(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 Oc(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 Ko(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
37
|
+
`);let c=t?"Y/n":"y/N",m=await n.question(`Enable telemetry for this project? [${c}] `),u=MC(m,t);return Ce.write(`
|
|
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(`
|
|
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 sh=["item","history","relationship","json"];function NR(e){let t=e.trim().toLowerCase();if(sh.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${sh.join(", ")}.`,d.USAGE)}function LR(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 Mc(e,t){try{return await xR(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function FR(e){let t=T(process.cwd(),e.path);return await k(C(t))?A(t):null}function MR(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function oh(e,t){let n=NR(e.artifact),r=LR(e.prefer),s=PR.resolve(e.outputPath??e.oursPath),[o,i,a]=await Promise.all([Mc(e.basePath,"base"),Mc(e.oursPath,"ours"),Mc(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=X_(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 _=Q_(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 FR(t),h=th(o,i,a,{format:MR(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 _=rh(o,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await OR(s,c,"utf8"),m!==void 0){let _=await gp(m);_!==null&&(p.receipt=Jn(_))}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 ch 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 ih(e,t){return t==="body"?e.body:e.metadata[t]}function $c(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)&&$c(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)&&$c(s,n[r]))}function ah(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 ou(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 $R(e,t,n){let r=ch.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=>$c(ih(t,h),ih(n,h)))),i=new Set([...s].filter(h=>!o.has(h))),a=ah(e,i),c=ah(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 DR(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=jt(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 UR(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 GR(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?ch.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 jR(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 qR(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 ur(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=iu(c),p=t.normalizeProvenance?_p(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=au(p.entries),_=new Set(p.entries.map(ie=>ie.item_hash_version).filter(ie=>ie!==void 0)),h=Es(p.entries,f),y=await DR(i,s,c,f),g=h.finalDocument,b=y.currentItemReplay!==null&&Pe(g,f)!==Pe(y.currentItemReplay,f),v=b&&y.currentItemReplay?$R(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,M=UR({message:t.message,entriesRehashed:h.entriesRehashed,entriesPatchRepaired:h.entriesPatchRepaired,reconcileNeeded:b}),{rewrittenEntries:G,auditEntryAdded:Ie}=GR({reanchorEntries:h.entries,changed:E,reconcileNeeded:b,currentItemReplay:y.currentItemReplay,finalReplay:g,author:N,message:M,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=jR(E,h.skippedOps,v);return E&&!P&&pe.push(...await qR({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 dh(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 zo(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 Gu(n,i),c=e.normalizeProvenance?await hp(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 ur(_,{...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 ru(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 lh(e,t){let n=e.dryRun===!0,r=await yp(process.cwd(),{includeLossless:!0}),{pendingDecisions:s}=bp(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(Jn)}}])),a=await zo({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=>ur(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=>wp(process.cwd(),g))),p=r.length);let f=await Js({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(Jn)},validation:f,guidance:y,generated_at:f.generated_at}}import{createHash as KR}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 ph=1,fh=/^[A-Za-z0-9_-]+$/,zR=100,mh=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 BR(e){return KR("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 uh(e,t){let n={version:ph,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 HR(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===ph,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 VR(e,t){let n=e.trim();if(n.length===0||n.length>4096||!fh.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(!HR(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function WR(e){let t=e??zR;if(!Number.isSafeInteger(t)||t<0||t>mh)throw new l(`Mutation event limit must be an integer from 0 to ${mh}.`,d.USAGE,{code:"invalid_event_limit"});return t}function YR(e,t){let n=e?.trim();if(!n)return{};if(fh.test(n))return{cursor:VR(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 JR(e,t){let n=await Ji(e,t);if(n===null){if(!await eu(e))return{...await tu(e,t),source:"authoritative_history"};n=await Ji(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 XR(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 Bo(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=WR(e.limit),r=XR(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=Iu(s.agent_identity.harness_signals),a=xu({provenance:e.provenanceFilter},i),c=Ke(e.harness),m=BR(e),{cursor:u,sinceTimestamp:p}=YR(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 JR(t,f),h=_.events.map(y=>({...r==="row"?{cursor:uh(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:Ou(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:uh(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Pu(_.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 QR="1h",ZR="now",eI="+1d";function It(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function _h(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 hh(e,t,n,r){let s=_h(e,t,n),o=[];return It(o,"start",n.start??ZR),n.end!==void 0?It(o,"end",n.end):It(o,"duration",n.duration??QR),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 gh(e,t,n){return hh("Meeting",e,t,n)}function yh(e,t,n){return hh("Event",e,t,n)}function bh(e,t,n){let r=_h("Reminder",e,t),s=[];return It(s,"at",t.at??eI),It(s,"text",t.text??e),r.reminder=[s.join(",")],At(r,n)}import fr from"node:crypto";import{cp as vh,lstat as iI,mkdir as tn,readFile as Nn,readdir as Uc,rename as Eh,rm as jc,writeFile as Vo}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 wh=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"}]]),tI=/^[a-z][a-z0-9_]{0,63}$/u,nI=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))),rI={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function sI(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&wh.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:nI.get(Math.abs(t.errno))??null}function oI(e,t,n={}){let r=sI(e);if(r===null)return null;if(!tI.test(t))throw new l("Host environment operation labels must be bounded identifiers.",d.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let s=wh.get(r);return new l(`Host filesystem operation ${t} ${s.summary}.`,d.GENERIC_FAILURE,{code:n.codes?.[s.category]??rI[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 Ho(e,t,n={}){try{return await t()}catch(r){throw oI(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]="36aacc71-c5f5-56f1-85f4-28b2be5b02e2")}catch{}})();var Th="https://schema.unbrained.dev/pm/workspace-snapshot/v1",Ah=L.join("runtime","workspace-snapshots"),aI=new Set(["checkpoints","locks","runtime","search","transactions"]),cI=/^[a-z0-9][a-z0-9._-]*$/,pr="sdk-workspace-transaction",Dc={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Ch={renameEntry:Eh,removeEntry:async e=>{await jc(e,{recursive:!0,force:!0})}},Gc=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!==pr||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 Eh(m,L.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function _r(e,t){let n=await uI(e,t),r=await Ph(L.join(nn(e),"objects",n,"manifest.json"),t);if(r.schema!==Th||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 zc(e){let t=nn(e),n=await Uc(L.join(t,"objects")).catch(s=>{if(s instanceof Error&&"code"in s&&_t(s))return[];throw s}),r=await Uc(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=>_r(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 Bc(e,t){let n=await _r(e,t),{manifest:r,contents:s}=await Ih(e),o=new Map(r.files.map((p,f)=>[p,s[f]])),i=await dI(L.join(nn(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=kh(o.get(p)),_=kh(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 Nh(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,pr,s,r,!1,!1,o),a=new Gc(Nr(e,pr),r,s);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await Bc(e,t),f=await _r(e,t),_=await Kc(e),h=f.fingerprint,y=nn(e),g=L.join(y,"objects",h,"files"),b=L.dirname(e),v=L.basename(e);c=L.join(b,`.${v}.restore-${fr.randomUUID()}`);let E=L.join(b,`.${v}.backup-${fr.randomUUID()}`);await xh("restore_stage",async()=>{await tn(c,{recursive:!0}),await vh(g,c,{recursive:!0,force:!1}),await tn(L.join(c,"runtime"),{recursive:!0}),await vh(y,L.join(c,Ah),{recursive:!0,force:!1})});let N=await cu({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 M=Nr(c,pr);return await tn(L.dirname(M),{recursive:!0}),await Vo(M,await Nn(Nr(e,pr)),{flag:"wx"}),m=!0,await mI(c,e,E,Ch,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([jc(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function Lh(e,t){qc(t);let n=nn(e);if(!/^[a-f0-9]{64}$/.test(t))return await Sh(L.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await zc(e);if(r.some(s=>s.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Sh(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 hr(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 Fh(e){return J_(hr(e),e.global)}function Mh(e){let t=hr(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 Bo({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 $h(e){let t=hr(e),n=lt(t,"subcommand");if(n==="install")return Xu({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return lh({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return vp({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return oh({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 Dh(e){let t=hr(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 Kc(s,{name:w(t,"name")});if(r==="list")return zc(s);let o=lt(t,"target");if(r==="inspect")return _r(s,o);if(r==="delete")return Lh(s,o);if(r==="restore")return t.dryRun===!0?Bc(s,o):Nh(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 Wo(e){let t=hr(e),n=lt(t,"title");return e.action==="meet"?gh(n,t,e.global):e.action==="event"?yh(n,t,e.global):bh(n,t,e.global)}import TI from"node:path";import pI from"node:fs/promises";import Uh 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 fI="templates",_I=".json",hI=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,gI=hs.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),yI=new Set(gI);function bI(e){let t=e.trim();if(!hI.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 Gh(e){return Uh.join(e,fI)}function jh(e,t){return Uh.join(Gh(e),`${t}${_I}`)}async function wI(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function qh(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function vI(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(yI.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 qh(t)}function kI(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 qh(r)}function SI(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=kI(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 EI(e,t){let n=await q(jh(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return SI(n,t)}async function Hc(e,t,n){let r=T(process.cwd(),n.path);await wI(r);let s=bI(e),o=vI(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=jh(r,s),c=i;await k(a)&&(c=(await EI(r,s)).created_at);let m={name:s,created_at:c,updated_at:i,options:o},u=await A(r);return await pI.mkdir(Gh(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 Hh=["list","show","apply","lint"],AI="schema-types",CI="schema-statuses",RI="schema-fields";function Yo(){let e=I();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Vh(){let{profiles:e,warnings:t}=im(Yo());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:mm(n.definition)})),warnings:t,generated_at:S()}}function Wh(e){let t;try{t=ms(e,Yo())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...um(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function Yh(e){let t;try{t=ms(e,Yo())}catch(s){throw new l(s instanceof Error?s.message:String(s),d.USAGE)}let{resolved:n}=t,r=Im(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 II(e,t){return TI.join(e,"templates",`${t}.json`)}async function xI(e,t){let n=await q(II(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 Kh(e,t,n,r){let s=new Map;for(let o of r.templates){let i=await xI(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 zh(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 OI(e){if(!await k(C(e)))throw new l(`Tracker is not initialized at ${e}. Run pm init first.`,d.NOT_FOUND)}function PI(e){try{let t=ms(e,Yo());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function Jh(e,t,n){let r=T(process.cwd(),n.path);await OI(r);let s=PI(e),o=s.profile,i=s.warnings,a=t.dryRun===!0,c=await A(r),m=us(c.schema);if(a){let b=await Kh(r,m,c,o),v=Bh(o,b);return zh(o,v,!1,!0,[...i])}let u=R(t.author,c.author_default),p=lu(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(AI),await y(CI),await y(RI);let b=await Kh(r,m,c,o);if(g=Bh(o,b),g.types.changed){let v=rt(r,m.files.types,nt.types);await vt({pmRoot:r,filePath:v,raw:ls(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=>em(P).name)),N=g.types.file.definitions.filter(P=>E.has(P.name));await rp(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:lm(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:am(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=fs(v.key);E!==void 0&&_s(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 Hc(v.name,{...v.options},n)}finally{for(let b of h.reverse())try{await b()}catch{}}return zh(o,g,g.changed,!1,_)}function Bh(e,t){try{return xm(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import Qh from"node:fs/promises";import Zh 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 NI(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 LI(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 Xh(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return NI(t.ids,n,t.minEntries)}return LI(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 FI(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 MI(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 $I(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 DI(e,t,n){let r=e.located?await K(e.located,{schema:t.schema}):null;return r?{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:Pe(jt(r.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function UI(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 GI(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 jI(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=MI(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),s=$I(r,t,e.boundary.compactCount),i=[De({nowIso:S(),author:e.author,op:"history_compact_baseline",before:Gt(Ss()),after:Gt(t),message:GI(e.boundary)}),...s.entries];return e.dryRun||i.push(De({nowIso:S(),author:e.author,op:"history_compact",before:Gt(n),after:Gt(n),message:UI(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function qI(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 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 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=FI(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 DI(i,s,m);g.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:E}=jI({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 qI({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((M,G)=>M.localeCompare(G)),generated_at:S()}}var KI=3;function eg(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 zI(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function BI(e){let t=j(e.settings.schema),n=Xs(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=Zh.join(e.pmRoot,"history"),i=[],a=[];if(!await k(o))return{candidates:i,preselectionErrors:a};let c=(await Qh.readdir(o)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=Zh.join(o,m),p=m.slice(0,-6);try{let f=await Qh.readFile(u,"utf8");await un({path:u,scope:"project"}),i.push({id:p,entries:zI(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 HI(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 Vc(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 tg(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 BI({pmRoot:n,settings:r,typeToFolder:s.type_to_folder}),a=e.ids!==void 0&&e.ids.length>0?"ids":"scan",c=e.minEntries??KI,m=r.history.compact_policy,u=a==="scan"&&e.allOver===void 0&&m.enabled,p=e.allOver??(u?m.max_entries:void 0),f=Xh(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 HI({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 ng(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return dh(n,t),t?zo(e.options,e.global):ur(n,e.options,e.global)}function rg(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 eg(e.id,{ids:n,allOver:r,scope:c}),e.id!==void 0?Vc(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):tg({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 sg(e,t,n){let r;if(typeof e.lines=="string")r=Vs(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=Vs(`${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 VI=Gi("list").properties.outputSession,WI={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:{...VI},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},og={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."},YI=`Operation name (one of): ${Mi.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,JI={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."}},XI={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{...og,properties:{...og.properties,...e},required:t}}var QI=[{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:[...Mi],description:YI},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."},...WI},["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"},...XI},["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"},...JI})},{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:[...Sm]},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:[...ki]},description:`Lifecycle roles for add-status: ${ki.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."}})}],ZI={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"},ex=QI.map(e=>{let t=ZI[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Gi(t,{properties:n,required:r})}});function ig(){return ex.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]="6fc2cd04-2fe4-5a0e-944d-fab0f86509e2")}catch{}})();var tx=new Set(["claim","close","context","create","get","help","list","next","plan","release","search","update","validate"]),nx=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),cg=Object.freeze([...zn.map(e=>({command:e,tier:tx.has(e)?"core":nx.has(e)?"standard":"full"})),{command:"completion-statuses",tier:"internal"},{command:"completion-tags",tier:"internal"},{command:"completion-types",tier:"internal"},{command:"test-runs-worker",tier:"internal"}]),ag={core:0,standard:1,full:2,internal:3},rx=new Map(cg.map(({command:e,tier:t})=>[e,t]));function dg(e,t="standard"){return rx.get(e.trim().toLowerCase())??t}function lg(e){let t=ag[e];return cg.filter(n=>n.tier!=="internal"&&ag[n.tier]<=t).map(n=>n.command)}var Cq=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});var Rq=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),Iq=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9a66a2a0-94be-595b-983d-347ec95af85e")}catch{}})();var mg=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"],vg=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Xo=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"]),gr=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"]),kg=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"]]),Sg=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"]]),Eg=new Map([...Sg.entries()].flatMap(([e,t])=>mt(t).map(n=>[n,e]))),Tg=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],Ag=new Map(Tg.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),ox=10,ix=20,ug=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."]]),Cg=[["init",_l],["install",gl],["uninstall",yl],["explore",bl],["manage",Tl],["describe",wl],["reload",Al],["doctor",Cl],["catalog",Rl],["adopt",Il],["adopt-all",vl],["activate",kl],["deactivate",Sl],["migrate",El]],ax=Cg.map(([e,t])=>e==="init"?[e,hl]:[e,t]),cx=[...Cg.map(([e,t])=>[`extension ${e}`,t]),...ax.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Kr],["config",fl],["extension",zr],["package",Gn],["packages",Gn],["install",xl],["create",Jr],["item mutate",Jl],["item complete",Xl],["copy",Xr],["focus",Qr],["update",Zr],["update-many",es],["upgrade",Ol],["calendar",jn],["cal",jn],["context",qn],["ctx",qn],["get",ns],["search",as],["eval",Zl],["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",is],["aggregate",Ur],["deps",ss],["graph",os],["guide",rs],["reindex",Pl],["history",Gr],["history-compact",ml],["history-redact",dl],["history-repair",ll],["history-author-acknowledge",jr],["merge",cl],["schema",ul],["profile",pl],["plan",qr],["restore",Fl],["delete",Ml],["close",Nl],["close-many",Br],["append",Hr],["claim",Ll],["release",$l],["start-task",Dl],["pause-task",Ul],["close-task",Gl],["comments",rl],["notes",sl],["learnings",ol],["files",il],["docs",al],["test",Kl],["test-all",zl],["telemetry",Bl],["test-runs",Hl],["gc",Vl],["stats",Vr],["duplicates",Wr],["validate",Wl],["health",Yr],["assurance",Yl],["contracts",cs],["completion",ds],["activity",ts],...[...vg].map(e=>[e,Dr])],Xc=new Map(cx);function dx(e){let t=Eg.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function pg(e){return zn.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)}`):Xo.has(e)?Sg.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} `))}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 Jo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function yr(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=yr(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 Wc(e,t){let r=yr(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 Rg(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 fg(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 Yc(e,t,n){n&&(e[t]=!0)}function _g(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=_g(e.long,"long"),n=_g(e.short,"short"),r=t??n;if(!r)return null;let s={flag:r};n&&t&&(s.short=n),Yc(s,"required",e.required===!0),Yc(s,"repeatable",e.repeatable===!0),Yc(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 Ig(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=Ig(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)??Rg(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:fg(o.examples),failure_hints:fg(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:Rg(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 Fr({pmRoot:r,settings:s,cwd:process.cwd(),noExtensions:!1}),i=await Mr({...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 Fi){let s=Xo.has(r);if(s&&!t.includePackageOwnedActions)continue;let o=pg(r);n.set(r,{action:r,provider:s?"extension":"core",requires_extension:s,command_path:o})}if(t.includePackageOwnedActions)for(let r of Xo)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:pg(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=>kg.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 xg(e){return Xc.get(e)??$r}function Tx(e){return gr.has(e)?!1:Xc.has(e)}function Ax(e){return vg.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function hg(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=hg(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=>hg(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,Pi(s.flags));return n}function gg(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 Pi(n)}function Ix(e,t,n,r){return e.map(s=>{let o=Tx(s),i=o?xg(s):[],a=n.get(Ax(s))??[],c=t.get(s),m=gg(i,a),u=gg(m,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":o?"core":"extension";return{command:s,flags:u,...r?{canonical_command:Jc(s),visibility:dg(Jc(s)),flag_invocations:jm(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 Tg){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:Om,create_repeatable_options:hs,update_string_options:Pm,update_repeatable_options:Nm,list_string_options:Qd,search_string_options:Zd,calendar_string_options:el,context_string_options:tl,activity_string_options:nl}}function yg(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=an(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]=yg(s,"strict"),n[r]=yg(s,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function Nx(e,t){let n=yr(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=Jo(e.action)!==void 0||Jo(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=Jo(e.action),u=Jo(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 Mx(e,t=A){try{return await t(e)}catch{return structuredClone(pt)}}async function $x(e,t){let n=await Mx(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:Ig(r.flagRegistrations)}}function bg(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Xo.has(e.selectedAction)||e.selectedCommand!==void 0&&gr.has(e.selectedCommand))}function Dx(e,t){let n=Sx(t,{includePackageOwnedActions:bg(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Tm);return n.filter(s=>!r.has(s.action))}return bg(e)&&e.selectedCommand!==void 0&&gr.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([...zn.filter(n=>!gr.has(n)),...[...Xc.keys()].filter(n=>!gr.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=kg.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?Eg.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(yr(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=Rm,n=yr(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 wg(e,t,n){let r=new Set(t.actionDescriptors.map(o=>o.action)),s=e.selectedAction?ux(n,e.selectedAction):e.selectedCommand?Wc(n,new Set(t.scopedActionDescriptors.map(o=>o.action))):Wc(n,r);return e.runtimeOnly&&!e.selectedAction?Wc(s,new Set(t.actions)):s}function Wx(e,t,n){let r=Vx(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?Nx(wg(e,n,r),t.createRequiredOptionContracts):wg(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 Jc(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":Ag.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=ug.get(e)??(e.includes(" ")?void 0:ug.get(Jc(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=[]){return[...new Set(e.map(we))].filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r)).map(n=>{let r=$i(n,{generateFallback:!0}),s=n.split(" ")[0],o=Ag.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),i=new Set([...xg(n).map(m=>m.flag),...t.filter(m=>mt(m.command).includes(n)).flatMap(m=>m.flags.map(u=>u.flag))]),a=(mg.get(n)??mg.get(o)??sx).filter(m=>i.has(m)),c=Zx(n,t);return{command:n,...c,...a.length>0?{flags:a}:{},default_max_estimated_tokens:r.default_max_estimated_tokens,default_max_estimated_tokens_by_format:{...r.default_max_estimated_tokens_by_format}}})}function tO(e){return e.map(t=>({budget:$i(t,{generateFallback:!0}),envelope:qm(t)}))}function nO(e){let t=new Map;for(let n of e){let r=Mm(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:[...gm],services:[...ym],policy_modes:[...bm],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...km],trust_modes:[...wm],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...vm],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...xd],create_modes:[...Od],close_validation_modes:[...Pd],workflow_enforcement_modes:[...Nd]},e.relationship_kind_contracts=[...Gd,...(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(Gp).filter(([i])=>o.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...Up],compact_fields:[...Dp]}))}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){e.command_summaries=eO(t,n),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Am],allows_unbounded_opt_out:!0},e.grammar_contracts={nouns:dn.nouns,shared_verbs:dn.shared_verbs,scope_before_verb:dn.scope_before_verb,visible_top_level_ceiling:dn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:dn.ceiling_raise_requires_pm_item}}async function Og(e,t){let n=Lx(e);Fx(n);let r=T(process.cwd(),t.path),s=await $x(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);if((n.summary||n.fullOutput)&&dO(m,c,u),n.summary)return m;let p=xx(o.commandCatalog);return n.flagsOnly&&!n.fullOutput||oO(m,s,n),iO(m,n,i,u),aO(m,n,s,c,p),cO(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...Mu],gate_triggers:[...Fu]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=Lm),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=ig(),m.context_intents=$m(),m.read_output_dimensions=Di,m.error_codes=Gm,m.command_output_contracts=tO(c),m.command_exit_contracts={vocabulary:Fm,command_sets:nO(c)}),m}import HO from"node:fs/promises";import Yg 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 Qo(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)||(Qo(f,i,p,s,"min")&&(i=f,s=p),Qo(f,a,p,o,"max","max")&&(a=f,o=p))}return{id:e,bytes:n,lines:r,oldest_ts:s,newest_ts:o}}function Pg(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);Qo(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);Qo(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 Fg 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 Ng=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 Qc(e){if(e===null)return{format_version:Ng,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!==Ng||!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,Lg=1e3,gO=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Mg(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 br(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>Lg)throw new l(`Improvement observation limit must be an integer from 0 to ${Lg}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function $g(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=Mg(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=br(n.source,"source"),a=br(n.itemId,"itemId"),c=br(n.unit,"unit"),m=br(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:$g(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=br(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await _O("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Dd(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 Dg(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=Fg.join(n,"improvement-ledger.json"),i=await du({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=Qc(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 Ug(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:Mg(e.metric),r=e.since===void 0?void 0:$g(e.since,"since"),s=bO(e.limit),i=Qc(await q(Fg.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 Gg(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 Zc(e=Bn,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 ed(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=Gg(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,jg=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>jg)throw new l(`History analytics event limit must be an integer from 1 to ${jg}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function qg(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 Kg(e,t){let n=NO(t.eventLimit),r=LO(t.since),s=[],o=r,i=!1;for(;s.length<n;){let a=await Bo({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 MO(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 $O(e){return PO.some(t=>e.startsWith(t))}function zg(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=MO(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=zg(r,a);p.events+=1,$O(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&&(zg(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=Zc(t),s=ed(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 Bg(e,t=Bn,n={}){let r=qg(n.minimumSample);return{...KO(e.events.map(s=>s.entry),t,r),window:e.receipt}}function Hg(e,t,n,r={}){let s=qg(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 wr(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 Vg(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 Wg(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=Zn(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=Yg.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=Yg.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 wr(t.observe,r))n.push(await Dg({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=Zn(e,"assignee",n)),t.byTag&&(r.tag=Zn(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=Zn(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 Kg(e,o):void 0;return{provenanceCoverage:s.provenanceCoverage&&i?Bg(i,n.agent_identity?.harness_signals,o):void 0,fleetAttribution:s.fleetAttribution&&i?Hg(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 td(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 pu({pmRoot:n,settings:r,itemIds:a.map(E=>E.id),commandLabel:"stats"});let c=Xs(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?Pg(u):void 0,_=t.metadataCoverage?Mp(a,c):void 0,h=QO(a,t,c),y=t.fieldUtilization?$p(a):void 0,g=t.measurements===!0||s.length>0?await Ug({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 Jg(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 ty=Ot.join("runtime","telemetry","events.jsonl"),ny=Ot.join("runtime","telemetry","state.json"),nP=Ot.join("runtime","telemetry"),rP=20,Xg=["status","flush","stats","clear"],Qg=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},nd=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Zg=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},sP=e=>({command:nd(e.event.command,"<unknown>"),eventType:nd(e.event.event_type,"unknown"),eventSchemaVersion:Zg(e.event.schema_version),clientSchemaVersion:Zg(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 nd(t,"")||void 0},ry=(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&&ry(e.resolution_counts,r)},dP=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,ey=(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)),ry(r.event_type_counts,n.eventType),ey(r.event_schema_versions,n.eventSchemaVersion),ey(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:Qg(r,.5),duration_p95_ms:Qg(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(Xg.includes(t))return t;throw Ee({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Xg,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},rd=()=>{throw new l("--limit must be a positive integer",d.USAGE)},sy=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?rd():e,pP=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?rd():sy(Number.parseInt(t,10))},fP=e=>e===void 0?rP:typeof e=="number"?sy(e):typeof e=="string"?pP(e):rd(),_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),oy=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)},Zo=e=>e??null,ei=async e=>{let t=await A(e),n=Ot.join(e,ty),r=Ot.join(e,ny),s=await q(n),o=oy(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:Zo(i.last_attempted_flush_at),last_successful_flush_at:Zo(i.last_successful_flush_at),last_failed_flush_at:Zo(i.last_failed_flush_at),last_failed_flush_error:Zo(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 ei(t.globalPmRoot),generated_at:S()}),SP=async(e,t)=>{let n=await ei(t.globalPmRoot);await Ru(t.globalPmRoot);let r=await ei(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=oy(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 ei(t.globalPmRoot),generated_at:S()}},AP={status:kP,flush:SP,stats:EP,clear:TP};async function iy(e,t){let n=uP(e.subcommand),r=et(process.cwd());return AP[n](e,{globalPmRoot:r,queuePath:Ot.join(r,ty),statePath:Ot.join(r,ny)})}import{spawn as Ty}from"node:child_process";import{cp as my,mkdir as OP,mkdtemp as Ay,open as ad,readdir as cd,rm as Cy}from"node:fs/promises";import{tmpdir as Ry}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 ay=20;function CP(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return ay;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?ay:t}function sd(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 ti(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=sd([...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 cy=100;function od(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<=cy?n:`${n.slice(0,cy-3)}...`}function dy(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 ly(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: ${dy(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=od(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: ${dy(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 ri=20*1024*1024,PP=3e3,NP=1e4,LP=5e3,uy=120,FP=new Set(["locks","extensions","runtime"]),MP=new Set(["history","index","search","extensions","locks","runtime"]),$P=[/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 md(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 md("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",PP)}function qP(){return md("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",NP)}function KP(){return md("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 ud(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 si(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Vt.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${Vt.join(", ")}`,d.USAGE)}function Iy(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:si(e.pm_context_mode)}function xy(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=or(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=ir(r,t);s&&n.push(...s)}return[...new Set(n)]}function XP(e){let t=oi(e);return Xn(t).some(n=>ua(n)!==null)}function Oy(e){let t=oi(e);return Xn(t).some(n=>{let r=ua(n);if(!r)return!1;let s=Np(r);return s?GP.has(s.subcommand):!1})}function ni(e){if(e)return xp.has(e.subcommand)?Tn(e.args,Op)?.subcommand:e.subcommand}function py(e,t){if(e==="npx"||e==="bunx")return Ys(t)?.command;if(e==="pnpm")return ni(Tn(t,Ap));if(e==="npm")return ni(Tn(t,Cp));if(e==="yarn")return ni(Tn(t,Rp));if(e==="bun")return ni(Tn(t,Ip))}function fy(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function id(e){return!e||!fa(e.command)&&!Pp(e.command)?!1:Ws(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 Py(e){let t=e.split(" ").filter(i=>i.length>0),n=pa(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?Py(s.slice(i+1).join(" ")):!1}return fa(r)||_a(r)?Ws(s)==="test-all":r==="node"&&s.length>0&&_a(s[0])?Ws(s.slice(1))==="test-all":ZP.has(r)?id(Ys(s)):r==="pnpm"?id(ha(s)):r==="npm"?id(ga(s)):!1}function Ny(e){let t=oi(e);return Xn(t).some(n=>Py(n))}function Ly(e){if(Ny(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function oi(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=pa(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"?fy(Ys(t)?.command):e==="pnpm"||e==="npm"?fy((e==="pnpm"?ha(t):ga(t))?.command)||py(e,t)==="vitest":(e==="yarn"||e==="bun")&&py(e,t)==="vitest"}function Fy(e){let t=oi(e);if(Xn(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(Ny(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=wo(t)?vo(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 Ly(r),Fy(r),{command:r,path:de(n.path),scope:HP(n.scope),timeout_seconds:cN(de(n.timeout_seconds),de(n.timeout)),pm_context_mode:Ao(de(n.pm_context_mode),"--add"),env_set:or(de(n.env_set),"--add"),env_clear:ir(de(n.env_clear),"--add"),shared_host_safe:To(de(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Yt(de(n.assert_stdout_contains)),assert_stdout_regex:xn(de(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Yt(de(n.assert_stderr_contains)),assert_stderr_regex:xn(de(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Co(de(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Ro(de(n.assert_json_field_equals),"--add"),assert_json_field_gte:Io(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=Cf(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);Ly(s),Fy(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 My(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=uy?t:`${t.slice(0,uy-3)}...`}function $y(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function dd(e){try{process.stderr.write(`${e}
|
|
49
|
-
`)}catch{}}function pN(e,t){if(
|
|
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 MN(e,t=mr,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 $N(e,t,n){t&&(await yy(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await yy(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await by(t.projectPmRoot,e.trackerProjectPmPath),await by(t.globalPmRoot,e.trackerGlobalPmPath)))}function DN(e,t,n){return e.some(r=>{let s=r.command??"",o=s.length>0&&Oy(s),i=n?.autoPmContext===!0&&o?"auto":Iy(r,t,n?.overrideLinkedPmContext===!0);return xy(i,o)==="tracker"})}async function UN(e,t){return{sourceProjectItemCount:t?await Mn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Mn(t.globalPmRoot):0,schemaProjectItemCount:await Mn(e.schemaProjectPmPath),schemaGlobalItemCount:await Mn(e.schemaGlobalPmPath),trackerProjectItemCount:await Mn(e.trackerProjectPmPath),trackerGlobalItemCount:await Mn(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?si(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?Oy(n):!1,o=e.options?.autoPmContext===!0&&s,i=o?"auto":Iy(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=xy(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 Sy(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function ld(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 Sy(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=oN(e.linkedTest.command);if(t)return Sy(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 ld(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)?ld(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 gy(n,e.runtimeDirectives),gy(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[Hs]="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?ld(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 pd(e,t,n){let r=[],s=await Ay(le.join(Ry(),"pm-linked-test-")),o=FN(s),i=si(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 MN(o,mr,u),await $N(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 Cy(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 $(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:od(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?ly(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:si(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 pd(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=ud(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=wr(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 ti({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 Ey(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=Vg(t,o,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Wg(t,e.metricDiff)}}async function ai(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);wr(t.measure,"validation"),Ey(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=ii(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?sd([..._.testRuns,N]):_.testRuns,M=Ey(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}:{},...M}}(function(){try{var e=typeof window<"u"?window:typeof 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},Dy=(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"},ci=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Uy=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:ci(e.assert_stdout_contains),assert_stdout_regex:ci(e.assert_stdout_regex),assert_stderr_contains:ci(e.assert_stderr_contains),assert_stderr_regex:ci(e.assert_stderr_regex),assert_stdout_min_lines:hL(e.assert_stdout_min_lines),assert_json_field_equals:Uy(e.assert_json_field_equals),assert_json_field_gte:Uy(e.assert_json_field_gte)};return JSON.stringify(t)},yL=e=>{let t=fd(e.command);return t!==void 0?`command:${e.scope}:${uL(t)}`:`path:${e.scope}:${fd(e.path)??""}`},Gy=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},di=(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 ai(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=Dy(e.options.limit,"--limit"),o=Dy(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=Gy(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=Gy(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 pd(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=ii(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 ti({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},fd=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:fd(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:ii([]),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()){di(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),di(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=ud(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(" "),ML=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 di(e,FL({...s,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:s.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:o,runStartedAt:i}},$L=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}},jy=async(e,t)=>{let n=await ML(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=$L({options:e,accumulation:r,failOnEmptyTestRunTriggered:s});return di(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 qy(e){return ps("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 Ky(){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 By=[{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"]}],zy=new Map;for(let e of By){zy.set(e.id,e);for(let t of e.aliases)zy.set(t,e)}function _d(){return By.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 Iz=[...Ar],xz=[...Cr],DL=new Set(Kn.filter(e=>e.hidden).map(e=>e.alias)),Oz=lg("full").filter(e=>!DL.has(e)),Pz=F(Dr),Nz=F(Ur),Lz=F(Hr),Fz=F(Xr),Mz=F(Qr),$z=F(jl),Dz=F(ql),Uz=F(Jr),Gz=F(ns),jz=F(Zr),qz=F(es),Kz=F(Br),zz=F(ts),Bz=F(Gr),Hz=F(jr,!1),Vz=F(Ql),Wz=F(jn),Yz=F(qn),Jz=F(is),Xz=F(ss),Qz=F(Wr),Zz=F(os),eB=F(rs),tB=F(as),nB=F(Vr),rB=F(Yr),sB=F(Kr),oB=F(cs),iB=F(qr);var UL=F(ds),aB=`${UL} bash zsh fish`,cB=GL(_d());var dB=F(zr),lB=F(Gn);var mB=$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]="48d9b905-70a1-52c3-9b9c-33624661e6eb")}catch{}})();var Yy=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[Yy]=!0,n}run(t,n={}){return Jy({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Bp(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Zi(await this.list(Qi(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 Hy=Km(),fF=new jL;function li(){qi(zd()),Ki(Bd()),zi(Hd()),Bi(Vd()),Hi(Wd()),Vi(Yd()),Wi(Jd())}async function _F(e,t,n,r){return zm(()=>t===void 0?Hy.read(()=>Vy(e,n,r)):Hy.write(()=>gF(t,()=>Vy(e,n,r))))}async function Vy(e,t,n){let r=T(t,e.path);if(e.noExtensions)return li(),Ia({pmRoot:r},()=>n(null));if(!await k(C(r)))return li(),n(null);let s=null,o;try{let i=await A(r),a=await Fr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Mr({...a,loaded:a.loaded});o={loadResult:a,activationResult:c},qi(c.hooks),Ki(c.commands),zi(c.parsers),Bi(c.preflight),Hi(c.services),Vi(c.renderers),Wi(c.registrations),s={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){li(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Ia({pmRoot:r,packages:s?.packages},()=>n(s))}finally{li(),o&&await Xd(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=qt(e),a=s.registrations.commands.find(m=>qt(m.action)===o)?.command??s.commands.handlers.find(m=>qt(m.command)===o)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=await ys({command:aa(a),args:he(n.args??t.args),options:ca(t,n),global:r,pm_root:s.pmRoot,sdk:Yp(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=qt(t),r=ui(Vp,n),s=r?.action??n,o={...e,action:s};return r?.options!==void 0&&(o.options={...r.options,...Oi(e.options)}),s==="package"&&(o.options={...Oi(o.options),vocabulary:"package"}),{action:s,args:o}}function wF(e){return!yF.has(qt(e))}async function Jy(e){let t=bF(e),n=sa(t.args),r=wF(t.action),s=w(t.args,"cwd"),o=s??process.cwd();try{return e[Yy]===!0||fF.getStore()===!0?await Wy(t.action,t.args,n,null):await _F(n,s,o,i=>Wy(t.action,t.args,n,i))}finally{r&&Ta()}}function ui(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function mi(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),Ea(await Et(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function kF(e){let t=ln("search",e.options);return t.compact===void 0&&t.full===void 0&&t.fields===void 0&&(t.compact=!0),Ea(await tr(Je(e.args,"query"),t,e.global),t)}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 hc(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=so(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")),uf(W(e),t,e.global)}function Xy(e,t){return Tp(sg(e.options,t,Le),e.global)}function RF(e){let t=he(e.options.lookupPath);if(t&&t.length>0)return Xy(e,t);let n=W(e);return e.options.discover===!0?ma(n,ia(e.options),e.global):Ep(n,zs(e.options),e.global)}function IF(e){return iy({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:Ku(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),kp(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 N_(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 Lu(Nu(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 m_({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 MF(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 $F(e){let{ctx:t,subcommand:n,name:r,author:s,force:o}=e,a=ui({list:()=>ip(t.global),show:()=>ap(r,t.global),"show-status":()=>cp(r,t.global),"list-fields":()=>mp(t.global),"show-field":()=>up(r,t.global),"remove-type":()=>np(r,{author:s,force:o},t.global),"remove-field":()=>lp(r,{author:s,force:o},t.global),"remove-status":()=>op(r,{author:s,force:o},t.global),"apply-preset":()=>pp(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 dp(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 sp(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 tp(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 Zu(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:s,force:o},t.global)}function qF(e){let t=MF(e),n=$F(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?fp({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:ep,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=ui({list:()=>Vh(),show:()=>Wh(r),lint:()=>Yh(r),apply:()=>Jh(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:Hh,exit_code:64});return o()}async function zF(e){let{changedFields:t,idOnly:n,runnerOptions:r}=Ve(e.args,e.options);return st(await Xp(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 Zf(la(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 mf(da(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 zt(W(e,r),s,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Qy(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=qy(j(n.schema)),s=W(e),o=await io(s,e.force,e.global,e.options),i=await at(s,{...Qy(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,{...Qy(e.options),status:s,force:e.force},e.global),i=await ao(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 ao(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 Uu(Je(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),Hu(t),e.global)}function QF(e){return Wu(T(process.cwd(),e.global.path),{...e.args,...e.options})}var ZF={init:e=>mr(w(e.args,"prefix"),e.global,e.options),context:e=>va(ln("context",e.options),e.global),next:e=>er(ln("next",e.options),e.global),eval:Fh,events:Mh,merge:$h,workspace:Dh,meet:Wo,event:Wo,remind:Wo,list:vF,get:e=>ka(W(e),e.global,ln("get",e.options)),search:kF,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:he(e.options.status);return Sa(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=>yc(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?sf(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):io(W(e),e.force,e.global,e.options),release:e=>ao(W(e),e.force,e.global,e.options),"start-task":WF,"pause-task":YF,"close-task":JF,close:AF,comments:CF,notes:e=>ff(W(e),so(e.options),e.global),learnings:e=>pf(W(e),so(e.options),e.global),files:RF,docs:e=>Sp(W(e),zs(e.options),e.global),test:e=>ai(W(e),e.options,e.global),"test-all":e=>jy(e.options,e.global),telemetry:IF,validate:e=>Js(e.options,e.global,{runUpdate:(t,n,r)=>at(t,n,r)}),health:xF,assurance:e=>Lp(e.args,e.options,e.global),contracts:e=>Og(e.options,e.global),config:OF,activity:PF,aggregate:e=>ya(e.options,e.global),extension:e=>En(mi(e),e.options,e.global),package:e=>En(mi(e),e.options,e.global),install:e=>En(mi(e),{...e.options,install:!0},e.global),upgrade:e=>qp(mi(e),e.options,e.global),delete:e=>gc(W(e),e.options,e.global),deps:e=>Du(W(e),e.options,e.global),graph:XF,"files-discover":e=>ma(W(e),e.options,e.global),"files-lookup":e=>Xy(e,he(e.options.paths)),history:e=>jp(W(e),e.options,e.global),"history-redact":e=>gu(W(e),e.options,e.global),"history-repair":ng,"history-compact":rg,"history-author-acknowledge":QF,plan:LF,schema:qF,profile:KF,stats:e=>td(e.global,Jg(e.options)),append:zF,"update-many":BF,"close-many":HF,gc:e=>Kp(e.global,e.options)};async function Wy(e,t,n,r){let s=oa(t,e);Ui(e,s),Cm(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=ui(ZF,e),a=i?await i(o):await hF(e,t,s,n,r);return s.resolvedOutputFormat="json",Um(e,s,a)}var eM={closeManyOptionsFromFlat:da,extensionOptionsFromArgs:ca,globalOptions:sa,mutationListOptions:Bu,normalizeActionName:qt,normalizeCommandPath:aa,normalizeMcpUpdateOptions:Vu,normalizeMcpOptionsArrays:zu,optionsWithAuthor:oa,readRequiredString:Je,readScalarString:ju,readScalarStringAllowBlank:qu,readStringArray:he,updateManyOptionsFromFlat:la,withAddNoteOption:zs,withFilesDiscoveryOptions:ia,withMutationCompaction:Ve};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=eM);(function(){try{var e=typeof window<"u"?window:typeof 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,Wm as BASELINE_ITEM_FORMAT_VERSION,Bn as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,Ar as BUILTIN_ITEM_TYPE_VALUES,Rr as CONFIDENCE_TEXT_VALUES,Ym as CURRENT_ITEM_FORMAT_VERSION,Ft as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,sn as ISSUE_SEVERITY_VALUES,Id as ITEM_TYPE_VALUES,Aa as PM_CLI_EXPECTED_ERROR_NAME,Wb as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,Hb as PM_READ_OUTPUT_DIMENSIONS,Vb as PM_READ_OUTPUT_OPTION_FLAGS,Di as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,U as PmClient,rn as RISK_VALUES,_w as SEMANTIC_ATTRIBUTION_LIMITS,Cr as STATUS_VALUES,sw as agentSessionEnvironment,WL as aggregate,Zc as analyzeAgentProvenanceDescriptorCoverage,ew as analyzeSdkCliParameterCompleteness,rF as append,Xb as applyReadOutputDimensions,jb as applyReadOutputSessionReferences,qb as attachReadOutputSessionReceipt,tw as boundAgentEpisodeIdentity,He as canonicalDocument,aF as claim,cF as claimNext,Qm as classifyItemFormatVersion,iF as close,YL as comments,qL as context,lF as copy,sF as create,Wp as createPmCliExpectedError,Bb as decodeReadOutputContinuationCursor,mF as deleteItem,tF as deps,cw as detectAgentIdentity,mw as detectHarnessIdentity,dw as diagnoseAgentIdentity,eF as docs,Jm as effectiveItemFormatVersion,Ky as emptyImportedDocument,zb as encodeReadOutputContinuationCursor,CO as evaluateSemanticAttributionCoverage,pw as explainSourceTraceability,QL as files,ZL as filesDiscover,pF as focus,HL as get,nF as graph,RO as groupHistoryByEpisode,rf as isAlreadyClaimedError,to as isPmCliExpectedError,Qb as isReadOutputBudgetExceeded,XL as learnings,KL as list,zL as listAllComplete,VL as next,Xm as normalizeItemFormatVersion,_e as normalizeItemId,ne as normalizeStatusInput,JL as notes,S as nowIso,Gb as parseReadOutputSession,Vs as parseSourceLineRange,ws as readAuthorEnvironment,Kb as readOutputSessionRemainingTokens,ba as recordClaimSemanticAttribution,Qs as recordFocusSemanticAttribution,wa as recordReleaseSemanticAttribution,ow as registerHarnessSignalDescriptors,dF as release,nw as resolveAgentSessionContextFromSignals,uw as resolveAuthorIdentity,Gg as resolveHistoryEpisodeGroupIdentity,Jb as resolveReadOutputDimensions,Zb as resolveReadOutputEncoding,Yb as resolveReadOutputSurface,fw as resolveSemanticLineageIds,uF as restore,Jy as runAction,rw as runWithAgentSessionContext,iw as runWithHarnessDetectionSignals,aw as runWithWorkspaceHarnessSignalDescriptors,BL as search,hw as semanticAttributionAffinity,$e as serializeItemDocument,AO as summarizeAgentModelProvenance,ed as summarizeAgentProvenance,oF as update,Ui as validateReadOutputOptions,lw as writeAuthorEnvironment};
|
|
40
|
+
`}function ER(e){return e.map((t,n)=>({...t,sequence:n+1}))}function oh(e,t,n){Nc(e,"base");let r=Nc(t,"ours"),s=Nc(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:qo(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:qo(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:qo(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=_n(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=ER([...r.slice(0,i),...u]);return{merged:qo(p),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:m.length,entries_total:p.length,reanchored:!0}}var TR=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],AR=["updated_at"];function tn(e,t){return J(e??null)===J(t??null)}function CR(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 RR(e,t){return _n(String(e),String(t))>=0?e:t}function ih(e,t,n,r){return tn(t,n)?{value:t,from_theirs:!1,conflict:!1}:tn(e,t)?{value:n,from_theirs:!0,conflict:!1}:tn(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function ah(e,t,n,r,s){let o=ih(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 Lc(e){return{...e.metadata}}function Fc(e,t,n){try{return He(iu(e,n),n)}catch(r){throw new l(`Item merge input (${t}) is not a readable item document: ${String(r)}`,d.GENERIC_FAILURE)}}function IR(e,t,n,r,s){let o=new Set(TR),i=new Set(AR),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=CR(u,p,f);c.merged[m]=h,tn(h,p)||c.unionFields.push(m);continue}if(i.has(m)){c.merged[m]=RR(p,f);continue}let _=ah(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 ch(e,t,n,r={}){let s=r.preferred??"ours",o=r.conflictResolution??"preferred_side",i=e.trim().length>0,a=Fc(t,"ours",r),c=Fc(n,"theirs",r),m=i?Fc(e,"base",r):a,u=i?Lc(m):{},p=Lc(a),f=Lc(c),{merged:_,conflictFields:h,fieldsFromTheirs:y,unionFields:g,conflictDecisions:b}=IR(u,p,f,s,o),v=ah(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:Me({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 $c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mc(e,t){let n=ks(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 xR(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 OR(e,t,n,r,s,o,i){if(!$c(t)||!$c(n))return null;let a=$c(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=PR(a,t,n,u,r,p,o,i);f!==void 0&&(c[u]=f)}return c}function dh(e,t,n,r,s,o,i){if(tn(t,n))return t;let a=xR(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(s),a.merged;let c=OR(e,t,n,r,s,o,i);if(c!==null)return c;let m=ih(e,t,n,r);return m.conflict?o.push(s):m.from_theirs&&i.push(s),m.value}function PR(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 dh(e[r],t[r],n[r],s,o,i,a);if(c){if(u&&tn(e[r],t[r])){a.push(o);return}return u?(i.push(o),s==="theirs"?void 0:t[r]):t[r]}if(!(u&&tn(e[r],n[r])))return u?(i.push(o),s==="theirs"?n[r]:void 0):(a.push(o),n[r])}function lh(e,t,n,r={}){let s=r.preferred??"ours",o=Mc(e,"base"),i=Mc(t,"ours"),a=Mc(n,"theirs"),c=[],m=[],u=dh(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 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 Fh(e,t=""){let n=await jc(L.join(e,t),{withFileTypes:!0}),r=[];for(let s of n.sort((o,i)=>o.name.localeCompare(i.name))){if(t.length===0&&lI.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 Fh(e,o));else if(s.isFile())r.push(o);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${o}`)}return r}async function $h(e){let t=await Fh(e),n=pr.createHash("sha256"),r=[],s=0;for(let i of t){let a=await Nn(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:Ph,fingerprint:o,files:t,bytes:s},contents:r}}function Ih(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
|
|
43
|
+
`).filter(t=>t.trim().length>0).length}async function uI(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 Nn(L.join(e,i))]));for(let[i,a]of o)n.set(i,a)}return n}function zc(e){if(!mI.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 Mh(e,t){return Bo(`workspace_snapshot_${e}`,t,{codes:{capacity:Gc.capacity.code,permission:Gc.permission.code,resource:Gc.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 rn(e){return L.join(e,Nh)}function Dh(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 Uh(e,t){try{return JSON.parse(await Nn(e,"utf8"))}catch(n){throw _t(n)?Dh(t):n}}async function xh(e,t,n){try{await Kc(e,{recursive:n})}catch(r){throw _t(r)?Dh(t):r}}async function pI(e,t,n=Lh){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 fI(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 _I(e,t){return zc(t),/^[a-f0-9]{64}$/.test(t)?t:(await Uh(L.join(rn(e),"refs",`${t}.json`),t)).fingerprint}async function Bc(e,t={}){if(t.name!==void 0&&(zc(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 $h(e),s=rn(e),o=L.join(s,"objects",n.fingerprint),i=!1;try{i=(await dI(o)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&_t(a)))throw a}if(!i){let a=L.join(s,"objects",`.create-${process.pid}-${pr.randomUUID()}`);await Mh("create_object",async()=>{await nn(L.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=L.join(a,"files",m);await nn(L.dirname(u),{recursive:!0}),await Ho(u,r[c])}await Ho(L.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
|
|
44
|
+
`,"utf8"),await nn(L.dirname(o),{recursive:!0})}),i=await pI(a,o)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=L.join(s,"refs");await nn(c,{recursive:!0});let m=L.join(c,`.ref-${process.pid}-${pr.randomUUID()}`);await Ho(m,`${JSON.stringify(a,null,2)}
|
|
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 pN(e,t){if(!Gy(t))return null;let n=Uy(e.command),r=Date.now();md(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let s=setInterval(()=>{let o=Date.now()-r;md(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${o} command="${n}"`)},qP());return s.unref?.(),s}function fN(e,t,n,r){if(!Gy(r))return;let s=Uy(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(" ")}`:"";md(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${o}${u} command="${s}"`)}async function yy(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Ry("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 _N(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function hN(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 yy(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{yy(r)},jP()),t.forceKillTimer.unref?.()}}function gN(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)},KP()),r.unref?.())}),e.on("close",(o,i)=>{s({code:o,signal:i})})})}function yN(e,t,n,r){return Ry(e,{cwd:process.cwd(),env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function by(e){let t=await dd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,ni),s=Buffer.alloc(r);return r>0&&await t.read(s,0,r,0),{text:s.toString("utf8"),truncated:n>ni}}finally{await t.close()}}async function bN(e,t,n,r,s){let o=Date.now(),i=await Iy(le.join(Oy(),"pm-linked-test-output-"));try{let a=le.join(i,"stdout.log"),c=le.join(i,"stderr.log"),[m,u]=await Promise.all([dd(a,"w"),dd(c,"w")]),p;try{p=yN(e,n,m.fd,u.fd)}finally{await Promise.all([m.close(),u.close()])}uN(p);let f={heartbeat:pN(r,s),forceKillTimer:null,timedOutTimer:null},_=hN(p,f),h=!1,y;p.on("error",G=>{y=G.message}),f.timedOutTimer=setTimeout(()=>{h=!0,_()},t),f.timedOutTimer.unref?.();let{code:g,signal:b}=await gN(p);_N(f);let[v,E]=await Promise.all([by(a),by(c)]),N=v.truncated||E.truncated,P=N?`
|
|
50
|
+
[pm linked-test output truncated at ${ni} bytes per stream; the child process continued to completion]
|
|
51
|
+
`:"",$={stdout:`${v.text}${P}`,stderr:E.text,exitCode:g,signal:b,timedOut:h,maxBufferExceeded:!1,outputTruncated:N,spawnError:y};return fN(r,$,o,s),$}finally{await xy(i,{recursive:!0,force:!0})}}function wN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${ni} 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 vN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
52
|
+
`);return MP.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>DP.test(n)&&UP.test(n))}function kN(e){return vN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function SN(){return{infra_collision:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function oi(e){let t=SN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function wy(e,t){for(let[n,r]of Object.entries(t.env_set))Yt.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)Yt.has(n.toUpperCase())||delete e[n]}function EN(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 TN(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 AN(e,t,n){return{env_set:YP(e,"--env-set"),env_clear:JP(t,"--env-clear"),shared_host_safe:n===!0}}async function Mn(e,t,n=!1,r=OP){if(await k(e))try{await Bo("seed_linked_test",async()=>{if(await r(le.dirname(t),{recursive:!0}),n){await fy(e,t,{recursive:!0,force:!0});return}await fy(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&&_t(s))return;throw s}}async function vy(e,t,n){await Mn(C(n.projectPmRoot),C(e)),await Mn(le.join(n.projectPmRoot,"extensions"),le.join(e,"extensions"),!0),await Mn(C(n.globalPmRoot),C(t)),await Mn(le.join(n.globalPmRoot,"extensions"),le.join(t,"extensions"),!0)}async function ky(e,t){if(!await k(e))return;let n=await ld(e,{withFileTypes:!0});for(let r of n){if(FP.has(r.name))continue;let s=le.join(e,r.name),o=le.join(t,r.name);if(r.isDirectory()){await Mn(s,o,!0);continue}r.isFile()&&await Mn(s,o)}}async function $n(e){if(!await k(e))return 0;let t=0,n=await ld(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||$P.has(r.name))continue;let s=le.join(e,r.name),o;try{o=await ld(s,{withFileTypes:!0})}catch{continue}for(let i of o)i.isFile()&&Ud.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function CN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function RN(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 Sy(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=RN(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 IN(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 xN(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?tt(e,t):Object.is(e,t)}function ON(e,t,n){let r=[];r.push(...Ey("stdout",t,e.assert_stdout_contains)),r.push(...Ty("stdout",t,e.assert_stdout_regex)),r.push(...Ey("stderr",n,e.assert_stderr_contains)),r.push(...Ty("stderr",n,e.assert_stderr_regex)),r.push(...PN(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=Sy(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=IN(m);xN(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=Sy(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 Ey(e,t,n){let r=[];for(let s of n??[])t.includes(s)||r.push(`${e} missing required text: "${s}"`);return r}function Ty(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 PN(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 NN=[{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 LN(e,t){let n=`${e}
|
|
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};
|
|
55
55
|
//# sourceMappingURL=sdk-core.js.map
|