@unbrained/pm-cli 2026.8.25 → 2026.8.26

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.
Files changed (116) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +33 -0
  3. package/dist/cli-bundle/bundle-manifest.json +133 -133
  4. package/dist/cli-bundle/chunks/chunk-E2GCFJSU.js +35 -0
  5. package/dist/cli-bundle/chunks/{chunk-QKGMHGEI.js → chunk-ES25LX3D.js} +51 -51
  6. package/dist/cli-bundle/chunks/{chunk-TPQIBSL2.js → chunk-FRDWWB6R.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-65MHLHAA.js → chunk-ICQ3RVIY.js} +2 -2
  8. package/dist/cli-bundle/chunks/chunk-IV64RJVE.js +13 -0
  9. package/dist/cli-bundle/chunks/{chunk-QLUORNIB.js → chunk-KBFP3E4E.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-T2ENPRXF.js → chunk-MVYLQ67M.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-5I5RWIJC.js → chunk-S4U76VZF.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-OWHNAR2B.js → chunk-UKBCRPA2.js} +2 -2
  13. package/dist/cli-bundle/chunks/chunk-WRHJ3MB6.js +8 -0
  14. package/dist/cli-bundle/chunks/{chunk-244MI4GS.js → chunk-ZNRLJ54C.js} +60 -60
  15. package/dist/cli-bundle/chunks/{register-list-query-XVN2ZLI7.js → register-list-query-EMCPMICY.js} +2 -2
  16. package/dist/cli-bundle/chunks/{register-mutation-QCKAEGIJ.js → register-mutation-OJ67ABCB.js} +2 -2
  17. package/dist/cli-bundle/chunks/{register-operations-SDEAXE7E.js → register-operations-H2GLP7LT.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-setup-LXVBRCJ3.js → register-setup-GLZAHLVI.js} +2 -2
  19. package/dist/cli-bundle/focused-chunks/{chunk-NOOZGIXP.js → chunk-4K2II4TV.js} +2 -2
  20. package/dist/cli-bundle/focused-chunks/{chunk-IBZZZGK3.js → chunk-4XNH2HM7.js} +2 -2
  21. package/dist/cli-bundle/focused-chunks/{chunk-VXWATRFL.js → chunk-57XY346D.js} +2 -2
  22. package/dist/cli-bundle/focused-chunks/{chunk-GQR3WH3F.js → chunk-66VGB23P.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-42S3GGZ7.js → chunk-72T6JGAE.js} +45 -45
  24. package/dist/cli-bundle/focused-chunks/{chunk-RAFKLNZX.js → chunk-FXDLT6FL.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-H5JZEIQV.js → chunk-IBHXMFE7.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-N7W67YIG.js → chunk-LV5N3LK5.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-2UIWOP3O.js → chunk-MMXUPDDJ.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-ONYQCALA.js → chunk-P2E6LDAE.js} +6 -6
  29. package/dist/cli-bundle/focused-chunks/{chunk-XUQPEKRN.js → chunk-TMJDFHVD.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-OVJL6NZE.js → chunk-UYBA57GY.js} +4 -4
  31. package/dist/cli-bundle/main.js +2 -2
  32. package/dist/cli-bundle/sdk-authoring.js +1 -1
  33. package/dist/cli-bundle/sdk-contracts.js +1 -1
  34. package/dist/cli-bundle/sdk-core.js +31 -31
  35. package/dist/cli-bundle/sdk-governance.js +1 -1
  36. package/dist/cli-bundle/sdk-graph.js +1 -1
  37. package/dist/cli-bundle/sdk-merge.js +18 -18
  38. package/dist/cli-bundle/sdk-query.js +1 -1
  39. package/dist/cli-bundle/sdk-runtime.js +1 -1
  40. package/dist/cli-bundle/sdk-testing.js +1 -1
  41. package/dist/cli-bundle/sdk.js +7 -6
  42. package/dist/core/extensions/manifest-schema.d.ts +20 -0
  43. package/dist/core/extensions/manifest-schema.js +28 -10
  44. package/dist/mcp/http-server.d.ts +60 -0
  45. package/dist/mcp/http-server.js +451 -0
  46. package/dist/mcp/legacy-adapter.d.ts +50 -0
  47. package/dist/mcp/legacy-adapter.js +64 -0
  48. package/dist/mcp/server.d.ts +42 -9
  49. package/dist/mcp/server.js +457 -58
  50. package/dist/sdk/agent/refusal-closure-census.d.ts +6 -2
  51. package/dist/sdk/agent/refusal-closure-census.js +16 -8
  52. package/dist/sdk/compose.d.ts +4 -1
  53. package/dist/sdk/compose.js +23 -36
  54. package/dist/sdk/extension/author-manifest.d.ts +22 -0
  55. package/dist/sdk/extension/author-manifest.js +93 -0
  56. package/dist/sdk/extension.js +6 -3
  57. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +20 -5
  58. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +6 -3
  59. package/dist/sdk/governance/health.js +7 -2
  60. package/dist/sdk/index.d.ts +6 -0
  61. package/dist/sdk/index.js +8 -2
  62. package/dist/sdk/mcp/authorization.d.ts +134 -0
  63. package/dist/sdk/mcp/authorization.js +405 -0
  64. package/dist/sdk/mcp/interactions.d.ts +118 -0
  65. package/dist/sdk/mcp/interactions.js +337 -0
  66. package/dist/sdk/mcp/protocol.d.ts +142 -0
  67. package/dist/sdk/mcp/protocol.js +174 -0
  68. package/dist/sdk/mcp/subscriptions.d.ts +65 -0
  69. package/dist/sdk/mcp/subscriptions.js +212 -0
  70. package/dist/sdk/mcp/tasks.d.ts +107 -0
  71. package/dist/sdk/mcp/tasks.js +431 -0
  72. package/dist/sdk/mcp/transport.d.ts +30 -0
  73. package/dist/sdk/mcp/transport.js +261 -0
  74. package/dist/sdk/merge/receipts.d.ts +16 -0
  75. package/dist/sdk/merge/receipts.js +9 -8
  76. package/dist/sdk/runtime-primitives.d.ts +1 -1
  77. package/dist/sdk/runtime-primitives.js +3 -3
  78. package/dist/sdk/test/execution.d.ts +6 -0
  79. package/dist/sdk/test/execution.js +32 -3
  80. package/docs/AGENT_PROVENANCE_ADR.md +6 -4
  81. package/docs/AGENT_RUNTIME_PRIMITIVES.md +6 -5
  82. package/docs/CLAUDE_CODE_PLUGIN.md +12 -5
  83. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +8 -0
  84. package/docs/EXTENSIONS.md +3 -4
  85. package/docs/MCP_2026_07_28.md +138 -0
  86. package/docs/MCP_2026_07_28_CONFORMANCE.md +30 -0
  87. package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +180 -0
  88. package/docs/README.md +4 -0
  89. package/docs/RELEASING.md +3 -2
  90. package/docs/SDK.md +22 -1
  91. package/docs/SDK_AGENT_SESSION_CONTEXT.md +18 -13
  92. package/docs/SDK_MCP_INTERACTIONS.md +227 -0
  93. package/docs/TESTING.md +4 -0
  94. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +9 -8
  95. package/marketplace.json +2 -2
  96. package/package.json +7 -5
  97. package/packages/pm-beads/package.json +1 -1
  98. package/packages/pm-calendar/package.json +1 -1
  99. package/packages/pm-command-kit/package.json +1 -1
  100. package/packages/pm-digital-twin/package.json +1 -1
  101. package/packages/pm-governance-audit/package.json +1 -1
  102. package/packages/pm-guide-shell/package.json +1 -1
  103. package/packages/pm-kanban/package.json +1 -1
  104. package/packages/pm-lifecycle-hooks/package.json +1 -1
  105. package/packages/pm-linked-test-adapters/package.json +1 -1
  106. package/packages/pm-search-advanced/package.json +1 -1
  107. package/packages/pm-templates/package.json +1 -1
  108. package/packages/pm-todos/package.json +1 -1
  109. package/packages/pm-vcs/package.json +1 -1
  110. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  111. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  112. package/scripts/finalize-build.mjs +1 -0
  113. package/sdk/public-surface.json +628 -2
  114. package/dist/cli-bundle/chunks/chunk-2F3LUFMW.js +0 -8
  115. package/dist/cli-bundle/chunks/chunk-6C7GIMIL.js +0 -13
  116. package/dist/cli-bundle/chunks/chunk-YQMYF3YD.js +0 -35
@@ -1,26 +1,26 @@
1
- import{n as qm,o as To,p as Vm,q as Wm,r as Qi,s as Ro,t as Ym,u as Zi,v as Io,y as pu,z as fu}from"./focused-chunks/chunk-2UIWOP3O.js";import{a as yu,f as bu,h as zt,m as Su,o as Eu,r as Tu,s as Au,t as Cu,x as Ru}from"./focused-chunks/chunk-IBZZZGK3.js";import{$ as Pa,$a as yf,Aa as nf,Ba as rf,Ca as of,Da as sf,Ea as af,Fa as Pn,H as ir,I as w,J as Lp,Ja as cr,K as Np,Ka as cf,Kb as If,L as Me,La as df,Lb as Nf,M as Fp,Ma as lf,Mb as Ff,N as Aa,Na as mf,O as Mp,Oa as uf,P as Ca,Pa as is,Q as os,Qa as pf,R as Ra,Ra as as,S as Wt,Sa as ff,T as Ia,U as ke,V as xa,Va as _f,W as $e,Wa as cs,X as $p,Xa as nv,Y as Dp,Ya as hf,Z as Oa,Za as gf,_ as Up,_a as La,a as ca,ab as bf,b as pp,bb as wf,cb as vf,db as kf,eb as Sf,fb as dr,gb as Na,ha as Gp,hb as Fa,i as Rp,ib as ds,j as Ip,ja as ar,jb as Ma,ka as jp,kb as Ef,la as ss,lb as $a,ma as qp,mb as ls,na as Kp,nb as Ln,oa as zp,ob as Da,pa as Bp,pb as Ua,qa as Hp,qb as Tf,ra as Vp,rb as Af,sa as Wp,sb as Cf,ta as Yp,tb as Nn,ua as Jp,ub as Ga,va as Xp,vb as Rf,wa as Qp,xa as Zp,ya as ef,yb as ms,za as tf}from"./focused-chunks/chunk-42S3GGZ7.js";import{e as Um,g as Gm,h as jm,k as Km,q as Hm}from"./focused-chunks/chunk-XUQPEKRN.js";import{b as _u,c as xo,e as hu,f as gu,g as Uw}from"./focused-chunks/chunk-YO3ZF3FI.js";import{H as aa,L as uu,a as Il,b as xl,c as Ol,d as Pl,f as Ll}from"./focused-chunks/chunk-7YCDTCBC.js";import{a as lp,b as mp,c as fs}from"./focused-chunks/chunk-H5JZEIQV.js";import{P as Pp,b as up,j as Op}from"./focused-chunks/chunk-N7W67YIG.js";import{$a as Ba,G as at,I as ja,Qa as za,Va as ur,Xa as Lf,c as wa,e as va,g as dp,k as kp,l as Sp,m as Ep,n as Tp,o as Ap,ob as pr,p as Cp,pb as Ha,q as lr,ta as rv,ua as qa,v as us,va as Ka,w as Of,wa as ps,x as mr,xa as ov,y as Pf,ya as sv}from"./focused-chunks/chunk-RAFKLNZX.js";import{a as Iu,b as xu,c as Ou}from"./focused-chunks/chunk-A644DUFQ.js";import{B as it,C as _p,D as Yo,E as xt,F as ce,G as In,H as Jo,I as Xo,L as Qo,M as Zo,Ma as On,N as hp,Na as bp,O as es,Oa as Ta,P as ts,Pa as wp,Q as xn,R as Ea,S as ns,Ta as vp,U as gp,V as yp,Va as _s,W as rr,Za as Fn,a as rp,b as jo,c as ka,d as op,e as sp,f as ip,g as ap,h as cp,i as qo,j as Ko,k as zo,l as Bo,p as It,q as Cn,r as Ho,s as Rn,t as Vo,u as oe,v as Wo,w as Ke,x as Sa,y as fp,z as ve}from"./focused-chunks/chunk-ONYQCALA.js";import{c as Mm,f as $m,g as Dm,i as Eo,j as Et,k as Jm,l as Xm,m as Qm}from"./focused-chunks/chunk-NOOZGIXP.js";import{$ as cm,A as Zr,Aa as Im,B as ql,Ba as lo,C as Kl,Ca as xm,D as zl,Da as Om,E as eo,Ea as Pm,F as Bl,Fa as mo,G as Hl,Ga as uo,H as Vl,Ha as po,I as to,Ia as fo,J as no,Ja as Xn,K as Wl,Ka as _o,L as ro,La as Lm,Ma as Qn,N as Yl,Na as ho,O as Jn,Oa as go,P as Jl,Pa as yo,Q as Xl,Qa as bo,R as Ql,Ra as Nm,S as Zl,Sa as St,T as em,Ta as wo,U as tm,Ua as vo,V as nm,Va as ko,W as rm,Wa as So,X as om,Y as sm,Z as im,Za as Fm,_ as am,aa as dm,ab as $,ba as lm,ca as mm,d as Yi,da as um,e as Nl,ea as pm,fa as oo,ga as so,h as Fl,ha as fm,i as Ji,ia as _m,j as Kt,ja as hm,ka as gm,l as Ml,la as ym,ma as bm,na as wm,oa as vm,q as Xi,qa as km,ra as Sm,s as Jr,sa as Em,t as Xr,ta as Tm,u as Qr,ua as Am,v as $l,va as Cm,w as Dl,wa as io,x as Ul,xa as ao,y as Gl,ya as co,z as jl,za as Rm}from"./focused-chunks/chunk-7I23XGWO.js";import{c as xf}from"./focused-chunks/chunk-GQR3WH3F.js";import{$a as Vu,Ba as zu,Bb as ae,Cb as ep,Db as Go,Eb as st,F as No,Fb as tp,G as Nu,Gb as ne,H as Fu,Hb as np,I as wn,Ia as qe,Ib as xe,J as er,Ja as At,Jb as xp,K as zw,Kb as or,L as Bw,La as Uo,Lb as sr,M as Hw,Ma as En,Mb as Ot,N as Vw,Na as Ht,O as Ww,Oa as Bu,P as Yw,Pa as tr,Q as Jw,R as Xw,Rb as rs,S as Qw,T as Fo,Ta as ya,U as Zw,V as ev,Va as Hu,W as tv,Wa as Vt,X as vn,Y as C,Z as S,a as Pu,aa as kn,ab as Wu,bb as Ct,c as Lu,ca as te,da as be,db as Yu,e as da,eb as Ju,f as la,fb as T,g as ma,ga as Mu,gb as Ie,h as ua,ha as Mo,hb as Xu,i as pa,ia as $u,ib as Qu,j as fa,ja as Du,jb as Rt,k as _a,ka as Uu,kb as ba,l as x,la as Gu,lb as we,m as yn,ma as ju,mb as nr,n as Bt,o as W,oa as X,p as Po,q as bn,qa as Z,ra as $o,sa as ha,sb as Tn,t as Lo,ta as Do,ua as je,ub as An,v as Ge,va as Ye,w as Gw,wa as Sn,wb as Zu,x as jw,xa as qu,xb as R,y as qw,ya as Ku,yb as U,z as Kw,za as ga,zb as V}from"./focused-chunks/chunk-VXWATRFL.js";import{$ as _l,B as Vi,C as Wn,D as ge,G as O,Ga as Wr,H as _e,Ha as Rl,I as Br,Ia as Yr,J as _n,K as Yn,L as pl,La as rt,M as E,N as fl,Na as Ao,O as tt,Oa as ot,P as ye,Pa as Tt,Q as qt,Qa as zm,S as Re,Sa as D,T as Hr,Ta as Co,Ua as We,Wa as Bm,Z as hn,ba as Wi,ca as hl,ea as gl,ga as Vr,h as vt,i as Kr,ia as yl,j as zr,ja as bl,la as wl,ma as vl,na as kl,oa as Sl,pa as El,q as L,qa as Tl,r as jt,ra as Al,s as kt,t as B,u as fe,w as fn}from"./focused-chunks/chunk-OVJL6NZE.js";import{b as Oo,h as wu,i as vu,l as gn,p as ku}from"./focused-chunks/chunk-OHIHZ7HS.js";import{A as cl,B as dl,C as ll,D as ml,E as Gi,Ea as Aw,F as ji,Fa as Cw,G as qi,Ga as Rw,H as Ki,Ha as Iw,I as zi,J as Bi,Ja as cu,L as qr,Na as du,R as Hi,Sa as ra,T as ul,W as wt,Y as d,Z as l,Za as xw,_a as Ow,aa as H,ba as nt,ca as Cl,ea as Zn,ia as Zm,ib as Pw,ja as eu,ka as tu,kb as Lw,l as Ur,la as nu,lb as Nw,m as sl,ma as ru,mb as oa,n as Gr,na as ou,nb as sa,o as Ui,oa as ea,ob as ia,pa as su,pb as lu,ra as iu,rb as mu,s as Gt,sb as Fw,t as et,u as un,ua as ta,ub as Mw,v as pn,va as au,vb as $w,w as jr,wa as na,wb as Dw,y as il,z as al}from"./focused-chunks/chunk-LMKG3DFE.js";import{AsyncLocalStorage as oM}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 Mf(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function iv(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 Va(e,t){let n=iv(t),r=n==="brief"?n:Mf(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:Mf(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 $f(e,t){let n=E(t??process.cwd(),e),r=await T(n);return ae(n,r.item_format,O(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]="10052b6f-216f-5b50-81ec-ee373cc13d17")}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 av=new Map;function Wa(){av.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 cv={"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 Df(e){return Object.fromEntries(iu.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Uf={ctx:{action:"context"},...cv,...Df("extension"),...Df("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 Ya="PmCliError";function dv(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 Gf(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,dv(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 hs(e){if(!(e instanceof Error)||e.name!==Ya)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 Ja(e){let t=gl();for(let n of e)t.register(n);return t}function jf(e,t){return{client:t,isItemNotFoundError:n=>hs(n)&&n.exitCode===d.NOT_FOUND,getItemAt:(n,r)=>dp(n,r,{pmRoot:e}),openRelationshipEventStore:n=>mp.open({pmRoot:e,nodes:n.nodes,registry:Ja(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new bl(n.nodes,n.edges,Ja(n.definitions)),analyzeRelationshipImpact:(n,r,o)=>up(n,r,o),validateRelationshipEvents:n=>{let r=new lp(n.nodes,{registry:Ja(n.definitions)});return n.events.map(o=>r.append({...o,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>pp({...n,pmRoot:e})}}import{readFile as lv}from"node:fs/promises";import mv 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]="1a7548f2-93a0-5dfc-9d9a-c5aef4656c7c")}catch{}})();var Xa="context-intents.json";function gs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function uv(e,t,n){if(!gs(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function qf(e,t){let n=Array.isArray(e)?e:gs(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,o)=>uv(r,t,o))}async function pv(e){let t=mv.join(e,Xa),n;try{n=await lv(t,"utf8")}catch(o){if(jt(o))return[];throw await Zu(e),o}let r;try{r=JSON.parse(n)}catch(o){let s=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Xa}: ${s}`,{cause:o})}return qf(r,Xa)}function fv(e){if(!gs(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return gs(n)?n.contextIntents??n.context_intents:void 0}function _v(e){return e.flatMap(t=>{let n=fv(t.module);return n===void 0?[]:qf(n,`package ${t.name}`)})}async function hv(e){let t=await pv(e.pmRoot),n=_v(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Qa(e,t){let n=await hv(e);return await vu(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]="b4b1f63b-12f9-574c-8e92-a5cc9c6178c1")}catch{}})();async function Kf(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=xt(),o=E(process.cwd(),n.path);await R(o);let s=await T(o),i=C(t.author,s.author_default),c=(await r.resolveValue(t.body,"--body",_p(t,"body"))).trim();if(c.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",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 ne({pmRoot:o,settings:s,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
1
+ import{n as Km,o as Ao,p as Wm,q as Ym,r as Zi,s as Io,t as Jm,u as ea,v as xo,y as fu,z as _u}from"./focused-chunks/chunk-MMXUPDDJ.js";import{a as bu,f as wu,h as zt,m as Eu,o as Tu,r as Au,s as Cu,t as Ru,x as Iu}from"./focused-chunks/chunk-4XNH2HM7.js";import{$ as Na,$a as bf,Aa as rf,Ba as of,Ca as sf,Da as af,Ea as cf,Fa as Pn,H as ir,I as w,J as Np,Ja as cr,K as Fp,Ka as df,Kb as xf,L as Me,La as lf,Lb as Ff,M as Mp,Ma as mf,Mb as Mf,N as Ra,Na as uf,O as $p,Oa as pf,P as Ia,Pa as as,Q as ss,Qa as ff,R as xa,Ra as cs,S as Wt,Sa as _f,T as Oa,U as ke,V as Pa,Va as hf,W as $e,Wa as ds,X as Dp,Xa as ov,Y as Up,Ya as gf,Z as La,Za as yf,_ as Gp,_a as Fa,a as da,ab as wf,b as fp,bb as vf,cb as kf,db as Sf,eb as Ef,fb as dr,gb as Ma,ha as jp,hb as $a,i as Ip,ib as ls,j as xp,ja as ar,jb as Da,ka as qp,kb as Tf,la as is,lb as Ua,ma as Kp,mb as ms,na as zp,nb as Ln,oa as Bp,ob as Ga,pa as Hp,pb as ja,qa as Vp,qb as Af,ra as Wp,rb as Cf,sa as Yp,sb as Rf,ta as Jp,tb as Nn,ua as Xp,ub as qa,va as Qp,vb as If,wa as Zp,xa as ef,ya as tf,yb as us,za as nf}from"./focused-chunks/chunk-72T6JGAE.js";import{e as Gm,g as jm,h as qm,k as zm,q as Vm}from"./focused-chunks/chunk-TMJDFHVD.js";import{b as hu,c as Oo,e as gu,f as yu,g as jw}from"./focused-chunks/chunk-YO3ZF3FI.js";import{H as ca,L as pu,a as xl,b as Ol,c as Pl,d as Ll,f as Nl}from"./focused-chunks/chunk-7YCDTCBC.js";import{a as mp,b as up,c as _s}from"./focused-chunks/chunk-IBHXMFE7.js";import{P as Lp,b as pp,j as Pp}from"./focused-chunks/chunk-LV5N3LK5.js";import{$a as Va,G as ct,I as Ka,Qa as Ha,Va as ur,Xa as Nf,c as ka,e as Sa,g as lp,k as Sp,l as Ep,m as Tp,n as Ap,o as Cp,ob as pr,p as Rp,pb as Wa,q as lr,ta as sv,ua as za,v as ps,va as Ba,w as Pf,wa as fs,x as mr,xa as iv,y as Lf,ya as av}from"./focused-chunks/chunk-FXDLT6FL.js";import{a as xu,b as Ou,c as Pu}from"./focused-chunks/chunk-A644DUFQ.js";import{B as at,C as hp,D as Jo,E as xt,F as de,G as In,H as Xo,I as Qo,L as Zo,M as es,Ma as On,N as gp,Na as wp,O as ts,Oa as Ca,P as ns,Pa as vp,Q as xn,R as Aa,S as rs,Ta as kp,U as yp,V as bp,Va as hs,W as rr,Za as Fn,a as op,b as qo,c as Ea,d as sp,e as ip,f as ap,g as cp,h as dp,i as Ko,j as zo,k as Bo,l as Ho,p as It,q as Cn,r as Vo,s as Rn,t as Wo,u as oe,v as Yo,w as Ke,x as Ta,y as _p,z as ve}from"./focused-chunks/chunk-P2E6LDAE.js";import{c as $m,f as Dm,g as Um,i as To,j as Tt,k as Xm,l as Qm,m as Zm}from"./focused-chunks/chunk-4K2II4TV.js";import{$ as dm,A as eo,Aa as xm,B as Kl,Ba as mo,C as zl,Ca as Om,D as Bl,Da as Pm,E as to,Ea as Lm,F as Hl,Fa as uo,G as Vl,Ga as po,H as Wl,Ha as fo,I as no,Ia as _o,J as ro,Ja as Xn,K as Yl,Ka as ho,L as oo,La as Nm,Ma as Qn,N as Jl,Na as go,O as Jn,Oa as yo,P as Xl,Pa as bo,Q as Ql,Qa as wo,R as Zl,Ra as Fm,S as em,Sa as Et,T as tm,Ta as vo,U as nm,Ua as ko,V as rm,Va as So,W as om,Wa as Eo,X as sm,Y as im,Z as am,Za as Mm,_ as cm,aa as lm,ab as $,ba as mm,ca as um,d as Ji,da as pm,e as Fl,ea as fm,fa as so,ga as io,h as Ml,ha as _m,i as Xi,ia as hm,j as Kt,ja as gm,ka as ym,l as $l,la as bm,ma as wm,na as vm,oa as km,q as Qi,qa as Sm,ra as Em,s as Xr,sa as Tm,t as Qr,ta as Am,u as Zr,ua as Cm,v as Dl,va as Rm,w as Ul,wa as ao,x as Gl,xa as co,y as jl,ya as lo,z as ql,za as Im}from"./focused-chunks/chunk-7I23XGWO.js";import{c as Of}from"./focused-chunks/chunk-66VGB23P.js";import{$a as Wu,Ba as Bu,Bb as ce,Cb as tp,Db as jo,Eb as it,F as Fo,Fb as np,G as Fu,Gb as ne,H as Mu,Hb as rp,I as wn,Ia as qe,Ib as xe,J as er,Ja as Ct,Jb as Op,K as Hw,Kb as or,L as Vw,La as Go,Lb as sr,M as Ww,Ma as En,Mb as Ot,N as Yw,Na as Ht,O as Jw,Oa as Hu,P as Xw,Pa as tr,Q as Qw,R as Zw,Rb as os,S as ev,T as Mo,Ta as ba,U as tv,V as nv,Va as Vu,W as rv,Wa as Vt,X as vn,Y as C,Ya as wa,Z as S,a as Lu,aa as kn,ab as Yu,bb as Je,c as Nu,ca as te,da as be,db as Ju,e as la,eb as Xu,f as ma,fb as T,g as ua,ga as $u,gb as Ie,h as pa,ha as $o,hb as Qu,i as fa,ia as Du,ib as Zu,j as _a,ja as Uu,jb as Rt,k as ha,ka as Gu,kb as va,l as x,la as ju,lb as we,m as yn,ma as qu,mb as nr,n as Bt,o as W,oa as X,p as Lo,q as bn,qa as Z,ra as Do,sa as ga,sb as Tn,t as No,ta as Uo,ua as je,ub as An,v as Ge,va as Ye,w as qw,wa as Sn,wb as ep,x as Kw,xa as Ku,xb as R,y as zw,ya as zu,yb as U,z as Bw,za as ya,zb as V}from"./focused-chunks/chunk-57XY346D.js";import{C as Wi,D as Wn,E as ye,H as O,Ha as Yr,I as he,Ia as Il,J as Hr,Ja as Jr,K as _n,L as Yn,M as fl,Ma as ot,N as E,O as _l,Oa as Co,P as nt,Pa as st,Q as ae,Qa as At,R as qt,Ra as Bm,T as Re,Ta as D,U as Vr,Ua as Ro,Va as We,Xa as Hm,_ as hn,aa as hl,ca as Yi,da as gl,fa as yl,h as kt,ha as Wr,i as zr,j as Br,ja as bl,ka as wl,ma as vl,na as kl,oa as Sl,pa as El,qa as Tl,r as P,ra as Al,s as jt,sa as Cl,t as St,u as q,v as _e,x as fn}from"./focused-chunks/chunk-UYBA57GY.js";import{b as Po,h as vu,i as ku,l as gn,p as Su}from"./focused-chunks/chunk-OHIHZ7HS.js";import{A as dl,B as ll,C as ml,D as ul,E as ji,Ea as Rw,F as qi,Fa as Iw,G as Ki,Ga as xw,H as zi,Ha as Ow,I as Bi,J as Hi,Ja as du,L as Kr,Na as lu,R as Vi,Sa as oa,T as pl,W as vt,Y as d,Z as l,Za as Pw,_a as Lw,aa as H,ba as rt,ca as Rl,ea as Zn,ia as eu,ib as Nw,ja as tu,ka as nu,kb as Fw,l as Gr,la as ru,lb as Mw,m as il,ma as ou,mb as sa,n as jr,na as su,nb as ia,o as Gi,oa as ta,ob as aa,pa as iu,pb as mu,ra as au,rb as uu,s as Gt,sb as $w,t as tt,u as un,ua as na,ub as Dw,v as pn,va as cu,vb as Uw,w as qr,wa as ra,wb as Gw,y as al,z as cl}from"./focused-chunks/chunk-LMKG3DFE.js";import{AsyncLocalStorage as iM}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 $f(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function cv(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 Ya(e,t){let n=cv(t),r=n==="brief"?n:$f(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:$f(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 Df(e,t){let n=E(t??process.cwd(),e),r=await T(n);return ce(n,r.item_format,O(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]="10052b6f-216f-5b50-81ec-ee373cc13d17")}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 dv=new Map;function Ja(){dv.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 lv={"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 Uf(e){return Object.fromEntries(au.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Gf={ctx:{action:"context"},...lv,...Uf("extension"),...Uf("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 Xa="PmCliError";function mv(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 jf(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,mv(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 gs(e){if(!(e instanceof Error)||e.name!==Xa)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 Qa(e){let t=yl();for(let n of e)t.register(n);return t}function qf(e,t){return{client:t,isItemNotFoundError:n=>gs(n)&&n.exitCode===d.NOT_FOUND,getItemAt:(n,r)=>lp(n,r,{pmRoot:e}),openRelationshipEventStore:n=>up.open({pmRoot:e,nodes:n.nodes,registry:Qa(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new wl(n.nodes,n.edges,Qa(n.definitions)),analyzeRelationshipImpact:(n,r,o)=>pp(n,r,o),validateRelationshipEvents:n=>{let r=new mp(n.nodes,{registry:Qa(n.definitions)});return n.events.map(o=>r.append({...o,expectedVersion:r.version}))},commitWorkspaceTransaction:n=>fp({...n,pmRoot:e})}}import{readFile as uv}from"node:fs/promises";import pv 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]="1a7548f2-93a0-5dfc-9d9a-c5aef4656c7c")}catch{}})();var Za="context-intents.json";function ys(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fv(e,t,n){if(!ys(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function Kf(e,t){let n=Array.isArray(e)?e:ys(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,o)=>fv(r,t,o))}async function _v(e){let t=pv.join(e,Za),n;try{n=await uv(t,"utf8")}catch(o){if(jt(o))return[];throw await ep(e),o}let r;try{r=JSON.parse(n)}catch(o){let s=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Za}: ${s}`,{cause:o})}return Kf(r,Za)}function hv(e){if(!ys(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return ys(n)?n.contextIntents??n.context_intents:void 0}function gv(e){return e.flatMap(t=>{let n=hv(t.module);return n===void 0?[]:Kf(n,`package ${t.name}`)})}async function yv(e){let t=await _v(e.pmRoot),n=gv(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function ec(e,t){let n=await yv(e);return await ku(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]="b4b1f63b-12f9-574c-8e92-a5cc9c6178c1")}catch{}})();async function zf(e,t,n){if(t.body===void 0)throw new l("Missing required --body text",d.USAGE);let r=xt(),o=E(process.cwd(),n.path);await R(o);let s=await T(o),i=C(t.author,s.author_default),c=(await r.resolveValue(t.body,"--body",hp(t,"body"))).trim();if(c.length===0)throw new l("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",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 ne({pmRoot:o,settings:s,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(u){let p=u.body.trim().length>0?`
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 gv}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]="39acab93-f9ad-5b95-871e-625d912f1322")}catch{}})();function bs(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,ve(e,t)}function zf(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 Za(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Yt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Mn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let s=oe(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function ec(e){return typeof e=="object"&&e!==null&&"code"in e}function hr(e,t){if(!it(e))throw new l(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,d.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function yv(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=xt(),o=it(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",o)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return hr(e,"--stdin"),{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);if(s==="-")return hr(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await gv(s,"utf8"),emptyFlag:"--file"}}catch(i){if(ec(i)&&jt(i))throw new l(`--file path not found: ${s}. Use --file - to read stdin.`,d.USAGE);let a=i instanceof Error?i.message:String(i);throw new l(`Failed to read --file path "${s}": ${a}. Use --file - to read stdin.`,d.USAGE)}}async function ws(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 yv(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 _r(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 Hf(e){return e==="comments"?"--stdin":"--add -"}function bv(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let o=Hf(t.collectionKey),s=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 ${o} to read stdin, or use text=${r} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${s} ${o}`,`${s} --add text=${r}`]})}function wv(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> ${Hf(e.collectionKey)}`]})}async function $n(e,t,n,r){wv(r,t);let o=E(process.cwd(),n.path);await R(o);let s=await T(o),i=O(s,x()),a=rr(t.limit);if(r.input.mode==="list"){let _=await U(o,e,s.id_prefix,s.item_format,i.type_to_folder);if(!_)throw new l(`Item ${e} not found`,d.NOT_FOUND);let g=await V(_,{schema:s.schema}),y=Yt(g.document.metadata,r.collectionKey);return ys(_.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=C(t.author,s.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,g;try{g=await ne({pmRoot:o,settings:s,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(h){let b=Yt(h.metadata,r.collectionKey),v=Bf(r.input.index,b.length,r.collectionKey);return zf(b[v],"deleted"),b.splice(v,1),h.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(h){_r(h,r.conflictGuidance)}let y=Yt(g.item,r.collectionKey);return ys(g.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??"";bv(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,g;try{g=await ne({pmRoot:o,settings:s,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(h){let b=Yt(h.metadata,r.collectionKey),v=Bf(r.input.index,b.length,r.collectionKey),k=b[v];return zf(k,"edited"),b[v]={...k,text:u,edited_at:S()},h.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(h){_r(h,r.conflictGuidance)}let y=Yt(g.item,r.collectionKey);return ys(g.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 ne({pmRoot:o,settings:s,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(_){let g=Yt(_.metadata,r.collectionKey),y={created_at:S(),author:c,text:u};return g.push(r.createEntry(y)),_.metadata[r.collectionKey]=g,{changedFields:[r.collectionKey]}}})}catch(_){_r(_,r.conflictGuidance)}let f=Yt(p.item,r.collectionKey);return ys(p.item.id,r.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:f.length,entry:f.at(-1)},t.fullHistory===!0)}function Bf(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,s=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${o} index ${e??"(missing)"} out of range (item has ${s})`,d.USAGE)}return e-1}function ys(e,t,n,r,o,s,i=!1){let a=s===void 0||i?Za(n,s!==void 0&&i?void 0:r):s.entry===void 0?[]:[s.entry],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...[o,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...s===void 0?{}:{mutation_receipt:{action:s.action,entry_index:s.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 Vf(e,t,n){return[...await Sn(Re(e,t),t).catch(()=>[])].reverse().find(s=>s.patch.some(i=>i.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a61bf25-e320-5adc-8f5a-a427bc89af1a")}catch{}})();var Wf="no_available_next_item";function Yf(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function vs(e,t,n,r={}){let o=E(process.cwd(),n.path);await R(o);let s=await T(o),i=D(s.schema),a=C(r.author,s.author_default),c=vn(a),m=null,u=!1,p=[],f=await ne({pmRoot:o,settings:s,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",h=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,Bm(_.metadata.status,i)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&h!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let v=await Vf(o,_.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 qa({pmRoot:o,settings:s,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 Jf(e,t,n={},r={}){let o=vv(n.maxAttempts),s=await T(E(process.cwd(),t.path)),i={...n,author:C(n.author,s.author_default)},a=await ur({...r,callerAuthor:i.author,limit:String(o)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return kv(c.slice(0,o),e,t,i)}function vv(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 kv(e,t,n,r={},o=vs){let s=0;for(let a of e){s+=1;try{let c=await o(a.id,t,n,r),m={...c,recommendation:a,attempts:s,available:!0};if(!c.skipped)return m}catch(c){if(!Yf(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:C(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[Wf]};let i=s===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:Wf,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 ks(e,t,n,r={}){let o=E(process.cwd(),n.path);await R(o);let s=await T(o),i=C(r.author,s.author_default),a=vn(i),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await ne({pmRoot:o,settings:s,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){_r(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:o,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 Sv=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function Xf(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 tc(e,t){return nc(e,t,{operation:"close"})}function nc(e,t,n){let r=Xf(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",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:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function rc(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],s=o.filter(m=>m.kind==="blocked_by"),i=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),i&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let m=o.filter(u=>u.kind!=="blocked_by");m.length>0?e.dependencies=m:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...s.map(m=>m.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[t.orderingEdges==="preserve"?`closed_preserved_predecessors:${e.id}:${c.join(",")}`:`closed_removed_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="781b5118-7b07-53c7-802f-c889cb797a96")}catch{}})();var Ev=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function Tv(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 Av(e){let t=[];for(let n of Ev){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function Cv(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let s=o.trim();if(s===n)return!0;if(r.has(s))return!1;r.add(s),o=(await e(s))?.duplicate_of}return!1}function Rv(e){return typeof e!="string"||e.trim().length===0}async function Iv(e,t,n,r){let o=n?.trim();if(!o)return;if(o===r)throw new l("An item cannot be closed as a duplicate of itself.",d.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=O(t,x()),i=new Map,a=async m=>{if(i.has(m))return i.get(m)??null;let u=await U(e,m,t.id_prefix,t.item_format,s.type_to_folder);if(!u)return i.set(m,null),null;let{document:p}=await V(u,{schema:t.schema});return i.set(m,p.metadata),p.metadata},c=await a(o);if(!c)throw new l(`Duplicate target "${o}" was not found. Create or locate the canonical item first.`,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 ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await Cv(a,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${o}" 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 "${o}" 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 xv(e,t,n){return e.filter(r=>r.parent===t&&!Z(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function Ov(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),o=xf(e),s=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:o.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let m=r.get(c);return m!==void 0&&Z(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function Pv(e,t,n,r,o,s){let i=Ov(n,r,s),a=[];for(let c of i)try{let m=await ne({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(g=>{let y=g.id.trim().toLowerCase();return g.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=s.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let u=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${u}`)}return a}function Lv(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:s}of r){if(typeof o!="string")continue;let i=o.trim();i.length!==0&&(e[s]=i,n.push(s))}return n}function Nv(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:s}of r)Rv(e[o])&&(e[o]=s,n.push(o));return n}function Fv(e,t,n,r){let o=[];if(t!=="off"){let s=Av(e);if(s.length>0){let i=s.map(a=>a.label);if(t==="strict"){let a=s.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(m=>[m,"<value>"])];throw new 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:Oo(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}o.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new 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);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function Mv(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function $v(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function Dv(e,t){if(Z(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use --force to close again.`,d.CONFLICT);let n=Lv(e,t.options),r=Nv(e,t.duplicateOf),o=Fv(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let i=["status","closed_at",...s?["completed_at"]:[],...Mv(e,t.closeReason),...n];if(wp(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(...$v(e));let a=rc(e,t.lifecyclePolicy);return i.push(...a.changedFields),o.push(...a.warnings),{changedFields:i,...o.length>0?{warnings:o}:{}}}async function Qf(e,t,n,r){let o=E(process.cwd(),r.path);await R(o);let s=await T(o),i=D(s.schema),a=C(n.author,s.author_default),c=O(s,x()).type_to_folder,m=await U(o,e,s.id_prefix,s.item_format,c);if(!m)throw await st(o,e,s.id_prefix,c);let u=await Iv(o,s,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=tc({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=Tv(n.validateClose)??s.governance.close_validation_default,g=await ae(o,s.item_format,c,void 0,s.schema),y=xv(g,m.id,i),h=new Date().toISOString(),b=n.completedAt===void 0?h:te(n.completedAt,new Date(h),"completed-at"),v=await ne({pmRoot:o,settings:s,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(k){return Dv(k.metadata,{pmRoot:o,statusRegistry:i,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:h,completedAt:b,lifecyclePolicy:p})}});return{item:v.item,changed_fields:v.changedFields,warnings:[...v.warnings,...await Pv(o,s,g,m.id,a,i)]}}function ct(e,t,n,r){return Qf(e,t,n,r)}import Uv from"fast-json-patch";import oc 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]="db5f3a6d-9ae5-5f9b-bedf-766b2b79324c")}catch{}})();function Gv(e,t){return rp(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function jv(e){let t=ka(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Ye(Ht(t))}async function qv(e,t,n,r){let o=await U(e,t,n.id_prefix,n.item_format,r);if(o){let c=Re(e,o.id),m=await Xu({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"});return{id:o.id,historyPath:c,located:o,historyPolicyWarnings:m.warnings}}let s=we(t,n.id_prefix),i=ba(t),a=s===i?[s]:[s,i];for(let c of a){let m=Re(e,c);if(await L(m))return{id:c,historyPath:m,located:null,historyPolicyWarnings:[]}}throw new l(`Item ${t} not found`,d.NOT_FOUND)}function Kv(e,t){let n=tr(e),r=tr(t),o=Uv.compare(n,r),s=new Set;for(let i of o){if(i.path==="/body"||i.path.startsWith("/body/")){s.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];s.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(s).sort((i,a)=>i.localeCompare(a))}async function zv(e){if(await B(e.subject.historyPath)!==e.historyRawBeforeLock)throw new l(`History for ${e.resolvedId} changed while waiting for lock; retry restore.`,d.CONFLICT);let n=await U(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),r=n?await V(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 Bv(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:jv(t),originalRaw:null}}function Hv(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 Vv(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await fe(e.existingItemPath,e.resolvedOriginalRaw),await oc.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await fe(e.existingItemPath,e.resolvedOriginalRaw);return}await oc.rm(e.restoredItemPath,{force:!0})}async function Wv(e){return[...await W({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await W({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function Jt(e,t,n,r){let o=E(process.cwd(),r.path);await R(o);let s=await T(o),i=O(s,x()),a=await qv(o,e,s,i.type_to_folder),c=a.id,m=await B(a.historyPath),u=await Sn(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let p=Gv(t,u),f=op(ka(u,p.historyIndex),p),_=Bu(f,{schema:s.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 V(a.located,{schema:s.schema}):null)?.raw??null,h=C(n.author,s.author_default),b=await be(o,c,s.locks.ttl_seconds,h,!!n.force,s.governance.force_required_for_stale_lock,s.locks.wait_ms);try{let{loadedItemUnderLock:v,existingItemPath:k}=await zv({pmRoot:o,resolvedId:c,subject:a,settings:s,typeToFolder:i.type_to_folder,historyRawBeforeLock:m,currentItemRawBeforeLock:y}),I="toon",A=Bv(v,u),N=Hv({document:A.document,author:h,force:n.force,enforcement:s.governance.ownership_enforcement,resolvedId:c}),M=Kv(A.document,_);await Po({pm_root:o,operation:"restore",before:A.document,after:_,changed_fields:M,sdk:Go({pmRoot:o,settings:s,typeToFolder:i.type_to_folder})});let pe=je(_,{format:I,schema:s.schema}),ee=qt(o,_.metadata.type,c,I,i.type_to_folder),he=await Tn(o,h),le=[];try{await fe(ee,pe),k&&ee!==k&&await oc.rm(k);let _t=qe({nowIso:S(),author:h,op:"restore",before:A.document,after:_,message:n.message});try{await At(a.historyPath,_t)}catch(ht){throw await Vv({existingItemPath:k,resolvedOriginalRaw:A.originalRaw,restoredItemPath:ee}),ht}le=await An({pmRoot:o,preferredFormat:s.item_format,typeToFolder:i.type_to_folder,schema:s.schema,itemPath:ee,previousItemPath:k??void 0,document:_})}finally{await he()}let Ue=await Wv({restoredItemPath:ee,historyPath:a.historyPath,before:A.document,after:_});yn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:A.document.metadata.status,status:_.metadata.status,previous:Bt(A.document.metadata,M),current:Bt(_.metadata,M),changed_fields:M});let ft=u[p.historyIndex];return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,entry_ts:ft.ts,entry_op:ft.op},changed_fields:M,warnings:[...a.historyPolicyWarnings,...N,...le,...Ue]}}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]="a97a3cf0-beef-5967-8f5b-2372a6c9f2f7")}catch{}})();var e_=1,sc="close-many",Yv=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function Jv(e,t){return lr(e,t,{includePagination:!1})}function Xv(e,t){return lr(e,t)}function Qv(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 Zv(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function ek(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 tk(e,t){let n=D(t.schema),r=O(t,x()),o=await ae(e,t.item_format,r.type_to_folder,void 0,t.schema),s=new Map,i=new Map;for(let a of o){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),Z(a.status,n)))continue;let c=s.get(a.parent);c?c.push(a.id):s.set(a.parent,[a.id])}for(let a of s.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:s,parentByChild:i}}function Zf(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,s=t.get(e),i=[],a=new Set,c=!1;for(;s!==void 0&&!a.has(s);){let m=n?.get(s);if(m!==void 0){o+=m+1;break}a.add(s),i.push(s),o+=1,s=t.get(s)}if(s!==void 0&&a.has(s)&&(c=!0),!c){n?.set(e,o);for(let[m,u]of i.entries())n?.set(u,o-m-1)}return o}async function nk(e){let t=await zo(e.pmRoot,sc,e.rollbackId,e_),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Bo(t.items,(o,s)=>Jt(o,s,{author:e.options.author,message:n,force:!0},e.global));return{...zt({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 rk(e,t,n,r,o){return e.map(s=>{let i=(t.get(s.id)??[]).filter(c=>!n.has(c)),a=!t_(s,r,o);return{id:s.id,title:typeof s.title=="string"?s.title:"",status:s.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function ok(e){let t=await Ko(e.pmRoot,sc,e.checkpointId,{schema_version:e_,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function sk(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await ct(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){t.push({id:r.id,status:"failed",error:hn(o)})}}return{rows:t,closedIds:n}}function ik(e){return typeof e.rollback=="string"?e.rollback:void 0}function ak(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(Xv(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function ck(e){if(!Jv(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${Yv}). Refusing to match every item.`,d.USAGE)}function dk(e,t){let n=new Map;return[...e].sort((r,o)=>{let s=Zf(o.id,t,n)-Zf(r.id,t,n);return s!==0?s:r.id.localeCompare(o.id)})}function t_(e,t,n){return n||!Z(e.status,t)}function lk(e,t,n){return new Set(e.filter(r=>t_(r,t,n)).map(r=>r.id))}async function mk(e){ck(e.options);let t=D(e.settings.schema),n=ek(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await at(e.options.status,Zv(e.options.list),e.global),{childrenByParent:s,parentByChild:i}=await tk(e.pmRoot,e.settings),a=dk(o.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],m=c.length===0?[]:(await at(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,u=new Set(m.map(f=>f.id)),p=lk(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!u.has(f)),planRows:rk(a,s,p,t,r)}}function uk(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!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function pk(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 ok({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 n_(e,t){let n=E(process.cwd(),t.path);await R(n);let r=await T(n),o=e.dryRun===!0,s=ik(e);if(Qv(e.list),s!==void 0)return ak(e,s),nk({pmRoot:n,rollbackId:s,options:e,global:t});let i=await mk({pmRoot:n,settings:r,options:e,global:t});if(o)return uk(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=S(),m=qo(sc,c),u=await pk({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 sk({matched:i.matched,closableIds:a,reason:i.reason,closeOptions:p,global:t}),g=f.filter(b=>b.status==="closed").length,y=f.filter(b=>b.status==="skipped").length,h=f.filter(b=>b.status==="failed").length;return{...zt({applied:g,skipped:y,failed:h,unmatched:i.unmatchedIds?.length??0}),mode:"apply",matched_count:i.matched.length,dry_run:!1,...i.reason!==void 0?{reason:i.reason}:{},filters:i.listed.filters,...i.validateCloseMode?{validate_close:i.validateCloseMode}:{},...u?{checkpoint:u}:{},closed_count:g,skipped_count:y,failed_count:h,rows:f,ids:_,...i.unmatchedIds!==void 0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}import{readFile as fk}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]="5167b367-26cf-52d5-8040-bb001ce3592a")}catch{}})();async function ic(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",s=Number(n)+Number(r)+Number(o);if(s===0)return;if(s>1)throw new 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",it(e))??"",emptyFlag:"--add"};if(r)return hr(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);if(i==="-")return hr(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await fk(i,"utf8"),emptyFlag:"--file"}}catch(a){if(ec(a)&&jt(a))throw new l(`--file path not found: ${i}. Use --file - to read stdin.`,d.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${i}": ${c}. Use --file - to read stdin.`,d.USAGE)}}async function _k(e,t){let n=e.edit,r=e.delete,o=n!==void 0,s=r!==void 0;if(o&&s)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(s){if(await ic(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(o){let c=await ic(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 ic(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 r_(e,t,n){let r=xt(),o=await _k(t,r),s=o.mode==="add"||o.mode==="edit",i=o.value??"";return $n(e,t,n,{input:{...o,rawValue:t.add??i,value:s?Mn(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm comments pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="93184f29-f215-5413-9628-fb5b34523995")}catch{}})();async function o_(e,t,n){return $n(e,t,n,{input:await ws(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Mn(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 hk(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 gk(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 yk(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 s_(e,t,n){let r=hk(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let s=r===void 0?void 0:H(r),i=[t.since,t.eventType].some(g=>g!==void 0),a=yk(t.since),c=rr(t.limit),m=await $n(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await ws(s===void 0?t:{add:s},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:g=>Mn(g),createEntry:g=>r===void 0?g:{...g,format:"json",data:r,event_type:gk(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm notes pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}}),u=t.eventType?.trim(),p=m.notes.filter(g=>{let y=[g.format==="json",g.data!==void 0].every(Boolean),h=[a===void 0,Date.parse(g.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),b=[!u,g.event_type===u].includes(!0);return[!i,[y,h,b].every(Boolean)].includes(!0)}),f=i?Za(p,c):p,_=f.filter(g=>g.format==="json").length;return{...m,notes:f,count:f.length,...i?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d6f359cb-2bc9-5f96-8789-db91512d0bd5")}catch{}})();function gr(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function yr(e,t,n=Ot()){for(let r of t??[])try{yl(e,r.id,r.kind,n)}catch(o){throw new l(hn(o),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function i_(e,t){return(await V(e,{schema:t})).document.metadata.created_at}async function bk(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await U(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:i_(n,t.schema)}function wk(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 vk(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:s})=>s===null?[]:[[o,s]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await i_(n.get(o),e.context.schema)])));for(let o of e.holders){let s=await bk(o,e.context);if(s!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(s),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw wk({holder:o,dependency:i,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function Xt(e){let t=e.registry??Ot(),n=(e.dependencies??[]).filter(i=>!xp(i.source_kind)),r=[...new Set(n.map(i=>i.id))],o=await Promise.all(r.map(async i=>({target:i,located:await U(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=o.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${s.length===1?"":"s"} not found: ${s.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:s,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${s.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await vk({dependencies:n,missingTargets:s,resolutions:o,holders:e.holders??[],registry:t,context:e}),s.map(i=>`dependency_target_unresolved:${i}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcbb6070-7457-5454-abf1-fa8153c8efd6")}catch{}})();function Ss(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Es(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ts(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(jr.includes(t))return t;let n=ce(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 As(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 kk=new Set(["none","null"]);function Cs(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function ze(e){return e===void 0?!1:kk.has(e.trim().toLowerCase())}function Rs(e,t,n){if(!ze(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Se(e,t,n){if(!e||e.length===0||!e.some(s=>ze(s)))return;let o=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${o}`.trim(),d.USAGE)}function Is(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 o=r;if(!o.some(a=>ze(a)))continue;if(o.filter(a=>!ze(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2fcfbe50-039b-5031-8b18-a208908a0d87")}catch{}})();function c_(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 ac(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Ee(e,t,n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE);return e}var d_=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Sk(e,t){return t==="defined"?e!==void 0:!!e}function a_(e,t,n){if(!Sk(e,n))return;let r=ce(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function Ek(e,t,n){let r=e?te(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 Tk(e){return Array.from(new Set(ac(e).map(t=>Ee(t.toLowerCase(),ml,"event weekday")))).sort((t,n)=>Gi(t)-Gi(n))}function Ak(e){return Array.from(new Set(ac(e).map(t=>{let n=ce(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 Ck(e,t){return Array.from(new Set(ac(e).map(n=>te(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function l_(e,t,n,r){let o=e.recur_freq?.trim(),s=e.recur_interval?.trim(),i=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![o,s,i,a,c,m,u].some(k=>k!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let f=Ee(o.toLowerCase(),ll,"event recurrence frequency"),_=a_(s,"recur_interval",r),g=a_(i,"recur_count",r),y=Ek(a,t,n),h=Tk(c),b=Ak(m),v=Ck(u,n);return{freq:f,interval:_,count:g,until:y,by_weekday:h.length>0?h: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 m_="--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.",Rk="--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).",Ik=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,xk=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,p_=1e3,cc=60*p_,Ok=60*cc;function u_(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 Pk(e,t){let n=new Date(e),r=t.trim(),o=Ik.exec(r);if(o){let a=o[1]==="-"?-1:1,c=Number.parseInt(o[2],10)*a;return u_(n.getTime()+c*cc,r)}let s=xk.exec(r);if(s){let[,a,c,m,u]=s;if(c||m||u){let f=a==="-"?-1:1,_=Number.parseInt(c??"0",10),g=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),h=_*Ok+g*cc+y*p_;return u_(n.getTime()+f*h,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return te(i,n,"event.duration")}function f_(e,t,n,r){if(t&&n)throw new l(Rk,d.USAGE);if(n){let s=Pk(e,n);if(s<e)throw new l(m_,d.USAGE);return s===e?void 0:s}if(!t)return;let o=te(t,r,"event.end");if(o<e)throw new l(m_,d.USAGE);if(o!==e)return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var Lk=["at","date","text","title"],Nk=["start","date","end","duration","title","description","location","timezone","all_day",...d_],Fk=["key","value"];function __(e,t){return t==="trimmed"?e?.trim():e}function Mk(e,t){return t==="defined"?e!==void 0:!!e}function xs(e,t,n){return e.map(r=>{let o=oe(r,"--reminder");Ke(o,"--reminder",Lk);let s=__(o.at??o.date,n.valueMode),i=__(o.text??o.title,n.valueMode);if(!s||!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:te(s,t,"reminder.at"),text:a}})}function Os(e,t,n){return e.map(r=>{let o=oe(r,"--event");Ke(o,"--event",Nk);let s=(o.start??o.date)?.trim();if(!s)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let i=te(s,t,"event.start"),a=o.end?.trim(),c=o.duration?.trim(),m=f_(i,a,c,t),u=o.title,p=o.description,f=o.location,_=o.timezone,g=u?.trim(),y=p?.trim(),h=f?.trim(),b=_?.trim(),v=[["title",u,g],["description",p,y],["location",f,h],["timezone",_,b]];for(let[N,M,pe]of v)if(M!==void 0&&!pe)throw new l(`--event ${N} must not be empty`,d.USAGE);let k=o.all_day?.trim(),I=l_(o,i,t,n.recurrenceEmptyNumericGuard),A=Mk(k,n.allDayEmptyGuard)?c_(k,"--event all_day"):void 0;return{start_at:i,end_at:m,title:g,description:y,location:h,all_day:A,timezone:b,recurrence:I}})}function Ps(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 o,s;if(r.includes(",")||r.includes(`
5
- `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=oe(r,"--type-option");Ke(a,"--type-option",Fk),o=a.key?.trim(),s=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),m=a;if(a<=0&&c>0&&(m=c),m<=0||m===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);o=r.slice(0,m).trim(),s=r.slice(m+1).trim()}if(!o||!s)throw new l("--type-option requires key and value",d.USAGE);t[o]=s}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39a36d42-29b1-5f0f-a8b2-f3bfc0ef78c2")}catch{}})();var $k="hierarchy-integrity";async function Ls(e){let t=e.required?await be(e.pmRoot,$k,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var Dk=new Set(["event","meeting","reminder","milestone","decision","adr"]);function h_(e,t,n,r){if(Dk.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=Co("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm start-task ${e}`,to_status:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="44e6a87d-0ca5-53af-b199-b66bb2b98fb5")}catch{}})();var Qt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],Uk=new Set(Qt),Gk=Qt.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),jk=new RegExp(`^(?:[-*+]\\s+)?(?:${Gk})\\s*[:=]`,"i");function Ns(e){return e.startsWith("```")||e.includes(`
6
- `)?!0:jk.test(e)}function Fs(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!Uk.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw new l(`${t} provides key "${o}" more than once after case normalization`,d.USAGE);n[i]=s}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${Qt.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:o,...s}=n;return{...s,command:s.command??o}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64adcc3c-3646-5990-9442-4c4374a2dc7d")}catch{}})();var tn=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",ar,jp,"FORCE_COLOR"]),Ds=/^[A-Za-z_][A-Za-z0-9_]*$/,en=["schema","tracker","auto"],g_=["source","isolated","snapshot"];function br(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=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=o.slice(0,s).trim(),a=o.slice(s+1);if(!Ds.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(tn.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 wr(e,t){if(!e)return;let n=On(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(!Ds.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(tn.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function Us(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 Gs(e,t){if(!e)return;let n=e.trim().toLowerCase();if(en.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${en.join(", ")}`,d.USAGE)}function nn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(g_.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${g_.join(", ")}`,d.USAGE)}function rn(e){if(!e)return;let t=On(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Dn(e,t,n){let r=rn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(s){throw new l(`${t} ${n} includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`,d.USAGE)}return r}}function js(e,t){if(!e)return;let n=ce(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 qs(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+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 Ks(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+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 qk=new Set(Qt);function zs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kk(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!qk.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw t(`provides key "${o}" more than once after case normalization`);n[i]=s}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${Qt.join(", ")}.`);return n}function Zt(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 Ms(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=o.filter(i=>i.length>0);return s.length>0?s:void 0}function y_(e,t,n){let r=Ms(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`)}return r}}function $s(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 zk(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:$s(n,"timeout_seconds",t),s=r===void 0?void 0:$s(r,"timeout",t);if(o!==void 0&&s!==void 0&&o!==s)throw t("timeout and timeout_seconds must match when both are provided");let i=o??s;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function Bk(e,t){let n=Zt(e,"scope",t);if(n===void 0)return"project";if(!et.includes(n))throw t(`field "scope" must be one of: ${et.join(", ")}`);return n}function Hk(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!zs(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Ds.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(tn.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=s}return Object.keys(r).length>0?r:void 0}function Vk(e,t){let n=Ms(e,"env_clear",t);if(n){for(let r of n){if(!Ds.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(tn.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function Wk(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 Yk(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=$s(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 Jk(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!zs(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(s)}return Object.keys(r).length>0?r:void 0}function Xk(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!zs(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=$s(s,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function Qk(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!zs(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Qt.join(", ")}.`);let o=Kk(e,r),s=Zt(o,"command",r),i=Zt(o,"cmd",r);if(s!==void 0&&i!==void 0&&s!==i)throw r("command and cmd must match when both are provided");let a=s??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=Zt(o,"path",r),m=Zt(o,"pm_context_mode",r);if(m!==void 0&&!en.includes(m))throw r(`field "pm_context_mode" must be one of: ${en.join(", ")}`);let u=nn(Zt(o,"workspace_context_mode",r),`${n} ${t}`),p=Zt(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:Bk(o,r),timeout_seconds:zk(o,r),pm_context_mode:m,workspace_context_mode:u,env_set:Hk(o,r),env_clear:Vk(o,r),shared_host_safe:Wk(o,"shared_host_safe",r),assert_stdout_contains:Ms(o,"assert_stdout_contains",r),assert_stdout_regex:y_(o,"assert_stdout_regex",r),assert_stderr_contains:Ms(o,"assert_stderr_contains",r),assert_stderr_regex:y_(o,"assert_stderr_regex",r),assert_stdout_min_lines:Yk(o,r),assert_json_field_equals:Jk(o,r),assert_json_field_gte:Xk(o,r),note:p!==void 0&&p.trim().length>0?p.trim():void 0}}function b_(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(s){throw new l(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return o.map((s,i)=>Qk(s,o.length>1?`entry ${i+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0062e981-158a-5e6a-b028-6c7cef0f59ba")}catch{}})();var dc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],lc=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],w_=[...dc,...lc],Bs=[{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 Hs(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let o=r.trim().toLowerCase();if(!o)throw new l("--unset values must not be empty",d.USAGE);if(ze(o))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let s=e.resolveDefinition(o);if(!s)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function Vs(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let s of o){if(s.allow_unset===!1)continue;let i=new Set;if(typeof s.key=="string"&&s.key.length>0&&i.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&i.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(i.add(s.cli_flag.replaceAll("-","_").toLowerCase()),i.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let a of s.cli_aliases)typeof a!="string"||a.length===0||(i.add(a.replaceAll("-","_").toLowerCase()),i.add(a.toLowerCase()));if(i.has(r))return{optionKey:s.key,metadataKey:s.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="002f45a2-edc3-5aa0-9af8-d9b1dfecc097")}catch{}})();var Zk={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 eS(e){return Zk[e]}function mc(e){return eS(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]="02c41ea1-8d4e-5239-b95a-a07210b63d7f")}catch{}})();var tS=["strict","progressive"],nS=["lightweight"],E_=new Set(["Reminder","Meeting","Event"]),rS=new Set(["author","created_at","text"]),pc=[...w_,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...Bs],oS=(()=>{let e=new Map;for(let t of pc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Ws=new Map(pc.map(e=>[e.optionKey,e.canonical])),sS=pc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function iS(e,t){let n=X(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function aS(e,t){let n=e.default_status;if(n!==void 0){let r=X(n,t);if(r)return r}return t.open_status}function uc(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 cS=Cs();function T_(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s};ze(t.template)&&(t.template=void 0);let r=new Set([...Ws.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!ze(s))continue;let i=o==="rank"?"order":Ws.get(o)??o;n(i),t[o]=void 0}return ve(e,Is(t,cS))}function me(e){if(e!==void 0)return e}function dS(e,t){return Hs({raw:e,supportedFields:sS,resolveDefinition:n=>oS.get(n)??Vs(n,"create",t)})}var v_=["id","kind","type","author","created_at","source_kind"],Ys=["path","scope","note"];function lS(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let i=s.trim(),a=fc(i,v_);gr(i,a);let c=a?oe(s,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",v_);let m=me(c.id),u=mS(me(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=or(me(c.source_kind)),f=me(c.author);return{id:sr(m,n,p),kind:Ee(u,Gt,"dependency kind"),created_at:uc(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function mS(e){return typeof e=="string"?Vr(e)??e.trim():e}function fc(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:Wo(e)}function sn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Se(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(i=>{let a=i.trim(),c=()=>{if(a.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:a}},m;try{m=oe(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!rS.has(f)).length>0)return{created_at:uc(m.created_at,n),author:me(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:uc(m.created_at,n),author:me(m.author)??r,text:p}}),explicitEmpty:!1})}function _c(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),o=fc(r,Ys),s=o?oe(n,"--file"):{path:r};if(o&&Ke(s,"--file",Ys),!s.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:s.path,scope:Ee(s.scope??"project",et,"file scope"),note:me(s.note)}}),explicitEmpty:!1})}function hc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),o=Ns(r)?Fs(oe(n,"--test"),"--test"):{command:r},s=me(o.command),i=me(o.path);if(!s)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let a=me(o.timeout_seconds),c=me(o.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:s,path:i,scope:Ee(o.scope??"project",et,"test scope"),timeout_seconds:m?ce(m,"timeout_seconds"):void 0,pm_context_mode:Gs(o.pm_context_mode,"--test"),workspace_context_mode:nn(o.workspace_context_mode,"--test"),env_set:br(o.env_set,"--test"),env_clear:wr(o.env_clear,"--test"),shared_host_safe:Us(o.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:rn(o.assert_stdout_contains),assert_stdout_regex:Dn(o.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:rn(o.assert_stderr_contains),assert_stderr_regex:Dn(o.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:js(o.assert_stdout_min_lines,"--test"),assert_json_field_equals:qs(o.assert_json_field_equals,"--test"),assert_json_field_gte:Ks(o.assert_json_field_gte,"--test"),note:me(o.note)}}),explicitEmpty:!1})}function gc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),o=fc(r,Ys),s=o?oe(n,"--doc"):{path:r};if(o&&Ke(s,"--doc",Ys),!s.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:s.path,scope:Ee(s.scope??"project",et,"doc scope"),note:me(s.note)}}),explicitEmpty:!1})}function uS(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--reminder","Use --clear-reminders to clear reminders."),{values:xs(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function pS(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--event","Use --clear-events to clear linked events."),{values:Os(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function fS(e,t,n,r=[]){let o=[...qr.filter(s=>e[s]!==void 0),...r.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(o))}function _S(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function k_(e,t,n){let r=Wn("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function hS(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 A_(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 gS(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(k_(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(k_(r,e.name,"required_create_repeatables"));return n}function yS(e,t,n,r){for(let o of e)if(!(!A_(t,o)&&!n.has(o)))throw new l(`Option ${ge("create",o)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function bS(e,t,n){if(t!=="strict")return;let r=e.filter(s=>n.has(s)&&!mc(s));if(r.length===0)return;let o=[...new Set(r.map(s=>ge("create",s)))].sort((s,i)=>s.localeCompare(i));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function wS(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Ps(e),explicitEmpty:!1})}async function vS(e){return await Yo(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function kS(e){return it(e)?await vS(e):e}function SS(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: ${tS.join(", ")}`,d.USAGE)}function ES(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: ${nS.join(", ")}`,d.USAGE)}function TS(e,t,n){let r=SS(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 AS(e,t,n,r){let o=e.name,s=hS(t),i=gS(e,n),a=_n(e,"create",i);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);yS(a.disabled,s,r,o),bS(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&mc(u)?!0:A_(s,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>ge("create",u)))].sort((u,p)=>u.localeCompare(p))}var C_=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function CS(e,t){let n=[];for(let r of e){let o=r.match(C_);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function RS(e,t){return e.filter(n=>{let r=n.match(C_);return!r||r[2]!==t})}function IS(e,t,n,r){let o=RS(e,t);if(o.length===0)return;let s=R_(n,[],[],r.open_status);throw new l(o.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function xS(e,t){let r=e.options.find(o=>o.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function OS(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 R_(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],i=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of i)a.has(c)||(o.push(...OS(c,e.name,r)),a.add(c));for(let c of n){let m=xS(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function yc(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 PS(e){return xn(e)}function LS(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=Array.isArray(o)?[...o]:o;for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=Array.isArray(o)?[...o]:o);return n}function NS(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function FS(){let e=x();return e?e.commands.some(t=>t.action==="templates-show"||NS(t.command)==="templates show"):!1}function MS(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[o,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[o]=s;continue}if(Array.isArray(s)&&s.every(i=>typeof i=="string")){r[o]=[...s];continue}throw new l(`Templates package returned unsupported option value for "${o}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function $S(e,t,n){if(!FS())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await Lo({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let o=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${o}`,d.USAGE)}return MS(r.result,e)}function DS(e){return R(e)}function q(e,t,n){return e.has(t)||n===void 0?void 0:me(n)}function on(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var US=new Set(["milestone","meeting","reminder","event"]);function I_(e,t,n,r){let o=t!==void 0,s=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return US.has(e.toLowerCase())&&!o&&!s&&!i}function GS(e,t,n,r,o){let s=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),I_(e,n,r,o)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function jS(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await No(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function qS(e,t,n,r,o,s){let i=Zo(o);if(ts(r,i,t.id_prefix),await U(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let c=we(i,t.id_prefix);return{parent:i,warnings:es(c,s).warnings}}async function KS(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await qS(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function zS(e){if(e.explicitId===void 0)return nr(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||hp(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=we(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 S_(e,t,n,r,o){let s=q(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let i=ns(r,s,o);return{value:i.value,warnings:i.warnings}}async function BS(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:s,status:i,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(s===void 0)return{dependencyValues:u,status:i};let p=we(s,n.id_prefix),f=await U(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:i};if((u??[]).some(y=>y.id===f.id&&y.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:i};let g=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((y,h)=>y.localeCompare(h))[0]??o.open_status;return{dependencyValues:u,status:g}}function HS(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let o=t.governance.create_default_type?.trim();if(o&&o.length>0&&_e(o,n)){e.type=o;return}_e("Task",n)&&(e.type="Task")}function VS(e,t){return e.options.filter(n=>Wn("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 WS(e,t,n,r,o){let s=e,i=[];if(s.template!==void 0){let g=s.template.trim();if(g.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let y=await $S(g,t,n);s=T_(LS(y,s))}if(s.type===void 0&&HS(s,r,o),s.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let a=_e(s.type,o);if(!a){let g=yp(s.type),y=g?_e(g,o):void 0;if(y)i.push(`type_coercion:${s.type.trim()}:${y}`),s.type=y,a=y;else throw new l(Et(s.type,o.types,Tt(n,r.schema)),d.USAGE)}let c=Br(a,o);if(!c)throw new l(`Invalid type value "${s.type}"`,d.USAGE);let m=c.name,u=VS(c,s),p=u.map(g=>`${g.key}=${String(s[g.key])}`);if(p.length>0){s.typeOption=[...p,...s.typeOption??[]];for(let g of u)delete s[g.key]}let f=ES(s.schedulePreset);if(f!==void 0&&!E_.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=TS(s.createMode,f,r.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function YS(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of o)if(s.enabled){if(s.values&&s.values.length>0)throw new l(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,d.USAGE);n.add(s.metadataKey),r.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function JS(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=Ws.get(r)??r;throw new l(`Cannot combine --unset ${s} with ${ge("create",r)}`,d.USAGE)}}function XS(e){let t=(n,r)=>{let o=Ws.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;Rs(n,ge("create",r),s)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function QS(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 ZS(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:s,type:i,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(_=>{let g=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${g}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),u=[R_(n,r,o,s),...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".'),E_.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 eE(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?It(t.tags):[];return Rn(n,t.addTags)}function tE(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=on(e,"order",n,o=>ce(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function nE(e,t,n,r,o,s){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?s:te(r.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:i,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:nc(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function rE(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:s,author:i,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:g}=e,y=qt(t,n,r,o.item_format,s.type_to_folder),h=Re(t,r),b=Ot(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(N=>b.resolve(N.kind)?.hierarchy),k=await Ls({pmRoot:t,author:i,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:v}),I=v,A=[];try{let N=await be(t,r,o.locks.ttl_seconds,i,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let M=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await ae(t,o.item_format,s.type_to_folder,void 0,o.schema):void 0;if(await U(t,r,o.id_prefix,o.item_format,s.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);if(M){let le=D(o.schema);rs(M,[...M,c.metadata],r,Ue=>Z(Ue,le),b)}await Po({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:Go({pmRoot:t,settings:o,typeToFolder:s.type_to_folder})});let ee=await Tn(t,i,{required:o.governance.duplicate_detection_mode==="strict"&&g!==!0}),he=[];try{o.governance.duplicate_detection_mode==="strict"&&g!==!0&&await Fn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await fe(y,je(c,{format:o.item_format,schema:o.schema,extensionFieldNames:a}));try{let le=qe({nowIso:f,author:i,op:"create",before:m,after:c,message:u});await At(h,le)}catch(le){throw await fn(y),le}I&&(await k(),I=!1),he=await An({pmRoot:t,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:y,document:c})}finally{await ee()}A=[...M?fs(M,[...M,c.metadata],r):[],...he,...await W({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await W({path:h,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],yn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Bt(c.metadata,p),changed_fields:p})}finally{await N()}}finally{I&&await k()}return A}async function Pt(e,t){let n=T_(await kS(e)),r=E(process.cwd(),t.path);await DS(r);let o=await T(r),s=D(o.schema),i=We(o.schema),a=O(o,x()),c=await WS(n,t,r,o,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=dS(n.unset,i),{explicitUnsets:_,clearOptionKeys:g}=YS(n,f);JS(n,f),XS(n);let y=AS(m,n,p,g),h=S(),b=C(me(n.author),o.author_default),v=lS(n.dep,h,o.id_prefix,b),k=sn("--comment",n.comment,h,b),I=sn("--note",n.note,h,b),A=sn("--learning",n.learning,h,b),N=_c(n.file),M=hc(n.test);M.values=await Nn(M.values,b,h);let pe=gc(n.doc),ee=uS(n.reminder,h),he=pS(n.event,h),le=wS(n.typeOption),Ue=Yn(u,le.values,a),ft=x(),_t=vt(ft),ht=Kr(n.field,ft),gt=Mu(n,i,u),Ri=new Set(gt.missing_required_flags),Ii=i.definitions.filter(z=>Ri.has(`--${z.cli_flag}`));QS(ht,gt,f);let Vn=CS(Ue.errors,u),Dt=Vn.map(z=>`--type-option ${z}=<value>`),Hd=[...new Set([...y,...Dt,...gt.missing_required_flags])].sort((z,Di)=>z.localeCompare(Di));ZS({combinedMissingFlags:Hd,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:Vn,openStatus:s.open_status,type:u,createMode:p,missingRequiredRuntimeFields:Ii}),IS(Ue.errors,u,m,s);let Ce=await zS({pmRoot:r,settings:o,typeRegistry:a,explicitId:n.id}),yt=n.status!==void 0?iS(n.status,s):aS(m,s),xi=n.priority!==void 0?PS(n.priority):2,P=f.metadataKeys,Fe=eE(P,n),Ze=on(P,"deadline",n.deadline,z=>te(z,new Date(h),"deadline")),Fr=on(P,"estimated_minutes",n.estimatedMinutes,z=>In(z,"estimated-minutes")),bt=q(P,"acceptance_criteria",n.acceptanceCriteria),Oi=q(P,"definition_of_ready",n.definitionOfReady),Ve=tE(P,n),Pi=q(P,"goal",n.goal),Mr=q(P,"objective",n.objective),Bb=q(P,"value",n.value),Hb=q(P,"impact",n.impact),Vb=q(P,"outcome",n.outcome),Wb=q(P,"why_now",n.whyNow),Yb=q(P,"assignee",n.assignee),Jb=P.has("author")?void 0:me(n.author)??b,Xb=q(P,"parent",n.parent),Vd=await jS(Xb,n,P,r),Li=Vd.parent,Qb=Vd.parentSource,Zb=q(P,"reviewer",n.reviewer),ew=on(P,"risk",n.risk,z=>Ee(Ss(z),un,"risk")),tw=on(P,"confidence",n.confidence,z=>Ts(z)),nw=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Wd=o.validation.sprint_release_format,Ut=[...c.warnings,...GS(u,Ce,Ze,ee.values,he.values)],Yd=await KS({itemId:Ce,parent:Li,pmRoot:r,settings:o,typeRegistry:a,policy:nw});Li=Yd.parent,Ut.push(...Yd.warnings);let Jd=S_(P,"sprint",n.sprint,"sprint",Wd),rw=Jd.value;Ut.push(...Jd.warnings);let Xd=S_(P,"release",n.release,"release",Wd),ow=Xd.value;Ut.push(...Xd.warnings);let Qd=q(P,"blocked_by",n.blockedBy),Zd=await BS({pmRoot:r,settings:o,typeRegistry:a,statusRegistry:s,blockedBy:Qd,dependencyValues:v.values,status:yt,statusExplicit:n.status!==void 0,nowValue:h,author:b}),Ni=Zd.dependencyValues;yr(Ce,Ni),Ut.push(...await Xt({pmRoot:r,dependencies:Ni,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ce,createdAt:h}],schema:o.schema})),yt=Zd.status;let sw=q(P,"blocked_reason",n.blockedReason),iw=q(P,"unblock_note",n.unblockNote),aw=q(P,"reporter",n.reporter),cw=on(P,"severity",n.severity,z=>Ee(Es(z),pn,"severity")),dw=q(P,"environment",n.environment),lw=q(P,"repro_steps",n.reproSteps),el=q(P,"resolution",n.resolution),mw=q(P,"expected_result",n.expectedResult),uw=q(P,"actual_result",n.actualResult),pw=q(P,"affected_version",n.affectedVersion),fw=q(P,"fixed_version",n.fixedVersion),_w=q(P,"component",n.component),hw=on(P,"regression",n.regression,z=>As(z)),gw=q(P,"customer_impact",n.customerImpact),Fi=yc(n.title,"--title"),Mi=n.description??"",$r=n.body??"",tl=await Fn({title:Fi,description:Mi,body:$r},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Ut.push(..._s(tl));let $i=nE(yt,s,o,n,el,h),yw=$i.closeReason,bw=yt===s.close_status?h:void 0,ww=$i.completedAt;Ut.push(...$i.warnings);let Dr=ha({id:Ce,title:Fi,description:Mi,type:u,type_options:Ue.normalized,status:yt,closed_at:bw,completed_at:ww,close_reason:yw,priority:xi,tags:Fe,created_at:h,updated_at:h,deadline:Ze,assignee:Yb,author:Jb,estimated_minutes:Fr,acceptance_criteria:bt,definition_of_ready:Oi,order:Ve,goal:Pi,objective:Mr,value:Bb,impact:Hb,outcome:Vb,why_now:Wb,parent:Li,reviewer:Zb,risk:ew,confidence:tw,sprint:rw,release:ow,blocked_by:Qd,blocked_reason:sw,unblock_note:iw,reporter:aw,severity:cw,environment:dw,repro_steps:lw,resolution:el,expected_result:mw,actual_result:uw,affected_version:pw,fixed_version:fw,component:_w,regression:hw,customer_impact:gw,dependencies:Ni,comments:k.values,notes:I.values,learnings:A.values,files:N.values,tests:M.values,docs:pe.values,reminders:ee.values,events:he.values,...ht,...gt.values});try{zr(Dr,ft)}catch(z){throw new l(z instanceof Error?z.message:"Invalid extension item field values",d.USAGE)}let vw=Ye({metadata:Dr,body:$r},{schema:o.schema,extensionFieldNames:_t}),kw={metadata:{},body:""},nl=[..._].sort((z,Di)=>z.localeCompare(Di)),Sw=_S(n.message,nl),rl=fS(Dr,$r,nl,[...Object.keys(ht),...Object.keys(gt.values??{})]),Ew=await rE({pmRoot:r,type:u,id:Ce,settings:o,typeRegistry:a,author:b,extensionFieldNames:_t,afterDocument:vw,beforeDocument:kw,historyMessage:Sw,changedFields:rl,nowValue:h,similarityCandidate:{title:Fi,description:Mi,body:$r},allowDuplicate:n.allowDuplicate}),ol=structuredClone(Dr);p==="strict"&&_.has("dependencies")&&(ol.dependencies=[]);let Tw=h_(Ce,u,yt,s);return I_(u,Ze,ee.values,he.values)&&zu(`[pm] warning: ${u} '${Ce}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ce} --deadline <ISO>' or 'pm update ${Ce} --event "start=<ISO>,end=<ISO>"'.`),{item:ol,changed_fields:rl,warnings:[...Ut,...Ew],...Object.fromEntries([["parent_source",Qb],["next_transition",Tw],["similarity_advisory",tl]].filter(z=>z[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]="6865ca88-7ca1-52fd-86fb-2a3439abeafa")}catch{}})();var kc=[...dc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...lc,...Bs],oE=(()=>{let e=new Map;for(let t of kc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Js=new Map(kc.map(e=>[e.optionKey,e.canonical])),sE=kc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),iE=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),aE=Cs({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function $_(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s},r=new Set([...Js.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!ze(s))continue;let i=o==="rank"?"order":Js.get(o)??o;n(i),t[o]=void 0}return ve(e,Is(t,aE))}function D_(e,t,n=[]){return Hs({raw:e,supportedFields:sE,resolveDefinition:r=>{let o=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return oE.get(r)??Vs(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var x_=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 O_(e){let t=e.disallowedFlags.flatMap(r=>{let o=x_.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=x_.get(r);return o?[`Replace ${r} with: ${o(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 cE(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let s=(c,m,u)=>{c&&u.push(m)};if(o){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw O_({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let i=[];s(t.status!==void 0,"--status",i),s(t.closeReason!==void 0,"--close-reason",i),s(t.assignee!==void 0,"--assignee",i),s(t.parent!==void 0,"--parent",i),s(t.blockedBy!==void 0,"--blocked-by",i),s(t.blockedReason!==void 0,"--blocked-reason",i),s(t.unblockNote!==void 0,"--unblock-note",i),s(t.dep!==void 0,"--dep",i),s(t.depRemove!==void 0,"--dep-remove",i),s(t.replaceDeps===!0,"--replace-deps",i),s(t.replaceTests===!0,"--replace-tests",i),s(t.replaceFiles===!0,"--replace-files",i),s(t.replaceDocs===!0,"--replace-docs",i),s(t.note!==void 0,"--note",i),s(t.learning!==void 0,"--learning",i),s(t.test!==void 0,"--test",i),s(t.reminder!==void 0,"--reminder",i),s(t.event!==void 0,"--event",i),s(t.clearDeps===!0,"--clear-deps",i),s(t.clearComments===!0,"--clear-comments",i),s(t.clearNotes===!0,"--clear-notes",i),s(t.clearLearnings===!0,"--clear-learnings",i),s(t.clearFiles===!0,"--clear-files",i),s(t.clearTests===!0,"--clear-tests",i),s(t.clearDocs===!0,"--clear-docs",i),s(t.clearReminders===!0,"--clear-reminders",i),s(t.clearEvents===!0,"--clear-events",i);let a=[...n].filter(c=>iE.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw O_({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 dE(e,t){let n=X(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function lE(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Xm({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=X(e.fromStatus,e.statusRegistry)??e.fromStatus,r=X(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Qm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,d.USAGE);return`workflow_transition_not_allowed: ${o}`}function mE(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:U_(e)}function U_(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(t).toISOString()}function Un(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var uE=["id","kind","type","author","created_at","source_kind"],pE=["id","kind","type","author","created_at","source_kind"];function G_(e){return e.startsWith("```")||e.includes(`
8
- `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Wo(e)}function j_(e){return typeof e=="string"?Vr(e)??e.trim():e}function Qs(e,t,n,r){return e?(Se(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let i=s.trim(),a=G_(i);gr(i,a);let c=a?oe(s,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",uE);let m=c.id?.trim(),u=j_((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=or(Un(c.source_kind)),f=Un(c.author);return{id:sr(m,t,p),kind:Ee(u,Gt,"dependency kind"),created_at:mE(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function fE(e,t){return e?(Se(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);let o=G_(r);if(gr(r,o,"--dep-remove"),o){let s=oe(r,"--dep-remove");Ke(s,"--dep-remove",pE);let i=s.id?.trim();if(!i)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(i.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${i}"`,d.USAGE);let a=j_(Un(s.kind??s.type)),c=or(Un(s.source_kind)),m=Un(s.author),u=Un(s.created_at);return{id:sr(i,t,c),kind:a?Ee(a,Gt,"dependency kind"):void 0,source_kind:c,author:m,created_at:u?U_(u):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:we(r,t)}})):[]}function Xs(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function _E(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),s=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function hE(e,t,n,r){let o=[...e??[]],s=!1;if(t===void 0){let i=o.filter(a=>a.kind!=="blocked_by");return i.length!==o.length&&(o=i,s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(i=>i.kind==="blocked_by"&&i.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function gE(e,t,n,r,o,s){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await U(n,we(i,r),r,o,s);return a?{id:a.id}:{unresolved:i}}function yE(e,t,n,r,o){let s=hE(e.dependencies,t,n,r);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,o.includes("dependencies")||o.push("dependencies"))}function bE(e){return`${e.path}::${e.scope}`}function wE(e){return`${e.path}::${e.scope}`}function vE(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function q_(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function kE(e){return xn(e)}function P_(e,t){let n=Wn("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function SE(e,t,n){let r=new Set,o=(s,i)=>{i&&r.add(s)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=D_(e.unset,t,n);for(let i of s.optionKeys)o(i,!0)}return r}function EE(e,t,n,r,o){let s=Br(e,n);if(!s)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=_n(s,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let a=SE(t,r,o);for(let c of i.disabled)if(a.has(P_(c,e)))throw new l(`Option ${ge("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of i.required)if(!a.has(P_(c,e)))throw new l(`Missing required option ${ge("update",c)} for type "${e}"`,d.USAGE)}var TE=new Set(["order","rank"]),AE=Vi.filter(e=>!TE.has(e)),K_=["tags","closeReason",...AE],CE=["title","description","body","status","closeReason","completedAt","priority","type",...Vi,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],RE=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>te(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>In(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"}],IE=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Ee(Ss(e),un,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Ts(e)}],xE=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Ee(Es(e),pn,"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=>As(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function vc(e,t,n){for(let r of e){let o=t[r.optionKey],s=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!s)){if(s){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new l(`${ge("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function OE(e){return $_(await Yo(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function Sc(e){return it(e)?await OE(e):$_(e)}function PE(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 bc(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);bc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),bc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),bc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function LE(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 NE(e){let t={};for(let n of K_)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function FE(e,t){let n=NE(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=Js.get(r)??r;throw new l(`Cannot combine --unset ${s} with ${ge("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 ME(e){let t=(n,r)=>{let o=Js.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;Rs(n,ge("update",r),s)};for(let n of K_)t(e[n],String(n));t(e.order??e.rank,"order"),Se(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Se(e.event,"--event","Use --clear-events to clear linked events.")}function $E(e,t){let n={};for(let r of CE)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 DE(e){let t=await U(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await st(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await V(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function UE(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return ae(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function GE(e){e.before&&rs(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>Z(t,e.statusRegistry),Ot())}async function jE(e){await R(e)}function qE(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 KE(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Zo(e.options.parent);if(ts(e.id,t,e.settings.id_prefix),await U(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=we(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:es(r,e.parentReferencePolicy).warnings}}function zE(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function BE(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await U(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await st(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await V(t,{schema:e.settings.schema}),r=e.options.type!==void 0?_e(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=lE({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function HE(e){if(!e.fieldFlags.status||X(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],o=[];if(n.length>0){let a=ve(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),c=await dt(e.id,a,e.global);o=c.changed_fields,r.push(...c.warnings)}let s=await ct(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...e.workflowTransitionWarnings,...r,...s.warnings,"auto_routed_from_update_to_close"];return{item:s.item,changed_fields:[...o,...s.changed_fields],warnings:i}}function VE(e,t,n,r){return t.title!==void 0&&(e.metadata.title=yc(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")),X(e.metadata.status,n)??e.metadata.status}function WE(e,t,n,r,o){let s=dE(n,t.statusRegistry);if(e.metadata.status=s,o.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!Z(s,t.statusRegistry)&&Z(r,t.statusRegistry)&&e.metadata.closed_at!==void 0&&(delete e.metadata.closed_at,o.push("closed_at"),e.metadata.completed_at!==void 0&&(delete e.metadata.completed_at,o.push("completed_at")))}function YE(e,t,n,r){if(t.options.status!==void 0&&WE(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!Z(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=te(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function JE(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&Z(n,t.statusRegistry)&&!Z(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function XE(e,t,n,r){YE(e,t,n,r),JE(e,t,n,r)}function QE(e,t,n){let r=_e(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=kE(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=_e(t.options.type,t.typeRegistry);if(!o)throw new l(Et(t.options.type,t.typeRegistry.types,Tt(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=o,r=o,n.push("type")}return EE(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),ZE(e,t,r,n),r}function ZE(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let s=Ps(t.options.typeOption??[]),i=Yn(n,s,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 o=Yn(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=o.normalized}function eT(e,t){let n=new Set(t.map(o=>Xs(o))),r=new Set;return e.filter(o=>{if(!n.has(Xs(o)))return!0;let s=_E(o);return r.has(s)?!1:(r.add(s),!0)})}function tT(e,t,n){let r=t.filter(o=>!e.some(s=>q_(s,o)));if(r.length!==0)throw new l(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,d.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function nT(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=eT(r,t.dependencyUpdates.additions);let o=new Set(r.map(s=>Xs(s)));for(let s of t.dependencyUpdates.additions){let i=Xs(s);o.has(i)||(r.push(s),o.add(i))}}t.dependencyRemovals.length>0&&(tT(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(s=>q_(o,s)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function rT(e,t,n){wc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),wc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),wc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function wc(e,t,n,r,o,s){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],s.push(t))}function oT(e,t,n){L_(e,"files",t.options.file,t.fileUpdates.values,bE,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),sT(e,t,n),L_(e,"docs",t.options.doc,t.docUpdates.values,wE,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function L_(e,t,n,r,o,s,i,a){if(!(n===void 0&&!i.has(t))){if(s)e.metadata[t]=r;else if(i.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(u=>o(u)));for(let u of r){let p=o(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function sT(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=N_(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=N_([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function N_(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=vE(r);n.has(o)||(t.push(r),n.add(o))}return t}function iT(e,t,n){let r=t.options.addTags,o=t.options.removeTags,s=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?It(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Vo(Rn(i,r),o),n.changedFields.push("tags")}vc(RE,t.options,n),cT(e,t,n.changedFields)}function aT(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let s=Ho(Cn(e.metadata.acceptance_criteria),r,o);if(s.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let i=s.criteria.join("; ");e.metadata.acceptance_criteria!==i&&(i===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=i,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function cT(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=ce(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function dT(e,t,n,r){lT(e,t,n.changedFields),mT(e,t,n.changedFields),vc(IE,t.options,n),F_(e,t,"sprint",r,n.changedFields),F_(e,t,"release",r,n.changedFields),uT(e,t,n.changedFields),vc(xE,t.options,n)}function lT(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 mT(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 F_(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=ns(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,r.push(...s.warnings)}o.push(n)}}function uT(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)&&yE(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function pT(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=xs(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=Os(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function fT(e,t,n){M_(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),M_(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let i=o.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===o)?.cli_flag??i;throw new l(`Cannot combine --unset ${i} with --${c}`,d.USAGE)}nt(e[o],s)||(e[o]=s,n.push(o))}let r=Kr(t.options.field,t.extensionRegistrations);for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new l(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,d.USAGE);for(let[o,s]of Object.entries(r))nt(e[o],s)||(e[o]=s,n.push(o))}function M_(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function _T(e,t){let n=structuredClone(e.metadata),r=e.body,o=[],s=[],i=VE(e,t.options,t.statusRegistry,o),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};XE(e,t,i,o),QE(e,t,o),nT(e,t,o),rT(e,t,o),oT(e,t,o),iT(e,t,c),aT(e,t,c),dT(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&yr(e.metadata.id,e.metadata.dependencies),X(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),pT(e,t,o),fT(a,t,o);try{zr(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(o)].filter(p=>p==="body"?e.body!==r:!nt(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${Cn(n.acceptance_criteria).length}:${Cn(m.acceptance_criteria).length}`),{changedFields:u,warnings:s}}async function z_(e,t,n,r={}){t=await Sc(t);let o=E(process.cwd(),n.path);await jE(o);let s=await T(o),i=D(s.schema),a=We(s.schema),c=x(),m=vt(c),u=O(s,c),p=s.governance.workflow_enforcement??"off",f=p==="off"?[]:Jm(s.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],g=D_(t.unset,a,m),y=new Set(g.optionKeys),h=new Set(g.metadataKeys);Ec(t),LE({definitions:PE(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:h}),cE(e,t,h),FE(t,g),ME(t);let b=C(t.author,s.author_default),v=new Date,k=v.toISOString(),I=Qs(t.dep,s.id_prefix,k,b);yr(e,I.additions);let A=await Xt({pmRoot:o,dependencies:I.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),N=fE(t.depRemove,s.id_prefix),M=sn("--comment",t.comment,k,b),pe=t.ownershipMetadataBypass===!0&&M.values?{...M,values:M.values.map(Fe=>({...Fe,author:b}))}:M,ee=sn("--note",t.note,k,b),he=sn("--learning",t.learning,k,b),le=_c(t.file),Ue=hc(t.test);Ue.values=await Nn(Ue.values,b,k);let ft=gc(t.doc),_t=[],ht=await KE({id:e,options:t,unsetTargets:g,pmRoot:o,settings:s,typeRegistry:u,parentReferencePolicy:_}),gt=await gE(t.blockedBy,h.has("blocked_by"),o,s.id_prefix,s.item_format,u.type_to_folder),Ri=gt.id,Ii=[...ht.warnings,...zE(gt)],Vn=Mo(t,a,t.runtimeFieldCommands),Dt=$E(t,Vn);if(!Object.values(Dt).some(Boolean))return DE({pmRoot:o,id:e,settings:s,typeRegistry:u});_t.push(...await BE({options:t,fieldFlags:Dt,workflowEnforcement:p,typeWorkflows:f,statusRegistry:i,typeRegistry:u,pmRoot:o,id:e,settings:s}));let Ce=await HE({options:t,fieldFlags:Dt,statusRegistry:i,workflowTransitionWarnings:_t,global:n,id:e});if(Ce)return Ce;qE(t);let yt=Ot(),xi=Dt.parent&&!h.has("parent")||I.additions.some(Fe=>yt.resolve(Fe.kind)?.hierarchy),P=await Ls({pmRoot:o,author:b,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:xi});try{let Fe=await UE({fieldFlags:Dt,clearedMetadataKeys:h,pmRoot:o,settings:s,typeToFolder:u.type_to_folder}),Ze,Fr,bt=await tp({pmRoot:o,settings:s,typeToFolder:u.type_to_folder,id:e,op:hT(t,r),author:b,message:t.message,resolveHistoryContext:()=>Fr,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(Ve){Ze=gT({document:Ve,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),Fr=Ze?{recurrence:Ze}:void 0,Fe=Fe?.map(Mr=>Mr.id===Ve.metadata.id?structuredClone(Ve.metadata):Mr);let Pi=_T(Ve,{options:t,settings:s,typeRegistry:u,statusRegistry:i,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:h,dependencyUpdates:I,dependencyRemovals:N,commentUpdates:pe,noteUpdates:ee,learningUpdates:he,fileUpdates:le,testUpdates:Ue,docUpdates:ft,resolvedParentValue:ht.resolvedParentValue,resolvedBlockedByDependencyId:Ri,runtimeFieldUpdates:Vn,nowValue:v,nowIso:k,author:b,pmRoot:o});return GE({before:Fe,document:Ve,statusRegistry:i}),Pi}});await P();let Oi=Fe?fs(Fe,Fe.map(Ve=>Ve.id===bt.item.id?bt.item:Ve),bt.item.id):[];return{item:bt.item,changed_fields:bt.changedFields,warnings:[..._t,...Ii,...A,...Oi,...bt.warnings],...Ze===void 0?{}:{lifecycle_transition:Ze}}}finally{await P()}}function hT(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function gT(e){if(e.recurrenceReason===void 0)return;let t=X(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!Z(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,d.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=X(n,e.statusRegistry)??n,o=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(i=>{let a=o[i];return typeof a=="string"?[[i,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:s}}async function dt(e,t,n){return z_(e,t,n)}async function B_(e,t,n,r){let o=await z_(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,d.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fada7a33-ad1d-54f1-ae03-c5f8e4568d75")}catch{}})();var V_=1,Ac="update-many",yT=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),bT=["--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(", "),wT={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"},vT=[{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"}],kT={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"},W_=e=>{let t={};for(let[n,r]of Object.entries(e))yT.has(n)||r!==void 0&&(t[n]=r);return t},ST=e=>Object.keys(W_(e)).length>0,Y_=e=>typeof e=="string"?e.trim():e,ET=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},TT=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Y_(e)},AT={priority:ET,estimatedMinutes:Tc,order:Tc,rank:Tc,regression:TT},CT=(e,t)=>{if(t!==void 0)return(AT[e]??Y_)(t)},RT=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return kT[t]??t},Zs=(e,t)=>nt(e,t),IT=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],xT=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,OT=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",H_=(e,t)=>t===void 0?void 0:e[t],Gn=e=>Array.isArray(e)?e.length:0,PT=(e,t,n)=>{let r=n[e.addKey],o=H_(n,e.removeKey),s=Gn(r),i=Gn(o),a=n[e.clearKey]===!0,c=H_(n,e.replaceKey)===!0;if(![a,c,s>0,i>0].includes(!0))return;let m=IT(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:OT({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:s,remove_count:i,before_count:xT(e.field,m)}}},LT=(e,t)=>{let n=[];for(let r of vT){let o=PT(r,e,t);o!==void 0&&n.push(o)}return n},NT=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],FT=(e,t)=>{if(![t.tags!==void 0,Gn(t.addTags)>0,Gn(t.removeTags)>0].includes(!0))return;let n=NT(e.tags),r=t.tags===void 0?n:It(t.tags),o=Rn(r,t.addTags),s=Vo(o,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!Zs(i,s))return{field:"tags",before:n,after:s}},MT=(e,t)=>{let n=e.acceptance_criteria,r=Ho(Cn(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 o=r.criteria.join("; ");if(!Zs(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},$T=(e,t,n)=>{for(let[r,o]of Object.entries(wT)){let s=n[r];if(s===void 0)continue;let i=t[o],a=CT(r,s);Zs(i,a)||e.push({field:o,before:i,after:a})}},DT=(e,t,n,r)=>{let o=Mo(n,r,["update_many"]);for(let[s,i]of Object.entries(o)){let a=t[s];Zs(a,i)||e.push({field:s,before:a,after:i})}},UT=(e,t,n)=>{for(let r of n??[]){let o=RT(r),s=t[o];s!==void 0&&e.push({field:o,before:s,after:null})}},GT=(e,t,n={})=>{let r=e,o=[],s=FT(r,n);if(s&&o.push(s),$T(o,r,n),Gn(n.addAc)>0||Gn(n.removeAc)>0){let i=MT(r,n);i!==void 0&&o.push(i)}return o.push(...LT(r,n)),DT(o,r,n,t),UT(o,r,n.unset),{id:e.id,changes:o}},jT=(e,t)=>gp(e,t,{strict:!0,flagLabel:"--filter-status"}),qT=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)},KT=[({update:e})=>{e.priority!==void 0&&xn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=O(t,x());if(!_e(e.type,r))throw new l(Et(e.type,r.types,Tt(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!X(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&&te(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&In(e.estimatedMinutes,"estimated-minutes")}],zT=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let s of KT)s(o)},BT=async e=>{let t=await zo(e.pmRoot,Ac,e.rollbackId,V_),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Bo(t.items,(o,s)=>Jt(o,s,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...zt({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}},HT=async e=>{let t={schema_version:V_,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Ko(e.pmRoot,Ac,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},VT=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},Cc=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},WT=async e=>{let t=E(process.cwd(),e.path);await R(t);let n=await T(t);return{pmRoot:t,settings:n,statusRegistry:D(n.schema),runtimeFieldRegistry:We(n.schema)}},YT=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(lr(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 BT({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},JT=async e=>{jT(e.options.status,e.runtime.statusRegistry);let t=await at(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let s=GT(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?s:{...s,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await at(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:VT(e.options.list?.ids,r)}},XT=e=>({outcome:"effect",exit_code:d.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...Cc(e)}),QT=e=>({...zt({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...Cc(e)}),ZT=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(s=>s.changes.length>0).map(s=>s.id));for(let s of e.items){if(!o.has(s.id)){t.push({id:s.id,status:"skipped"});continue}try{let i=Sa({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),a=await dt(s.id,i,e.global);t.push({id:s.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(s.id)}catch(i){t.push({id:s.id,status:"failed",error:hn(i)})}}return{rows:t,updatedIds:n}},eA=async e=>{if(e.plan.actionable.length===0)return QT(e.plan);let t=S(),n=qo(Ac,t),r=new Set(e.plan.actionable.map(p=>p.id)),o=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),s=e.options.checkpoint===!1?void 0:await HT({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),i=await ZT({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{...zt({applied:c,skipped:m,failed:u,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...s?{checkpoint:s}:{},updated_count:c,skipped_count:m,failed_count:u,rows:i.rows,ids:i.updatedIds,...Cc(e.plan)}},J_=async(e,t)=>{let n=await WT(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:Sa(await Sc(e.update))});let o=W_(e.update);if(qT(e.list),r!==void 0)return YT({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!ST(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${bT}), or pass --dry-run for a filter-only preview.`,d.USAGE);zT(e.update,n.settings,n.statusRegistry,n.pmRoot),Ec(e.update);let s=await Xt({pmRoot:n.pmRoot,dependencies:Qs(e.update.dep,n.settings.id_prefix,S(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:O(n.settings,x()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await JT({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:s});return await Xt({pmRoot:n.pmRoot,dependencies:Qs(e.update.dep,n.settings.id_prefix,S(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:O(n.settings,x()).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?XT(i):eA({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]="f7e870b6-fd80-5742-bc81-826d8f102d30")}catch{}})();var tA=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],X_=["brief","standard","deep"],eh="plan-step-",Lc="draft",Pc=["bug-investigation","feature-implementation","refactoring-sprint"],Q_={"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 nA(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(Q_,t)?Q_[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${Pc.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Pc[0]}`]});return n.map(r=>({...r}))}function rA(e,t){return t>0?Math.round(e/t*100):0}function th(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 De(e){return Array.isArray(e)?e.flatMap(t=>On(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?On(e,{unique:!1}):[]}function Te(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function nh(e,t=Lc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=ji.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${ji.join(", ")}`,d.USAGE);return r}function Nc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=qi.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${qi.join(", ")}`,d.USAGE);return r}function rh(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=zi.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${zi.join(", ")}`,d.USAGE);return r}function oA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ki.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${Ki.join(", ")}`,d.USAGE);return n}function sA(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=X_.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${X_.join(", ")}`,d.USAGE);return n}function iA(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 Rc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function aA(e,t){let n=e,r={},o=[];for(let s of t){let i=s.startsWith("plan.")?s.slice(5):s;if(i.length!==0){if(!Rc.has(i)){o.push(s);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...Rc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...Rc].join(",")}`}});return r}function Fc(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let s=o.indexOf("=");if(s<=0)throw new l(`Invalid ${t} entry "${o}"; 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[o.slice(0,s).trim().toLowerCase()]=o.slice(s+1).trim()}return n}function Mc(e){let t=Fc(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=Fc(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 Dc(e){let t=Fc(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 cA(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=rA(t.completed,t.total),t}function dA(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${eh}${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 jn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),s=e.find(i=>i.order===o);if(s)return s}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function Z_(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 lA(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],o=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",d.USAGE);for(let i of e.slice().sort((a,c)=>a.order-c.order)){let a=Z_(i);if(a){o.push({from_step:i.id,...a});continue}r.push(i)}return{targets:r,skipped:o}}let s=new Set;for(let i of t){let a=jn(e,i);if(s.has(a.id))continue;s.add(a.id);let c=Z_(a);if(c){o.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:o}}function mA(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 uA(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function pA(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 Oe(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=cA(n),o=uA(n),s={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Lc,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:pA(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(s.steps=n),t==="deep"&&(s.decisions=e.plan_decisions??[],s.discoveries=e.plan_discoveries??[],s.validation=e.plan_validation??[]),s}function Pe(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&&!Ta(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function oh(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 fA(e){let t=E(process.cwd(),e.path);await R(t);let n=await T(t);return{pmRoot:t,settings:n}}async function sh(e,t){let n=O(e.settings,x()),r=await U(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 o=await V(r,{schema:e.settings.schema});return oh(o.document.metadata),{document:o.document,itemId:r.id}}function _A(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of De(e.related))t.push(`id=${n},kind=related`);for(let n of De(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of De(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function hA(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 gA(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||De(e.dependsOn).length>0||De(e.link).length>0}function yA(e){let t=e.stepTitle?.trim()||void 0,n=th(e.step),r=e.template?.trim()?nA(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function bA(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new l("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",d.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${Pc[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new l("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",d.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function wA(e,t){let n=Nc(e.stepStatus,"pending"),r=Uc(e,"depends_on"),o=Te(e.file).map(Mc),s=Te(e.test).map($c),i=Te(e.doc).map(Dc),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:o.length>0?o:void 0,tests:s.length>0?s:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function vA(e){let t=yA(e),n=gA(e);if(bA(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[wA(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=S();return{steps:t.stepTitles.map((o,s)=>({id:`${eh}${String(s+1).padStart(3,"0")}`,order:s+1,title:o,body:t.templateSteps[s]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function ih(e,t,n=[]){ve(e,t),n.length>0&&fp(t,n)}async function kA(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 o=nh(e.mode,Lc),s=oA(e.harness),i=e.fromSearch?.trim(),a=hA(e),{steps:c,hasPerStepDetailOptions:m}=vA(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?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:Te(e.file),test:Te(e.test),doc:Te(e.doc),field:Te(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:_A(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")};ih(e,f);let _=await Pt(f,t),g=await ne({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(h){let b=["plan_mode"];h.metadata.plan_mode=o,s&&(h.metadata.plan_harness=s,b.push("plan_harness"));let v=e.scope?.trim();v&&(h.metadata.plan_scope=v,b.push("plan_scope"));let k=e.resumeContext?.trim();return k&&(h.metadata.plan_resume_context=k,b.push("plan_resume_context")),h.metadata.plan_steps=c,b.push("plan_steps"),a&&(h.metadata.plan_validation=[...h.metadata.plan_validation??[],a],b.push("plan_validation")),p&&(h.metadata.assignee=p,b.push("assignee")),{changedFields:b}}}),y=Oe(g.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Pe(_.item.id,y),warnings:[..._.warnings],generated_at:S()}}async function SA(e,t,n){let r=sA(t.depth),o=iA(t.fields),{document:s,itemId:i}=await sh(n,e),a=Oe(s.metadata,o===null?r:"deep");return{action:"show",plan:o===null?a:aA(a,o),next_actions:Pe(i,a),warnings:[],generated_at:S()}}function EA(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function Je(e){let t=C(e.options.author,e.ctx.settings.author_default),n,r=await ne({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){oh(o.metadata);let s=D(e.ctx.settings.schema);if(Z(o.metadata.status,s)||Ta(o.metadata.plan_mode))throw new l(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.metadata.plan_mode??"unset"}) and cannot be mutated.`,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=(o.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(o.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,o);n=c.resultStep;let m=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));o.metadata.plan_steps=m;let u=EA(a,o.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function TA(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let o=Nc(t.stepStatus,"pending"),s=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await Je({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;ah(u,void 0,o,s);let f=AA(u,t,{order:p,title:r,status:o});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Oe(i.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Pe(c,m),warnings:[],generated_at:S()}}function ah(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(s=>s.id!==t&&s.status==="in_progress");if(o)throw new l(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function AA(e,t,n){let r=Uc(t,"depends_on"),o=Te(t.file).map(Mc),s=Te(t.test).map($c),i=Te(t.doc).map(Dc),a=S();return{id:dA(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:s.length>0?s:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function Uc(e,t){let n=De(e.dependsOn).map(u=>({id:u,kind:t})),r=De(e.related).map(u=>({id:u,kind:"related"})),o=De(e.blocks).map(u=>({id:u,kind:"blocks"})),s=De(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=De(e.link),a=rh(e.linkKind,t),c=e.linkNote?.trim(),m=i.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...o,...s,...m]}async function Ic(e,t,n,r){let{document:o,resultStep:s,itemId:i}=await Je({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=jn(c,r.stepRef),p=S(),f=r.finalStatus??Nc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return ah(c,u.status==="in_progress"?u.id:void 0,f,_),CA(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Oe(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:s,next_actions:Pe(i,a),warnings:[],generated_at:S()}}function CA(e,t,n,r){RA(e,t,n),IA(e,t),e.status=n,e.updated_at=r,xA(e,n,r)}function RA(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 IA(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=Te(t.file).map(Mc),o=Te(t.test).map($c),s=Te(t.doc).map(Dc);r.length>0&&(e.files=xc(e.files,r)),o.length>0&&(e.tests=xc(e.tests,o)),s.length>0&&(e.docs=xc(e.docs,s))}function xc(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let s=JSON.stringify(o);r.has(s)||(r.add(s),n.push(o))}return n}function xA(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function OA(e,t,n,r,o){let{document:s,itemId:i}=await Je({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(c){let m=jn(c,r),u=c.filter(f=>f.id!==m.id),p=Math.max(1,Math.min(o,u.length+1));return u.splice(p-1,0,m),u.forEach((f,_)=>{f.order=_+1,f.updated_at=S()}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=Oe(s.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Pe(i,a),warnings:[],generated_at:S()}}async function PA(e,t,n,r){let{document:o,itemId:s}=await Je({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=jn(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=Oe(o.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:S()}}async function LA(e,t,n,r){let o=Uc(t,rh(t.linkKind,"related"));if(o.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let s=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await Je({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=jn(u,r),_=f.linked_items??[],g=h=>`${h.kind}:${h.id}`,y=new Set(_.map(g));for(let h of o){let b=g(h);y.has(b)||(_.push(h),y.add(b))}if(f.linked_items=_,f.updated_at=S(),s){let h=p.metadata.dependencies??[],b=k=>`${k.kind}:${k.id}`,v=new Set(h.map(b));for(let k of o){let I=k.kind==="depends_on"?"blocked_by":k.kind,A={id:k.id,kind:I,created_at:S(),author:C(t.author,n.settings.author_default)};v.has(b(A))||(h.push(A),v.add(b(A)))}p.metadata.dependencies=h}return{changedSteps:[f.id],resultStep:f}}}),m=Oe(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Pe(a,m),warnings:[],generated_at:S()}}async function NA(e,t,n,r){let o=De(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:s,itemId:i,resultStep:a}=await Je({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=jn(m,r),p=(u.linked_items??[]).filter(f=>!o.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=S(),{changedSteps:[u.id],resultStep:u}}}),c=Oe(s.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Pe(i,c),warnings:[],generated_at:S()}}async function Oc(e,t,n,r){let o=mA(r,t);if(!o){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 s=C(t.author,n.settings.author_default),{document:i,itemId:a}=await Je({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:s,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:s,text:o}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Oe(i.metadata,"deep");return{action:r,plan:c,next_actions:Pe(a,c),warnings:[],generated_at:S()}}async function FA(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:o,itemId:s}=await Je({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=Oe(o.metadata,"brief");return{action:"resume",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:S()}}async function MA(e,t,n){let r=nh(t.mode??"approved","approved"),{document:o,itemId:s}=await Je({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=Oe(o.metadata,"brief");return{action:"approve",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:S()}}function ch(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function $A(e,t){let n=Oe(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Pe(e.itemId,n),warnings:ch(t),generated_at:S()}}function DA(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let s=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${s}`)}return r}async function UA(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Te(e.options.field)){let s=o.indexOf("=");if(s<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0)throw new l(`Invalid --field entry "${o}"; 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 "${o}"; 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 "${o}"; "${p}" is reserved by materialize and cannot be overridden`,d.USAGE);n[p]=a}for(let o of e.targets){let s={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:DA(e.parent,e.planItemId,o)};ih(e.options,s,["description",...Object.keys(n)]);let i=await Pt(s,{path:e.pmRoot});t.push({id:i.item.id,title:i.item.title,type:e.resolvedTypeName,parent:i.item.parent,tags:i.item.tags??[],from_step:o.id})}return t}function GA(e,t,n){for(let r of t){let o=n.find(a=>a.from_step===r.id);if(!o)continue;let s=e.find(a=>a.id===r.id);if(!s)continue;let i=s.linked_items??[];i.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),s.linked_items=i,s.updated_at=S()}}async function jA(e,t,n){let r=De(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let o=t.materializeType?.trim()||"Task",s=O(n.settings,x()),i=_e(o,s);if(!i)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await sh(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=lA(u,r);if(p.length===0){if(f.length>0)return $A(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await UA({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:g,itemId:y}=await Je({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(b){return GA(b,p,_),{changedSteps:p.map(v=>v.id)}}}),h=Oe(g.metadata,"standard");return{action:"materialize",plan:h,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Pe(y,h),warnings:ch(f),generated_at:S()}}function qA(e){if(e.subcommand==="create")return e;let t=th(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:ve(e.options,{...e.options,stepTitle:t[0]})}:e}function lt(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function an(e,t){let n=lt(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function KA(e){let t=an(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 zA={create:(e,t)=>kA(e.options,e.global,t),show:(e,t)=>SA(lt(e,"show"),e.options,t),"add-step":(e,t)=>TA(lt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=an(e,"update-step");return Ic(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=an(e,"complete-step");return Ic(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=an(e,"block-step");return Ic(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=KA(e);return OA(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=an(e,"remove-step");return PA(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=an(e,"link");return LA(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=an(e,"unlink");return NA(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Oc(lt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Oc(lt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Oc(lt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>FA(lt(e,"resume"),e.options,t),approve:(e,t)=>MA(lt(e,"approve"),e.options,t),materialize:(e,t)=>jA(lt(e,"materialize"),e.options,t)};function BA(e){let t=zA[e];if(!t)throw xe({command_path:"plan",token:e,allowed:tA});return t}async function dh(e){let t=await fA(e.global),n=qA(e);return BA(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]="b59e8e54-f9e0-5cdb-bc59-6dcbf67f278d")}catch{}})();function HA(e,t){return[...new Set([...qr.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,o)=>r.localeCompare(o))}function VA(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function Gc(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await T(r),s=O(o,x()),i=await U(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!i)throw await st(r,e,o.id_prefix,s.type_to_folder);let a=await V(i,{schema:o.schema}),c=a.document.metadata,m=S(),u=C(t.author,o.author_default),p=await nr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:s.type_to_folder,probeExisting:!1}),f=D(o.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let g={...c,id:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete g.closed_at,delete g.completed_at,delete g.close_reason,delete g.test_runs;let y=vt(x()),h=Ye({metadata:g,body:a.document.body},{schema:o.schema,extensionFieldNames:y}),b=await Fn({title:h.metadata.title,description:h.metadata.description,body:h.body,excludeIds:[i.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=HA(h.metadata,h.body),k=qt(r,h.metadata.type,p,o.item_format,s.type_to_folder),I=Re(r,p),A=await be(r,p,o.locks.ttl_seconds,u,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),N={metadata:{},body:""},M,pe;try{let ee=await Tn(r,u,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await Fn({title:h.metadata.title,description:h.metadata.description,body:h.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let he=await U(r,p,o.id_prefix,o.item_format,s.type_to_folder);if(he)throw new l(`Cannot copy to ${p}: an item with that id already exists at ${he.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${he.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await fe(k,je(h,{format:o.item_format,schema:o.schema,extensionFieldNames:y}));try{let le=qe({nowIso:m,author:u,op:"create",before:N,after:h,message:VA(i.id,t.message)});await At(I,le)}catch(le){throw await fn(k),le}pe=await An({pmRoot:r,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:k,document:h})}finally{await ee()}M=[...await W({path:k,scope:"project",op:"create",item_id:h.metadata.id,item_type:h.metadata.type,before:N,after:h,changed_fields:v}),...await W({path:I,scope:"project",op:"create:history",item_id:h.metadata.id,item_type:h.metadata.type,before:N,after:h,changed_fields:v})],yn({id:h.metadata.id,op:"create",item_type:h.metadata.type,status:h.metadata.status,current:Bt(h.metadata,v),changed_fields:v})}finally{await A()}return{source_id:i.id,item:structuredClone(h.metadata),changed_fields:v,warnings:[..._s(b),...pe,...M],...b===void 0?{}:{similarity_advisory:b}}}import ei 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]="7819b53c-b0e4-50b0-a670-f80b36765085")}catch{}})();async function jc(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await T(r),s=C(t.author,o.author_default),i=await np({pmRoot:r,settings:o,id:e,author:s,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?ei.relative(r,i.targetPath).split(ei.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:ei.relative(r,Re(r,i.item.id)).split(ei.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]="a5ddb139-9780-50e0-87a5-621913cb0de4")}catch{}})();async function WA(e){await R(e)}async function qc(e,t,n){let r=E(process.cwd(),n.path);if(await WA(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 T(r),f=vn(C(void 0,p.author_default));return await Fu(r),await ps({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 No(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 YA(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let s=await T(r),i=O(s,x()),a=await U(r,e,s.id_prefix,s.item_format,i.type_to_folder);if(!a)throw await st(r,e,s.id_prefix,i.type_to_folder);let c=we(a.id,s.id_prefix),m=await V(a,{schema:s.schema}),u=lh(m.document.metadata.title);return await Nu(r,c),await ps({pmRoot:r,settings:s,principal:vn(C(void 0,s.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function YA(e,t){let n=await T(e),r=O(n,x()),o=await U(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let s=await V(o,{schema:n.schema});return lh(s.document.metadata.title)}function lh(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]="77fa2822-1681-59d5-8388-037cf13c45dd")}catch{}})();var mh=new Set(["item_format"]),uh=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"]),JA=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),XA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),QA={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function ZA(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(mh.has(t)||uh.has(t)||JA.has(t)||t==="context")return t}function eC(e){let t=e.trim().toLowerCase();return QA[t]??e}function ph(e,t){let n=ZA(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."}:mh.has(n)?{routable:!0,flag:"format",value:t}:uh.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:XA.has(n)?eC(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]="09703f32-9491-5d3a-9f90-f038d9982e17")}catch{}})();var tC=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Kc=128,nC=1e4;function fh(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>Kc)throw new Error(`A legacy author must contain 1-${Kc} characters.`);return t}function rC(e){let t=e?.trim().toLowerCase();if(!t||!tC.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function oC(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function sC(e,t){let n=new Set;for(let r of(e??[]).slice(0,nC)){let o=r.trim().slice(0,Kc);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function iC(e,t){let n=fh(t.legacy_author),r=rC(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function aC(e,t){if(t.operation==="add")return iC(e,t);if(t.operation==="remove"){let r=fh(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function zc(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function _h(e,t){let n=e?.version??1,r={...e?.aliases},o=aC(r,t),s={version:o?n+1:n,aliases:oC(r)};return{vocabulary:s,preview:{operation:t.operation,changed:o,version_before:n,version_after:s.version,alias_count:Object.keys(s.aliases).length,residual_author_count:sC(t.observed_authors,s.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2f750f85-6c55-5f0f-b5c0-396764839d2a")}catch{}})();var hh=["project","global"],mt={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},cC=Object.keys(mt).map(e=>mt[e][0]),dC=Object.fromEntries(Object.keys(mt).flatMap(e=>mt[e].map(t=>[t,e]))),lC={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},mC=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],uC=new Set(["metadata_required_fields",...mC]),pC=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),fC=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),_C=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),hC=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),gC=new Set(["governance_preset","governance_create_default_type"]),vh=e=>uC.has(e),yC=e=>_C.has(e),bC=e=>hC.has(e),wC=e=>gC.has(e);function Bc(e){return e==="definition_of_done"||vh(e)}function vC(e){if(hh.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${hh.join(", ")}`,d.USAGE)}function kC(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw xe({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function SC(e){let t=dC[e];if(t)return t;let n=Qi.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${cC.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function EC(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",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 TC(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 kh(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 AC(e){return Vc(e,"test-result-tracking")}function Vc(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,d.USAGE)}function Sh(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 Wc(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 Eh(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 Th(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 Ah(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 Ch(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 Rh(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 Ih(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 xh(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)}var CC={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function gh(e,t){let n=CC[e];if(n)return Vc(t,n);switch(e){case"history_missing_stream_policy":return kh(t);case"sprint_release_format_policy":return Ea(t);case"parent_reference_policy":case"governance_parent_reference_policy":return Qo(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Wc(t);case"governance_preset":return Eh(t);case"governance_ownership_enforcement":return Th(t);case"governance_create_mode_default":return Ah(t);case"governance_close_validation_default":return Ch(t);case"governance_require_close_reason":return xh(t);case"governance_workflow_enforcement":return Rh(t);case"governance_force_required_for_stale_lock":return Ih(t);case"telemetry_tracking":return Sh(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var yh={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"},RC=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function IC(e,t){let n=[...new Set((e??[]).map(s=>s.trim()).filter(s=>s.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(s=>s.toLowerCase().replaceAll("-","_")),o=r.filter(s=>yh[s]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${RC.join(", ")}`,d.USAGE);return[...new Set(r.map(s=>yh[s]))].sort((s,i)=>s.localeCompare(i))}function xC(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,s)=>o.localeCompare(s));if(n){if(r.length>0)throw new l(`Config set ${mt[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${mt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function OC(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function PC(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 SC(t)}function Oh(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var LC={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>zc(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function Yc(e,t){return LC[t](e)}function Ae(e,t){return t.length===0?e:{...e,warnings:t}}async function NC(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):tt(n),o=ye(r);return e==="project"&&await R(r),{pmRoot:r,settingsPath:o}}function FC(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 bh(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 MC(e,t,n,r,o){let s=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!Bi.includes(c))throw new l(`Context --default-depth must be one of ${Bi.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,s=!0)}if(t.activityLimit!==void 0){let c=bh(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,s=!0)}if(t.staleThresholdDays!==void 0){let c=bh(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,s=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of a){let u=FC(m);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,s=!0)}}return s&&await Ie(n.pmRoot,e,"config:set:context"),Ae({scope:r,key:"context",context_settings:{default_depth:i.default_depth,activity_limit:i.activity_limit,stale_threshold_days:i.stale_threshold_days,sections:{...i.sections}},settings_path:n.settingsPath,changed:s},o)}function $C(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 DC(e,t,n,r,o,s){if(o===void 0)return s;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 $C(t,o,s);Oh(n);let i=ph(n,o);if(!i.routable)throw new l(i.reason,d.USAGE);if(i.flag==="criterion"){if(s.criterion!==void 0&&s.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...s,criterion:i.values}}if(i.flag==="format")return{...s,format:i.value};if(s.policy!==void 0&&gh(n,s.policy)!==gh(n,i.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${s.policy}". Pass only one.`,d.USAGE);return{...s,policy:i.value}}function UC(e){let t=Object.keys(mt).map(r=>({key:r,aliases:mt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":Bc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:Bc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:lC[r],value:Yc(e.settings,r)})),n=Qi.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Zi(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 Ae({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function GC(e){let t=Object.fromEntries(Object.keys(mt).map(n=>[n,Yc(e.settings,n)]));return Ae({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function jC(e,t){let n=Yc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Ae({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Ae({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Ae({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Ae({...r,criteria:n},e.warnings):Ae({...r,policy:n},e.warnings)}async function qC(e,t,n,r){if(t==="get"){let a=Zi(e.settings,n);return Ae({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let s=Ym(n,o);if(!s.ok)throw new l(s.error.message,d.USAGE);let i=Io(e.settings,n,s.parsed.value);return i&&await Ie(e.target.pmRoot,e.settings,`config:set:${n.path}`),Ae({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:s.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function Y(e,t,n){t&&await Ie(e.target.pmRoot,e.settings,n)}function wh(e,t,n){return e!==n||t!==n}function se(e,t,n,r){return Ae({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Hc(e,t,n,r){return Ae({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function KC(e,t){let n=TC(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let s=O(e.settings,x()),i=await bp(e.target.pmRoot,n,"config:set:item_format:migrate",s.type_to_folder,e.settings.schema);o={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await Ie(e.target.pmRoot,e.settings,"config:set:item_format")}return Ae({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function zC(e,t,n){if(t==="history_missing_stream_policy"){let s=kh(n.policy),i=e.settings.history.missing_stream!==s;return e.settings.history.missing_stream=s,await Y(e,i,"config:set:history_missing_stream_policy"),se(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let s=Ea(n.policy),i=e.settings.validation.sprint_release_format!==s;return e.settings.validation.sprint_release_format=s,await Y(e,i,"config:set:sprint_release_format_policy"),se(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let s=Qo(n.policy),i=e.settings.validation.parent_reference!==s||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==s;return e.settings.validation.parent_reference=s,e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,await Y(e,i,"config:set:parent_reference_policy"),se(e,t,e.settings.validation.parent_reference,i)}let r=Wc(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Y(e,o,"config:set:metadata_validation_profile"),se(e,t,e.settings.validation.metadata_profile,o)}async function BC(e,t,n){if(t==="metadata_required_fields"){let a=IC(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((m,u)=>m!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await Y(e,c,"config:set:metadata_required_fields"),Hc(e,t,[...e.settings.validation.metadata_required_fields],c)}let o={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],s=xC(t,n.criterion,n.clearCriteria),i=s.length!==o.length||s.some((a,c)=>a!==o[c]);return o.splice(0,o.length,...s),await Y(e,i,`config:set:${t}`),Hc(e,t,[...o],i)}async function HC(e,t,n){if(t==="governance_preset"){let c=Eh(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Y(e,m,"config:set:governance_preset"),se(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Y(e,c,"config:set:governance_create_default_type"),se(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let s=O(e.settings,x()),i=_e(o,s);if(!i)throw new l(Et(o,s.types,Tt(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 Y(e,a,"config:set:governance_create_default_type"),se(e,t,e.settings.governance.create_default_type,a)}async function VC(e,t,n){if(t==="governance_ownership_enforcement"){let s=Th(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==s;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=s,await Y(e,i,"config:set:governance_ownership_enforcement"),se(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let s=Ah(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==s;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=s,await Y(e,i,"config:set:governance_create_mode_default"),se(e,t,e.settings.governance.create_mode_default,i)}let r=Ch(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Y(e,o,"config:set:governance_close_validation_default"),se(e,t,e.settings.governance.close_validation_default,o)}async function WC(e,t,n){if(t==="governance_parent_reference_policy"){let s=Qo(n.policy),i=e.settings.governance.preset!=="custom"||wh(e.settings.governance.parent_reference,e.settings.validation.parent_reference,s);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,e.settings.validation.parent_reference=s,await Y(e,i,"config:set:governance_parent_reference_policy"),se(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let s=Wc(n.policy),i=e.settings.governance.preset!=="custom"||wh(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,s);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=s,e.settings.validation.metadata_profile=s,await Y(e,i,"config:set:governance_metadata_validation_profile"),se(e,t,e.settings.governance.metadata_profile,i)}let r=Rh(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Y(e,o,"config:set:governance_workflow_enforcement"),se(e,t,e.settings.governance.workflow_enforcement,o)}async function YC(e,t,n){if(t==="governance_require_close_reason"){let a=xh(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await Y(e,c,"config:set:governance_require_close_reason"),se(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let o=Ih(n.policy)==="enabled",s=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==o;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=o,await Y(e,s,"config:set:governance_force_required_for_stale_lock"),se(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",s)}async function JC(e,t,n){if(t==="test_result_tracking"){let a=AC(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await Y(e,c,"config:set:test_result_tracking"),se(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}if(t==="untrusted_linked_test_execution"){let a=Vc(n.policy,"untrusted-linked-test-execution")==="enabled",c=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await Y(e,c,"config:set:untrusted_linked_test_execution"),se(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",c)}let o=Sh(n.policy)==="enabled",s=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await Y(e,s,"config:set:telemetry_tracking"),se(e,t,e.settings.telemetry.enabled?"enabled":"disabled",s)}async function XC(e,t,n){let r=EC(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((s,i)=>s!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await Y(e,o,"config:set:definition_of_done"),Hc(e,t,[...e.settings.workflow.definition_of_done],o)}function QC(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",d.USAGE)}function ZC(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',d.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",d.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",d.USAGE);return{}}async function eR(e,t){let{operation:n,dryRun:r}=QC(t.policy),o=ZC(n,t.value),s;try{s=_h(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(i){throw new l(i.message,d.USAGE)}return s.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:s.vocabulary},await Y(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${s.preview.version_after}`)),Ae({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:zc(r?e.settings.agent_identity?.identity_vocabulary:s.vocabulary),vocabulary_mutation:s.preview,settings_path:e.target.settingsPath,changed:s.preview.changed&&!r},e.warnings)}async function tR(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"?KC(e,n):t==="context"?MC(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?eR(e,n):t==="definition_of_done"?XC(e,t,n):vh(t)?BC(e,t,n):pC.has(t)?JC(e,t,n):fC.has(t)?YC(e,t,n):yC(t)?VC(e,t,n):bC(t)?WC(e,t,n):wC(t)?HC(e,t,n):zC(e,t,n)}async function Ph(e,t,n,r,o,s){let i=vC(e),a=kC(t),c=a==="get"||a==="set"?Ro(n):void 0,m=c?void 0:PC(a,n),u=DC(a,n,m,c,s,r),p=await NC(i,o),{settings:f,metadata:_,warnings:g}=await Ju(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:OC(g)};return c?qC(y,a,c,u):a==="list"?UC(y):a==="export"?GC(y):(Oh(m),a==="get"?jC(y,m):tR(y,m,u))}import PR from"node:fs/promises";import J from"node:path";import LR from"node:readline/promises";import{stdin as NR,stdout as Le}from"node:process";import Xc from"node:fs/promises";import ie from"node:path";import nR from"node:readline/promises";import{stdin as rR,stdout as ti}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e404796d-439b-5f4c-9330-5b12ff41d7b2")}catch{}})();var Nh=["ask","add","skip","status"],oR=["AGENTS.md","CLAUDE.md"],sR=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],iR=8,Qc=1,aR="<!-- pm-cli:agent-guidance:start:",cR=`<!-- pm-cli:agent-guidance:start:v${Qc} -->`,Jc="<!-- pm-cli:agent-guidance:end -->",Sr="Add workflow guidance later: pm init --agent-guidance add";var dR=()=>nR.createInterface({input:rR,output:ti});function vr(e,t){let n=ie.relative(e,t);return n.length===0?ie.basename(t):n.split(ie.sep).join("/")}function Lh(e){return e.endsWith(`
4
+ `,{changedFields:["body"]}}});return{item:m.item,appended:c,changed_fields:m.changedFields}}import{readFile as bv}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]="39acab93-f9ad-5b95-871e-625d912f1322")}catch{}})();function ws(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,ve(e,t)}function Bf(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 tc(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function Yt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Mn(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let s=oe(n,"--add");return Object.keys(s).map(c=>c.trim().toLowerCase()).some(c=>c!=="text")?n:s.text?.trim()||n}catch{return n}}function nc(e){return typeof e=="object"&&e!==null&&"code"in e}function hr(e,t){if(!at(e))throw new l(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,d.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function wv(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=xt(),o=at(e);if(e.add!==void 0)return{value:await r.resolveValue(e.add,"--add",o)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return hr(e,"--stdin"),{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);if(s==="-")return hr(e,"--file -"),{value:await r.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await bv(s,"utf8"),emptyFlag:"--file"}}catch(i){if(nc(i)&&jt(i))throw new l(`--file path not found: ${s}. Use --file - to read stdin.`,d.USAGE);let a=i instanceof Error?i.message:String(i);throw new l(`Failed to read --file path "${s}": ${a}. Use --file - to read stdin.`,d.USAGE)}}async function vs(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 wv(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 _r(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 Vf(e){return e==="comments"?"--stdin":"--add -"}function vv(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let r=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(r))return;let o=Vf(t.collectionKey),s=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 ${o} to read stdin, or use text=${r} for literal dash-leading text.`,d.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${r} when the text really starts with "-".`,examples:[`${s} ${o}`,`${s} --add text=${r}`]})}function kv(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> ${Vf(e.collectionKey)}`]})}async function $n(e,t,n,r){kv(r,t);let o=E(process.cwd(),n.path);await R(o);let s=await T(o),i=O(s,x()),a=rr(t.limit);if(r.input.mode==="list"){let _=await U(o,e,s.id_prefix,s.item_format,i.type_to_folder);if(!_)throw new l(`Item ${e} not found`,d.NOT_FOUND);let g=await V(_,{schema:s.schema}),y=Yt(g.document.metadata,r.collectionKey);return bs(_.id,r.collectionKey,y,a,t.includeMeta===!0)}let c=C(t.author,s.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,g;try{g=await ne({pmRoot:o,settings:s,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(h){let b=Yt(h.metadata,r.collectionKey),v=Hf(r.input.index,b.length,r.collectionKey);return Bf(b[v],"deleted"),b.splice(v,1),h.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(h){_r(h,r.conflictGuidance)}let y=Yt(g.item,r.collectionKey);return bs(g.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??"";vv(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,g;try{g=await ne({pmRoot:o,settings:s,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(h){let b=Yt(h.metadata,r.collectionKey),v=Hf(r.input.index,b.length,r.collectionKey),k=b[v];return Bf(k,"edited"),b[v]={...k,text:u,edited_at:S()},h.metadata[r.collectionKey]=b,{changedFields:[r.collectionKey]}}})}catch(h){_r(h,r.conflictGuidance)}let y=Yt(g.item,r.collectionKey);return bs(g.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 ne({pmRoot:o,settings:s,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(_){let g=Yt(_.metadata,r.collectionKey),y={created_at:S(),author:c,text:u};return g.push(r.createEntry(y)),_.metadata[r.collectionKey]=g,{changedFields:[r.collectionKey]}}})}catch(_){_r(_,r.conflictGuidance)}let f=Yt(p.item,r.collectionKey);return bs(p.item.id,r.collectionKey,f,a,t.includeMeta===!0,{action:"add",entryIndex:f.length,entry:f.at(-1)},t.fullHistory===!0)}function Hf(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,s=t===1?`1 ${r}`:`${t} ${n}`;throw new l(`${o} index ${e??"(missing)"} out of range (item has ${s})`,d.USAGE)}return e-1}function bs(e,t,n,r,o,s,i=!1){let a=s===void 0||i?tc(n,s!==void 0&&i?void 0:r):s.entry===void 0?[]:[s.entry],c=s!==void 0&&a.length<n.length;return{id:e,[t]:a,count:a.length,...[o,s!==void 0].includes(!0)?{total_count:n.length,returned_count:a.length,has_more:c||a.length<n.length,...r!==void 0?{limit:r}:{}}:{},...s===void 0?{}:{mutation_receipt:{action:s.action,entry_index:s.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 Wf(e,t,n){return[...await Sn(Re(e,t),t).catch(()=>[])].reverse().find(s=>s.patch.some(i=>i.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${n}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a61bf25-e320-5adc-8f5a-a427bc89af1a")}catch{}})();var Yf="no_available_next_item";function Jf(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 ks(e,t,n,r={}){let o=E(process.cwd(),n.path);await R(o);let s=await T(o),i=D(s.schema),a=C(r.author,s.author_default),c=vn(a),m=null,u=!1,p=[],f=await ne({pmRoot:o,settings:s,id:e,op:"claim",author:a,message:r.message,force:t,skipNoop:!0,async mutate(_){let y=_.metadata.assignee??"",h=_.metadata.claim_principal?.trim()||y;if(m=y.trim().length>0?y:null,Hm(_.metadata.status,i)&&!t)throw new l(`Cannot claim terminal item ${_.metadata.id} without --force`,d.CONFLICT);if(m!==null&&h!==c){if(r.ifAvailable===!0)return u=!0,p.push(`claim_skipped_held_by:${m}`),{changedFields:[]};if(!t){let v=await Wf(o,_.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 za({pmRoot:o,settings:s,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 Xf(e,t,n={},r={}){let o=Sv(n.maxAttempts),s=await T(E(process.cwd(),t.path)),i={...n,author:C(n.author,s.author_default)},a=await ur({...r,callerAuthor:i.author,limit:String(o)},t),c=[a.recommended,...a.ready].filter(m=>m!==null).map(m=>({...m,reasons:"reasons"in m?m.reasons:["ranked ready candidate"]}));return Ev(c.slice(0,o),e,t,i)}function Sv(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 Ev(e,t,n,r={},o=ks){let s=0;for(let a of e){s+=1;try{let c=await o(a.id,t,n,r),m={...c,recommendation:a,attempts:s,available:!0};if(!c.skipped)return m}catch(c){if(!Jf(c))throw c}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:C(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[Yf]};let i=s===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:Yf,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 Ss(e,t,n,r={}){let o=E(process.cwd(),n.path);await R(o);let s=await T(o),i=C(r.author,s.author_default),a=vn(i),c=r.ownershipReleaseBypass===!0,m=null,u;try{u=await ne({pmRoot:o,settings:s,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){_r(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 Ba({pmRoot:o,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 Tv=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function Qf(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 rc(e,t){return oc(e,t,{operation:"close"})}function oc(e,t,n){let r=Qf(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new l("Close reason text is required because governance.require_close_reason is enabled",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:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function sc(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],s=o.filter(m=>m.kind==="blocked_by"),i=e.blocked_reason!==void 0,a=[];if(r&&(delete e.blocked_by,a.push("blocked_by")),i&&(delete e.blocked_reason,a.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let m=o.filter(u=>u.kind!=="blocked_by");m.length>0?e.dependencies=m:delete e.dependencies,a.push("dependencies")}let c=[...new Set([...n?[n]:[],...s.map(m=>m.id)])];return c.length===0?{changedFields:a,warnings:[]}:{changedFields:a,warnings:[t.orderingEdges==="preserve"?`closed_preserved_predecessors:${e.id}:${c.join(",")}`:`closed_removed_predecessors:${e.id}:${c.join(",")}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="781b5118-7b07-53c7-802f-c889cb797a96")}catch{}})();var Av=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function Cv(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 Rv(e){let t=[];for(let n of Av){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}async function Iv(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let s=o.trim();if(s===n)return!0;if(r.has(s))return!1;r.add(s),o=(await e(s))?.duplicate_of}return!1}function xv(e){return typeof e!="string"||e.trim().length===0}async function Ov(e,t,n,r){let o=n?.trim();if(!o)return;if(o===r)throw new l("An item cannot be closed as a duplicate of itself.",d.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=O(t,x()),i=new Map,a=async m=>{if(i.has(m))return i.get(m)??null;let u=await U(e,m,t.id_prefix,t.item_format,s.type_to_folder);if(!u)return i.set(m,null),null;let{document:p}=await V(u,{schema:t.schema});return i.set(m,p.metadata),p.metadata},c=await a(o);if(!c)throw new l(`Duplicate target "${o}" was not found. Create or locate the canonical item first.`,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 ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await Iv(a,c.duplicate_of,r))throw new l(`Circular duplicate reference detected. Target "${o}" 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 "${o}" 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 Pv(e,t,n){return e.filter(r=>r.parent===t&&!Z(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function Lv(e,t,n){let r=new Map(e.map(a=>[a.id.trim().toLowerCase(),a])),o=Of(e),s=t.trim().toLowerCase(),i=n.blocked_statuses;return e.filter(a=>i.has(a.status)).map(a=>({item:a,blockerIds:o.get(a.id.trim().toLowerCase())})).filter(({blockerIds:a})=>a.includes(s)).filter(({blockerIds:a})=>a.every(c=>{if(c===s)return!0;let m=r.get(c);return m!==void 0&&Z(m.status,n)})).map(({item:a,blockerIds:c})=>({id:a.id,blocker_ids:c})).sort((a,c)=>a.id.localeCompare(c.id))}async function Nv(e,t,n,r,o,s){let i=Lv(n,r,s),a=[];for(let c of i)try{let m=await ne({pmRoot:e,settings:t,id:c.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(u){let p=u.metadata.dependencies??[],f=p.filter(g=>{let y=g.id.trim().toLowerCase();return g.kind!=="blocked_by"||!c.blocker_ids.includes(y)});u.metadata.status=s.open_status,delete u.metadata.blocked_by,delete u.metadata.blocked_reason,u.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,f.length>0?u.metadata.dependencies=f:delete u.metadata.dependencies;let _=["status","blocked_by","blocked_reason","unblock_note"];return f.length!==p.length&&_.push("dependencies"),{changedFields:_}}});a.push(`auto_unblocked:${m.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(m){let u=m instanceof Error?m.message.replace(/\s+/g," ").trim():"unknown";a.push(`auto_unblock_failed:${c.id}:${u}`)}return a}function Fv(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:s}of r){if(typeof o!="string")continue;let i=o.trim();i.length!==0&&(e[s]=i,n.push(s))}return n}function Mv(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:s}of r)xv(e[o])&&(e[o]=s,n.push(o));return n}function $v(e,t,n,r){let o=[];if(t!=="off"){let s=Rv(e);if(s.length>0){let i=s.map(a=>a.label);if(t==="strict"){let a=s.map(m=>`--${m.key.replaceAll("_","-")}`),c=["--pm-path",r,"update",e.id,...a.flatMap(m=>[m,"<value>"])];throw new 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:Po(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}o.push(`close_validation_missing_fields:${e.id}:${i.join(",")}`)}if(n.length>0){if(t==="strict")throw new 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);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function Dv(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function Uv(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function Gv(e,t){if(Z(e.status,t.statusRegistry)&&!t.force)throw new l(`Item ${e.id} is already terminal; use --force to close again.`,d.CONFLICT);let n=Fv(e,t.options),r=Mv(e,t.duplicateOf),o=$v(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let i=["status","closed_at",...s?["completed_at"]:[],...Dv(e,t.closeReason),...n];if(vp(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(...Uv(e));let a=sc(e,t.lifecyclePolicy);return i.push(...a.changedFields),o.push(...a.warnings),{changedFields:i,...o.length>0?{warnings:o}:{}}}async function Zf(e,t,n,r){let o=E(process.cwd(),r.path);await R(o);let s=await T(o),i=D(s.schema),a=C(n.author,s.author_default),c=O(s,x()).type_to_folder,m=await U(o,e,s.id_prefix,s.item_format,c);if(!m)throw await it(o,e,s.id_prefix,c);let u=await Ov(o,s,n.duplicateOf,m.id),p={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},f=rc({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},p.requireCloseReason).closeReason,_=Cv(n.validateClose)??s.governance.close_validation_default,g=await ce(o,s.item_format,c,void 0,s.schema),y=Pv(g,m.id,i),h=new Date().toISOString(),b=n.completedAt===void 0?h:te(n.completedAt,new Date(h),"completed-at"),v=await ne({pmRoot:o,settings:s,id:m.id,op:"close",author:a,message:n.message,force:n.force,mutate(k){return Gv(k.metadata,{pmRoot:o,statusRegistry:i,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:f,closedAt:h,completedAt:b,lifecyclePolicy:p})}});return{item:v.item,changed_fields:v.changedFields,warnings:[...v.warnings,...await Nv(o,s,g,m.id,a,i)]}}function dt(e,t,n,r){return Zf(e,t,n,r)}import jv from"fast-json-patch";import ic 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]="db5f3a6d-9ae5-5f9b-bedf-766b2b79324c")}catch{}})();function qv(e,t){return op(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Kv(e){let t=Ea(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Ye(Ht(t))}async function zv(e,t,n,r){let o=await U(e,t,n.id_prefix,n.item_format,r);if(o){let c=Re(e,o.id),m=await Qu({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"});return{id:o.id,historyPath:c,located:o,historyPolicyWarnings:m.warnings}}let s=we(t,n.id_prefix),i=va(t),a=s===i?[s]:[s,i];for(let c of a){let m=Re(e,c);if(await P(m))return{id:c,historyPath:m,located:null,historyPolicyWarnings:[]}}throw new l(`Item ${t} not found`,d.NOT_FOUND)}function Bv(e,t){let n=tr(e),r=tr(t),o=jv.compare(n,r),s=new Set;for(let i of o){if(i.path==="/body"||i.path.startsWith("/body/")){s.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];s.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(s).sort((i,a)=>i.localeCompare(a))}async function Hv(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 U(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),r=n?await V(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 Vv(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Kv(t),originalRaw:null}}function Wv(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 Yv(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await _e(e.existingItemPath,e.resolvedOriginalRaw),await ic.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await _e(e.existingItemPath,e.resolvedOriginalRaw);return}await ic.rm(e.restoredItemPath,{force:!0})}async function Jv(e){return[...await W({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await W({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function Jt(e,t,n,r){let o=E(process.cwd(),r.path);await R(o);let s=await T(o),i=O(s,x()),a=await zv(o,e,s,i.type_to_folder),c=a.id,m=await q(a.historyPath),u=await Sn(a.historyPath,c);if(u.length===0)throw new l(`No history exists for ${c}; restore is unavailable.`,d.NOT_FOUND);let p=qv(t,u),f=sp(Ea(u,p.historyIndex),p),_=Hu(f,{schema:s.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 V(a.located,{schema:s.schema}):null)?.raw??null,h=C(n.author,s.author_default),b=await be(o,c,s.locks.ttl_seconds,h,!!n.force,s.governance.force_required_for_stale_lock,s.locks.wait_ms);try{let{loadedItemUnderLock:v,existingItemPath:k}=await Hv({pmRoot:o,resolvedId:c,subject:a,settings:s,typeToFolder:i.type_to_folder,historyRawBeforeLock:m,currentItemRawBeforeLock:y}),I="toon",A=Vv(v,u),N=Wv({document:A.document,author:h,force:n.force,enforcement:s.governance.ownership_enforcement,resolvedId:c}),M=Bv(A.document,_);await Lo({pm_root:o,operation:"restore",before:A.document,after:_,changed_fields:M,sdk:jo({pmRoot:o,settings:s,typeToFolder:i.type_to_folder})});let fe=je(_,{format:I,schema:s.schema}),ee=qt(o,_.metadata.type,c,I,i.type_to_folder),ge=await Tn(o,h),me=[];try{await _e(ee,fe),k&&ee!==k&&await ic.rm(k);let ht=qe({nowIso:S(),author:h,op:"restore",before:A.document,after:_,message:n.message});try{await Ct(a.historyPath,ht)}catch(gt){throw await Yv({existingItemPath:k,resolvedOriginalRaw:A.originalRaw,restoredItemPath:ee}),gt}me=await An({pmRoot:o,preferredFormat:s.item_format,typeToFolder:i.type_to_folder,schema:s.schema,itemPath:ee,previousItemPath:k??void 0,document:_})}finally{await ge()}let Ue=await Jv({restoredItemPath:ee,historyPath:a.historyPath,before:A.document,after:_});yn({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:A.document.metadata.status,status:_.metadata.status,previous:Bt(A.document.metadata,M),current:Bt(_.metadata,M),changed_fields:M});let _t=u[p.historyIndex];return{item:_.metadata,restored_from:{kind:p.kind,target:p.raw,history_index:p.historyIndex+1,entry_ts:_t.ts,entry_op:_t.op},changed_fields:M,warnings:[...a.historyPolicyWarnings,...N,...me,...Ue]}}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]="a97a3cf0-beef-5967-8f5b-2372a6c9f2f7")}catch{}})();var t_=1,ac="close-many",Xv=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function Qv(e,t){return lr(e,t,{includePagination:!1})}function Zv(e,t){return lr(e,t)}function ek(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 tk(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function nk(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 rk(e,t){let n=D(t.schema),r=O(t,x()),o=await ce(e,t.item_format,r.type_to_folder,void 0,t.schema),s=new Map,i=new Map;for(let a of o){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),Z(a.status,n)))continue;let c=s.get(a.parent);c?c.push(a.id):s.set(a.parent,[a.id])}for(let a of s.values())a.sort((c,m)=>c.localeCompare(m));return{childrenByParent:s,parentByChild:i}}function e_(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,s=t.get(e),i=[],a=new Set,c=!1;for(;s!==void 0&&!a.has(s);){let m=n?.get(s);if(m!==void 0){o+=m+1;break}a.add(s),i.push(s),o+=1,s=t.get(s)}if(s!==void 0&&a.has(s)&&(c=!0),!c){n?.set(e,o);for(let[m,u]of i.entries())n?.set(u,o-m-1)}return o}async function ok(e){let t=await Bo(e.pmRoot,ac,e.rollbackId,t_),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await Ho(t.items,(o,s)=>Jt(o,s,{author:e.options.author,message:n,force:!0},e.global));return{...zt({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 sk(e,t,n,r,o){return e.map(s=>{let i=(t.get(s.id)??[]).filter(c=>!n.has(c)),a=!n_(s,r,o);return{id:s.id,title:typeof s.title=="string"?s.title:"",status:s.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function ik(e){let t=await zo(e.pmRoot,ac,e.checkpointId,{schema_version:t_,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function ak(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await dt(r.id,e.reason,e.closeOptions,e.global);t.push({id:r.id,status:"closed",changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){t.push({id:r.id,status:"failed",error:hn(o)})}}return{rows:t,closedIds:n}}function ck(e){return typeof e.rollback=="string"?e.rollback:void 0}function dk(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(Zv(e.list,e.status))throw new l("Rollback mode does not accept filter options",d.USAGE)}function lk(e){if(!Qv(e.list,e.status))throw new l(`close-many requires at least one filter to scope the close (for example: ${Xv}). Refusing to match every item.`,d.USAGE)}function mk(e,t){let n=new Map;return[...e].sort((r,o)=>{let s=e_(o.id,t,n)-e_(r.id,t,n);return s!==0?s:r.id.localeCompare(o.id)})}function n_(e,t,n){return n||!Z(e.status,t)}function uk(e,t,n){return new Set(e.filter(r=>n_(r,t,n)).map(r=>r.id))}async function pk(e){lk(e.options);let t=D(e.settings.schema),n=nk(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await ct(e.options.status,tk(e.options.list),e.global),{childrenByParent:s,parentByChild:i}=await rk(e.pmRoot,e.settings),a=mk(o.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],m=c.length===0?[]:(await ct(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,u=new Set(m.map(f=>f.id)),p=uk(a,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:a,unmatchedIds:c.length===0?void 0:c.filter(f=>!u.has(f)),planRows:sk(a,s,p,t,r)}}function fk(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!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function _k(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 ik({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 r_(e,t){let n=E(process.cwd(),t.path);await R(n);let r=await T(n),o=e.dryRun===!0,s=ck(e);if(ek(e.list),s!==void 0)return dk(e,s),ok({pmRoot:n,rollbackId:s,options:e,global:t});let i=await pk({pmRoot:n,settings:r,options:e,global:t});if(o)return fk(i);let a=new Set(i.planRows.filter(b=>b.action==="close").map(b=>b.id)),c=S(),m=Ko(ac,c),u=await _k({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 ak({matched:i.matched,closableIds:a,reason:i.reason,closeOptions:p,global:t}),g=f.filter(b=>b.status==="closed").length,y=f.filter(b=>b.status==="skipped").length,h=f.filter(b=>b.status==="failed").length;return{...zt({applied:g,skipped:y,failed:h,unmatched:i.unmatchedIds?.length??0}),mode:"apply",matched_count:i.matched.length,dry_run:!1,...i.reason!==void 0?{reason:i.reason}:{},filters:i.listed.filters,...i.validateCloseMode?{validate_close:i.validateCloseMode}:{},...u?{checkpoint:u}:{},closed_count:g,skipped_count:y,failed_count:h,rows:f,ids:_,...i.unmatchedIds!==void 0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}import{readFile as hk}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]="5167b367-26cf-52d5-8040-bb001ce3592a")}catch{}})();async function cc(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",s=Number(n)+Number(r)+Number(o);if(s===0)return;if(s>1)throw new 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",at(e))??"",emptyFlag:"--add"};if(r)return hr(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new l("--file path cannot be empty",d.USAGE);if(i==="-")return hr(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await hk(i,"utf8"),emptyFlag:"--file"}}catch(a){if(nc(a)&&jt(a))throw new l(`--file path not found: ${i}. Use --file - to read stdin.`,d.USAGE);let c=a instanceof Error?a.message:String(a);throw new l(`Failed to read --file path "${i}": ${c}. Use --file - to read stdin.`,d.USAGE)}}async function gk(e,t){let n=e.edit,r=e.delete,o=n!==void 0,s=r!==void 0;if(o&&s)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(s){if(await cc(e,t)!==void 0)throw new l("--delete does not take comment text",d.USAGE);return{mode:"delete",index:r}}if(o){let c=await cc(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 cc(e,t);return i===void 0?{mode:"list"}:{mode:i.emptyFlag==="--add"?"add":i.emptyFlag==="--stdin"?"stdin":"file",value:i.value,emptyFlag:i.emptyFlag}}async function o_(e,t,n){let r=xt(),o=await gk(t,r),s=o.mode==="add"||o.mode==="edit",i=o.value??"";return $n(e,t,n,{input:{...o,rawValue:t.add??i,value:s?Mn(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm comments pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="93184f29-f215-5413-9628-fb5b34523995")}catch{}})();async function s_(e,t,n){return $n(e,t,n,{input:await vs(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>Mn(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 yk(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 bk(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 wk(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 i_(e,t,n){let r=yk(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new l("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",d.USAGE,{code:"structured_event_input_conflict"});let s=r===void 0?void 0:H(r),i=[t.since,t.eventType].some(g=>g!==void 0),a=wk(t.since),c=rr(t.limit),m=await $n(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await vs(s===void 0?t:{add:s},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:g=>Mn(g),createEntry:g=>r===void 0?g:{...g,format:"json",data:r,event_type:bk(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm notes pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}}),u=t.eventType?.trim(),p=m.notes.filter(g=>{let y=[g.format==="json",g.data!==void 0].every(Boolean),h=[a===void 0,Date.parse(g.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),b=[!u,g.event_type===u].includes(!0);return[!i,[y,h,b].every(Boolean)].includes(!0)}),f=i?tc(p,c):p,_=f.filter(g=>g.format==="json").length;return{...m,notes:f,count:f.length,...i?{total_count:p.length,returned_count:f.length,has_more:f.length<p.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d6f359cb-2bc9-5f96-8789-db91512d0bd5")}catch{}})();function gr(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new l(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,d.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function yr(e,t,n=Ot()){for(let r of t??[])try{bl(e,r.id,r.kind,n)}catch(o){throw new l(hn(o),d.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function a_(e,t){return(await V(e,{schema:t})).document.metadata.created_at}async function vk(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await U(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:a_(n,t.schema)}function kk(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 Sk(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:s})=>s===null?[]:[[o,s]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await a_(n.get(o),e.context.schema)])));for(let o of e.holders){let s=await vk(o,e.context);if(s!==void 0)for(let i of t){let a=r.get(i.id),c=Date.parse(s),m=Date.parse(a);if(!(Number.isFinite(c)&&Number.isFinite(m)&&c>m))throw kk({holder:o,dependency:i,sourceCreatedAt:s,targetCreatedAt:a,registry:e.registry})}}}async function Xt(e){let t=e.registry??Ot(),n=(e.dependencies??[]).filter(i=>!Op(i.source_kind)),r=[...new Set(n.map(i=>i.id))],o=await Promise.all(r.map(async i=>({target:i,located:await U(e.pmRoot,i,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=o.filter(({located:i})=>i===null).map(({target:i})=>i).sort((i,a)=>i<a?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new l(`Dependency target${s.length===1?"":"s"} not found: ${s.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:s,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${s.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await Sk({dependencies:n,missingTargets:s,resolutions:o,holders:e.holders??[],registry:t,context:e}),s.map(i=>`dependency_target_unresolved:${i}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dcbb6070-7457-5454-abf1-fa8153c8efd6")}catch{}})();function Es(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Ts(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function As(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(qr.includes(t))return t;let n=de(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 Cs(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 Ek=new Set(["none","null"]);function Rs(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function ze(e){return e===void 0?!1:Ek.has(e.trim().toLowerCase())}function Is(e,t,n){if(!ze(e))return;let r=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${r}`.trim(),d.USAGE)}function Se(e,t,n){if(!e||e.length===0||!e.some(s=>ze(s)))return;let o=n?` ${n}`:"";throw new l(`${t} no longer accepts "none" or "null".${o}`.trim(),d.USAGE)}function xs(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 o=r;if(!o.some(a=>ze(a)))continue;if(o.filter(a=>!ze(a)).length>0)throw new l(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,d.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2fcfbe50-039b-5031-8b18-a208908a0d87")}catch{}})();function d_(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 dc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Ee(e,t,n){if(!t.includes(e))throw new l(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,d.USAGE);return e}var l_=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Tk(e,t){return t==="defined"?e!==void 0:!!e}function c_(e,t,n){if(!Tk(e,n))return;let r=de(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new l(`--event ${t} must be an integer >= 1`,d.USAGE);return r}function Ak(e,t,n){let r=e?te(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 Ck(e){return Array.from(new Set(dc(e).map(t=>Ee(t.toLowerCase(),ul,"event weekday")))).sort((t,n)=>ji(t)-ji(n))}function Rk(e){return Array.from(new Set(dc(e).map(t=>{let n=de(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 Ik(e,t){return Array.from(new Set(dc(e).map(n=>te(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function m_(e,t,n,r){let o=e.recur_freq?.trim(),s=e.recur_interval?.trim(),i=e.recur_count?.trim(),a=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),m=e.recur_by_month_day?.trim(),u=e.recur_exdates?.trim();if(![o,s,i,a,c,m,u].some(k=>k!==void 0))return;if(!o)throw new l("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",d.USAGE);let f=Ee(o.toLowerCase(),ml,"event recurrence frequency"),_=c_(s,"recur_interval",r),g=c_(i,"recur_count",r),y=Ak(a,t,n),h=Ck(c),b=Rk(m),v=Ik(u,n);return{freq:f,interval:_,count:g,until:y,by_weekday:h.length>0?h: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 u_="--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.",xk="--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).",Ok=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,Pk=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,f_=1e3,lc=60*f_,Lk=60*lc;function p_(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 Nk(e,t){let n=new Date(e),r=t.trim(),o=Ok.exec(r);if(o){let a=o[1]==="-"?-1:1,c=Number.parseInt(o[2],10)*a;return p_(n.getTime()+c*lc,r)}let s=Pk.exec(r);if(s){let[,a,c,m,u]=s;if(c||m||u){let f=a==="-"?-1:1,_=Number.parseInt(c??"0",10),g=Number.parseInt(m??"0",10),y=Number.parseInt(u??"0",10),h=_*Lk+g*lc+y*f_;return p_(n.getTime()+f*h,r)}}let i=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return te(i,n,"event.duration")}function __(e,t,n,r){if(t&&n)throw new l(xk,d.USAGE);if(n){let s=Nk(e,n);if(s<e)throw new l(u_,d.USAGE);return s===e?void 0:s}if(!t)return;let o=te(t,r,"event.end");if(o<e)throw new l(u_,d.USAGE);if(o!==e)return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd41d2bf-7be0-55ee-9048-a9d5092a9a21")}catch{}})();var Fk=["at","date","text","title"],Mk=["start","date","end","duration","title","description","location","timezone","all_day",...l_],$k=["key","value"];function h_(e,t){return t==="trimmed"?e?.trim():e}function Dk(e,t){return t==="defined"?e!==void 0:!!e}function Os(e,t,n){return e.map(r=>{let o=oe(r,"--reminder");Ke(o,"--reminder",Fk);let s=h_(o.at??o.date,n.valueMode),i=h_(o.text??o.title,n.valueMode);if(!s||!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:te(s,t,"reminder.at"),text:a}})}function Ps(e,t,n){return e.map(r=>{let o=oe(r,"--event");Ke(o,"--event",Mk);let s=(o.start??o.date)?.trim();if(!s)throw new l("--event requires start=<iso|relative> or date=<iso|relative>",d.USAGE);let i=te(s,t,"event.start"),a=o.end?.trim(),c=o.duration?.trim(),m=__(i,a,c,t),u=o.title,p=o.description,f=o.location,_=o.timezone,g=u?.trim(),y=p?.trim(),h=f?.trim(),b=_?.trim(),v=[["title",u,g],["description",p,y],["location",f,h],["timezone",_,b]];for(let[N,M,fe]of v)if(M!==void 0&&!fe)throw new l(`--event ${N} must not be empty`,d.USAGE);let k=o.all_day?.trim(),I=m_(o,i,t,n.recurrenceEmptyNumericGuard),A=Dk(k,n.allDayEmptyGuard)?d_(k,"--event all_day"):void 0;return{start_at:i,end_at:m,title:g,description:y,location:h,all_day:A,timezone:b,recurrence:I}})}function Ls(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 o,s;if(r.includes(",")||r.includes(`
5
+ `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=oe(r,"--type-option");Ke(a,"--type-option",$k),o=a.key?.trim(),s=a.value?.trim()}else{let a=r.indexOf("="),c=r.indexOf(":"),m=a;if(a<=0&&c>0&&(m=c),m<=0||m===r.length-1)throw new l("--type-option requires key=value or key=<name>,value=<value> entries",d.USAGE);o=r.slice(0,m).trim(),s=r.slice(m+1).trim()}if(!o||!s)throw new l("--type-option requires key and value",d.USAGE);t[o]=s}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[0])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39a36d42-29b1-5f0f-a8b2-f3bfc0ef78c2")}catch{}})();var Uk="hierarchy-integrity";async function Ns(e){let t=e.required?await be(e.pmRoot,Uk,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e009d7f9-8d50-519a-9a43-632efd3bf443")}catch{}})();var Gk=new Set(["event","meeting","reminder","milestone","decision","adr"]);function g_(e,t,n,r){if(Gk.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=Ro("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm start-task ${e}`,to_status:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="44e6a87d-0ca5-53af-b199-b66bb2b98fb5")}catch{}})();var Qt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],jk=new Set(Qt),qk=Qt.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),Kk=new RegExp(`^(?:[-*+]\\s+)?(?:${qk})\\s*[:=]`,"i");function Fs(e){return e.startsWith("```")||e.includes(`
6
+ `)?!0:Kk.test(e)}function Ms(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!jk.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw new l(`${t} provides key "${o}" more than once after case normalization`,d.USAGE);n[i]=s}if(r.length>0)throw new l(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${Qt.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:o,...s}=n;return{...s,command:s.command??o}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64adcc3c-3646-5990-9442-4c4374a2dc7d")}catch{}})();var tn=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT",ar,qp,"FORCE_COLOR"]),Us=/^[A-Za-z_][A-Za-z0-9_]*$/,en=["schema","tracker","auto"],y_=["source","isolated","snapshot"];function br(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=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=o.slice(0,s).trim(),a=o.slice(s+1);if(!Us.test(i))throw new l(`${t} env_set key "${i}" is invalid`,d.USAGE);if(tn.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 wr(e,t){if(!e)return;let n=On(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(!Us.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,d.USAGE);if(tn.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,d.USAGE)}return n}function Gs(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 js(e,t){if(!e)return;let n=e.trim().toLowerCase();if(en.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${en.join(", ")}`,d.USAGE)}function nn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(y_.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${y_.join(", ")}`,d.USAGE)}function rn(e){if(!e)return;let t=On(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Dn(e,t,n){let r=rn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(s){throw new l(`${t} ${n} includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`,d.USAGE)}return r}}function qs(e,t){if(!e)return;let n=de(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 Ks(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+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 zs(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,d.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+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 zk=new Set(Qt);function Bs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bk(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!zk.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw t(`provides key "${o}" more than once after case normalization`);n[i]=s}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${Qt.join(", ")}.`);return n}function Zt(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 $s(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=o.filter(i=>i.length>0);return s.length>0?s:void 0}function b_(e,t,n){let r=$s(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`)}return r}}function Ds(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 Hk(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:Ds(n,"timeout_seconds",t),s=r===void 0?void 0:Ds(r,"timeout",t);if(o!==void 0&&s!==void 0&&o!==s)throw t("timeout and timeout_seconds must match when both are provided");let i=o??s;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function Vk(e,t){let n=Zt(e,"scope",t);if(n===void 0)return"project";if(!tt.includes(n))throw t(`field "scope" must be one of: ${tt.join(", ")}`);return n}function Wk(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Bs(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Us.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(tn.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=s}return Object.keys(r).length>0?r:void 0}function Yk(e,t){let n=$s(e,"env_clear",t);if(n){for(let r of n){if(!Us.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(tn.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function Jk(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 Xk(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=Ds(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 Qk(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Bs(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(s)}return Object.keys(r).length>0?r:void 0}function Zk(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Bs(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=Ds(s,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function eS(e,t,n){let r=f=>new l(`${n} ${t} ${f}`,d.USAGE);if(!Bs(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Qt.join(", ")}.`);let o=Bk(e,r),s=Zt(o,"command",r),i=Zt(o,"cmd",r);if(s!==void 0&&i!==void 0&&s!==i)throw r("command and cmd must match when both are provided");let a=s??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=Zt(o,"path",r),m=Zt(o,"pm_context_mode",r);if(m!==void 0&&!en.includes(m))throw r(`field "pm_context_mode" must be one of: ${en.join(", ")}`);let u=nn(Zt(o,"workspace_context_mode",r),`${n} ${t}`),p=Zt(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:Vk(o,r),timeout_seconds:Hk(o,r),pm_context_mode:m,workspace_context_mode:u,env_set:Wk(o,r),env_clear:Yk(o,r),shared_host_safe:Jk(o,"shared_host_safe",r),assert_stdout_contains:$s(o,"assert_stdout_contains",r),assert_stdout_regex:b_(o,"assert_stdout_regex",r),assert_stderr_contains:$s(o,"assert_stderr_contains",r),assert_stderr_regex:b_(o,"assert_stderr_regex",r),assert_stdout_min_lines:Xk(o,r),assert_json_field_equals:Qk(o,r),assert_json_field_gte:Zk(o,r),note:p!==void 0&&p.trim().length>0?p.trim():void 0}}function w_(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(s){throw new l(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,d.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new l(`${t} array must include at least one linked-test entry object`,d.USAGE);return o.map((s,i)=>eS(s,o.length>1?`entry ${i+1}`:"entry",t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0062e981-158a-5e6a-b028-6c7cef0f59ba")}catch{}})();var mc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],uc=[{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"}],v_=[...mc,...uc],Hs=[{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 Vs(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let r of e.raw){let o=r.trim().toLowerCase();if(!o)throw new l("--unset values must not be empty",d.USAGE);if(ze(o))throw new l('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',d.USAGE);let s=e.resolveDefinition(o);if(!s)throw new l(`Unsupported --unset field "${r}". Supported fields: ${e.supportedFields}`,d.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function Ws(e,t,n){let r=e.trim().toLowerCase();if(!n)return;let o=n.command_to_fields?.get(t)??[];for(let s of o){if(s.allow_unset===!1)continue;let i=new Set;if(typeof s.key=="string"&&s.key.length>0&&i.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&i.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(i.add(s.cli_flag.replaceAll("-","_").toLowerCase()),i.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let a of s.cli_aliases)typeof a!="string"||a.length===0||(i.add(a.replaceAll("-","_").toLowerCase()),i.add(a.toLowerCase()));if(i.has(r))return{optionKey:s.key,metadataKey:s.metadata_key}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="002f45a2-edc3-5aa0-9af8-d9b1dfecc097")}catch{}})();var tS={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function nS(e){return tS[e]}function pc(e){return nS(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]="02c41ea1-8d4e-5239-b95a-a07210b63d7f")}catch{}})();var rS=["strict","progressive"],oS=["lightweight"],T_=new Set(["Reminder","Meeting","Event"]),sS=new Set(["author","created_at","text"]),_c=[...v_,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...Hs],iS=(()=>{let e=new Map;for(let t of _c)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Ys=new Map(_c.map(e=>[e.optionKey,e.canonical])),aS=_c.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function cS(e,t){let n=X(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function dS(e,t){let n=e.default_status;if(n!==void 0){let r=X(n,t);if(r)return r}return t.open_status}function fc(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 lS=Rs();function A_(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s};ze(t.template)&&(t.template=void 0);let r=new Set([...Ys.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!ze(s))continue;let i=o==="rank"?"order":Ys.get(o)??o;n(i),t[o]=void 0}return ve(e,xs(t,lS))}function ue(e){if(e!==void 0)return e}function mS(e,t){return Vs({raw:e,supportedFields:aS,resolveDefinition:n=>iS.get(n)??Ws(n,"create",t)})}var k_=["id","kind","type","author","created_at","source_kind"],Js=["path","scope","note"];function uS(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(s=>{let i=s.trim(),a=hc(i,k_);gr(i,a);let c=a?oe(s,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",k_);let m=ue(c.id),u=pS(ue(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=or(ue(c.source_kind)),f=ue(c.author);return{id:sr(m,n,p),kind:Ee(u,Gt,"dependency kind"),created_at:fc(c.created_at,t),author:f??r,source_kind:p??"cli:create:dep",author_source:f?"asserted":"detected"}}),explicitEmpty:!1})}function pS(e){return typeof e=="string"?Wr(e)??e.trim():e}function hc(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:Yo(e)}function sn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Se(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(i=>{let a=i.trim(),c=()=>{if(a.length===0)throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:n,author:r,text:a}},m;try{m=oe(i,e)}catch(f){if(e==="--comment"||e==="--note"||e==="--learning")return c();throw f}if(Object.keys(m).filter(f=>!sS.has(f)).length>0)return{created_at:fc(m.created_at,n),author:ue(m.author)??r,text:a};let p=m.text??"";if(p==="")throw new l(`${e} requires text=<value>`,d.USAGE);return{created_at:fc(m.created_at,n),author:ue(m.author)??r,text:p}}),explicitEmpty:!1})}function gc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--file","Use --clear-files to clear linked files."),{values:e.map(n=>{let r=n.trim(),o=hc(r,Js),s=o?oe(n,"--file"):{path:r};if(o&&Ke(s,"--file",Js),!s.path)throw new l("--file requires path=<value> or a bare file path",d.USAGE);return{path:s.path,scope:Ee(s.scope??"project",tt,"file scope"),note:ue(s.note)}}),explicitEmpty:!1})}function yc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(n=>{let r=n.trim(),o=Fs(r)?Ms(oe(n,"--test"),"--test"):{command:r},s=ue(o.command),i=ue(o.path);if(!s)throw new l("--test requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);let a=ue(o.timeout_seconds),c=ue(o.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:s,path:i,scope:Ee(o.scope??"project",tt,"test scope"),timeout_seconds:m?de(m,"timeout_seconds"):void 0,pm_context_mode:js(o.pm_context_mode,"--test"),workspace_context_mode:nn(o.workspace_context_mode,"--test"),env_set:br(o.env_set,"--test"),env_clear:wr(o.env_clear,"--test"),shared_host_safe:Gs(o.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:rn(o.assert_stdout_contains),assert_stdout_regex:Dn(o.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:rn(o.assert_stderr_contains),assert_stderr_regex:Dn(o.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:qs(o.assert_stdout_min_lines,"--test"),assert_json_field_equals:Ks(o.assert_json_field_equals,"--test"),assert_json_field_gte:zs(o.assert_json_field_gte,"--test"),note:ue(o.note)}}),explicitEmpty:!1})}function bc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(n=>{let r=n.trim(),o=hc(r,Js),s=o?oe(n,"--doc"):{path:r};if(o&&Ke(s,"--doc",Js),!s.path)throw new l("--doc requires path=<value> or a bare doc path",d.USAGE);return{path:s.path,scope:Ee(s.scope??"project",tt,"doc scope"),note:ue(s.note)}}),explicitEmpty:!1})}function fS(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Os(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function _S(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--event","Use --clear-events to clear linked events."),{values:Ps(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function hS(e,t,n,r=[]){let o=[...Kr.filter(s=>e[s]!==void 0),...r.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(o))}function gS(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function S_(e,t,n){let r=Wn("create",e);if(!r)throw new l(`Unsupported ${n} entry "${e}" for type "${t}"`,d.CONFLICT);return r}function yS(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 C_(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 bS(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(S_(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(S_(r,e.name,"required_create_repeatables"));return n}function wS(e,t,n,r){for(let o of e)if(!(!C_(t,o)&&!n.has(o)))throw new l(`Option ${ye("create",o)} is disabled for type "${r}" by command_option_policies`,d.USAGE)}function vS(e,t,n){if(t!=="strict")return;let r=e.filter(s=>n.has(s)&&!pc(s));if(r.length===0)return;let o=[...new Set(r.map(s=>ye("create",s)))].sort((s,i)=>s.localeCompare(i));throw new l(`Strict create mode requires concrete values for ${o.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,d.USAGE)}function kS(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Se(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Ls(e),explicitEmpty:!1})}async function SS(e){return await Jo(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function ES(e){return at(e)?await SS(e):e}function TS(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new l(`Invalid --create-mode value "${e}". Allowed: ${rS.join(", ")}`,d.USAGE)}function AS(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: ${oS.join(", ")}`,d.USAGE)}function CS(e,t,n){let r=TS(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new l("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",d.USAGE);return"progressive"}function RS(e,t,n,r){let o=e.name,s=yS(t),i=bS(e,n),a=_n(e,"create",i);if(a.errors.length>0)throw new l(a.errors.join("; "),d.CONFLICT);wS(a.disabled,s,r,o),vS(a.required,n,r);let c=u=>u==="status"&&e.default_status!==void 0||r.has(u)&&pc(u)?!0:C_(s,u),m=a.required.filter(u=>!c(u));return[...new Set(m.map(u=>ye("create",u)))].sort((u,p)=>u.localeCompare(p))}var R_=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function IS(e,t){let n=[];for(let r of e){let o=r.match(R_);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function xS(e,t){return e.filter(n=>{let r=n.match(R_);return!r||r[2]!==t})}function OS(e,t,n,r){let o=xS(e,t);if(o.length===0)return;let s=I_(n,[],[],r.open_status);throw new l(o.join("; "),d.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function PS(e,t){let r=e.options.find(o=>o.key===t)?.values[0];return typeof r=="string"&&r.trim().length>0?r:"<value>"}function LS(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 I_(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],i=[...new Set([...s,...t])],a=new Set(["--title","--description","--type"]);for(let c of i)a.has(c)||(o.push(...LS(c,e.name,r)),a.add(c));for(let c of n){let m=PS(e,c);o.push("--type-option",`${c}=${m}`)}return o.join(" ")}function wc(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 NS(e){return xn(e)}function FS(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=Array.isArray(o)?[...o]:o;for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=Array.isArray(o)?[...o]:o);return n}function MS(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function $S(){let e=x();return e?e.commands.some(t=>t.action==="templates-show"||MS(t.command)==="templates show"):!1}function DS(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[o,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){r[o]=s;continue}if(Array.isArray(s)&&s.every(i=>typeof i=="string")){r[o]=[...s];continue}throw new l(`Templates package returned unsupported option value for "${o}" in template "${t}".`,d.GENERIC_FAILURE)}return r}async function US(e,t,n){if(!$S())throw new l("--template requires the templates package. Install it first (for example: pm install templates --project).",d.USAGE);let r=await No({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled){let o=r.warnings.length>0?` (${r.warnings.join(", ")})`:"";throw new l(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${o}`,d.USAGE)}return DS(r.result,e)}function GS(e){return R(e)}function K(e,t,n){return e.has(t)||n===void 0?void 0:ue(n)}function on(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var jS=new Set(["milestone","meeting","reminder","event"]);function x_(e,t,n,r){let o=t!==void 0,s=n!==void 0&&n.length>0,i=r!==void 0&&r.length>0;return jS.has(e.toLowerCase())&&!o&&!s&&!i}function qS(e,t,n,r,o){let s=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),x_(e,n,r,o)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function KS(e,t,n,r){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await Fo(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function zS(e,t,n,r,o,s){let i=es(o);if(ns(r,i,t.id_prefix),await U(e,i,t.id_prefix,t.item_format,n.type_to_folder))return{parent:i,warnings:[]};let c=we(i,t.id_prefix);return{parent:i,warnings:ts(c,s).warnings}}async function BS(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await zS(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function HS(e){if(e.explicitId===void 0)return nr(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||gp(t))throw new l("--id must not be empty or use a placeholder token",d.USAGE);let n=we(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 E_(e,t,n,r,o){let s=K(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let i=rs(r,s,o);return{value:i.value,warnings:i.warnings}}async function VS(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:s,status:i,statusExplicit:a,nowValue:c,author:m}=e,u=e.dependencyValues;if(s===void 0)return{dependencyValues:u,status:i};let p=we(s,n.id_prefix),f=await U(t,p,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:u,status:i};if((u??[]).some(y=>y.id===f.id&&y.kind==="blocked_by")||(u=[...u??[],{id:f.id,kind:"blocked_by",created_at:c,author:m,source_kind:"cli:create:blocked_by",author_source:"detected"}]),a)return{dependencyValues:u,status:i};let g=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((y,h)=>y.localeCompare(h))[0]??o.open_status;return{dependencyValues:u,status:g}}function WS(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let o=t.governance.create_default_type?.trim();if(o&&o.length>0&&he(o,n)){e.type=o;return}he("Task",n)&&(e.type="Task")}function YS(e,t){return e.options.filter(n=>Wn("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 JS(e,t,n,r,o){let s=e,i=[];if(s.template!==void 0){let g=s.template.trim();if(g.length===0)throw new l("--template must not be empty. Omit --template to disable template usage.",d.USAGE);let y=await US(g,t,n);s=A_(FS(y,s))}if(s.type===void 0&&WS(s,r,o),s.type===void 0)throw new l("Missing required option --type <value>",d.USAGE);let a=he(s.type,o);if(!a){let g=bp(s.type),y=g?he(g,o):void 0;if(y)i.push(`type_coercion:${s.type.trim()}:${y}`),s.type=y,a=y;else throw new l(Tt(s.type,o.types,At(n,r.schema)),d.USAGE)}let c=Hr(a,o);if(!c)throw new l(`Invalid type value "${s.type}"`,d.USAGE);let m=c.name,u=YS(c,s),p=u.map(g=>`${g.key}=${String(s[g.key])}`);if(p.length>0){s.typeOption=[...p,...s.typeOption??[]];for(let g of u)delete s[g.key]}let f=AS(s.schedulePreset);if(f!==void 0&&!T_.has(m))throw new l(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,d.USAGE);let _=CS(s.createMode,f,r.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:m,schedulePreset:f,createMode:_,warnings:i}}function XS(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of o)if(s.enabled){if(s.values&&s.values.length>0)throw new l(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,d.USAGE);n.add(s.metadataKey),r.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function QS(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=Ys.get(r)??r;throw new l(`Cannot combine --unset ${s} with ${ye("create",r)}`,d.USAGE)}}function ZS(e){let t=(n,r)=>{let o=Ys.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;Is(n,ye("create",r),s)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function eE(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 tE(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:s,type:i,createMode:a,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let m=c.map(_=>{let g=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${g}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),u=[I_(n,r,o,s),...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".'),T_.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 nE(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?It(t.tags):[];return Rn(n,t.addTags)}function rE(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=on(e,"order",n,o=>de(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new l("Order must be an integer",d.USAGE);return r}function oE(e,t,n,r,o,s){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?s:te(r.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:i,warnings:[]};let a=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:oc(a,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:i,warnings:[]}}async function sE(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:s,author:i,extensionFieldNames:a,afterDocument:c,beforeDocument:m,historyMessage:u,changedFields:p,nowValue:f,similarityCandidate:_,allowDuplicate:g}=e,y=qt(t,n,r,o.item_format,s.type_to_folder),h=Re(t,r),b=Ot(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(N=>b.resolve(N.kind)?.hierarchy),k=await Ns({pmRoot:t,author:i,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:v}),I=v,A=[];try{let N=await be(t,r,o.locks.ttl_seconds,i,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let M=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await ce(t,o.item_format,s.type_to_folder,void 0,o.schema):void 0;if(await U(t,r,o.id_prefix,o.item_format,s.type_to_folder))throw new l(`Item "${r}" already exists`,d.CONFLICT);if(M){let me=D(o.schema);os(M,[...M,c.metadata],r,Ue=>Z(Ue,me),b)}await Lo({pm_root:t,operation:"create",before:null,after:c,changed_fields:p,sdk:jo({pmRoot:t,settings:o,typeToFolder:s.type_to_folder})});let ee=await Tn(t,i,{required:o.governance.duplicate_detection_mode==="strict"&&g!==!0}),ge=[];try{o.governance.duplicate_detection_mode==="strict"&&g!==!0&&await Fn(_,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await _e(y,je(c,{format:o.item_format,schema:o.schema,extensionFieldNames:a}));try{let me=qe({nowIso:f,author:i,op:"create",before:m,after:c,message:u});await Ct(h,me)}catch(me){throw await fn(y),me}I&&(await k(),I=!1),ge=await An({pmRoot:t,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:y,document:c})}finally{await ee()}A=[...M?_s(M,[...M,c.metadata],r):[],...ge,...await W({path:y,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p}),...await W({path:h,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:m,after:c,changed_fields:p})],yn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:Bt(c.metadata,p),changed_fields:p})}finally{await N()}}finally{I&&await k()}return A}async function Pt(e,t){let n=A_(await ES(e)),r=E(process.cwd(),t.path);await GS(r);let o=await T(r),s=D(o.schema),i=We(o.schema),a=O(o,x()),c=await JS(n,t,r,o,a);n=c.resolvedOptions;let{typeDefinition:m,type:u,createMode:p}=c,f=mS(n.unset,i),{explicitUnsets:_,clearOptionKeys:g}=XS(n,f);QS(n,f),ZS(n);let y=RS(m,n,p,g),h=S(),b=C(ue(n.author),o.author_default),v=uS(n.dep,h,o.id_prefix,b),k=sn("--comment",n.comment,h,b),I=sn("--note",n.note,h,b),A=sn("--learning",n.learning,h,b),N=gc(n.file),M=yc(n.test);M.values=await Nn(M.values,b,h);let fe=bc(n.doc),ee=fS(n.reminder,h),ge=_S(n.event,h),me=kS(n.typeOption),Ue=Yn(u,me.values,a),_t=x(),ht=kt(_t),gt=zr(n.field,_t),yt=$u(n,i,u),Ii=new Set(yt.missing_required_flags),xi=i.definitions.filter(B=>Ii.has(`--${B.cli_flag}`));eE(gt,yt,f);let Vn=IS(Ue.errors,u),Dt=Vn.map(B=>`--type-option ${B}=<value>`),Vd=[...new Set([...y,...Dt,...yt.missing_required_flags])].sort((B,Ui)=>B.localeCompare(Ui));tE({combinedMissingFlags:Vd,typeDefinition:m,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:Vn,openStatus:s.open_status,type:u,createMode:p,missingRequiredRuntimeFields:xi}),OS(Ue.errors,u,m,s);let Ce=await HS({pmRoot:r,settings:o,typeRegistry:a,explicitId:n.id}),bt=n.status!==void 0?cS(n.status,s):dS(m,s),Oi=n.priority!==void 0?NS(n.priority):2,L=f.metadataKeys,Fe=nE(L,n),et=on(L,"deadline",n.deadline,B=>te(B,new Date(h),"deadline")),Mr=on(L,"estimated_minutes",n.estimatedMinutes,B=>In(B,"estimated-minutes")),wt=K(L,"acceptance_criteria",n.acceptanceCriteria),Pi=K(L,"definition_of_ready",n.definitionOfReady),Ve=rE(L,n),Li=K(L,"goal",n.goal),$r=K(L,"objective",n.objective),Vb=K(L,"value",n.value),Wb=K(L,"impact",n.impact),Yb=K(L,"outcome",n.outcome),Jb=K(L,"why_now",n.whyNow),Xb=K(L,"assignee",n.assignee),Qb=L.has("author")?void 0:ue(n.author)??b,Zb=K(L,"parent",n.parent),Wd=await KS(Zb,n,L,r),Ni=Wd.parent,ew=Wd.parentSource,tw=K(L,"reviewer",n.reviewer),nw=on(L,"risk",n.risk,B=>Ee(Es(B),un,"risk")),rw=on(L,"confidence",n.confidence,B=>As(B)),ow=n.allowMissingParent===!0&&o.validation.parent_reference==="strict_error"?"warn":o.validation.parent_reference,Yd=o.validation.sprint_release_format,Ut=[...c.warnings,...qS(u,Ce,et,ee.values,ge.values)],Jd=await BS({itemId:Ce,parent:Ni,pmRoot:r,settings:o,typeRegistry:a,policy:ow});Ni=Jd.parent,Ut.push(...Jd.warnings);let Xd=E_(L,"sprint",n.sprint,"sprint",Yd),sw=Xd.value;Ut.push(...Xd.warnings);let Qd=E_(L,"release",n.release,"release",Yd),iw=Qd.value;Ut.push(...Qd.warnings);let Zd=K(L,"blocked_by",n.blockedBy),el=await VS({pmRoot:r,settings:o,typeRegistry:a,statusRegistry:s,blockedBy:Zd,dependencyValues:v.values,status:bt,statusExplicit:n.status!==void 0,nowValue:h,author:b}),Fi=el.dependencyValues;yr(Ce,Fi),Ut.push(...await Xt({pmRoot:r,dependencies:Fi,idPrefix:o.id_prefix,itemFormat:o.item_format,typeToFolder:a.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ce,createdAt:h}],schema:o.schema})),bt=el.status;let aw=K(L,"blocked_reason",n.blockedReason),cw=K(L,"unblock_note",n.unblockNote),dw=K(L,"reporter",n.reporter),lw=on(L,"severity",n.severity,B=>Ee(Ts(B),pn,"severity")),mw=K(L,"environment",n.environment),uw=K(L,"repro_steps",n.reproSteps),tl=K(L,"resolution",n.resolution),pw=K(L,"expected_result",n.expectedResult),fw=K(L,"actual_result",n.actualResult),_w=K(L,"affected_version",n.affectedVersion),hw=K(L,"fixed_version",n.fixedVersion),gw=K(L,"component",n.component),yw=on(L,"regression",n.regression,B=>Cs(B)),bw=K(L,"customer_impact",n.customerImpact),Mi=wc(n.title,"--title"),$i=n.description??"",Dr=n.body??"",nl=await Fn({title:Mi,description:$i,body:Dr},{pmRoot:r,mode:o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Ut.push(...hs(nl));let Di=oE(bt,s,o,n,tl,h),ww=Di.closeReason,vw=bt===s.close_status?h:void 0,kw=Di.completedAt;Ut.push(...Di.warnings);let Ur=ga({id:Ce,title:Mi,description:$i,type:u,type_options:Ue.normalized,status:bt,closed_at:vw,completed_at:kw,close_reason:ww,priority:Oi,tags:Fe,created_at:h,updated_at:h,deadline:et,assignee:Xb,author:Qb,estimated_minutes:Mr,acceptance_criteria:wt,definition_of_ready:Pi,order:Ve,goal:Li,objective:$r,value:Vb,impact:Wb,outcome:Yb,why_now:Jb,parent:Ni,reviewer:tw,risk:nw,confidence:rw,sprint:sw,release:iw,blocked_by:Zd,blocked_reason:aw,unblock_note:cw,reporter:dw,severity:lw,environment:mw,repro_steps:uw,resolution:tl,expected_result:pw,actual_result:fw,affected_version:_w,fixed_version:hw,component:gw,regression:yw,customer_impact:bw,dependencies:Fi,comments:k.values,notes:I.values,learnings:A.values,files:N.values,tests:M.values,docs:fe.values,reminders:ee.values,events:ge.values,...gt,...yt.values});try{Br(Ur,_t)}catch(B){throw new l(B instanceof Error?B.message:"Invalid extension item field values",d.USAGE)}let Sw=Ye({metadata:Ur,body:Dr},{schema:o.schema,extensionFieldNames:ht}),Ew={metadata:{},body:""},rl=[..._].sort((B,Ui)=>B.localeCompare(Ui)),Tw=gS(n.message,rl),ol=hS(Ur,Dr,rl,[...Object.keys(gt),...Object.keys(yt.values??{})]),Aw=await sE({pmRoot:r,type:u,id:Ce,settings:o,typeRegistry:a,author:b,extensionFieldNames:ht,afterDocument:Sw,beforeDocument:Ew,historyMessage:Tw,changedFields:ol,nowValue:h,similarityCandidate:{title:Mi,description:$i,body:Dr},allowDuplicate:n.allowDuplicate}),sl=structuredClone(Ur);p==="strict"&&_.has("dependencies")&&(sl.dependencies=[]);let Cw=g_(Ce,u,bt,s);return x_(u,et,ee.values,ge.values)&&Bu(`[pm] warning: ${u} '${Ce}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ce} --deadline <ISO>' or 'pm update ${Ce} --event "start=<ISO>,end=<ISO>"'.`),{item:sl,changed_fields:ol,warnings:[...Ut,...Aw],...Object.fromEntries([["parent_source",ew],["next_transition",Cw],["similarity_advisory",nl]].filter(B=>B[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]="6865ca88-7ca1-52fd-86fb-2a3439abeafa")}catch{}})();var Ec=[...mc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...uc,...Hs],iE=(()=>{let e=new Map;for(let t of Ec)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Xs=new Map(Ec.map(e=>[e.optionKey,e.canonical])),aE=Ec.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),cE=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),dE=Rs({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function D_(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let s=t.unset?[...t.unset]:[];s.includes(o)||s.push(o),t.unset=s},r=new Set([...Xs.keys(),"rank"]);for(let o of r){let s=t[o];if(typeof s!="string"||!ze(s))continue;let i=o==="rank"?"order":Xs.get(o)??o;n(i),t[o]=void 0}return ve(e,xs(t,dE))}function U_(e,t,n=[]){return Vs({raw:e,supportedFields:aE,resolveDefinition:r=>{let o=n.find(i=>{let a=i.toLowerCase();return a===r||a.replaceAll("_","-")===r||a.replaceAll("-","_")===r});return iE.get(r)??Ws(r,"update",t)??(o?{optionKey:"field",metadataKey:o}:void 0)}})}var O_=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 P_(e){let t=e.disallowedFlags.flatMap(r=>{let o=O_.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=O_.get(r);return o?[`Replace ${r} with: ${o(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 lE(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new l("Choose only one package-provided ownership bypass mode.",d.USAGE);let s=(c,m,u)=>{c&&u.push(m)};if(o){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new l("The dependency ownership bypass requires at least one --dep value",d.USAGE);if(c.length>0)throw P_({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let i=[];s(t.status!==void 0,"--status",i),s(t.closeReason!==void 0,"--close-reason",i),s(t.assignee!==void 0,"--assignee",i),s(t.parent!==void 0,"--parent",i),s(t.blockedBy!==void 0,"--blocked-by",i),s(t.blockedReason!==void 0,"--blocked-reason",i),s(t.unblockNote!==void 0,"--unblock-note",i),s(t.dep!==void 0,"--dep",i),s(t.depRemove!==void 0,"--dep-remove",i),s(t.replaceDeps===!0,"--replace-deps",i),s(t.replaceTests===!0,"--replace-tests",i),s(t.replaceFiles===!0,"--replace-files",i),s(t.replaceDocs===!0,"--replace-docs",i),s(t.note!==void 0,"--note",i),s(t.learning!==void 0,"--learning",i),s(t.test!==void 0,"--test",i),s(t.reminder!==void 0,"--reminder",i),s(t.event!==void 0,"--event",i),s(t.clearDeps===!0,"--clear-deps",i),s(t.clearComments===!0,"--clear-comments",i),s(t.clearNotes===!0,"--clear-notes",i),s(t.clearLearnings===!0,"--clear-learnings",i),s(t.clearFiles===!0,"--clear-files",i),s(t.clearTests===!0,"--clear-tests",i),s(t.clearDocs===!0,"--clear-docs",i),s(t.clearReminders===!0,"--clear-reminders",i),s(t.clearEvents===!0,"--clear-events",i);let a=[...n].filter(c=>cE.has(c)).sort((c,m)=>c.localeCompare(m)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(i.push(...a),i.length>0)throw P_({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 mE(e,t){let n=X(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n}function uE(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Qm({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=X(e.fromStatus,e.statusRegistry)??e.fromStatus,r=X(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${Zm(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new l(o,d.USAGE);return`workflow_transition_not_allowed: ${o}`}function pE(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:G_(e)}function G_(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new l(`Invalid dependency created_at timestamp "${e}"`,d.USAGE);return new Date(t).toISOString()}function Un(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var fE=["id","kind","type","author","created_at","source_kind"],_E=["id","kind","type","author","created_at","source_kind"];function j_(e){return e.startsWith("```")||e.includes(`
8
+ `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Yo(e)}function q_(e){return typeof e=="string"?Wr(e)??e.trim():e}function Zs(e,t,n,r){return e?(Se(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(s=>{let i=s.trim(),a=j_(i);gr(i,a);let c=a?oe(s,"--dep"):{id:i,kind:"related"};a&&Ke(c,"--dep",fE);let m=c.id?.trim(),u=q_((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=or(Un(c.source_kind)),f=Un(c.author);return{id:sr(m,t,p),kind:Ee(u,Gt,"dependency kind"),created_at:pE(c.created_at,n),author:f??r,source_kind:p??"cli:update:dep",author_source:f?"asserted":"detected"}})}):{additions:[]}}function hE(e,t){return e?(Se(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);let o=j_(r);if(gr(r,o,"--dep-remove"),o){let s=oe(r,"--dep-remove");Ke(s,"--dep-remove",_E);let i=s.id?.trim();if(!i)throw new l("--dep-remove key/value form requires id=<value>",d.USAGE);if(i.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${i}"`,d.USAGE);let a=q_(Un(s.kind??s.type)),c=or(Un(s.source_kind)),m=Un(s.author),u=Un(s.created_at);return{id:sr(i,t,c),kind:a?Ee(a,Gt,"dependency kind"):void 0,source_kind:c,author:m,created_at:u?G_(u):void 0}}if(r.toLowerCase()==="undefined")throw new l(`--dep-remove id must not use placeholder token "${r}"`,d.USAGE);return{id:we(r,t)}})):[]}function Qs(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function gE(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),s=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function yE(e,t,n,r){let o=[...e??[]],s=!1;if(t===void 0){let i=o.filter(a=>a.kind!=="blocked_by");return i.length!==o.length&&(o=i,s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}return o.some(i=>i.kind==="blocked_by"&&i.id===t)||(o.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:o.length>0?o:void 0,changed:!0}:{dependencies:e,changed:!1}}async function bE(e,t,n,r,o,s){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let a=await U(n,we(i,r),r,o,s);return a?{id:a.id}:{unresolved:i}}function wE(e,t,n,r,o){let s=yE(e.dependencies,t,n,r);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,o.includes("dependencies")||o.push("dependencies"))}function vE(e){return`${e.path}::${e.scope}`}function kE(e){return`${e.path}::${e.scope}`}function SE(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function K_(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function EE(e){return xn(e)}function L_(e,t){let n=Wn("update",e);if(!n)throw new l(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,d.CONFLICT);return n}function TE(e,t,n){let r=new Set,o=(s,i)=>{i&&r.add(s)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=U_(e.unset,t,n);for(let i of s.optionKeys)o(i,!0)}return r}function AE(e,t,n,r,o){let s=Hr(e,n);if(!s)throw new l(`Invalid type value "${e}"`,d.USAGE);let i=_n(s,"update",[]);if(i.errors.length>0)throw new l(i.errors.join("; "),d.CONFLICT);let a=TE(t,r,o);for(let c of i.disabled)if(a.has(L_(c,e)))throw new l(`Option ${ye("update",c)} is disabled for type "${e}" by command_option_policies`,d.USAGE);for(let c of i.required)if(!a.has(L_(c,e)))throw new l(`Missing required option ${ye("update",c)} for type "${e}"`,d.USAGE)}var CE=new Set(["order","rank"]),RE=Wi.filter(e=>!CE.has(e)),z_=["tags","closeReason",...RE],IE=["title","description","body","status","closeReason","completedAt","priority","type",...Wi,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],xE=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>te(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>In(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],OE=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Ee(Es(e),un,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>As(e)}],PE=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Ee(Ts(e),pn,"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=>Cs(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Sc(e,t,n){for(let r of e){let o=t[r.optionKey],s=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!s)){if(s){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new l(`${ye("update",String(r.optionKey))} must be a string value`,d.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function LE(e){return D_(await Jo(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function Tc(e){return at(e)?await LE(e):D_(e)}function NE(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 vc(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 Ac(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);vc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),vc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),vc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function FE(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 ME(e){let t={};for(let n of z_)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function $E(e,t){let n=ME(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let s=Xs.get(r)??r;throw new l(`Cannot combine --unset ${s} with ${ye("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 DE(e){let t=(n,r)=>{let o=Xs.get(r),s=o?`Use --unset ${o} to clear this field.`:void 0;Is(n,ye("update",r),s)};for(let n of z_)t(e[n],String(n));t(e.order??e.rank,"order"),Se(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Se(e.event,"--event","Use --clear-events to clear linked events.")}function UE(e,t){let n={};for(let r of IE)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 GE(e){let t=await U(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 V(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function jE(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return ce(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function qE(e){e.before&&os(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>Z(t,e.statusRegistry),Ot())}async function KE(e){await R(e)}function zE(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 BE(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=es(e.options.parent);if(ns(e.id,t,e.settings.id_prefix),await U(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let r=we(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:ts(r,e.parentReferencePolicy).warnings}}function HE(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function VE(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await U(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 V(t,{schema:e.settings.schema}),r=e.options.type!==void 0?he(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=uE({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function WE(e){if(!e.fieldFlags.status||X(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let n=Object.entries(e.fieldFlags).filter(([a,c])=>c&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),r=[],o=[];if(n.length>0){let a=ve(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),c=await lt(e.id,a,e.global);o=c.changed_fields,r.push(...c.warnings)}let s=await dt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...e.workflowTransitionWarnings,...r,...s.warnings,"auto_routed_from_update_to_close"];return{item:s.item,changed_fields:[...o,...s.changed_fields],warnings:i}}function YE(e,t,n,r){return t.title!==void 0&&(e.metadata.title=wc(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")),X(e.metadata.status,n)??e.metadata.status}function JE(e,t,n,r,o){let s=mE(n,t.statusRegistry);if(e.metadata.status=s,o.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!Z(s,t.statusRegistry)&&Z(r,t.statusRegistry)&&e.metadata.closed_at!==void 0&&(delete e.metadata.closed_at,o.push("closed_at"),e.metadata.completed_at!==void 0&&(delete e.metadata.completed_at,o.push("completed_at")))}function XE(e,t,n,r){if(t.options.status!==void 0&&JE(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!Z(e.metadata.status,t.statusRegistry))throw new l("--completed-at can only be set on a terminal item",d.USAGE);e.metadata.completed_at=te(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function QE(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new l("--close-reason must not be empty",d.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&Z(n,t.statusRegistry)&&!Z(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function ZE(e,t,n,r){XE(e,t,n,r),QE(e,t,n,r)}function eT(e,t,n){let r=he(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=EE(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=he(t.options.type,t.typeRegistry);if(!o)throw new l(Tt(t.options.type,t.typeRegistry.types,At(t.pmRoot,t.settings.schema)),d.USAGE);e.metadata.type=o,r=o,n.push("type")}return AE(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),tT(e,t,r,n),r}function tT(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let s=Ls(t.options.typeOption??[]),i=Yn(n,s,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 o=Yn(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new l(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,d.USAGE);e.metadata.type_options=o.normalized}function nT(e,t){let n=new Set(t.map(o=>Qs(o))),r=new Set;return e.filter(o=>{if(!n.has(Qs(o)))return!0;let s=gE(o);return r.has(s)?!1:(r.add(s),!0)})}function rT(e,t,n){let r=t.filter(o=>!e.some(s=>K_(s,o)));if(r.length!==0)throw new l(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,d.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r,available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function oT(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=nT(r,t.dependencyUpdates.additions);let o=new Set(r.map(s=>Qs(s)));for(let s of t.dependencyUpdates.additions){let i=Qs(s);o.has(i)||(r.push(s),o.add(i))}}t.dependencyRemovals.length>0&&(rT(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(s=>K_(o,s)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function sT(e,t,n){kc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),kc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),kc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function kc(e,t,n,r,o,s){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],s.push(t))}function iT(e,t,n){N_(e,"files",t.options.file,t.fileUpdates.values,vE,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),aT(e,t,n),N_(e,"docs",t.options.doc,t.docUpdates.values,kE,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function N_(e,t,n,r,o,s,i,a){if(!(n===void 0&&!i.has(t))){if(s)e.metadata[t]=r;else if(i.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],m=new Set(c.map(u=>o(u)));for(let u of r){let p=o(u);m.has(p)||(c.push(u),m.add(p))}e.metadata[t]=c}a.push(t)}}function aT(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=F_(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=F_([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function F_(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=SE(r);n.has(o)||(t.push(r),n.add(o))}return t}function cT(e,t,n){let r=t.options.addTags,o=t.options.removeTags,s=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?It(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Wo(Rn(i,r),o),n.changedFields.push("tags")}Sc(xE,t.options,n),lT(e,t,n.changedFields)}function dT(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let s=Vo(Cn(e.metadata.acceptance_criteria),r,o);if(s.unmatchedRemovals.length>0)throw new l(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,d.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let i=s.criteria.join("; ");e.metadata.acceptance_criteria!==i&&(i===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=i,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function lT(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=de(r??"","order");if(!Number.isInteger(o))throw new l("Order must be an integer",d.USAGE);e.metadata.order=o}n.push("order")}}function mT(e,t,n,r){uT(e,t,n.changedFields),pT(e,t,n.changedFields),Sc(OE,t.options,n),M_(e,t,"sprint",r,n.changedFields),M_(e,t,"release",r,n.changedFields),fT(e,t,n.changedFields),Sc(PE,t.options,n)}function uT(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 pT(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 M_(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=rs(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,r.push(...s.warnings)}o.push(n)}}function fT(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&wE(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function _T(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Os(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=Ps(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function hT(e,t,n){$_(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),$_(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let i=o.replaceAll("_","-"),c=t.runtimeFieldRegistry.definitions.find(m=>m.metadata_key===o)?.cli_flag??i;throw new l(`Cannot combine --unset ${i} with --${c}`,d.USAGE)}rt(e[o],s)||(e[o]=s,n.push(o))}let r=zr(t.options.field,t.extensionRegistrations);for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new l(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,d.USAGE);for(let[o,s]of Object.entries(r))rt(e[o],s)||(e[o]=s,n.push(o))}function $_(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function gT(e,t){let n=structuredClone(e.metadata),r=e.body,o=[],s=[],i=YE(e,t.options,t.statusRegistry,o),a=e.metadata,c={metadataRecord:a,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};ZE(e,t,i,o),eT(e,t,o),oT(e,t,o),sT(e,t,o),iT(e,t,o),cT(e,t,c),dT(e,t,c),mT(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&yr(e.metadata.id,e.metadata.dependencies),X(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),_T(e,t,o),hT(a,t,o);try{Br(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(o)].filter(p=>p==="body"?e.body!==r:!rt(n[p],m[p]));return t.options.acceptanceCriteria!==void 0&&u.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${Cn(n.acceptance_criteria).length}:${Cn(m.acceptance_criteria).length}`),{changedFields:u,warnings:s}}async function B_(e,t,n,r={}){t=await Tc(t);let o=E(process.cwd(),n.path);await KE(o);let s=await T(o),i=D(s.schema),a=We(s.schema),c=x(),m=kt(c),u=O(s,c),p=s.governance.workflow_enforcement??"off",f=p==="off"?[]:Xm(s.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],g=U_(t.unset,a,m),y=new Set(g.optionKeys),h=new Set(g.metadataKeys);Ac(t),FE({definitions:NE(t),options:t,clearOptionKeys:y,clearItemMetadataKeys:h}),lE(e,t,h),$E(t,g),DE(t);let b=C(t.author,s.author_default),v=new Date,k=v.toISOString(),I=Zs(t.dep,s.id_prefix,k,b);yr(e,I.additions);let A=await Xt({pmRoot:o,dependencies:I.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:u.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),N=hE(t.depRemove,s.id_prefix),M=sn("--comment",t.comment,k,b),fe=t.ownershipMetadataBypass===!0&&M.values?{...M,values:M.values.map(Fe=>({...Fe,author:b}))}:M,ee=sn("--note",t.note,k,b),ge=sn("--learning",t.learning,k,b),me=gc(t.file),Ue=yc(t.test);Ue.values=await Nn(Ue.values,b,k);let _t=bc(t.doc),ht=[],gt=await BE({id:e,options:t,unsetTargets:g,pmRoot:o,settings:s,typeRegistry:u,parentReferencePolicy:_}),yt=await bE(t.blockedBy,h.has("blocked_by"),o,s.id_prefix,s.item_format,u.type_to_folder),Ii=yt.id,xi=[...gt.warnings,...HE(yt)],Vn=$o(t,a,t.runtimeFieldCommands),Dt=UE(t,Vn);if(!Object.values(Dt).some(Boolean))return GE({pmRoot:o,id:e,settings:s,typeRegistry:u});ht.push(...await VE({options:t,fieldFlags:Dt,workflowEnforcement:p,typeWorkflows:f,statusRegistry:i,typeRegistry:u,pmRoot:o,id:e,settings:s}));let Ce=await WE({options:t,fieldFlags:Dt,statusRegistry:i,workflowTransitionWarnings:ht,global:n,id:e});if(Ce)return Ce;zE(t);let bt=Ot(),Oi=Dt.parent&&!h.has("parent")||I.additions.some(Fe=>bt.resolve(Fe.kind)?.hierarchy),L=await Ns({pmRoot:o,author:b,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Oi});try{let Fe=await jE({fieldFlags:Dt,clearedMetadataKeys:h,pmRoot:o,settings:s,typeToFolder:u.type_to_folder}),et,Mr,wt=await np({pmRoot:o,settings:s,typeToFolder:u.type_to_folder,id:e,op:yT(t,r),author:b,message:t.message,resolveHistoryContext:()=>Mr,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:m,skipNoop:!0,mutate(Ve){et=bT({document:Ve,recurrenceReason:r.recurrenceReason,requestedStatus:t.status,statusRegistry:i}),Mr=et?{recurrence:et}:void 0,Fe=Fe?.map($r=>$r.id===Ve.metadata.id?structuredClone(Ve.metadata):$r);let Li=gT(Ve,{options:t,settings:s,typeRegistry:u,statusRegistry:i,runtimeFieldRegistry:a,extensionRegistrations:c,extensionFieldNames:m,clearItemMetadataKeys:h,dependencyUpdates:I,dependencyRemovals:N,commentUpdates:fe,noteUpdates:ee,learningUpdates:ge,fileUpdates:me,testUpdates:Ue,docUpdates:_t,resolvedParentValue:gt.resolvedParentValue,resolvedBlockedByDependencyId:Ii,runtimeFieldUpdates:Vn,nowValue:v,nowIso:k,author:b,pmRoot:o});return qE({before:Fe,document:Ve,statusRegistry:i}),Li}});await L();let Pi=Fe?_s(Fe,Fe.map(Ve=>Ve.id===wt.item.id?wt.item:Ve),wt.item.id):[];return{item:wt.item,changed_fields:wt.changedFields,warnings:[...ht,...xi,...A,...Pi,...wt.warnings],...et===void 0?{}:{lifecycle_transition:et}}}finally{await L()}}function yT(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function bT(e){if(e.recurrenceReason===void 0)return;let t=X(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!Z(t,e.statusRegistry))throw new l(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,d.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=X(n,e.statusRegistry)??n,o=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(i=>{let a=o[i];return typeof a=="string"?[[i,a]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:s}}async function lt(e,t,n){return B_(e,t,n)}async function H_(e,t,n,r){let o=await B_(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new l(`Item ${e} did not produce the required recurrence receipt.`,d.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fada7a33-ad1d-54f1-ae03-c5f8e4568d75")}catch{}})();var W_=1,Rc="update-many",wT=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),vT=["--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(", "),kT={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"},ST=[{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"}],ET={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"},Y_=e=>{let t={};for(let[n,r]of Object.entries(e))wT.has(n)||r!==void 0&&(t[n]=r);return t},TT=e=>Object.keys(Y_(e)).length>0,J_=e=>typeof e=="string"?e.trim():e,AT=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Cc=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},CT=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??J_(e)},RT={priority:AT,estimatedMinutes:Cc,order:Cc,rank:Cc,regression:CT},IT=(e,t)=>{if(t!==void 0)return(RT[e]??J_)(t)},xT=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return ET[t]??t},ei=(e,t)=>rt(e,t),OT=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],PT=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,LT=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",V_=(e,t)=>t===void 0?void 0:e[t],Gn=e=>Array.isArray(e)?e.length:0,NT=(e,t,n)=>{let r=n[e.addKey],o=V_(n,e.removeKey),s=Gn(r),i=Gn(o),a=n[e.clearKey]===!0,c=V_(n,e.replaceKey)===!0;if(![a,c,s>0,i>0].includes(!0))return;let m=OT(e.field,t[e.field]);return{field:e.field,before:m,after:{operation:LT({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:s,remove_count:i,before_count:PT(e.field,m)}}},FT=(e,t)=>{let n=[];for(let r of ST){let o=NT(r,e,t);o!==void 0&&n.push(o)}return n},MT=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],$T=(e,t)=>{if(![t.tags!==void 0,Gn(t.addTags)>0,Gn(t.removeTags)>0].includes(!0))return;let n=MT(e.tags),r=t.tags===void 0?n:It(t.tags),o=Rn(r,t.addTags),s=Wo(o,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!ei(i,s))return{field:"tags",before:n,after:s}},DT=(e,t)=>{let n=e.acceptance_criteria,r=Vo(Cn(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 o=r.criteria.join("; ");if(!ei(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},UT=(e,t,n)=>{for(let[r,o]of Object.entries(kT)){let s=n[r];if(s===void 0)continue;let i=t[o],a=IT(r,s);ei(i,a)||e.push({field:o,before:i,after:a})}},GT=(e,t,n,r)=>{let o=$o(n,r,["update_many"]);for(let[s,i]of Object.entries(o)){let a=t[s];ei(a,i)||e.push({field:s,before:a,after:i})}},jT=(e,t,n)=>{for(let r of n??[]){let o=xT(r),s=t[o];s!==void 0&&e.push({field:o,before:s,after:null})}},qT=(e,t,n={})=>{let r=e,o=[],s=$T(r,n);if(s&&o.push(s),UT(o,r,n),Gn(n.addAc)>0||Gn(n.removeAc)>0){let i=DT(r,n);i!==void 0&&o.push(i)}return o.push(...FT(r,n)),GT(o,r,n,t),jT(o,r,n.unset),{id:e.id,changes:o}},KT=(e,t)=>yp(e,t,{strict:!0,flagLabel:"--filter-status"}),zT=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)},BT=[({update:e})=>{e.priority!==void 0&&xn(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=O(t,x());if(!he(e.type,r))throw new l(Tt(e.type,r.types,At(n,t.schema)),d.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!X(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&&te(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&In(e.estimatedMinutes,"estimated-minutes")}],HT=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let s of BT)s(o)},VT=async e=>{let t=await Bo(e.pmRoot,Rc,e.rollbackId,W_),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await Ho(t.items,(o,s)=>Jt(o,s,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...zt({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}},WT=async e=>{let t={schema_version:W_,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await zo(e.pmRoot,Rc,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},YT=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},Ic=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},JT=async e=>{let t=E(process.cwd(),e.path);await R(t);let n=await T(t);return{pmRoot:t,settings:n,statusRegistry:D(n.schema),runtimeFieldRegistry:We(n.schema)}},XT=e=>{if(e.options.dryRun===!0)throw new l("--dry-run cannot be combined with --rollback",d.USAGE);if(lr(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 VT({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},QT=async e=>{KT(e.options.status,e.runtime.statusRegistry);let t=await ct(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let s=qT(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?s:{...s,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await ct(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:YT(e.options.list?.ids,r)}},ZT=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:[],...Ic(e)}),eA=e=>({...zt({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:[],...Ic(e)}),tA=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(s=>s.changes.length>0).map(s=>s.id));for(let s of e.items){if(!o.has(s.id)){t.push({id:s.id,status:"skipped"});continue}try{let i=Ta({...e.options.update,message:r,runtimeFieldCommands:["update_many"]}),a=await lt(s.id,i,e.global);t.push({id:s.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(s.id)}catch(i){t.push({id:s.id,status:"failed",error:hn(i)})}}return{rows:t,updatedIds:n}},nA=async e=>{if(e.plan.actionable.length===0)return eA(e.plan);let t=S(),n=Ko(Rc,t),r=new Set(e.plan.actionable.map(p=>p.id)),o=e.plan.listed.items.filter(p=>r.has(p.id)).map(p=>({id:p.id,target_updated_at:p.updated_at})),s=e.options.checkpoint===!1?void 0:await WT({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),i=await tA({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{...zt({applied:c,skipped:m,failed:u,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...s?{checkpoint:s}:{},updated_count:c,skipped_count:m,failed_count:u,rows:i.rows,ids:i.updatedIds,...Ic(e.plan)}},X_=async(e,t)=>{let n=await JT(t),r=typeof e.rollback=="string"?e.rollback:void 0;r===void 0&&(e={...e,update:Ta(await Tc(e.update))});let o=Y_(e.update);if(zT(e.list),r!==void 0)return XT({runtime:n,rollbackId:r,options:e,global:t,updateSummary:o});if(!TT(e.update)&&e.dryRun!==!0)throw new l(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${vT}), or pass --dry-run for a filter-only preview.`,d.USAGE);HT(e.update,n.settings,n.statusRegistry,n.pmRoot),Ac(e.update);let s=await Xt({pmRoot:n.pmRoot,dependencies:Zs(e.update.dep,n.settings.id_prefix,S(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:O(n.settings,x()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await QT({options:e,global:t,runtime:n,updateSummary:o,dependencyWarnings:s});return await Xt({pmRoot:n.pmRoot,dependencies:Zs(e.update.dep,n.settings.id_prefix,S(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:O(n.settings,x()).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?ZT(i):nA({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]="f7e870b6-fd80-5742-bc81-826d8f102d30")}catch{}})();var rA=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Q_=["brief","standard","deep"],th="plan-step-",Fc="draft",Nc=["bug-investigation","feature-implementation","refactoring-sprint"],Z_={"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 oA(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(Z_,t)?Z_[t]:void 0;if(!n)throw new l(`Unknown plan template "${e}". Allowed: ${Nc.join(", ")}`,d.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Nc[0]}`]});return n.map(r=>({...r}))}function sA(e,t){return t>0?Math.round(e/t*100):0}function nh(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 De(e){return Array.isArray(e)?e.flatMap(t=>On(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?On(e,{unique:!1}):[]}function Te(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function rh(e,t=Fc){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=qi.find(o=>o===n);if(!r)throw new l(`Invalid plan mode "${e}". Allowed: ${qi.join(", ")}`,d.USAGE);return r}function Mc(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Ki.find(o=>o===n);if(!r)throw new l(`Invalid step status "${e}". Allowed: ${Ki.join(", ")}`,d.USAGE);return r}function oh(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=Bi.find(o=>o===n);if(!r)throw new l(`Invalid step link kind "${e}". Allowed: ${Bi.join(", ")}`,d.USAGE);return r}function iA(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=zi.find(r=>r===t);if(!n)throw new l(`Invalid plan harness "${e}". Allowed: ${zi.join(", ")}`,d.USAGE);return n}function aA(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=Q_.find(r=>r===t);if(!n)throw new l(`Invalid --depth "${e}". Allowed: ${Q_.join(", ")}`,d.USAGE);return n}function cA(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 xc=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function dA(e,t){let n=e,r={},o=[];for(let s of t){let i=s.startsWith("plan.")?s.slice(5):s;if(i.length!==0){if(!xc.has(i)){o.push(s);continue}Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])}}if(o.length>0)throw new l(`Unknown Plan --fields value(s): ${o.join(", ")}`,d.USAGE,{nextSteps:[`Use --fields ${[...xc].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...xc].join(",")}`}});return r}function $c(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let s=o.indexOf("=");if(s<=0)throw new l(`Invalid ${t} entry "${o}"; 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[o.slice(0,s).trim().toLowerCase()]=o.slice(s+1).trim()}return n}function Dc(e){let t=$c(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 Uc(e){let t=$c(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 Gc(e){let t=$c(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 lA(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=sA(t.completed,t.total),t}function mA(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${th}${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 jn(e,t){let n=t.trim();if(n.length===0)throw new l("Step reference cannot be empty",d.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),s=e.find(i=>i.order===o);if(s)return s}throw new l(`Step "${t}" not found in plan`,d.NOT_FOUND)}function eh(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 uA(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),r=[],o=[];if(n.length>0){if(t.length>n.length)throw new l("pm plan materialize --steps all cannot be combined with other step refs",d.USAGE);for(let i of e.slice().sort((a,c)=>a.order-c.order)){let a=eh(i);if(a){o.push({from_step:i.id,...a});continue}r.push(i)}return{targets:r,skipped:o}}let s=new Set;for(let i of t){let a=jn(e,i);if(s.has(a.id))continue;s.add(a.id);let c=eh(a);if(c){o.push({from_step:a.id,...c});continue}r.push(a)}return{targets:r,skipped:o}}function pA(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 fA(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function _A(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 Oe(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),r=lA(n),o=fA(n),s={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Fc,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:_A(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(s.steps=n),t==="deep"&&(s.decisions=e.plan_decisions??[],s.discoveries=e.plan_discoveries??[],s.validation=e.plan_validation??[]),s}function Pe(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&&!Ca(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function sh(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 hA(e){let t=E(process.cwd(),e.path);await R(t);let n=await T(t);return{pmRoot:t,settings:n}}async function ih(e,t){let n=O(e.settings,x()),r=await U(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 o=await V(r,{schema:e.settings.schema});return sh(o.document.metadata),{document:o.document,itemId:r.id}}function gA(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of De(e.related))t.push(`id=${n},kind=related`);for(let n of De(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of De(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function yA(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 bA(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||De(e.dependsOn).length>0||De(e.link).length>0}function wA(e){let t=e.stepTitle?.trim()||void 0,n=nh(e.step),r=e.template?.trim()?oA(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function vA(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 ${Nc[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 kA(e,t){let n=Mc(e.stepStatus,"pending"),r=jc(e,"depends_on"),o=Te(e.file).map(Dc),s=Te(e.test).map(Uc),i=Te(e.doc).map(Gc),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:o.length>0?o:void 0,tests:s.length>0?s:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function SA(e){let t=wA(e),n=bA(e);if(vA(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[kA(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=S();return{steps:t.stepTitles.map((o,s)=>({id:`${th}${String(s+1).padStart(3,"0")}`,order:s+1,title:o,body:t.templateSteps[s]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function ah(e,t,n=[]){ve(e,t),n.length>0&&_p(t,n)}async function EA(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 o=rh(e.mode,Fc),s=iA(e.harness),i=e.fromSearch?.trim(),a=yA(e),{steps:c,hasPerStepDetailOptions:m}=SA(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?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:u,type:"Plan",template:void 0,file:Te(e.file),test:Te(e.test),doc:Te(e.doc),field:Te(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:gA(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")};ah(e,f);let _=await Pt(f,t),g=await ne({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(h){let b=["plan_mode"];h.metadata.plan_mode=o,s&&(h.metadata.plan_harness=s,b.push("plan_harness"));let v=e.scope?.trim();v&&(h.metadata.plan_scope=v,b.push("plan_scope"));let k=e.resumeContext?.trim();return k&&(h.metadata.plan_resume_context=k,b.push("plan_resume_context")),h.metadata.plan_steps=c,b.push("plan_steps"),a&&(h.metadata.plan_validation=[...h.metadata.plan_validation??[],a],b.push("plan_validation")),p&&(h.metadata.assignee=p,b.push("assignee")),{changedFields:b}}}),y=Oe(g.item,"brief");return{action:"create",plan:y,step:c[0],next_actions:Pe(_.item.id,y),warnings:[..._.warnings],generated_at:S()}}async function TA(e,t,n){let r=aA(t.depth),o=cA(t.fields),{document:s,itemId:i}=await ih(n,e),a=Oe(s.metadata,o===null?r:"deep");return{action:"show",plan:o===null?a:dA(a,o),next_actions:Pe(i,a),warnings:[],generated_at:S()}}function AA(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function Xe(e){let t=C(e.options.author,e.ctx.settings.author_default),n,r=await ne({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){sh(o.metadata);let s=D(e.ctx.settings.schema);if(Z(o.metadata.status,s)||Ca(o.metadata.plan_mode))throw new l(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.metadata.plan_mode??"unset"}) and cannot be mutated.`,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=(o.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(o.metadata).filter(([p])=>p.startsWith("plan_")).map(([p,f])=>[p,JSON.stringify(f)])),c=e.mutator(i,o);n=c.resultStep;let m=i.slice().sort((p,f)=>p.order-f.order).map((p,f)=>({...p,order:f+1}));o.metadata.plan_steps=m;let u=AA(a,o.metadata);return u.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:u.length>0?u:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function CA(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new l("pm plan add-step requires --step-title",d.USAGE);let o=Mc(t.stepStatus,"pending"),s=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await Xe({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(u){let p=u.length+1;ch(u,void 0,o,s);let f=RA(u,t,{order:p,title:r,status:o});return u.push(f),{changedSteps:[f.id],resultStep:f}}}),m=Oe(i.metadata,"standard");return{action:"add-step",plan:m,step:a,next_actions:Pe(c,m),warnings:[],generated_at:S()}}function ch(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(s=>s.id!==t&&s.status==="in_progress");if(o)throw new l(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,d.CONFLICT)}function RA(e,t,n){let r=jc(t,"depends_on"),o=Te(t.file).map(Dc),s=Te(t.test).map(Uc),i=Te(t.doc).map(Gc),a=S();return{id:mA(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:s.length>0?s:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function jc(e,t){let n=De(e.dependsOn).map(u=>({id:u,kind:t})),r=De(e.related).map(u=>({id:u,kind:"related"})),o=De(e.blocks).map(u=>({id:u,kind:"blocks"})),s=De(e.blockedBy).map(u=>({id:u,kind:"blocked_by"})),i=De(e.link),a=oh(e.linkKind,t),c=e.linkNote?.trim(),m=i.map(u=>{let p={id:u,kind:a};return c&&(p.note=c),p});return[...n,...r,...o,...s,...m]}async function Oc(e,t,n,r){let{document:o,resultStep:s,itemId:i}=await Xe({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,m){let u=jn(c,r.stepRef),p=S(),f=r.finalStatus??Mc(t.stepStatus,u.status),_=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return ch(c,u.status==="in_progress"?u.id:void 0,f,_),IA(u,t,f,p),m.metadata.updated_at=p,{changedSteps:[u.id],resultStep:u}}}),a=Oe(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:a,step:s,next_actions:Pe(i,a),warnings:[],generated_at:S()}}function IA(e,t,n,r){xA(e,t,n),OA(e,t),e.status=n,e.updated_at=r,PA(e,n,r)}function xA(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 OA(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=Te(t.file).map(Dc),o=Te(t.test).map(Uc),s=Te(t.doc).map(Gc);r.length>0&&(e.files=Pc(e.files,r)),o.length>0&&(e.tests=Pc(e.tests,o)),s.length>0&&(e.docs=Pc(e.docs,s))}function Pc(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let s=JSON.stringify(o);r.has(s)||(r.add(s),n.push(o))}return n}function PA(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function LA(e,t,n,r,o){let{document:s,itemId:i}=await Xe({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(c){let m=jn(c,r),u=c.filter(f=>f.id!==m.id),p=Math.max(1,Math.min(o,u.length+1));return u.splice(p-1,0,m),u.forEach((f,_)=>{f.order=_+1,f.updated_at=S()}),c.length=0,c.push(...u),{changedSteps:[m.id],resultStep:m}}}),a=Oe(s.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:Pe(i,a),warnings:[],generated_at:S()}}async function NA(e,t,n,r){let{document:o,itemId:s}=await Xe({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(a){let c=jn(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=Oe(o.metadata,"standard");return{action:"remove-step",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:S()}}async function FA(e,t,n,r){let o=jc(t,oh(t.linkKind,"related"));if(o.length===0)throw new l("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",d.USAGE);let s=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await Xe({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(u,p){let f=jn(u,r),_=f.linked_items??[],g=h=>`${h.kind}:${h.id}`,y=new Set(_.map(g));for(let h of o){let b=g(h);y.has(b)||(_.push(h),y.add(b))}if(f.linked_items=_,f.updated_at=S(),s){let h=p.metadata.dependencies??[],b=k=>`${k.kind}:${k.id}`,v=new Set(h.map(b));for(let k of o){let I=k.kind==="depends_on"?"blocked_by":k.kind,A={id:k.id,kind:I,created_at:S(),author:C(t.author,n.settings.author_default)};v.has(b(A))||(h.push(A),v.add(b(A)))}p.metadata.dependencies=h}return{changedSteps:[f.id],resultStep:f}}}),m=Oe(i.metadata,"standard");return{action:"link",plan:m,step:c,next_actions:Pe(a,m),warnings:[],generated_at:S()}}async function MA(e,t,n,r){let o=De(t.link);if(o.length===0)throw new l("pm plan unlink requires --link <id> to remove",d.USAGE);let{document:s,itemId:i,resultStep:a}=await Xe({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(m){let u=jn(m,r),p=(u.linked_items??[]).filter(f=>!o.includes(f.id));return u.linked_items=p.length>0?p:void 0,u.updated_at=S(),{changedSteps:[u.id],resultStep:u}}}),c=Oe(s.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:Pe(i,c),warnings:[],generated_at:S()}}async function Lc(e,t,n,r){let o=pA(r,t);if(!o){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 s=C(t.author,n.settings.author_default),{document:i,itemId:a}=await Xe({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:s,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),u.metadata.plan_decisions=_,{changedSteps:[]}}if(r==="discovery"){let _=u.metadata.plan_discoveries??[];return _.push({ts:p,author:s,text:o}),u.metadata.plan_discoveries=_,{changedSteps:[]}}let f=u.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),u.metadata.plan_validation=f,{changedSteps:[]}}}),c=Oe(i.metadata,"deep");return{action:r,plan:c,next_actions:Pe(a,c),warnings:[],generated_at:S()}}async function $A(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new l("pm plan resume requires --resume-context <text>",d.USAGE);let{document:o,itemId:s}=await Xe({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=Oe(o.metadata,"brief");return{action:"resume",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:S()}}async function DA(e,t,n){let r=rh(t.mode??"approved","approved"),{document:o,itemId:s}=await Xe({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=Oe(o.metadata,"brief");return{action:"approve",plan:i,next_actions:Pe(s,i),warnings:[],generated_at:S()}}function dh(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function UA(e,t){let n=Oe(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Pe(e.itemId,n),warnings:dh(t),generated_at:S()}}function GA(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let s=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${s}`)}return r}async function jA(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of Te(e.options.field)){let s=o.indexOf("=");if(s<=0)throw new l(`Invalid --field entry "${o}"; expected name=value`,d.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0)throw new l(`Invalid --field entry "${o}"; 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 "${o}"; 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 "${o}"; "${p}" is reserved by materialize and cannot be overridden`,d.USAGE);n[p]=a}for(let o of e.targets){let s={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:GA(e.parent,e.planItemId,o)};ah(e.options,s,["description",...Object.keys(n)]);let i=await Pt(s,{path:e.pmRoot});t.push({id:i.item.id,title:i.item.title,type:e.resolvedTypeName,parent:i.item.parent,tags:i.item.tags??[],from_step:o.id})}return t}function qA(e,t,n){for(let r of t){let o=n.find(a=>a.from_step===r.id);if(!o)continue;let s=e.find(a=>a.id===r.id);if(!s)continue;let i=s.linked_items??[];i.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),s.linked_items=i,s.updated_at=S()}}async function KA(e,t,n){let r=De(t.steps);if(r.length===0)throw new l("pm plan materialize requires --steps <ids|orders|all>",d.USAGE);let o=t.materializeType?.trim()||"Task",s=O(n.settings,x()),i=he(o,s);if(!i)throw new l(`Invalid --materialize-type "${o}"`,d.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,m=await ih(n,e),u=(m.document.metadata.plan_steps??[]).slice(),{targets:p,skipped:f}=uA(u,r);if(p.length===0){if(f.length>0)return UA(m,f);throw new l("No matching plan steps found for --steps",d.NOT_FOUND)}let _=await jA({targets:p,parent:a,planItemId:m.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:g,itemId:y}=await Xe({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(b){return qA(b,p,_),{changedSteps:p.map(v=>v.id)}}}),h=Oe(g.metadata,"standard");return{action:"materialize",plan:h,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:Pe(y,h),warnings:dh(f),generated_at:S()}}function zA(e){if(e.subcommand==="create")return e;let t=nh(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:ve(e.options,{...e.options,stepTitle:t[0]})}:e}function mt(e,t){if(!e.id)throw new l(`pm plan ${t} requires a plan id`,d.USAGE);return e.id}function an(e,t){let n=mt(e,t);if(!e.stepRef)throw new l(`pm plan ${t} requires <plan-id> <step>`,d.USAGE);return{id:n,stepRef:e.stepRef}}function BA(e){let t=an(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 HA={create:(e,t)=>EA(e.options,e.global,t),show:(e,t)=>TA(mt(e,"show"),e.options,t),"add-step":(e,t)=>CA(mt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=an(e,"update-step");return Oc(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=an(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=an(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=BA(e);return LA(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=an(e,"remove-step");return NA(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=an(e,"link");return FA(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=an(e,"unlink");return MA(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Lc(mt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Lc(mt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Lc(mt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>$A(mt(e,"resume"),e.options,t),approve:(e,t)=>DA(mt(e,"approve"),e.options,t),materialize:(e,t)=>KA(mt(e,"materialize"),e.options,t)};function VA(e){let t=HA[e];if(!t)throw xe({command_path:"plan",token:e,allowed:rA});return t}async function lh(e){let t=await hA(e.global),n=zA(e);return VA(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]="b59e8e54-f9e0-5cdb-bc59-6dcbf67f278d")}catch{}})();function WA(e,t){return[...new Set([...Kr.filter(r=>e[r]!==void 0),...Object.keys(e).filter(r=>e[r]!==void 0),...t.length>0?["body"]:[]])].sort((r,o)=>r.localeCompare(o))}function YA(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function qc(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await T(r),s=O(o,x()),i=await U(r,e,o.id_prefix,o.item_format,s.type_to_folder);if(!i)throw await it(r,e,o.id_prefix,s.type_to_folder);let a=await V(i,{schema:o.schema}),c=a.document.metadata,m=S(),u=C(t.author,o.author_default),p=await nr(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:s.type_to_folder,probeExisting:!1}),f=D(o.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new l("Copy --title must not be empty",d.USAGE);let g={...c,id:p,title:_??c.title,status:f.open_status,created_at:m,updated_at:m};delete g.closed_at,delete g.completed_at,delete g.close_reason,delete g.test_runs;let y=kt(x()),h=Ye({metadata:g,body:a.document.body},{schema:o.schema,extensionFieldNames:y}),b=await Fn({title:h.metadata.title,description:h.metadata.description,body:h.body,excludeIds:[i.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=WA(h.metadata,h.body),k=qt(r,h.metadata.type,p,o.item_format,s.type_to_folder),I=Re(r,p),A=await be(r,p,o.locks.ttl_seconds,u,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),N={metadata:{},body:""},M,fe;try{let ee=await Tn(r,u,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await Fn({title:h.metadata.title,description:h.metadata.description,body:h.body,excludeIds:[i.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let ge=await U(r,p,o.id_prefix,o.item_format,s.type_to_folder);if(ge)throw new l(`Cannot copy to ${p}: an item with that id already exists at ${ge.itemPath}. Retry the copy to allocate a new id.`,d.CONFLICT,{code:"item_id_collision",why:`Allocated id ${p} already exists at ${ge.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await _e(k,je(h,{format:o.item_format,schema:o.schema,extensionFieldNames:y}));try{let me=qe({nowIso:m,author:u,op:"create",before:N,after:h,message:YA(i.id,t.message)});await Ct(I,me)}catch(me){throw await fn(k),me}fe=await An({pmRoot:r,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:k,document:h})}finally{await ee()}M=[...await W({path:k,scope:"project",op:"create",item_id:h.metadata.id,item_type:h.metadata.type,before:N,after:h,changed_fields:v}),...await W({path:I,scope:"project",op:"create:history",item_id:h.metadata.id,item_type:h.metadata.type,before:N,after:h,changed_fields:v})],yn({id:h.metadata.id,op:"create",item_type:h.metadata.type,status:h.metadata.status,current:Bt(h.metadata,v),changed_fields:v})}finally{await A()}return{source_id:i.id,item:structuredClone(h.metadata),changed_fields:v,warnings:[...hs(b),...fe,...M],...b===void 0?{}:{similarity_advisory:b}}}import ti 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]="7819b53c-b0e4-50b0-a670-f80b36765085")}catch{}})();async function Kc(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await T(r),s=C(t.author,o.author_default),i=await rp({pmRoot:r,settings:o,id:e,author:s,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?ti.relative(r,i.targetPath).split(ti.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:ti.relative(r,Re(r,i.item.id)).split(ti.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]="a5ddb139-9780-50e0-87a5-621913cb0de4")}catch{}})();async function JA(e){await R(e)}async function zc(e,t,n){let r=E(process.cwd(),n.path);if(await JA(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 T(r),f=vn(C(void 0,p.author_default));return await Mu(r),await fs({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 Fo(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 XA(r,p);return{action:"show",focused_item:p,title:f,message:`Focused on ${p}${f?` (${f})`:""}. New items default --parent to it.`}}let s=await T(r),i=O(s,x()),a=await U(r,e,s.id_prefix,s.item_format,i.type_to_folder);if(!a)throw await it(r,e,s.id_prefix,i.type_to_folder);let c=we(a.id,s.id_prefix),m=await V(a,{schema:s.schema}),u=mh(m.document.metadata.title);return await Fu(r,c),await fs({pmRoot:r,settings:s,principal:vn(C(void 0,s.author_default)),itemId:c}),{action:"set",focused_item:c,title:u,message:`Focused on ${c}${u?` (${u})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function XA(e,t){let n=await T(e),r=O(n,x()),o=await U(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let s=await V(o,{schema:n.schema});return mh(s.document.metadata.title)}function mh(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]="77fa2822-1681-59d5-8388-037cf13c45dd")}catch{}})();var uh=new Set(["item_format"]),ph=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"]),QA=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),ZA=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),eC={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function tC(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(uh.has(t)||ph.has(t)||QA.has(t)||t==="context")return t}function nC(e){let t=e.trim().toLowerCase();return eC[t]??e}function fh(e,t){let n=tC(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:uh.has(n)?{routable:!0,flag:"format",value:t}:ph.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:ZA.has(n)?nC(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]="09703f32-9491-5d3a-9f90-f038d9982e17")}catch{}})();var rC=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Bc=128,oC=1e4;function _h(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>Bc)throw new Error(`A legacy author must contain 1-${Bc} characters.`);return t}function sC(e){let t=e?.trim().toLowerCase();if(!t||!rC.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function iC(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function aC(e,t){let n=new Set;for(let r of(e??[]).slice(0,oC)){let o=r.trim().slice(0,Bc);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function cC(e,t){let n=_h(t.legacy_author),r=sC(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function dC(e,t){if(t.operation==="add")return cC(e,t);if(t.operation==="remove"){let r=_h(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function Hc(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function hh(e,t){let n=e?.version??1,r={...e?.aliases},o=dC(r,t),s={version:o?n+1:n,aliases:iC(r)};return{vocabulary:s,preview:{operation:t.operation,changed:o,version_before:n,version_after:s.version,alias_count:Object.keys(s.aliases).length,residual_author_count:aC(t.observed_authors,s.aliases)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2f750f85-6c55-5f0f-b5c0-396764839d2a")}catch{}})();var gh=["project","global"],ut={definition_of_done:["definition-of-done","definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy"],parent_reference_policy:["parent-reference-policy","parent_reference_policy"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution"],telemetry_tracking:["telemetry-tracking","telemetry_tracking"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary"],context:["context"]},lC=Object.keys(ut).map(e=>ut[e][0]),mC=Object.fromEntries(Object.keys(ut).flatMap(e=>ut[e].map(t=>[t,e]))),uC={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},pC=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],fC=new Set(["metadata_required_fields",...pC]),_C=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),hC=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),gC=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),yC=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement"]),bC=new Set(["governance_preset","governance_create_default_type"]),kh=e=>fC.has(e),wC=e=>gC.has(e),vC=e=>yC.has(e),kC=e=>bC.has(e);function Vc(e){return e==="definition_of_done"||kh(e)}function SC(e){if(gh.includes(e))return e;throw new l(`Invalid config scope "${e}". Allowed: ${gh.join(", ")}`,d.USAGE)}function EC(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw xe({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function TC(e){let t=mC[e];if(t)return t;let n=Zi.map(r=>r.key).join(", ");throw new l(`Invalid config key "${e}". Supported: ${lC.join(", ")} (underscore variants also accepted). Nested leaf settings: ${n}.`,d.USAGE)}function AC(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new l("Config set definition-of-done cannot combine --clear-criteria with --criterion values",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 CC(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 Sh(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 RC(e){return Yc(e,"test-result-tracking")}function Yc(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new l(`Config set ${t} requires --policy with one of: enabled, disabled`,d.USAGE)}function Eh(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 Jc(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 Th(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 Ah(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 Ch(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 Rh(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 Ih(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 xh(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 Oh(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)}var IC={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"};function yh(e,t){let n=IC[e];if(n)return Yc(t,n);switch(e){case"history_missing_stream_policy":return Sh(t);case"sprint_release_format_policy":return Aa(t);case"parent_reference_policy":case"governance_parent_reference_policy":return Zo(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return Jc(t);case"governance_preset":return Th(t);case"governance_ownership_enforcement":return Ah(t);case"governance_create_mode_default":return Ch(t);case"governance_close_validation_default":return Rh(t);case"governance_require_close_reason":return Oh(t);case"governance_workflow_enforcement":return Ih(t);case"governance_force_required_for_stale_lock":return xh(t);case"telemetry_tracking":return Eh(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var bh={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"},xC=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function OC(e,t){let n=[...new Set((e??[]).map(s=>s.trim()).filter(s=>s.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(s=>s.toLowerCase().replaceAll("-","_")),o=r.filter(s=>bh[s]===void 0);if(o.length>0)throw new l(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${xC.join(", ")}`,d.USAGE);return[...new Set(r.map(s=>bh[s]))].sort((s,i)=>s.localeCompare(i))}function PC(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,s)=>o.localeCompare(s));if(n){if(r.length>0)throw new l(`Config set ${ut[e][0]} cannot combine --clear-criteria with --criterion values`,d.USAGE);return[]}if(r.length===0)throw new l(`Config set ${ut[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,d.USAGE);return r}function LC(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function NC(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 TC(t)}function Ph(e){if(!e)throw new l("Config action requires <key>",d.USAGE)}var FC={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>Hc(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,sections:{...e.context.sections}})};function Xc(e,t){return FC[t](e)}function Ae(e,t){return t.length===0?e:{...e,warnings:t}}async function MC(e,t){let n=process.cwd(),r=e==="project"?E(n,t.path):nt(n),o=ae(r);return e==="project"&&await R(r),{pmRoot:r,settingsPath:o}}function $C(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 wh(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 DC(e,t,n,r,o){let s=!1,i=e.context;if(t.defaultDepth!==void 0){let c=t.defaultDepth.trim().toLowerCase();if(!Hi.includes(c))throw new l(`Context --default-depth must be one of ${Hi.join("|")}`,d.USAGE);i.default_depth!==c&&(i.default_depth=c,s=!0)}if(t.activityLimit!==void 0){let c=wh(t.activityLimit,"--activity-limit");i.activity_limit!==c&&(i.activity_limit=c,s=!0)}if(t.staleThresholdDays!==void 0){let c=wh(t.staleThresholdDays,"--stale-threshold-days");i.stale_threshold_days!==c&&(i.stale_threshold_days=c,s=!0)}let a=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[c,m]of a){let u=$C(m);if(u!==void 0){let p=c;i.sections[p]!==u&&(i.sections[p]=u,s=!0)}}return s&&await Ie(n.pmRoot,e,"config:set:context"),Ae({scope:r,key:"context",context_settings:{default_depth:i.default_depth,activity_limit:i.activity_limit,stale_threshold_days:i.stale_threshold_days,sections:{...i.sections}},settings_path:n.settingsPath,changed:s},o)}function UC(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 GC(e,t,n,r,o,s){if(o===void 0)return s;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 UC(t,o,s);Ph(n);let i=fh(n,o);if(!i.routable)throw new l(i.reason,d.USAGE);if(i.flag==="criterion"){if(s.criterion!==void 0&&s.criterion.length>0)throw new l(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,d.USAGE);return{...s,criterion:i.values}}if(i.flag==="format")return{...s,format:i.value};if(s.policy!==void 0&&yh(n,s.policy)!==yh(n,i.value))throw new l(`Config set ${t} received both positional value "${o}" and --policy "${s.policy}". Pass only one.`,d.USAGE);return{...s,policy:i.value}}function jC(e){let t=Object.keys(ut).map(r=>({key:r,aliases:ut[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":Vc(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:Vc(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:uC[r],value:Xc(e.settings,r)})),n=Zi.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:ea(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 Ae({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function qC(e){let t=Object.fromEntries(Object.keys(ut).map(n=>[n,Xc(e.settings,n)]));return Ae({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function KC(e,t){let n=Xc(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Ae({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Ae({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Ae({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Ae({...r,criteria:n},e.warnings):Ae({...r,policy:n},e.warnings)}async function zC(e,t,n,r){if(t==="get"){let a=ea(e.settings,n);return Ae({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:a},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new l(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,d.USAGE);let s=Jm(n,o);if(!s.ok)throw new l(s.error.message,d.USAGE);let i=xo(e.settings,n,s.parsed.value);return i&&await Ie(e.target.pmRoot,e.settings,`config:set:${n.path}`),Ae({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:s.parsed.value},settings_path:e.target.settingsPath,changed:i},e.warnings)}async function Y(e,t,n){t&&await Ie(e.target.pmRoot,e.settings,n)}function vh(e,t,n){return e!==n||t!==n}function se(e,t,n,r){return Ae({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function Wc(e,t,n,r){return Ae({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function BC(e,t){let n=CC(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){let s=O(e.settings,x()),i=await wp(e.target.pmRoot,n,"config:set:item_format:migrate",s.type_to_folder,e.settings.schema);o={target_format:i.target_format,scanned:i.scanned,migrated:i.migrated,removed:i.removed,warnings:i.warnings},e.settings.item_format=n,await Ie(e.target.pmRoot,e.settings,"config:set:item_format")}return Ae({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function HC(e,t,n){if(t==="history_missing_stream_policy"){let s=Sh(n.policy),i=e.settings.history.missing_stream!==s;return e.settings.history.missing_stream=s,await Y(e,i,"config:set:history_missing_stream_policy"),se(e,t,e.settings.history.missing_stream,i)}if(t==="sprint_release_format_policy"){let s=Aa(n.policy),i=e.settings.validation.sprint_release_format!==s;return e.settings.validation.sprint_release_format=s,await Y(e,i,"config:set:sprint_release_format_policy"),se(e,t,e.settings.validation.sprint_release_format,i)}if(t==="parent_reference_policy"){let s=Zo(n.policy),i=e.settings.validation.parent_reference!==s||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==s;return e.settings.validation.parent_reference=s,e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,await Y(e,i,"config:set:parent_reference_policy"),se(e,t,e.settings.validation.parent_reference,i)}let r=Jc(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Y(e,o,"config:set:metadata_validation_profile"),se(e,t,e.settings.validation.metadata_profile,o)}async function VC(e,t,n){if(t==="metadata_required_fields"){let a=OC(n.criterion,n.clearCriteria),c=a.length!==e.settings.validation.metadata_required_fields.length||a.some((m,u)=>m!==e.settings.validation.metadata_required_fields[u]);return e.settings.validation.metadata_required_fields=a,await Y(e,c,"config:set:metadata_required_fields"),Wc(e,t,[...e.settings.validation.metadata_required_fields],c)}let o={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],s=PC(t,n.criterion,n.clearCriteria),i=s.length!==o.length||s.some((a,c)=>a!==o[c]);return o.splice(0,o.length,...s),await Y(e,i,`config:set:${t}`),Wc(e,t,[...o],i)}async function WC(e,t,n){if(t==="governance_preset"){let c=Th(n.policy),m=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Y(e,m,"config:set:governance_preset"),se(e,t,e.settings.governance.preset,m)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Y(e,c,"config:set:governance_create_default_type"),se(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new l('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',d.USAGE);let s=O(e.settings,x()),i=he(o,s);if(!i)throw new l(Tt(o,s.types,At(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 Y(e,a,"config:set:governance_create_default_type"),se(e,t,e.settings.governance.create_default_type,a)}async function YC(e,t,n){if(t==="governance_ownership_enforcement"){let s=Ah(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==s;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=s,await Y(e,i,"config:set:governance_ownership_enforcement"),se(e,t,e.settings.governance.ownership_enforcement,i)}if(t==="governance_create_mode_default"){let s=Ch(n.policy),i=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==s;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=s,await Y(e,i,"config:set:governance_create_mode_default"),se(e,t,e.settings.governance.create_mode_default,i)}let r=Rh(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Y(e,o,"config:set:governance_close_validation_default"),se(e,t,e.settings.governance.close_validation_default,o)}async function JC(e,t,n){if(t==="governance_parent_reference_policy"){let s=Zo(n.policy),i=e.settings.governance.preset!=="custom"||vh(e.settings.governance.parent_reference,e.settings.validation.parent_reference,s);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=s,e.settings.validation.parent_reference=s,await Y(e,i,"config:set:governance_parent_reference_policy"),se(e,t,e.settings.governance.parent_reference,i)}if(t==="governance_metadata_validation_profile"){let s=Jc(n.policy),i=e.settings.governance.preset!=="custom"||vh(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,s);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=s,e.settings.validation.metadata_profile=s,await Y(e,i,"config:set:governance_metadata_validation_profile"),se(e,t,e.settings.governance.metadata_profile,i)}let r=Ih(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Y(e,o,"config:set:governance_workflow_enforcement"),se(e,t,e.settings.governance.workflow_enforcement,o)}async function XC(e,t,n){if(t==="governance_require_close_reason"){let a=Oh(n.policy)==="enabled",c=e.settings.governance.require_close_reason!==a;return e.settings.governance.require_close_reason=a,await Y(e,c,"config:set:governance_require_close_reason"),se(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",c)}let o=xh(n.policy)==="enabled",s=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==o;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=o,await Y(e,s,"config:set:governance_force_required_for_stale_lock"),se(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",s)}async function QC(e,t,n){if(t==="test_result_tracking"){let a=RC(n.policy)==="enabled",c=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await Y(e,c,"config:set:test_result_tracking"),se(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",c)}if(t==="untrusted_linked_test_execution"){let a=Yc(n.policy,"untrusted-linked-test-execution")==="enabled",c=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await Y(e,c,"config:set:untrusted_linked_test_execution"),se(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",c)}let o=Eh(n.policy)==="enabled",s=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await Y(e,s,"config:set:telemetry_tracking"),se(e,t,e.settings.telemetry.enabled?"enabled":"disabled",s)}async function ZC(e,t,n){let r=AC(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((s,i)=>s!==e.settings.workflow.definition_of_done[i]);return e.settings.workflow.definition_of_done=r,await Y(e,o,"config:set:definition_of_done"),Wc(e,t,[...e.settings.workflow.definition_of_done],o)}function eR(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new l("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",d.USAGE)}function tR(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new l('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',d.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new l("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",d.USAGE);return{legacy_author:t}}if(t!==void 0)throw new l("Config set agent-identity-vocabulary --policy clear does not accept --value",d.USAGE);return{}}async function nR(e,t){let{operation:n,dryRun:r}=eR(t.policy),o=tR(n,t.value),s;try{s=hh(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(i){throw new l(i.message,d.USAGE)}return s.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:s.vocabulary},await Y(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${s.preview.version_after}`)),Ae({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:Hc(r?e.settings.agent_identity?.identity_vocabulary:s.vocabulary),vocabulary_mutation:s.preview,settings_path:e.target.settingsPath,changed:s.preview.changed&&!r},e.warnings)}async function rR(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"?BC(e,n):t==="context"?DC(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?nR(e,n):t==="definition_of_done"?ZC(e,t,n):kh(t)?VC(e,t,n):_C.has(t)?QC(e,t,n):hC.has(t)?XC(e,t,n):wC(t)?YC(e,t,n):vC(t)?JC(e,t,n):kC(t)?WC(e,t,n):HC(e,t,n)}async function Lh(e,t,n,r,o,s){let i=SC(e),a=EC(t),c=a==="get"||a==="set"?Io(n):void 0,m=c?void 0:NC(a,n),u=GC(a,n,m,c,s,r),p=await MC(i,o),{settings:f,metadata:_,warnings:g}=await Xu(p.pmRoot),y={scope:i,target:p,settings:f,metadata:_,warnings:LC(g)};return c?zC(y,a,c,u):a==="list"?jC(y):a==="export"?qC(y):(Ph(m),a==="get"?KC(y,m):rR(y,m,u))}import NR from"node:fs/promises";import J from"node:path";import FR from"node:readline/promises";import{stdin as MR,stdout as Le}from"node:process";import Zc from"node:fs/promises";import ie from"node:path";import oR from"node:readline/promises";import{stdin as sR,stdout as ni}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e404796d-439b-5f4c-9330-5b12ff41d7b2")}catch{}})();var Fh=["ask","add","skip","status"],iR=["AGENTS.md","CLAUDE.md"],aR=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],cR=8,ed=1,dR="<!-- pm-cli:agent-guidance:start:",lR=`<!-- pm-cli:agent-guidance:start:v${ed} -->`,Qc="<!-- pm-cli:agent-guidance:end -->",Sr="Add workflow guidance later: pm init --agent-guidance add";var mR=()=>oR.createInterface({input:sR,output:ni});function vr(e,t){let n=ie.relative(e,t);return n.length===0?ie.basename(t):n.split(ie.sep).join("/")}function Nh(e){return e.endsWith(`
9
9
  `)?e:`${e}
10
- `}function lR(e){return e.includes(`\r
10
+ `}function uR(e){return e.includes(`\r
11
11
  `)?`\r
12
12
  `:`
13
- `}function Fh(e){let t=e.indexOf(aR);if(t===-1)return null;let n=e.indexOf(Jc,t);return n===-1?null:{start_index:t,end_index:n+Jc.length}}function mR(e){return Fh(e)!==null}function uR(e,t="<your project test command>"){return[cR,"## pm Workflow (Agent Quickstart)","",'- Orient before mutate: `pm context --limit 10`, `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`.',"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, `pm close <id> "<evidence>" --validate-close warn`, `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Jc,""].join(e)}function pR(e,t="<your project test command>"){let n=lR(e),r=uR(n,t),o=Fh(e);if(o){let a=e.slice(o.end_index),c=a.startsWith(`\r
13
+ `}function Mh(e){let t=e.indexOf(dR);if(t===-1)return null;let n=e.indexOf(Qc,t);return n===-1?null:{start_index:t,end_index:n+Qc.length}}function pR(e){return Mh(e)!==null}function fR(e,t="<your project test command>"){return[lR,"## pm Workflow (Agent Quickstart)","",'- Orient before mutate: `pm context --limit 10`, `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`.',"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, `pm close <id> "<evidence>" --validate-close warn`, `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Qc,""].join(e)}function _R(e,t="<your project test command>"){let n=uR(e),r=fR(n,t),o=Mh(e);if(o){let a=e.slice(o.end_index),c=a.startsWith(`\r
14
14
  `)?a.slice(2):a.startsWith(`
15
- `)?a.slice(1):a,m=Lh(`${e.slice(0,o.start_index)}${r}${c}`);return{next_content:m,changed:m!==e}}let s=e.length===0?"":e.endsWith(`
15
+ `)?a.slice(1):a,m=Nh(`${e.slice(0,o.start_index)}${r}${c}`);return{next_content:m,changed:m!==e}}let s=e.length===0?"":e.endsWith(`
16
16
  `)?`
17
17
  `:`
18
18
 
19
- `,i=Lh(`${e}${s}${r}`);return{next_content:i,changed:i!==e}}async function fR(e){if(await L(ie.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Xc.readFile(ie.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=_R(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await L(ie.join(e,"pnpm-lock.yaml"))?"pnpm test":await L(ie.join(e,"bun.lock"))||await L(ie.join(e,"bun.lockb"))?"bun run test":await L(ie.join(e,"yarn.lock"))?"yarn test":"npm test"}function _R(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function hR(e,t){let n=ie.dirname(e);return ie.basename(e)==="pm"&&ie.basename(n)===".agents"?ie.dirname(n):ie.resolve(t,e)}function gR(e,t){let n=e.find(o=>ie.basename(o.file_path)==="AGENTS.md"&&o.exists);if(n)return n.file_path;let r=e.find(o=>o.exists);return r?r.file_path:ie.join(t,"AGENTS.md")}function yR(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 bR(e){let t=dR();try{ti.write(`
19
+ `,i=Nh(`${e}${s}${r}`);return{next_content:i,changed:i!==e}}async function hR(e){if(await P(ie.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Zc.readFile(ie.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=gR(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await P(ie.join(e,"pnpm-lock.yaml"))?"pnpm test":await P(ie.join(e,"bun.lock"))||await P(ie.join(e,"bun.lockb"))?"bun run test":await P(ie.join(e,"yarn.lock"))?"yarn test":"npm test"}function gR(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function yR(e,t){let n=ie.dirname(e);return ie.basename(e)==="pm"&&ie.basename(n)===".agents"?ie.dirname(n):ie.resolve(t,e)}function bR(e,t){let n=e.find(o=>ie.basename(o.file_path)==="AGENTS.md"&&o.exists);if(n)return n.file_path;let r=e.find(o=>o.exists);return r?r.file_path:ie.join(t,"AGENTS.md")}function wR(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 vR(e){let t=mR();try{ni.write(`
20
20
  Agent guidance check
21
- `),ti.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 ti.write(`
23
- `),yR(n,!0)}finally{t.close()}}function Mh(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:Qc,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 oR){let r=ie.join(e,n),o=await L(r);if(!o){t.push({file_path:r,exists:o,has_guidance:!1,has_marker:!1});continue}let s=await Xc.readFile(r,"utf8"),i=s.toLowerCase(),a=sR.filter(m=>i.includes(m)),c=mR(s);t.push({file_path:r,exists:o,has_guidance:c||a.length>=iR,has_marker:c})}return t}function Er(e,t){e.includes(t)||e.push(t)}function wR(e,t){let n=Mh(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function vR(e,t=ie.dirname(e)){let r=await L(e)?await Xc.readFile(e,"utf8"):"",o=pR(r,await fR(t));return o.changed?(await fe(e,o.next_content),{changed:!0,warnings:await W({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function kR(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=>vr(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>vr(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>vr(e.projectRoot,t.file_path))}}async function SR(e,t,n){return e?await $h(n):t}function kr(e,t,n){e.state={...e.state,...n,template_version:Qc,last_checked_files:t}}async function Dh(e,t){if(t.presentBefore)return;let n=await vR(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function ER(e,t){t||(e.warnings.push("agent_guidance:missing"),Er(e.nextSteps,Sr))}function TR(e,t){e.skipped=!0,kr(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Er(e.nextSteps,Sr)}async function AR(e,t){await Dh(e,t),kr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function CR(e,t){e.state.declined&&kr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function RR(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Er(e.nextSteps,Sr)}async function IR(e,t){if(e.prompted=!0,await bR(t.targetRelativePath)){await Dh(e,t),kr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,kr(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Er(e.nextSteps,Sr)}function xR(e){e.warnings.push("agent_guidance:missing_non_interactive"),Er(e.nextSteps,Sr)}async function OR(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(ER(n,t.presentBefore),n):t.mode==="skip"?(TR(n,t.checkedFiles),n):t.mode==="add"?(await AR(n,t),n):t.presentBefore?(CR(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(RR(n),n):t.interactive?(await IR(n,t),n):(xR(n),n)}async function Uh(e){let t=hR(e.pm_root,e.cwd),n=await $h(t),r=gR(n,t),o=vr(t,r),s=n.map(u=>vr(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await OR(Mh(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:o,checkedFiles:s,presentBefore:i,projectRoot:t}),c=wR(e.settings,a.state);return n=await SR(a.applied,n,t),{summary:kR({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:o,prompted:a.prompted,applied:a.applied,skipped:a.skipped,state:a.state}),warnings:a.warnings,next_steps:a.nextSteps,settings_changed:c.changed}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="75c0d2d2-6a89-508f-b7dd-b43d55978b44")}catch{}})();var FR=()=>LR.createInterface({input:NR,output:Le});function MR(){return structuredClone(wt)}var $R=["minimal","default","strict"];function jh(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: ${$R.join(", ")}`,d.USAGE)}function DR(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return Gm(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${Um.join(", ")}`,d.USAGE)}}}function UR(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 Zc(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:J.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function GR(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(o!==void 0){if(t.path!==void 0||Zc(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=J.resolve(e,o),u=J.join(m,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:m}}}if(t.path===void 0&&Zc(n)){let m=J.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let s=E(e,t.path),i=J.join(J.resolve(e),".agents","pm"),a=J.dirname(J.dirname(s)),c=J.resolve(s)===i?"current":"ancestor";return{pmRoot:s,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:s,workspace_root:a,discovery:c,requested_cwd:J.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:s}}}function jR(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(Zc(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&&Rt(e)!==Rt(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 ${Rt(e)}`,`pm init --id-prefix ${Rt(t)}`]});return t}function qR(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: ${Nh.join(", ")}`,d.USAGE)}function KR(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function qh(e,t){let n=ul[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function zR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function BR(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(zR).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function HR(e,t,n){let r=Ao(t.schema),o=ot(e,r.files.types,rt.types),i=$m(await B(o)),a=[],c=[];for(let m of jm(n)){let u=Dm(i,m);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await Ct({pmRoot:e,filePath:o,raw:Eo(i),op:"init:type-preset",author:C(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:o}}async function VR(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",J.join(".agents","pm")];for(let n of t)if(await L(J.join(e,n)))return!0;return!1}async function WR(e,t,n){if(!t||n||await L(J.join(e,"settings.json"))||!await VR(e))return;let r=J.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 Kh(e,t){let n=[],r=[];for(let o of t){let s=o?J.join(e,o):e,i=await L(s);await PR.mkdir(s,{recursive:!0}),i?r.push(`already_exists:${s}`):n.push(s),r.push(...await W({path:s,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function YR(e,t){let n=FR();try{Le.write(`pm init setup wizard (agent-optimized)
21
+ `),ni.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 ni.write(`
23
+ `),wR(n,!0)}finally{t.close()}}function $h(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:ed,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 Dh(e){let t=[];for(let n of iR){let r=ie.join(e,n),o=await P(r);if(!o){t.push({file_path:r,exists:o,has_guidance:!1,has_marker:!1});continue}let s=await Zc.readFile(r,"utf8"),i=s.toLowerCase(),a=aR.filter(m=>i.includes(m)),c=pR(s);t.push({file_path:r,exists:o,has_guidance:c||a.length>=cR,has_marker:c})}return t}function Er(e,t){e.includes(t)||e.push(t)}function kR(e,t){let n=$h(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function SR(e,t=ie.dirname(e)){let r=await P(e)?await Zc.readFile(e,"utf8"):"",o=_R(r,await hR(t));return o.changed?(await _e(e,o.next_content),{changed:!0,warnings:await W({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function ER(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=>vr(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>vr(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>vr(e.projectRoot,t.file_path))}}async function TR(e,t,n){return e?await Dh(n):t}function kr(e,t,n){e.state={...e.state,...n,template_version:ed,last_checked_files:t}}async function Uh(e,t){if(t.presentBefore)return;let n=await SR(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function AR(e,t){t||(e.warnings.push("agent_guidance:missing"),Er(e.nextSteps,Sr))}function CR(e,t){e.skipped=!0,kr(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),Er(e.nextSteps,Sr)}async function RR(e,t){await Uh(e,t),kr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function IR(e,t){e.state.declined&&kr(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function xR(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),Er(e.nextSteps,Sr)}async function OR(e,t){if(e.prompted=!0,await vR(t.targetRelativePath)){await Uh(e,t),kr(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,kr(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),Er(e.nextSteps,Sr)}function PR(e){e.warnings.push("agent_guidance:missing_non_interactive"),Er(e.nextSteps,Sr)}async function LR(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(AR(n,t.presentBefore),n):t.mode==="skip"?(CR(n,t.checkedFiles),n):t.mode==="add"?(await RR(n,t),n):t.presentBefore?(IR(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(xR(n),n):t.interactive?(await OR(n,t),n):(PR(n),n)}async function Gh(e){let t=yR(e.pm_root,e.cwd),n=await Dh(t),r=bR(n,t),o=vr(t,r),s=n.map(u=>vr(t,u.file_path)),i=n.some(u=>u.has_guidance),a=await LR($h(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:o,checkedFiles:s,presentBefore:i,projectRoot:t}),c=kR(e.settings,a.state);return n=await TR(a.applied,n,t),{summary:ER({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:o,prompted:a.prompted,applied:a.applied,skipped:a.skipped,state:a.state}),warnings:a.warnings,next_steps:a.nextSteps,settings_changed:c.changed}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="75c0d2d2-6a89-508f-b7dd-b43d55978b44")}catch{}})();var $R=()=>FR.createInterface({input:MR,output:Le});function DR(){return structuredClone(vt)}var UR=["minimal","default","strict"];function qh(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: ${UR.join(", ")}`,d.USAGE)}function GR(e){if(e!==void 0){if(e.trim().length===0)throw new l("--type-preset must not be empty",d.USAGE);try{return jm(e)}catch{throw new l(`Invalid --type-preset value "${e}". Allowed: ${Gm.join(", ")}`,d.USAGE)}}}function jR(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 td(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:J.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function qR(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new l("--workspace must not be empty",d.USAGE);if(o!==void 0){if(t.path!==void 0||td(n))throw new l("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",d.USAGE);let m=J.resolve(e,o),u=J.join(m,".agents","pm");return{pmRoot:u,prefixArg:n,target:{mode:"workspace-path",tracker_root:u,workspace_root:m}}}if(t.path===void 0&&td(n)){let m=J.resolve(e,n.trim());return{pmRoot:m,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:m}}}let s=E(e,t.path),i=J.join(J.resolve(e),".agents","pm"),a=J.dirname(J.dirname(s)),c=J.resolve(s)===i?"current":"ancestor";return{pmRoot:s,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:s,workspace_root:a,discovery:c,requested_cwd:J.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:i}:{}}:{mode:"tracker-path",tracker_root:s}}}function KR(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(td(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&&Rt(e)!==Rt(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 ${Rt(e)}`,`pm init --id-prefix ${Rt(t)}`]});return t}function zR(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: ${Fh.join(", ")}`,d.USAGE)}function BR(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Kh(e,t){let n=pl[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function HR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function VR(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(HR).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function WR(e,t,n){let r=Co(t.schema),o=st(e,r.files.types,ot.types),i=Dm(await q(o)),a=[],c=[];for(let m of qm(n)){let u=Um(i,m);i=u.file,(u.replaced?c:a).push(u.definition.name)}return await Je({pmRoot:e,filePath:o,raw:To(i),op:"init:type-preset",author:C(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:c,file:o}}async function YR(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",J.join(".agents","pm")];for(let n of t)if(await P(J.join(e,n)))return!0;return!1}async function JR(e,t,n){if(!t||n||await P(J.join(e,"settings.json"))||!await YR(e))return;let r=J.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 zh(e,t){let n=[],r=[];for(let o of t){let s=o?J.join(e,o):e,i=await P(s);await NR.mkdir(s,{recursive:!0}),i?r.push(`already_exists:${s}`):n.push(s),r.push(...await W({path:s,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function XR(e,t){let n=$R();try{Le.write(`pm init setup wizard (agent-optimized)
24
24
  `),Le.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
25
25
 
26
26
  `),Le.write(`1/3 Item ID prefix
@@ -30,26 +30,26 @@ Agent guidance check
30
30
  `),Le.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
31
31
  `),Le.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
32
32
  `),Le.write(`strict: ownership blocking, strict create defaults, close validation strict.
33
- `);let s=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),i=s.trim().length>0?s.trim():"minimal",a="minimal";try{a=jh(i)}catch{Le.write(`Unrecognized governance preset "${i}"; using minimal.
33
+ `);let s=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),i=s.trim().length>0?s.trim():"minimal",a="minimal";try{a=qh(i)}catch{Le.write(`Unrecognized governance preset "${i}"; using minimal.
34
34
  `)}Le.write(`
35
35
  3/3 Project telemetry
36
36
  `),Le.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=KR(m,t);return Le.write(`
38
- `),{prefix:o,preset:a,telemetry_enabled:u}}finally{n.close()}}function JR(e){return{presetFromOption:jh(e.preset),useDefaults:e.defaults===!0,authorFromOption:UR(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:qR(e.agentGuidance),typePreset:DR(e.typePreset)}}function XR(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 QR(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function ZR(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(qh(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 eI(e){let t=await T(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=XR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return QR(e.settingsPath,n,e.options.force===!0,e.target),ZR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Ie(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function tI(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await YR(t,wt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let s=n??"minimal",i=MR();i.id_prefix=t,qh(i,s);let a=Fo()?.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 Ie(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function Gh(e){return e.settingsExists?await eI(e):await tI({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function nI(e){let t=await Uh({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 Ie(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function rI(e,t){let n=[],r=[],o=await zm(e,t.schema);for(let s of o.created_paths)n.push(s),r.push(...await W({path:s,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function oI(e){if(e.typePreset===void 0)return;let t=await HR(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await W({path:t.file,scope:"project",op:"init:type_preset"})),t}async function sI(e){let n=O(e.settings,x()).folders.filter(o=>!Hi.includes(o)),r=await Kh(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function iI(e){let t=J.resolve(e.tracker_root),n=J.dirname(t);return J.basename(t)==="pm"&&J.basename(n)===".agents"?J.dirname(n):e.workspace_root}async function aI(e,t,n,r){if(!e)return;let o=await Pn("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let s=BR(o),i=s.packages.filter(a=>!a.ok).map(a=>a.alias);if(!s.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 s}function cI(e){let t=r=>Oo([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function dI(e,t,n,r=Kp){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function Tr(e,t,n={}){let r=process.cwd(),o=GR(r,t,e,n.workspace),s=o.pmRoot;e=jR(o.prefixArg,n.idPrefix);let i=JR(n);await WR(s,o.target.mode==="tracker-path",n.force===!0);let a=[],c=[],m=J.join(s,"settings.json"),u=await L(m),p;u&&(p=await Gh({pmRoot:s,settingsPath:m,settingsExists:u,normalizedPrefix:Rt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:o.target}));let f=await Kh(s,Hi);a.push(...f.createdDirs),c.push(...f.warnings),p??=await Gh({pmRoot:s,settingsPath:m,settingsExists:u,normalizedPrefix:Rt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:o.target});let{settings:_}=p,g=iI(o.target),y=await ss(g??J.dirname(s)),h=g??y,b=await nI({pmRoot:s,cwd:h??r,agentGuidanceMode:i.agentGuidanceMode,settings:_,warnings:c}),v=await rI(s,_);a.push(...v.createdDirs),c.push(...v.warnings);let k=await oI({pmRoot:s,settings:_,typePreset:i.typePreset,warnings:c});if(k&&(_=await T(s)),await sI({pmRoot:s,settings:_,createdDirs:a,warnings:c}),h&&i.agentGuidanceMode!=="status"){let N=await ca(h,{pmRoot:s});N.changed&&c.push(`updated:gitignore:${N.path}`)}!u&&n.mergeFence!==!1&&i.agentGuidanceMode!=="status"&&await dI(s,y,c);let I=await aI(i.installBundledPackages,t,s,c),A=cI({installBundledPackages:i.installBundledPackages,registeredTypePreset:k,agentGuidanceNextSteps:b.next_steps,target:o.target});return{ok:!0,path:s,target:o.target,settings:_,created_dirs:a,warnings:c,governance_preset:_.governance.preset,wizard_used:p.wizardUsed,...k?{registered_type_preset:k}:{},...I?{installed_packages:I}:{},next_steps:A,agent_guidance:b}}import hI from"node:fs/promises";import nd 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 Bh=10,cn="https://schema.unbrained.dev/pm/eval-query-set/v1";var ni={schema:cn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Be=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},lI=new Set(["keyword","semantic","hybrid"]);function zh(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function mI(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),o=zh(r,n),s=Array.from({length:t.size},()=>1),i=zh(s,n);return i===0?0:o/i}function uI(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function ed(e,t,n){let r=Math.min(n,e.length),o=0;for(let s=0;s<r;s+=1)t.has(e[s])&&(o+=1);return o}function pI(e,t,n){return n<=0?0:ed(e,t,n)/n}function fI(e,t,n){return t.size===0?0:ed(e,t,n)/t.size}function Hh(e,t,n){return{ndcg:mI(e,t,n),mrr:uI(e,t,n),precision:pI(e,t,n),recall:fI(e,t,n),relevant_total:t.size,retrieved_relevant:ed(e,t,n)}}function Vh(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function _I(e,t){if(typeof e!="object"||e===null)throw new Be(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new Be(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Be(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(s=>typeof s!="string"))throw new Be(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(s=>s.trim()).filter(s=>s.length>0))];if(o.length===0)throw new Be(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!lI.has(n.mode)))throw new Be(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function td(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==cn)throw new Be(`Unsupported eval query set schema; expected "${cn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new Be('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Be("Eval query set must contain at least one query");return{schema:cn,queries:n.map((r,o)=>_I(r,o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cc9405b-d2b8-59aa-893f-54892595788a")}catch{}})();var gI=nd.join("search","eval-queries.json"),rd={schema:cn,examples:[JSON.stringify(ni)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},yI=new Set(["keyword","semantic","hybrid"]),bI=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!yI.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},wI=e=>{if(e===void 0||e==="")return Bh;let t=_l(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},vI=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},Lt=e=>Math.round(e*1e4)/1e4,kI=async e=>{try{return await hI.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...rd,examples:[`echo '${JSON.stringify(ni)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},SI=(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,rd)}},EI=e=>{try{return td(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,rd)}},TI=async e=>EI(SI(await kI(e),e)),AI=(e,t)=>t?nd.resolve(process.cwd(),t):nd.join(e,gI),CI=async(e,t,n,r)=>{let o=e.mode??t,i=(await pr(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=Hh(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:Lt(a.ndcg),mrr:Lt(a.mrr),precision:Lt(a.precision),recall:Lt(a.recall)}}},RI=(e,t,n,r)=>{let o=Vh(n);return{k:e,query_count:t.length,aggregate:{ndcg:Lt(o.ndcg),mrr:Lt(o.mrr),precision:Lt(o.precision),recall:Lt(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||o.ndcg>=r}},Wh=async(e,t)=>{let n=E(process.cwd(),t.path);await R(n);let r=wI(e.k),o=bI(e.mode),s=vI(e.failUnder),i=AI(n,e.queries),a=await TI(i),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await CI(u,o,r,t);m.push(f),c.push(p)}return RI(r,c,m,s)};import{readFile as KI,writeFile as zI}from"node:fs/promises";import BI 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]="393f6460-bf8b-5479-8e3e-cac6f2680823")}catch{}})();function od(e,t){let n=$o(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[o,s]of e.split(/\r?\n/).entries()){let i=s.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 ${o+1}.`,d.GENERIC_FAILURE)}}return r}function Nt(e){return H({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function II(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Nt(e[r])===Nt(t[r]);)r+=1;return r}function Yh(e,t,n){od(e,"base");let r=od(t,"ours"),o=od(n,"theirs"),s=II(r,o);if(s===r.length&&s===o.length)return{merged:Vt(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===o.length)return{merged:Vt(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:Vt(o),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:o.length-s,entries_total:o.length,reanchored:!1};let i=r.slice(s),a=new Set(i.map(Nt)),c=o.slice(s).filter(p=>!a.has(Nt(p))),m=[...i,...c].sort((p,f)=>{let _=kn(p.ts,f.ts);if(_!==0)return _;let g=a.has(Nt(p)),y=a.has(Nt(f));return g!==y?Number(y)-Number(g):Nt(p).localeCompare(Nt(f))}),u=Hu([...r.slice(0,s),...m]);return{merged:Vt(u.entries),strategy:"union_reanchor",common_entries:s,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:u.entries.length,reanchored:!0}}function sd(e,t){let n=$o(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[o,s]of e.split(/\r?\n/).entries()){let i=s.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{throw new l(`Relationship merge input (${t}) contains invalid JSON at line ${o+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 ${o+1} is not a relationship event (eventId + sequence required).`,d.GENERIC_FAILURE);r.push(a)}return r}function ri(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=BR(m,t);return Le.write(`
38
+ `),{prefix:o,preset:a,telemetry_enabled:u}}finally{n.close()}}function QR(e){return{presetFromOption:qh(e.preset),useDefaults:e.defaults===!0,authorFromOption:jR(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:zR(e.agentGuidance),typePreset:GR(e.typePreset)}}function ZR(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function eI(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new l(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,d.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function tI(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&&(Kh(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 nI(e){let t=await T(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=ZR({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return eI(e.settingsPath,n,e.options.force===!0,e.target),tI({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Ie(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function rI(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let c=await XR(t,vt.telemetry.enabled);t=c.prefix,n=c.preset,r=c.telemetry_enabled,o=!0}let s=n??"minimal",i=DR();i.id_prefix=t,Kh(i,s);let a=Mo()?.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 Ie(e.pmRoot,i),{settings:i,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}async function jh(e){return e.settingsExists?await nI(e):await rI({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function oI(e){let t=await Gh({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 Ie(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function sI(e,t){let n=[],r=[],o=await Bm(e,t.schema);for(let s of o.created_paths)n.push(s),r.push(...await W({path:s,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function iI(e){if(e.typePreset===void 0)return;let t=await WR(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await W({path:t.file,scope:"project",op:"init:type_preset"})),t}async function aI(e){let n=O(e.settings,x()).folders.filter(o=>!Vi.includes(o)),r=await zh(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function cI(e){let t=J.resolve(e.tracker_root),n=J.dirname(t);return J.basename(t)==="pm"&&J.basename(n)===".agents"?J.dirname(n):e.workspace_root}async function dI(e,t,n,r){if(!e)return;let o=await Pn("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let s=VR(o),i=s.packages.filter(a=>!a.ok).map(a=>a.alias);if(!s.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 s}function lI(e){let t=r=>Po([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function mI(e,t,n,r=zp){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof l))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function Tr(e,t,n={}){let r=process.cwd(),o=qR(r,t,e,n.workspace),s=o.pmRoot;e=KR(o.prefixArg,n.idPrefix);let i=QR(n);await JR(s,o.target.mode==="tracker-path",n.force===!0);let a=[],c=[],m=J.join(s,"settings.json"),u=await P(m),p;u&&(p=await jh({pmRoot:s,settingsPath:m,settingsExists:u,normalizedPrefix:Rt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:o.target}));let f=await zh(s,Vi);a.push(...f.createdDirs),c.push(...f.warnings),p??=await jh({pmRoot:s,settingsPath:m,settingsExists:u,normalizedPrefix:Rt(e),prefixArg:e,options:n,normalizedOptions:i,warnings:c,target:o.target});let{settings:_}=p,g=cI(o.target),y=await is(g??J.dirname(s)),h=g??y,b=await oI({pmRoot:s,cwd:h??r,agentGuidanceMode:i.agentGuidanceMode,settings:_,warnings:c}),v=await sI(s,_);a.push(...v.createdDirs),c.push(...v.warnings);let k=await iI({pmRoot:s,settings:_,typePreset:i.typePreset,warnings:c});if(k&&(_=await T(s)),await aI({pmRoot:s,settings:_,createdDirs:a,warnings:c}),h&&i.agentGuidanceMode!=="status"){let N=await da(h,{pmRoot:s});N.changed&&c.push(`updated:gitignore:${N.path}`)}!u&&n.mergeFence!==!1&&i.agentGuidanceMode!=="status"&&await mI(s,y,c);let I=await dI(i.installBundledPackages,t,s,c),A=lI({installBundledPackages:i.installBundledPackages,registeredTypePreset:k,agentGuidanceNextSteps:b.next_steps,target:o.target});return{ok:!0,path:s,target:o.target,settings:_,created_dirs:a,warnings:c,governance_preset:_.governance.preset,wizard_used:p.wizardUsed,...k?{registered_type_preset:k}:{},...I?{installed_packages:I}:{},next_steps:A,agent_guidance:b}}import yI from"node:fs/promises";import od 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 Hh=10,cn="https://schema.unbrained.dev/pm/eval-query-set/v1";var ri={schema:cn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},Be=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},uI=new Set(["keyword","semantic","hybrid"]);function Bh(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function pI(e,t,n){if(t.size===0)return 0;let r=e.map(a=>t.has(a)?1:0),o=Bh(r,n),s=Array.from({length:t.size},()=>1),i=Bh(s,n);return i===0?0:o/i}function fI(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function nd(e,t,n){let r=Math.min(n,e.length),o=0;for(let s=0;s<r;s+=1)t.has(e[s])&&(o+=1);return o}function _I(e,t,n){return n<=0?0:nd(e,t,n)/n}function hI(e,t,n){return t.size===0?0:nd(e,t,n)/t.size}function Vh(e,t,n){return{ndcg:pI(e,t,n),mrr:fI(e,t,n),precision:_I(e,t,n),recall:hI(e,t,n),relevant_total:t.size,retrieved_relevant:nd(e,t,n)}}function Wh(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function gI(e,t){if(typeof e!="object"||e===null)throw new Be(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new Be(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new Be(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(s=>typeof s!="string"))throw new Be(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(s=>s.trim()).filter(s=>s.length>0))];if(o.length===0)throw new Be(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!uI.has(n.mode)))throw new Be(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function rd(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==cn)throw new Be(`Unsupported eval query set schema; expected "${cn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new Be('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new Be("Eval query set must contain at least one query");return{schema:cn,queries:n.map((r,o)=>gI(r,o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9cc9405b-d2b8-59aa-893f-54892595788a")}catch{}})();var bI=od.join("search","eval-queries.json"),sd={schema:cn,examples:[JSON.stringify(ri)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},wI=new Set(["keyword","semantic","hybrid"]),vI=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!wI.has(t))throw new l("Eval --mode must be one of keyword|semantic|hybrid",d.USAGE);return t},kI=e=>{if(e===void 0||e==="")return Hh;let t=hl(e);if(t===null)throw new l("Eval --k must be a positive integer",d.USAGE);return t},SI=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},Lt=e=>Math.round(e*1e4)/1e4,EI=async e=>{try{return await yI.readFile(e,"utf8")}catch{throw new l(`Eval query set not found at ${e}`,d.NOT_FOUND,{...sd,examples:[`echo '${JSON.stringify(ri)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},TI=(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,sd)}},AI=e=>{try{return rd(e)}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE,sd)}},CI=async e=>AI(TI(await EI(e),e)),RI=(e,t)=>t?od.resolve(process.cwd(),t):od.join(e,bI),II=async(e,t,n,r)=>{let o=e.mode??t,i=(await pr(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(c=>c.id).filter(c=>typeof c=="string"),a=Vh(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:Lt(a.ndcg),mrr:Lt(a.mrr),precision:Lt(a.precision),recall:Lt(a.recall)}}},xI=(e,t,n,r)=>{let o=Wh(n);return{k:e,query_count:t.length,aggregate:{ndcg:Lt(o.ndcg),mrr:Lt(o.mrr),precision:Lt(o.precision),recall:Lt(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:r===void 0||o.ndcg>=r}},Yh=async(e,t)=>{let n=E(process.cwd(),t.path);await R(n);let r=kI(e.k),o=vI(e.mode),s=SI(e.failUnder),i=RI(n,e.queries),a=await CI(i),c=[],m=[];for(let u of a.queries){let{report:p,metrics:f}=await II(u,o,r,t);m.push(f),c.push(p)}return xI(r,c,m,s)};import{readFile as BI,writeFile as HI}from"node:fs/promises";import VI 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]="393f6460-bf8b-5479-8e3e-cac6f2680823")}catch{}})();function id(e,t){let n=Do(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[o,s]of e.split(/\r?\n/).entries()){let i=s.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 ${o+1}.`,d.GENERIC_FAILURE)}}return r}function Nt(e){return H({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function OI(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&Nt(e[r])===Nt(t[r]);)r+=1;return r}function Jh(e,t,n){id(e,"base");let r=id(t,"ours"),o=id(n,"theirs"),s=OI(r,o);if(s===r.length&&s===o.length)return{merged:Vt(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===o.length)return{merged:Vt(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:Vt(o),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:o.length-s,entries_total:o.length,reanchored:!1};let i=r.slice(s),a=new Set(i.map(Nt)),c=o.slice(s).filter(p=>!a.has(Nt(p))),m=[...i,...c].sort((p,f)=>{let _=kn(p.ts,f.ts);if(_!==0)return _;let g=a.has(Nt(p)),y=a.has(Nt(f));return g!==y?Number(y)-Number(g):Nt(p).localeCompare(Nt(f))}),u=Vu([...r.slice(0,s),...m]);return{merged:Vt(u.entries),strategy:"union_reanchor",common_entries:s,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:u.entries.length,reanchored:!0}}function ad(e,t){let n=Do(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[o,s]of e.split(/\r?\n/).entries()){let i=s.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{throw new l(`Relationship merge input (${t}) contains invalid JSON at line ${o+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 ${o+1} is not a relationship event (eventId + sequence required).`,d.GENERIC_FAILURE);r.push(a)}return r}function oi(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
39
39
  `)}
40
- `}function xI(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Jh(e,t,n){sd(e,"base");let r=sd(t,"ours"),o=sd(n,"theirs"),s=Math.min(r.length,o.length),i=0;for(;i<s&&r[i].eventId===o[i].eventId;)i+=1;if(i===r.length&&i===o.length)return{merged:ri(r),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===o.length)return{merged:ri(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:ri(o),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:o.length-i,entries_total:o.length,reanchored:!1};let a=r.slice(i),c=new Set(a.map(f=>f.eventId)),m=o.slice(i).filter(f=>!c.has(f.eventId)),u=[...a,...m].sort((f,_)=>{if(f.timestamp!==void 0&&_.timestamp!==void 0){let h=kn(f.timestamp,_.timestamp);if(h!==0)return h}else{if(f.timestamp===void 0&&_.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let g=c.has(f.eventId),y=c.has(_.eventId);return g!==y?Number(y)-Number(g):0}),p=xI([...r.slice(0,i),...u]);return{merged:ri(p),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:m.length,entries_total:p.length,reanchored:!0}}var OI=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],PI=["updated_at"];function dn(e,t){return H(e??null)===H(t??null)}function LI(e,t,n){let r=u=>Array.isArray(u)?u:[],o=new Set(r(e).map(u=>H(u))),s=r(t),i=new Set(s.map(u=>H(u))),a=r(n),c=new Set(a.map(u=>H(u))),m=s.filter(u=>{let p=H(u);return!o.has(p)||c.has(p)});for(let u of a){let p=H(u);!i.has(p)&&!o.has(p)&&m.push(u)}return m}function Ar(e){if(typeof e!="object"||e===null||Array.isArray(e))return H(e);let{provenance:t,...n}=e;return H(n)}function NI(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function FI(e,t,n){let r=u=>Array.isArray(u)?u:[],o=new Set(r(e).map(Ar)),s=r(t),i=new Set(s.map(Ar)),a=r(n),c=new Set(a.map(Ar)),m=s.filter(u=>{let p=Ar(u);return!o.has(p)||c.has(p)});for(let u of a){let p=Ar(u);!i.has(p)&&!o.has(p)&&m.push(NI(u))}return m}function MI(e,t){return kn(String(e),String(t))>=0?e:t}function Xh(e,t,n,r){return dn(t,n)?{value:t,from_theirs:!1,conflict:!1}:dn(e,t)?{value:n,from_theirs:!0,conflict:!1}:dn(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function Qh(e,t,n,r,o){let s=Xh(e,t,n,r);if(!s.conflict||o==="preferred_side")return s;let i=H(n).localeCompare(H(t))<0;return{value:i?n:t,from_theirs:i,conflict:!0}}function id(e){return{...e.metadata}}function ad(e,t,n){try{return Ye(Do(e,n),n)}catch(r){throw new l(`Item merge input (${t}) is not a readable item document: ${String(r)}`,d.GENERIC_FAILURE)}}function $I(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?FI(e.baseValue,e.oursValue,e.theirsValue):LI(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,dn(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function DI(e){let t=Qh(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:e.baseValue,ours:e.oursValue,theirs:e.theirsValue,retained:t.value,discarded:t.from_theirs?e.oursValue:e.theirsValue})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function UI(e,t,n,r,o){let s=new Set(OI),i=new Set(PI),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(!$I({field:m,baseValue:u,oursValue:p,theirsValue:f,unionFieldSet:s,accumulator:c})){if(i.has(m)){c.merged[m]=MI(p,f);continue}DI({field:m,baseValue:u,oursValue:p,theirsValue:f,preferred:r,conflictResolution:o,accumulator:c})}}return c}function Zh(e,t,n,r={}){let o=r.preferred??"ours",s=r.conflictResolution??"preferred_side",i=e.trim().length>0,a=ad(t,"ours",r),c=ad(n,"theirs",r),m=i?ad(e,"base",r):a,u=i?id(m):{},p=id(a),f=id(c),{merged:_,conflictFields:g,fieldsFromTheirs:y,unionFields:h,conflictDecisions:b}=UI(u,p,f,o,s),v=Qh(i?m.body:"",a.body,c.body,o,s);return v.conflict?(g.push("body"),b.push({field:"body",base:i?m.body:"",ours:a.body,theirs:c.body,retained:v.value,discarded:v.from_theirs?a.body:c.body})):v.from_theirs&&y.push("body"),{merged:je({metadata:_,body:v.value},r),conflict_fields:g,fields_from_theirs:y,union_fields:h,conflict_decisions:b,requested_preference:o,conflict_resolution:s}}function cd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dd(e,t){let n=$o(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 GI(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=H(p);u.set(f,(u.get(f)??0)+1)}return u},o=r(e),s=r(t),i=r(n);for(let[m,u]of o)if((s.get(m)??0)<u||(i.get(m)??0)<u)return null;let a=new Map(s),c=[];for(let m of n){let u=H(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 jI(e,t,n,r,o,s,i){if(!cd(t)||!cd(n))return null;let a=cd(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=o.length>0?`${o}.${u}`:u,f=qI(a,t,n,u,r,p,s,i);f!==void 0&&(c[u]=f)}return c}function eg(e,t,n,r,o,s,i){if(dn(t,n))return t;let a=GI(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(o),a.merged;let c=jI(e,t,n,r,o,s,i);if(c!==null)return c;let m=Xh(e,t,n,r);return m.conflict?s.push(o):m.from_theirs&&i.push(o),m.value}function qI(e,t,n,r,o,s,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 eg(e[r],t[r],n[r],o,s,i,a);if(c){if(u&&dn(e[r],t[r])){a.push(s);return}return u?(i.push(s),o==="theirs"?void 0:t[r]):t[r]}if(!(u&&dn(e[r],n[r])))return u?(i.push(s),o==="theirs"?n[r]:void 0):(a.push(s),n[r])}function tg(e,t,n,r={}){let o=r.preferred??"ours",s=dd(e,"base"),i=dd(t,"ours"),a=dd(n,"theirs"),c=[],m=[],u=eg(s,i,a,o,"",c,m);return{merged:`${JSON.stringify(u??null,null,2)}
41
- `,conflict_paths:c,paths_from_theirs:m,preferred:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c8046a5-06aa-58f8-b347-e757086082d1")}catch{}})();var ng=["item","history","relationship","json"];function HI(e){let t=e.trim().toLowerCase();if(ng.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${ng.join(", ")}.`,d.USAGE)}function VI(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 ld(e,t){try{return await KI(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function WI(e){let t=E(process.cwd(),e.path);return await L(ye(t))?T(t):null}function YI(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function rg(e,t){let n=HI(e.artifact),r=VI(e.prefer),o=BI.resolve(e.outputPath??e.oursPath),[s,i,a]=await Promise.all([ld(e.basePath,"base"),ld(e.oursPath,"ours"),ld(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=Yh(s,i,a);c=_.merged,p.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=Jh(s,i,a);c=_.merged,p.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await WI(t),g=YI(e.itemPath??o,_),y=vt(x()),h=Zh(s,i,a,{format:g,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"stable_value_order"});if(c=h.merged,u.push(...h.conflict_fields),p.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0){let b=Do(c,{format:g,schema:_?.schema,extensionFieldNames:y}),v=b.metadata,k=[...new Set([...h.fields_from_theirs,...h.union_fields,...h.conflict_decisions.map(I=>I.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,mergedFieldHashes:Object.fromEntries(k.map(I=>[I,Cl(H(I==="body"?b.body:v[I]))])),decisions:h.conflict_decisions}}}else{let _=tg(s,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await zI(o,c,"utf8"),m!==void 0){let _=await cf(m);_!==null&&(p.receipt=cr(_))}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:o,requested_preference:r,conflicts:u,...p,guidance:f,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]="c3ec7d9d-f276-5e97-8e97-507925e5d33a")}catch{}})();var JI=4;async function XI(e){try{return{status:"fulfilled",value:await is(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function QI(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function ZI(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.force?e.pendingReceipts:e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>mf(e.gitWorkspaceRoot??process.cwd(),r,{requireExisting:!0}))),n.length}async function og(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await ss(r),s=await df(o??process.cwd(),{includeLossless:!0,pmRoot:r});if(s.invalid_evidence_count>0)throw new l(`Merge reconciliation refused ${s.invalid_evidence_count} invalid receipt evidence file(s).`,d.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let i=s.receipts,{pendingDecisions:a}=lf(i);if(!n&&e.force!==!0&&a.length>0)throw new l(`Merge reconciliation would accept ${a.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:a.map(A=>`Review receipt ${A.id} for ${A.item_id}: ${A.decisions.map(N=>N.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let c=new Map;for(let A of i){let N=c.get(A.item_id)??[];N.push(A),c.set(A.item_id,N)}let m=Object.fromEntries([...c].map(([A,N])=>[A,{merge:{receipts:N.map(cr)}}])),u=Object.fromEntries([...c].map(([A,N])=>[A,{gitWorkspaceRoot:o,receipts:N}])),p=await as({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:m,...i.length>0?{mergeReceiptProofById:u}:{}},t),f=new Set(p.streams.map(A=>A.id)),_=[...c.keys()].filter(A=>!f.has(A)),g=await af(_,JI,A=>XI({id:A,dryRun:n,options:e,global:t,auditContext:m[A],mergeReceiptProof:u[A]}));QI({receiptOnlyIds:_,results:g,repair:p});let y=await ZI({dryRun:n,force:e.force===!0,pendingReceipts:i,repair:p,gitWorkspaceRoot:o}),h=await ms({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),b=h.checks.every(A=>A.status==="ok"),v=n?i.length===0:y===i.length,k=p.totals.failed===0&&b&&v,I=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."]:k?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:k,dry_run:n,repair:p,receipts:{pending_before:i.length,reconciled:y,summaries:i.map(cr)},validation:h,guidance:I,generated_at:h.generated_at}}import{createHash as ex}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]="01043e67-99d4-5b68-a1b2-33f35f5cef5f")}catch{}})();var ag=1,cg=/^[A-Za-z0-9_-]+$/,tx=100,sg=1e3;var aq=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function He(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function nx(e){return ex("sha256").update(H({type:He(e.type),author:He(e.author),item:He(e.item),harness:He(e.harness),agent_instance:He(e.agentInstance),provenance:He(e.provenanceFilter)})).digest("hex").slice(0,24)}function ig(e,t){let n={version:ag,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 rx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===ag,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 ox(e,t){let n=e.trim();if(n.length===0||n.length>4096||!cg.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(!rx(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function sx(e){let t=e??tx;if(!Number.isSafeInteger(t)||t<0||t>sg)throw new l(`Mutation event limit must be an integer from 0 to ${sg}.`,d.USAGE,{code:"invalid_event_limit"});return t}function ix(e,t){let n=e?.trim();if(!n)return{};if(cg.test(n))return{cursor:ox(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 ax(e,t){let n=await ga(e,t);if(n===null){if(!await qu(e))return{...await Ku(e,t),source:"authoritative_history"};n=await ga(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 cx(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 oi(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await R(t);let n=sx(e.limit),r=cx(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 o=await T(t),s=o.agent_identity.identity_vocabulary,i=kp(o.agent_identity.harness_signals),a=Sp({provenance:e.provenanceFilter},i),c=He(e.harness),m=nx(e),{cursor:u,sinceTimestamp:p}=ix(e.since,m),f={...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:He(e.type),authors:He(e.author),harnesses:c,harness_alias_authors:c?Object.entries(s.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:He(e.agentInstance),provenance:[...a].map(([y,h])=>({dimension:y,values:[...h]})),stream_ids:He(e.item),limit:n},_=await ax(t,f),g=_.events.map(y=>({...r==="row"?{cursor:ig(y,m)}:{},item_id:y.stream_id,version:y.stream_offset+1,ts:y.entry.ts,author:y.entry.author,type:y.entry.op,...y.entry.message===void 0?{}:{message:y.entry.message},patch_count:y.entry.patch.length,...e.full===!0?{entry:y.entry}:{},...e.provenance===!0?{provenance:Ep(y.entry,s,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:g,count:g.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:ig(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Tp(_.events.map(y=>y.entry),s,i)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c7c75b13-7317-5089-9869-7e6e22ed95b2")}catch{}})();var dx="1h",lx="now",mx="+1d";function Ft(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function dg(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return ve(n,r)}async function lg(e,t,n,r){let o=dg(e,t,n),s=[];return Ft(s,"start",n.start??lx),n.end!==void 0?Ft(s,"end",n.end):Ft(s,"duration",n.duration??dx),Ft(s,"location",n.location),Ft(s,"timezone",n.timezone),n.allDay===!0&&Ft(s,"all_day","true"),o.event=[s.join(",")],Pt(o,r)}function mg(e,t,n){return lg("Meeting",e,t,n)}function ug(e,t,n){return lg("Event",e,t,n)}function pg(e,t,n){let r=dg("Reminder",e,t),o=[];return Ft(o,"at",t.at??mx),Ft(o,"text",t.text??e),r.reminder=[o.join(",")],Pt(r,n)}import Rr from"node:crypto";import{cp as _g,lstat as gx,mkdir as ln,readFile as qn,readdir as ud,rename as yg,rm as fd,writeFile as ii}from"node:fs/promises";import F from"node:path";import{constants as Mt}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 fg=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"}]]),ux=/^[a-z][a-z0-9_]{0,63}$/u,px=new Map([[Mt.errno.EACCES,"EACCES"],[Mt.errno.EDQUOT,"EDQUOT"],[Mt.errno.EMFILE,"EMFILE"],[Mt.errno.ENFILE,"ENFILE"],[Mt.errno.ENOMEM,"ENOMEM"],[Mt.errno.ENOSPC,"ENOSPC"],[Mt.errno.EPERM,"EPERM"],[Mt.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),fx={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function _x(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&fg.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:px.get(Math.abs(t.errno))??null}function hx(e,t,n={}){let r=_x(e);if(r===null)return null;if(!ux.test(t))throw new l("Host environment operation labels must be bounded identifiers.",d.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=fg.get(r);return new l(`Host filesystem operation ${t} ${o.summary}.`,d.GENERIC_FAILURE,{code:n.codes?.[o.category]??fx[o.category].code,reason:r,required:o.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[o.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function si(e,t,n={}){try{return await t()}catch(r){throw hx(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 bg="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var wg=F.join("runtime","workspace-snapshots"),yx=new Set(["checkpoints","locks","runtime","search","transactions"]),bx=/^[a-z0-9][a-z0-9._-]*$/,Cr="sdk-workspace-transaction",md={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},vg={renameEntry:yg,removeEntry:async e=>{await fd(e,{recursive:!0,force:!0})}},pd=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 qn(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!==Cr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await fe(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
42
- `)}};async function kg(e,t=""){let n=await ud(F.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((s,i)=>s.name.localeCompare(i.name))){if(t.length===0&&yx.has(o.name))continue;let s=F.posix.join(t.replaceAll(F.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${s}`);if(o.isDirectory())r.push(...await kg(e,s));else if(o.isFile())r.push(s);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${s}`)}return r}async function Sg(e){let t=await kg(e),n=Rr.createHash("sha256"),r=[],o=0;for(let i of t){let a=await qn(F.join(e,i));r.push(a),o+=a.byteLength,n.update(i),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let s=n.digest("hex");return{manifest:{schema:bg,fingerprint:s,files:t,bytes:o},contents:r}}function hg(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
43
- `).filter(t=>t.trim().length>0).length}async function wx(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),s=await Promise.all(o.map(async i=>[i,await qn(F.join(e,i))]));for(let[i,a]of s)n.set(i,a)}return n}function _d(e){if(!bx.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 Eg(e,t){return si(`workspace_snapshot_${e}`,t,{codes:{capacity:md.capacity.code,permission:md.permission.code,resource:md.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 mn(e){return F.join(e,wg)}function Tg(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 Ag(e,t){try{return JSON.parse(await qn(e,"utf8"))}catch(n){throw kt(n)?Tg(t):n}}async function gg(e,t,n){try{await fd(e,{recursive:n})}catch(r){throw kt(r)?Tg(t):r}}async function vx(e,t,n=vg){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 kx(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(s){throw await r.renameEntry(n,t),await r.removeEntry(e),s}await r.removeEntry(n)}async function Sx(e,t){return _d(t),/^[a-f0-9]{64}$/.test(t)?t:(await Ag(F.join(mn(e),"refs",`${t}.json`),t)).fingerprint}async function hd(e,t={}){if(t.name!==void 0&&(_d(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 Sg(e),o=mn(e),s=F.join(o,"objects",n.fingerprint),i=!1;try{i=(await gx(s)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&kt(a)))throw a}if(!i){let a=F.join(o,"objects",`.create-${process.pid}-${Rr.randomUUID()}`);await Eg("create_object",async()=>{await ln(F.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=F.join(a,"files",m);await ln(F.dirname(u),{recursive:!0}),await ii(u,r[c])}await ii(F.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
44
- `,"utf8"),await ln(F.dirname(s),{recursive:!0})}),i=await vx(a,s)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=F.join(o,"refs");await ln(c,{recursive:!0});let m=F.join(c,`.ref-${process.pid}-${Rr.randomUUID()}`);await ii(m,`${JSON.stringify(a,null,2)}
45
- `,"utf8"),await yg(m,F.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function Ir(e,t){let n=await Sx(e,t),r=await Ag(F.join(mn(e),"objects",n,"manifest.json"),t);if(r.schema!==bg||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 gd(e){let t=mn(e),n=await ud(F.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&kt(o))return[];throw o}),r=await ud(F.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&kt(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Ir(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await qn(F.join(t,"refs",o),"utf8"))))}}async function yd(e,t){let n=await Ir(e,t),{manifest:r,contents:o}=await Sg(e),s=new Map(r.files.map((p,f)=>[p,o[f]])),i=await wx(F.join(mn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),m=new Set([...a,...c]);for(let p of m){let f=s.get(p),_=i.get(p);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=hg(s.get(p)),_=hg(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 Cg(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",o=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,i=await be(e,Cr,o,r,!1,!1,s),a=new pd(Hr(e,Cr),r,o);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await yd(e,t),f=await Ir(e,t),_=await hd(e),g=f.fingerprint,y=mn(e),h=F.join(y,"objects",g,"files"),b=F.dirname(e),v=F.basename(e);c=F.join(b,`.${v}.restore-${Rr.randomUUID()}`);let k=F.join(b,`.${v}.backup-${Rr.randomUUID()}`);await Eg("restore_stage",async()=>{await ln(c,{recursive:!0}),await _g(h,c,{recursive:!0,force:!1}),await ln(F.join(c,"runtime"),{recursive:!0}),await _g(y,F.join(c,wg),{recursive:!0,force:!1})});let I=await Vu({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:p.changed_file_count,removed_file_count:p.removed_file_count,removed_item_count:p.removed_item_count,affected_history_stream_count:p.affected_history_stream_count,removed_history_entry_count:p.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:s}),A=F.relative(c,I.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let N=Hr(c,Cr);return await ln(F.dirname(N),{recursive:!0}),await ii(N,await qn(Hr(e,Cr)),{flag:"wx"}),m=!0,await kx(c,e,k,vg,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:A,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([fd(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function Rg(e,t){_d(t);let n=mn(e);if(!/^[a-f0-9]{64}$/.test(t))return await gg(F.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await gd(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await gg(F.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]="8a3a82a1-9e3d-555f-9111-3c3e19887f75")}catch{}})();function xr(e){let t={...e.args,...e.options};return ve(e.options,t)}function ut(e,t){let n=w(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Kn(e){return typeof e=="string"?[e]:ke(e)}function Ig(e){return Wh(xr(e),e.global)}function xg(e){let t=xr(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 oi({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Kn(t.type),author:Kn(t.author),item:Kn(t.item),limit:t.limit===void 0?void 0:Me(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:Kn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Kn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Kn(t.provenanceFilter)}})}function Og(e){let t=xr(e),n=ut(t,"subcommand");if(n==="install")return qp({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return og({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return uf({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return rg({artifact:ut(t,"artifact"),basePath:ut(t,"basePath"),oursPath:ut(t,"oursPath"),theirsPath:ut(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw xe({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Pg(e){let t=xr(e),n=ut(t,"subcommand");if(n!=="snapshot")throw xe({command_path:"workspace",token:n,allowed:["snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??ut(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return hd(o,{name:w(t,"name")});if(r==="list")return gd(o);let s=ut(t,"target");if(r==="inspect")return Ir(o,s);if(r==="delete")return Rg(o,s);if(r==="restore")return t.dryRun===!0?yd(o,s):Cg(o,s,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Me(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Me(t.lockWaitMs,"lockWaitMs")});throw xe({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function ai(e){let t=xr(e),n=ut(t,"title");return e.action==="meet"?mg(n,t,e.global):e.action==="event"?ug(n,t,e.global):pg(n,t,e.global)}import Mx from"node:path";import Ex from"node:fs/promises";import Lg 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]="5c70da27-21f6-5d31-b506-96e1818996d6")}catch{}})();var Tx="templates",Ax=".json",Cx=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Rx=xo.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),Ix=new Set(Rx);function xx(e){let t=e.trim();if(!Cx.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 Ng(e){return Lg.join(e,Tx)}function Fg(e,t){return Lg.join(Ng(e),`${t}${Ax}`)}async function Ox(e){await R(e)}function Mg(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function Px(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(Ix.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(s=>typeof s=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return Mg(t)}function Lx(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[o,s]of Object.entries(n)){let i=o.trim();if(i.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof s=="string"){r[i]=s;continue}if(Array.isArray(s)&&s.every(a=>typeof a=="string")){r[i]=[...s];continue}throw new l(`Template "${t}" contains invalid value for option "${i}".`,d.GENERIC_FAILURE)}return Mg(r)}function Nx(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,o=Lx(r.options,t),s=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:s,updated_at:typeof r.updated_at=="string"?r.updated_at:s,options:o}}async function Fx(e,t){let n=await B(Fg(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return Nx(n,t)}async function bd(e,t,n){let r=E(process.cwd(),n.path);await Ox(r);let o=xx(e),s=Px(t);if(Object.keys(s).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let i=S(),a=Fg(r,o),c=i;await L(a)&&(c=(await Fx(r,o)).created_at);let m={name:o,created_at:c,updated_at:i,options:s},u=await T(r);return await Ex.mkdir(Ng(r),{recursive:!0}),await Ct({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
46
- `,op:"templates:save",author:C(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:a,options:m.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f65b4f1f-5501-5829-a04b-d4fbcfb59f5c")}catch{}})();var Gg=["list","show","apply","lint"],$x="schema-types",Dx="schema-statuses",Ux="schema-fields";function ci(){let e=x();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function jg(){let{profiles:e,warnings:t}=qm(ci());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:Vm(n.definition)})),warnings:t,generated_at:S()}}function qg(e){let t;try{t=To(e,ci())}catch(r){throw new l(r instanceof Error?r.message:String(r),d.USAGE)}let{resolved:n}=t;return{action:"show",...Wm(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function Kg(e){let t;try{t=To(e,ci())}catch(o){throw new l(o instanceof Error?o.message:String(o),d.USAGE)}let{resolved:n}=t,r=pu(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 Gx(e,t){return Mx.join(e,"templates",`${t}.json`)}async function jx(e,t){let n=await B(Gx(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function $g(e,t,n,r){let o=new Map;for(let s of r.templates){let i=await jx(e,s.name);i!==void 0&&o.set(s.name,i)}return{typesRaw:await B(ot(e,t.files.types,rt.types)),statusesRaw:await B(ot(e,t.files.statuses,rt.statuses)),fieldsRaw:await B(ot(e,t.files.fields,rt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function zn(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function Dg(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:zn(t.types.changes),statuses:zn(t.statuses.changes),fields:zn(t.fields.changes),workflows:zn(t.workflows.changes.map(s=>({key:s.type,status:s.status}))),config:zn(t.config.changes),templates:zn(t.templates.changes.map(s=>({key:s.name,status:s.status}))),packages:t.packages,warnings:[...new Set(o)].sort((s,i)=>s.localeCompare(i)),generated_at:S()}}async function qx(e){await R(e)}function Kx(e){try{let t=To(e,ci());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function zg(e,t,n){let r=E(process.cwd(),n.path);await qx(r);let o=Kx(e),s=o.profile,i=o.warnings,a=t.dryRun===!0,c=await T(r),m=Ao(c.schema);if(a){let b=await $g(r,m,c,s),v=Ug(s,b);return Dg(s,v,!1,!0,[...i])}let u=C(t.author,c.author_default),p=Yu(c),f=!!t.force,_=[...i],g=[],y=async b=>{g.push(await be(r,b,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},h;try{await y($x),await y(Dx),await y(Ux);let b=await $g(r,m,c,s);if(h=Ug(s,b),h.types.changed){let v=ot(r,m.files.types,rt.types);await Ct({pmRoot:r,filePath:v,raw:Eo(h.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let k=new Set(s.types.map(A=>Mm(A).name)),I=h.types.file.definitions.filter(A=>k.has(A.name));await Wp(r,I,_,"profile:apply-type-folder"),_.push(...await W({path:v,scope:"project",op:"profile:apply-types"}))}if(h.statuses.changed){let v=ot(r,m.files.statuses,rt.statuses);await Ct({pmRoot:r,filePath:v,raw:Hm(h.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await W({path:v,scope:"project",op:"profile:apply-statuses"}))}if(h.fields.changed){let v=ot(r,m.files.fields,rt.fields);await Ct({pmRoot:r,filePath:v,raw:Km(h.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await W({path:v,scope:"project",op:"profile:apply-fields"}))}if(h.config.changed||h.workflows.changed){for(let v of h.config.changes){if(v.status==="unchanged")continue;let k=Ro(v.key);k!==void 0&&Io(c,k,v.value)}c.schema.type_workflows=h.workflows.result,await Ie(r,c,"profile:apply-config")}for(let v of h.templates.changes)v.status!=="unchanged"&&await bd(v.name,{...v.options},n)}finally{for(let b of g.reverse())try{await b()}catch{}}return Dg(s,h,h.changed,!1,_)}function Ug(e,t){try{return fu(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import Hg from"node:fs/promises";import Vg 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 zx(e,t,n){let r=new Set,o=[];for(let s of e){let i=s.trim();if(i.length===0||r.has(i))continue;r.add(i);let a=t.get(i);if(a===void 0){o.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){o.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return o}function Bx(e,t){let n=[...e].sort((o,s)=>s.entries-o.entries||o.id.localeCompare(s.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function Bg(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return zx(t.ids,n,t.minEntries)}return Bx(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]="31152621-df59-54a5-a28d-63119e734e6e")}catch{}})();function Hx(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 s=Number.parseInt(n,10);if(!Number.isSafeInteger(s)||s<1||s>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,s-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 o=0;for(let[s,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 ${s+1}.`,d.GENERIC_FAILURE);if(a>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function Vx(e,t){let n=Uo(),r=Uo();for(let o=0;o<e.length;o+=1){let s=e[o];if(En(n)!==s.before_hash)throw new l(`history-compact detected before-hash drift at entry ${o+1}; run pm history-repair first.`,d.CONFLICT);if(n=jo(n,s.patch,o+1,s.op),En(n)!==s.after_hash)throw new l(`history-compact detected after-hash drift at entry ${o+1}; run pm history-repair first.`,d.CONFLICT);o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function Wx(e,t,n){let r=structuredClone(t),o=[];for(let[s,i]of e.entries()){let a=En(r);r=jo(r,i.patch,n+s+1,i.op),o.push({...i,before_hash:a,after_hash:En(r)})}return{entries:o,finalReplay:r}}async function Yx(e,t,n){let r=e.located?await V(e.located,{schema:t.schema}):null;return r?{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:En(tr(r.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function Jx(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 Xx(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 Qx(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=Vx(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Wx(r,t,e.boundary.compactCount),i=[qe({nowIso:S(),author:e.author,op:"history_compact_baseline",before:Ht(Uo()),after:Ht(t),message:Xx(e.boundary)}),...o.entries];return e.dryRun||i.push(qe({nowIso:S(),author:e.author,op:"history_compact",before:Ht(n),after:Ht(n),message:Jx(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Zx(e){return ip({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})=>sp({historyPath:e.historyPath,nextHistoryRaw:Vt(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>W({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function wd(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await T(r),s=O(o,x()),i=await ap(r,e,o,s.type_to_folder),a=i.historyPath,c=await B(a);if(c===null)throw new l(`No history stream exists for ${i.id}.`,d.NOT_FOUND);let m=await Sn(a,i.id);if(m.length===0)throw new l(`No history entries exist for ${i.id}; nothing to compact.`,d.USAGE);let u=ya(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=Hx(t.before,m),f=p.compactCount>0,_=!!t.dryRun,g=C(t.author,o.author_default),y=[];f||y.push("history_compact_noop_before_boundary");let h=await Yx(i,o,m);h.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:k}=Qx({historyEntries:m,boundary:p,changed:f,dryRun:_,author:g,options:t}),I=ya(b);if(!I.ok)throw new l(`history-compact produced an invalid rewritten chain (${I.errors.join(", ")}).`,d.GENERIC_FAILURE);f&&!_&&y.push(...await Zx({pmRoot:r,subject:i,settings:o,typeRegistry:s,historyRawBeforeLock:c,currentItemRawBeforeLock:h.currentItemRawBeforeLock,author:g,force:t.force,loadedItem:h.loadedItem,historyPath:a,rewrittenEntries:b}));let A=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:A},history:{path:a,entries_scanned:m.length,entries_after:b.length,baseline_entry_added:v,audit_entry_added:k,verify_ok:I.ok,verify_errors:I.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:h.matchedChainBefore},warnings:[...new Set(y)].sort((N,M)=>N.localeCompare(M)),generated_at:S()}}var eO=3;function tO(e){let t=Xo(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:Jo(t)}}function Wg(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 nO(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function rO(e){let t=D(e.settings.schema),n=us(t),r=await ae(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),s=Vg.join(e.pmRoot,"history"),i=[],a=[];if(!await L(s))return{candidates:i,preselectionErrors:a};let c=(await Hg.readdir(s)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=Vg.join(s,m),p=m.slice(0,-6);try{let f=await Hg.readFile(u,"utf8");await bn({path:u,scope:"project"}),i.push({id:p,entries:nO(f),bucket:o.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:i,preselectionErrors:a}}async function oO(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 wd(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 Yg(e,t){let n=tO(e),r=E(process.cwd(),t.path);await R(r);let o=await T(r),s=O(o,x()),{candidates:i,preselectionErrors:a}=await rO({pmRoot:r,settings:o,typeToFolder:s.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??eO,u=o.history.compact_policy,p=c==="scan"&&e.allOver===void 0&&u.enabled,f=e.allOver??(p?u.max_entries:void 0),_=Bg(i,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),g=!!e.dryRun,y=[...a],h={streams_considered:i.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let b of _){let v=await oO({row:b,options:n,dryRun:g,global:t});if(y.push(v.result),!v.selected){h.items_skipped+=1;continue}h.selected+=1,v.compacted&&(h.items_compacted+=1),v.errored&&(h.items_errored+=1)}return{bulk:!0,dry_run:g,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:p},totals:h,results:y,generated_at: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]="4888a558-7f50-5c28-8e29-fcd19180cbd4")}catch{}})();function Jg(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return pf(n,t),t?as(e.options,e.global):is(n,e.options,e.global)}function Xg(e){let t=e.options.ids,n=Xo(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:Jo(n),o=Me(e.options.allOver??e.options.all_over,"history-compact allOver"),s=Me(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),i=w(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(i==="closed"||i==="all-streams")&&a.push(i);let c=[...new Set(a)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let m=c[0];return Wg(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?wd(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):Yg({ids:r,scope:m,allOver:o,minEntries:s,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function di(e){return Co("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08dcee99-5572-5133-b76a-6a50e4e292e7")}catch{}})();async function vd(e,t,n,r){let o=t.trim();if(o.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",d.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let s=E(process.cwd(),r.path),i=D((await T(s)).schema),a=i.open_status,c=di(i),m=n.status??a,u=X(m,i)??m;if(u!==a&&u!==c)throw new l(`Reopen target status must be ${a} or ${c}; received ${m}.`,d.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([a,c])],suggested_retry:`pm item reopen ${e} "${o}" --status ${a}`,suggested_retry_args:["item","reopen",e,o,"--status",a]}});let p=await B_(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:p.item,changed_fields:p.changed_fields,warnings:p.warnings,recurrence:p.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="55869854-565d-52d2-8dca-b66aade074bb")}catch{}})();function Qg(e,t){let n=e.id??w(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function Zg(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function ey(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await ct(Qg(e,r),Zg(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function ty(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await vd(Qg(e,r),Zg(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2ef0de1-bc44-5550-862c-f3929334fbef")}catch{}})();function ny(e,t,n){let r;if(typeof e.lines=="string")r=cs(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=cs(`${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 sO=aa("list").properties.outputSession,iO={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:{...sO},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},ry={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},re={type:"string",description:"pm item id, for example pm-abc1."},aO=`Operation name (one of): ${na.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,cO={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."}},dO={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function G(e,t=[]){return{...ry,properties:{...ry.properties,...e},required:t}}var lO=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:G({action:{type:"string",enum:[...na],description:aO},id:re,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."},...iO},["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:G({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:G({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid, options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:G({query:{type:"string"},options:{type:"object"},...dO},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:G({options:{type:"object"},...cO})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:G({id:re,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:G({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:G({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:re,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:G({id:re,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:G({id:re,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:G({id:re,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:re,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:G({id:re,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:G({id:re,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:re,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:G({id:re,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:G({id:re,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:G({id:re,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:G({id:re,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:G({id:re,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:G({id:re,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:G({subcommand:{type:"string",enum:[...su]},id:re,target:re,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:G({id:re,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:G({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:G({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:G({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Schema mutations write workspace config files, not item history.",inputSchema:G({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:[...Ui]},description:`Lifecycle roles for add-status: ${Ui.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:G({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:G({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:G({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],mO={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},uO=lO.map(e=>{let t=mO[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:aa(t,{properties:n,required:r})}});function oy(){return uO.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="428a19d2-be42-548a-a328-aa0e476b8a71")}catch{}})();var sy=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"]]]),pO=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],_y=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),mi=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"]),Or=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"]),hy=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"]]),gy=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"]]),yy=new Map([...gy.entries()].flatMap(([e,t])=>pt(t).map(n=>[n,e]))),by=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],wy=new Map(by.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),fO=10,_O=20,iy=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."]]),vy=[["init",Yl],["install",Xl],["uninstall",Ql],["explore",Zl],["manage",sm],["describe",em],["reload",im],["doctor",am],["catalog",cm],["adopt",dm],["adopt-all",tm],["activate",nm],["deactivate",rm],["migrate",om]],hO=vy.map(([e,t])=>e==="init"?[e,Jl]:[e,t]),gO=[...vy.map(([e,t])=>[`extension ${e}`,t]),...hO.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",no],["config",Wl],["extension",ro],["package",Jn],["packages",Jn],["install",lm],["create",lo],["item mutate",xm],["item complete",Om],["item reopen",Pm],["copy",mo],["focus",uo],["update",po],["update-many",fo],["upgrade",mm],["calendar",Xn],["cal",Xn],["context",Qn],["ctx",Qn],["get",ho],["search",vo],["eval",Nm],["workspace",St],["workspace snapshot",St],["workspace snapshot create",St],["workspace snapshot list",St],["workspace snapshot inspect",St],["workspace snapshot restore",St],["workspace snapshot delete",St],["next",wo],["aggregate",Qr],["deps",yo],["graph",bo],["guide",go],["reindex",um],["history",Zr],["history-compact",Bl],["history-redact",Kl],["history-repair",zl],["history-author-acknowledge",eo],["merge",ql],["schema",Hl],["profile",Vl],["plan",to],["restore",_m],["delete",hm],["close",pm],["close-many",oo],["append",so],["claim",fm],["release",gm],["start-task",ym],["pause-task",bm],["close-task",wm],["comments",$l],["notes",Dl],["learnings",Ul],["files",Gl],["docs",jl],["test",Sm],["test-all",Em],["telemetry",Tm],["test-runs",Am],["gc",Cm],["stats",io],["duplicates",ao],["validate",Rm],["health",co],["assurance",Im],...Fm,["contracts",ko],["completion",So],["activity",_o],...[..._y].map(e=>[e,Xr])],Td=new Map(gO);function yO(e){let t=yy.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function ay(e){return ea.includes(e)?ue(e):e.startsWith("extension-")?ue(`extension ${e.slice(10)}`):e.startsWith("package-")?ue(`package ${e.slice(8)}`):e.startsWith("item-")?ue(`item ${e.slice(5)}`):e.startsWith("test-runs-")?ue(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?ue(`templates ${e.slice(10)}`):mi.has(e)?gy.get(e)??ue(e):null}function bO(e,t){return e.command_path===null?!1:pt(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `)||t.startsWith(`${n} `))}function pt(e){return e.split("|").map(t=>ue(t)).filter(t=>t.length>0)}function wO(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let s of pt(o.command_path)){let i=s.split(" ").filter(a=>a.length>0);if(i.length!==0)for(let a=i.length;a>0;a-=1){let c=i.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,s)=>o.localeCompare(s))}function li(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Pr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function vO(e,t){if(!t)return{...e};let r=Pr(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:r}}function kd(e,t){let r=Pr(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function ue(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function ky(e){return e.replace(/\s+/g,"-")}function Xe(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function cy(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=Xe(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function Sd(e,t,n){n&&(e[t]=!0)}function dy(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 kO(e){let t=dy(e.long,"long"),n=dy(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),Sd(o,"required",e.required===!0),Sd(o,"repeatable",e.repeatable===!0),Sd(o,"list",e.list===!0);let s=Xe(e.description);s&&(o.description=s);let i=Xe(e.value_name);i&&(o.value_name=i);let a=[Xe(e.value_type),Xe(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(o.value_type=a),o}function Sy(e){let t=new Map;for(let r of e){let o=ue(r.target_command);if(o.length===0)continue;let s=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;s.sourceDedupe.has(i)||(s.sourceDedupe.add(i),s.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=kO(a);if(!c)continue;let m=`${c.flag}|${c.short??""}`;s.dedupe.has(m)||(s.dedupe.add(m),s.flags.push(c))}t.set(o,s)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((s,i)=>{let a=s.layer.localeCompare(i.layer);return a!==0?a:(s.name??"").localeCompare(i.name??"")})});return n}function SO(e){let t=Sy(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let i=ue(s.command);if(i.length===0)continue;let a=Xe(s.action)??ky(i),c=Array.isArray(s.arguments)?s.arguments.map(m=>{let u=Xe(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:Xe(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{command:i,action:a,source:{layer:s.layer,name:s.name},description:Xe(s.description),intent:Xe(s.intent),arguments:c,flags:t.get(i)?.flags??[],examples:cy(s.examples),failure_hints:cy(s.failure_hints)})}let r=new Set;for(let s of e.handlers)r.add(ue(s));for(let s of n.keys())r.add(s);for(let s of t.keys())r.add(s);let o=[];for(let s of[...r].sort((i,a)=>i.localeCompare(a))){let i=n.get(s);o.push(EO(s,i,t.get(s)?.flags??[]))}return o}function EO(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:ky(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function TO(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(o,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function AO(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 CO(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function RO(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=AO(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let s=TO(o);!s||n[s]!==void 0||(n[s]=CO(o,e.action),o.required===!0&&r.push(s))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function IO(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 xO(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((s,i)=>s.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let i=`${s.flag}|${s.short??""}`;if(!o.has(i))o.add(i),r.flags.push(s);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);a&&IO(a,s)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function OO(e,t=T){let n={mode:wt.extensions.policy.mode,trust_mode:wt.extensions.policy.trust_mode,default_sandbox_profile:wt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await L(ye(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),s=await Wr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),i=await Yr({...s,loaded:s.loaded});return{handlers:new Set(i.commands.handlers.map(c=>ue(c.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function PO(e,t={}){let n=new Map;for(let r of ta){let o=mi.has(r);if(o&&!t.includePackageOwnedActions)continue;let s=ay(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:s})}if(t.includePackageOwnedActions)for(let r of mi)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:ay(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:ue(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function LO(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?pt(e.command_path):[],r=n.some(i=>t.handlers.has(i)),o=n.map(i=>hy.get(i)).find(i=>typeof i=="string"),s=t.disabledReason===null&&r;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function Ey(e){return Td.get(e)??Jr}function NO(e){return Or.has(e)?!1:Td.has(e)}function FO(e){return _y.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function ly(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function MO(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function $O(e){let t=new Map;for(let r of e.definitions){let o=ly(r.cli_flag);if(!o)continue;let s=r.cli_aliases.map(a=>MO(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>ly(a)).filter(a=>a!==null&&a!==o);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=s?{flag:o,short:s}:{flag:o},u=`${m.flag}|${m.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(m));for(let p of i){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,Xi(o.flags));return n}function my(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let s=`${o.flag}|${o.short??""}`;r.has(s)||(r.add(s),n.push(o))}return Xi(n)}function DO(e,t,n,r){return e.map(o=>{let s=NO(o),i=s?Ey(o):[],a=n.get(FO(o))??[],c=t.get(o),m=my(i,a),u=my(m,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:o,flags:u,...r?{canonical_command:Ed(o),visibility:Tu(Ed(o)),positionals:Nl(o)?.slots??[],flag_invocations:Eu(o,u)}:{},provider:p,extension_sources:c?.sources}}).sort((o,s)=>o.command.localeCompare(s.command))}function UO(e,t=Zn){let n=new Set(e),r=new Map;for(let o of by){let s=o.aliases.filter(i=>n.has(i));r.set(o.canonical,{canonical:o.canonical,aliases:s,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let s=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};s.aliases.includes(o.alias)||s.aliases.push(o.alias),s.contracts.push(o),r.set(o.canonical,s)}return[...r.values()].map(({contracts:o,...s})=>o.length===0?s:{...s,contracts:o}).sort((o,s)=>o.canonical.localeCompare(s.canonical))}function GO(){return{create_string_options:_u,create_repeatable_options:xo,update_string_options:hu,update_repeatable_options:gu,list_string_options:Il,search_string_options:xl,calendar_string_options:Ol,context_string_options:Pl,activity_string_options:Ll}}function uy(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=_n(e,"create",n),o=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(o.map(a=>ge("create",a)))].sort((a,c)=>a.localeCompare(c)),i=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:o,required_flags:s,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function jO(e){let t={},n={};for(let r of[...e.types].sort((o,s)=>o.localeCompare(s))){let o=e.by_type[r];t[r]=uy(o,"strict"),n[r]=uy(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function qO(e,t){let n=Pr(e);if(n.length===0)return e;let r=!1,o=n.map(s=>{let i=s.properties;if(typeof i!="object"||i===null)return s;let a=i.action;return typeof a!="object"||a===null||a.const!=="create"?s:(r=!0,{...s,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function KO(e){let t=li(e.action)!==void 0||li(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,s=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=li(e.action),u=li(e.command),p=!r&&!c&&!o&&!s&&!i&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:o,flagsOnly:s,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function zO(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 BO(e,t=T){try{return await t(e)}catch{return structuredClone(wt)}}async function HO(e,t){let n=await BO(t),r=await OO(e),o=O(n,r.registrations??x()),s=We(n.schema),i=SO(r);return{settings:n,runtimeProbe:r,typeRegistry:o,statusRegistry:D(n.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:$O(s),createRequiredOptionContracts:jO(o),extensionContracts:i,mergedExtensionContracts:xO(i),extensionFlagMap:Sy(r.flagRegistrations)}}function py(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&mi.has(e.selectedAction)||e.selectedCommand!==void 0&&Or.has(e.selectedCommand))}function VO(e,t){let n=PO(t,{includePackageOwnedActions:py(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(au);return n.filter(o=>!r.has(o.action))}return py(e)&&e.selectedCommand!==void 0&&Or.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:yO(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function WO(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 YO(e,t){return[...new Set([...ea.filter(n=>!Or.has(n)),...[...Td.keys()].filter(n=>!Or.has(n)),...e.flatMap(n=>n.command_path?pt(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>ue(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function JO(e,t){let n=t.slice(0,fO),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),s=t.slice(0,_O),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: ${o}.`,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:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function XO(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 QO(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 ZO(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(s=>s.startsWith(`${e.selectedCommand} `));if(r.length>0)throw JO(e.selectedCommand,r);let o=hy.get(e.selectedCommand);throw o?XO(e.selectedCommand,o):QO(e.selectedCommand)}function eP(e,t){let n=VO(e,t.mergedExtensionContracts);WO(e,n);let r=YO(n,t.mergedExtensionContracts);ZO(e,r);let o=e.selectedCommand?yy.get(e.selectedCommand):void 0,s=e.selectedCommand?n.filter(m=>o?m.action===o:bO(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.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?s.filter(m=>m.action===e.selectedAction):s,a=[...new Map(i.map(m=>LO(m,t.runtimeProbe)).map(m=>[o?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(m=>m.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:s,scopedActionDescriptors:i,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function tP(e){return new Set(Pr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function nP(e){let t=uu,n=Pr(t),r=tP(t),o=e.filter(s=>!r.has(s.action)).map(s=>RO(s));return o.length>0?{...t,oneOf:[...n,...o]}:t}function fy(e,t,n){let r=new Set(t.actionDescriptors.map(s=>s.action)),o=e.selectedAction?vO(n,e.selectedAction):e.selectedCommand?kd(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):kd(n,r);return e.runtimeOnly&&!e.selectedAction?kd(o,new Set(t.actions)):o}function rP(e,t,n){let r=nP(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?qO(fy(e,n,r),t.createRequiredOptionContracts):fy(e,n,r);return{mergedSchema:r,filteredSchema:s}}function oP(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?wO(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function sP(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Zn.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function Ed(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":wy.get(t)??t}var iP=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"]]),aP=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function cP(e,t){let n=iy.get(e)??(e.includes(" ")?void 0:iy.get(Ed(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>pt(m.command).includes(e));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let o=e.split(" "),s=o.at(-1),i=o.slice(0,-1).join(" "),a=iP.get(s),c=aP.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function dP(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(ue))].filter(s=>s.length>0).sort((s,i)=>s.localeCompare(i)).map(s=>{let i=ra(s,{generateFallback:!0}),a=s.split(" ")[0],c=wy.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),m=new Set([...Ey(s).map(f=>f.flag),...t.filter(f=>pt(f.command).includes(s)).flatMap(f=>f.flags.map(_=>_.flag))]),u=(sy.get(s)??sy.get(c)??pO).filter(f=>m.has(f)),p=cP(s,t);return{command:s,intent:p.intent,...o||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:i.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...i.default_max_estimated_tokens_by_format}}:{}}})}function lP(e){return e.map(t=>({budget:ra(t,{generateFallback:!0}),envelope:Ru(t)}))}function mP(e){let t=new Map;for(let n of e){let r=bu(n),o=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,s=o.join(","),i=t.get(s)??{commands:[],exit_codes:o};i.commands.push(n),t.set(s,i)}return[...t.values()]}function uP(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>pt(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>pt(o.command).some(s=>r.has(s)))}return t.extensionContracts}function pP(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 fP(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,s])=>[o,[...new Set(s.map(i=>`--${i.cli_flag}`))].sort((i,a)=>i.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Zm],services:[...eu],policy_modes:[...tu],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...ou],trust_modes:[...nu],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...ru],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...il],create_modes:[...al],close_validation_modes:[...cl],workflow_enforcement_modes:[...dl]},e.relationship_kind_contracts=[...hl,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,s)=>o.kind.localeCompare(s.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function _P(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 hP(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=DO(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let s=new Set(r);e.list_projections=Object.entries(Ou).filter(([i])=>s.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...xu],compact_fields:[...Iu]}))}e.command_aliases=o}}function gP(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=GO();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function yP(e,t,n,r){e.command_summaries=dP(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...cu],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(ue))].filter(o=>sa(o)!==void 0).sort((o,s)=>o.localeCompare(s)).map(o=>({command:o,modes:[...lu(o).keys()]}))}:{}},e.grammar_contracts={nouns:Kt.nouns,shared_verbs:Kt.shared_verbs,scope_before_verb:Kt.scope_before_verb,visible_top_level_ceiling:Kt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Kt.ceiling_raise_requires_pm_item,positional_shape_budget:Kt.positional_shape_budget,positional_shape_count:new Set(Ji.map(({slots:o})=>Ml(o))).size,positional_action_count:Yi.length,positional_action_parents:[...new Set(Yi.map(({parent:o})=>o))].sort((o,s)=>o.localeCompare(s)),...r.includePositionalSignatures?{positional_signatures:Ji}:{}}}async function Ty(e,t){let n=KO(e);zO(n);let r=E(process.cwd(),t.path),o=await HO(t,r),s=eP(n,o),i=rP(n,o,s),a=oP(n,s),c=sP(n,a),m=pP(n,i,s,c),u=uP(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&yP(m,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return m;let f=UO(s.commandCatalog);return n.flagsOnly&&!n.fullOutput||fP(m,o,n),_P(m,n,i,u),hP(m,n,o,c,f),gP(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...Ip],gate_triggers:[...Rp]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=Fl),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=oy(),m.context_intents=wu(),m.read_output_dimensions=oa,m.error_codes=Su,m.command_output_contracts=lP(c),m.diagnostic_output_contracts=du,m.command_exit_contracts={vocabulary:yu,command_sets:mP(c)}),m}import tL from"node:fs/promises";import Ky 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 ui(e,t,n,r,o,s="min"){let i=o==="min"?e-t:t-e,a=s==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&a<0}function bP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,s=null,i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let u;try{u=JSON.parse(m)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(ui(f,i,p,o,"min")&&(i=f,o=p),ui(f,a,p,s,"max","max")&&(a=f,s=p))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:s}}function Ay(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:g})=>bP(_,g)),s=0,i=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of o){if(s+=_.lines,i+=_.bytes,_.oldest_ts!==null){let g=Date.parse(_.oldest_ts);ui(g,m,_.id,a?.id??null,"min")&&(m=g,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let g=Date.parse(_.newest_ts);ui(g,u,_.id,c?.id??null,"max")&&(u=g,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...o].sort((_,g)=>g.bytes-_.bytes||_.id.localeCompare(g.id)).slice(0,r),f=r===0?[]:[...o].sort((_,g)=>g.lines-_.lines||_.id.localeCompare(g.id)).slice(0,r);return{total_streams:e.length,total_lines:s,total_bytes:i,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as vP}from"node:crypto";import{execFile as kP}from"node:child_process";import Iy from"node:path";import{promisify as SP}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 Cy=1;function wP(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Ad(e){if(e===null)return{format_version:Cy,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!==Cy||!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(!wP(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]="c2e1edc9-c454-5cfa-85c8-e9fb0a76a296")}catch{}})();var EP=SP(kP),TP=50,Ry=1e3,AP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function xy(e){let t=e.trim().toLowerCase();if(!AP.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 CP(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 Lr(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 RP(e){let t=e??TP;if(!Number.isSafeInteger(t)||t<0||t>Ry)throw new l(`Improvement observation limit must be an integer from 0 to ${Ry}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Oy(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 IP(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=xy(n.metric),o=CP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let s=await OP(e,n.revision),i=Lr(n.source,"source"),a=Lr(n.itemId,"itemId"),c=Lr(n.unit,"unit"),m=Lr(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,r,i??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Oy(n.observedAt??S(),"observedAt"),...s,author:C(n.author,t.author_default),...a===void 0?{}:{item_id:a},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:vP("sha256").update(H(u)).digest("hex").slice(0,24),...u}}function xP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function OP(e,t){let n=Lr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await EP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:fl(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function PP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function Py(e,t={}){let n=E(process.cwd(),t.path);await R(n);let r=await T(n),o=await IP(n,r,e),s=Iy.join(n,"improvement-ledger.json"),i=await Wu({pmRoot:n,filePath:s,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Ad(a),m=xP(c,o);return m?{raw:a,result:m}:(c.observations.push(o),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${H(c)}
47
- `,result:o})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function Ly(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await R(t);let n=e.metric===void 0?void 0:xy(e.metric),r=e.since===void 0?void 0:Oy(e.since,"since"),o=RP(e.limit),i=Ad(await B(Iy.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of i){let m=a.get(c.metric)??[];m.push(c),a.set(c.metric,m)}return{observations:[...i].reverse().slice(0,o),total:i.length,truncated:i.length>o,trends:[...a].map(([,c])=>PP(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 Ny(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 LP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function NP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function Cd(e=er,t=wn){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function FP(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function Rd(e,t=wn,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let s of t){let i=`${o.agent_harness}\0${s}`,a=r.get(i)??{harness:o.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=o.agent_provenance?.[s];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(i,a)}return[...r.values()].map(o=>{let s=o.observed+o.unavailable;return{...o,coverage:s===0?null:o.observed/s,inert:s>=n&&o.observed===0}}).sort((o,s)=>o.harness.localeCompare(s.harness)||o.dimension.localeCompare(s.dimension))}function MP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let u=`${c.agent_harness}\0${m}`,p=o.get(u)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),o.set(u,p)}let s=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[u])=>m.localeCompare(u)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),i=s.filter(c=>c.entries>=r),a=i.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:i.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:s,failures:a}}function $P(e){let t=[...e].sort((s,i)=>s.ts.localeCompare(i.ts)||s.author.localeCompare(i.author)||s.op.localeCompare(i.op)||s.before_hash.localeCompare(i.before_hash)||s.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let s of t){let i=s.agent_episode,a=Ny(s),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(s);continue}let u={id:a.id,...i?.label===void 0?{}:{label:i.label},...i?.parent_id===void 0?{}:{parent_id:i.parent_id},source:a.source,entries:[s],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let o=[];for(let s of n.values()){let i=s.parent_id?r.get(s.parent_id):void 0;i&&LP(s,i,r)?i.children.push(s):o.push(s)}return NP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var DP=1e4,Fy=1e5,UP=1e3,GP=30,jP=["append","comment","docs","file","learning","note","test_run"];function qP(e){let t=e??DP;if(!Number.isSafeInteger(t)||t<1||t>Fy)throw new l(`History analytics event limit must be an integer from 1 to ${Fy}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function My(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 KP(e){let t=e?.trim();if(!t)return new Date(Date.now()-GP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*s).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new 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 $y(e,t){let n=qP(t.eventLimit),r=KP(t.since),o=[],s=r,i=!1;for(;o.length<n;){let a=await oi({pmRoot:e,since:s,limit:Math.min(UP,n-o.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),i=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:i,...i?{next_cursor:s}:{},source:"history_event_index"}}}function zP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function BP(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 HP(e){return jP.some(t=>e.startsWith(t))}function Dy(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 VP(e,t,n){let r=new Map,o=new Map,s=new Map;for(let i of t){let a=zP(i.entry,e),c=BP(i.entry),m=o.get(i.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&o.set(i.item_id,u),!a)continue;let p=Dy(r,a);p.events+=1,HP(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,s.set(i.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:s}}function WP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of o){let i=t.get(s);i&&(Dy(e,i).defectEscapes+=1)}}}function YP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function JP(e,t,n,r,o,s){let{buckets:i,lastCloseValue:a}=VP(e,t,r);return WP(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>YP(c,m,o,s)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function XP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),s=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(s)?1:Math.max(1,(s-o)/864e5)}function QP(e,t,n){let r=Cd(t),o=Rd(e,wn,n),s=o.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),i=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:o,inert:s,undeclared:i,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...i.map(a=>`provenance_dimension_undeclared:${a}`)]}}function Uy(e,t=er,n={}){let r=My(n.minimumSample);return{...QP(e.events.map(o=>o.entry),t,r),window:e.receipt}}function Gy(e,t,n,r={}){let o=My(r.minimumSample),s=XP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>JP(i,e.events,t,n,o,s)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var ZP=32;function eL(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let s=o.slice(0,o.indexOf("=")).trim();r.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Nr(e,t){let n=eL(e).map(o=>{let[s,...i]=o.split(","),a=s.indexOf("="),c=s.slice(0,a).trim(),m=s.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${o}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,f;for(let _ of i){let g=_.indexOf("="),y=_.slice(0,g).trim(),h=_.slice(g+1).trim();if(y==="unit"&&h.length>0)p=h;else if(y==="threshold"&&h.length>0&&Number.isFinite(Number(h)))f=Number(h);else throw new l(`Invalid --measure attribute "${_}"`,d.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(o=>[o.name,o])).values()].sort((o,s)=>o.name.localeCompare(s.name)).slice(0,ZP)}function jy(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function qy(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,i)=>i.recorded_at.localeCompare(s.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b56db1fc-d989-5d18-8b29-336a03f1e525")}catch{}})();function nL(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function rL(e,t,n,r,o){let s=mr(e,"type",r),i=new Set(s.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),m=(o?[...s.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=nL([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>o||f>0));return{byType:m,byStatus:p,omitted:o?0:a.length+Object.values(u).filter(f=>f===0).length}}function oL(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function sL(e){let t=Ky.join(e,"history");if(!await L(t))return[];await bn({path:t,scope:"project"});let n=(await tL.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,s)=>o.localeCompare(s)),r=[];for(let o of n){let s=Ky.join(t,o),i=await B(s);i!==null&&(await bn({path:s,scope:"project"}),r.push({id:o.slice(0,-6),raw:i}))}return r}async function iL(e,t){let n=[],r=S();for(let o of Nr(t.observe,r))n.push(await Py({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function aL(e,t,n){let r={};return t.byAssignee&&(r.assignee=mr(e,"assignee",n)),t.byTag&&(r.tag=mr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=mr(e,"priority",n)),r}async function cL(e,t,n,r,o){let s={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},i=o.provenanceCoverage||o.fleetAttribution?await $y(e,s):void 0;return{provenanceCoverage:o.provenanceCoverage&&i?Uy(i,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:o.fleetAttribution&&i?Gy(i,t,r,s):void 0}}function dL(e,t,n,r,o){let s=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...s?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:S()}}async function Id(e,t={}){let n=E(process.cwd(),e.path);await R(n);let r=await T(n),o=await iL(e,t),s=O(r,x()),i=D(r.schema),a=t.fieldUtilization?await ep(n,r.item_format,s.type_to_folder,void 0,r.schema):await ae(n,r.item_format,s.type_to_folder,void 0,r.schema);await Qu({pmRoot:n,settings:r,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=us(i),m=rL(a,s.types,i.definitions.map(k=>k.id),c,t.includeEmpty===!0),u=await sL(n),p=0;for(let k of u)p+=oL(k.raw);let f=t.storage?Ay(u):void 0,_=t.metadataCoverage?Of(a,c):void 0,g=aL(a,t,c),y=t.fieldUtilization?Pf(a):void 0,h=t.measurements===!0||o.length>0?await Ly({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:b,fleetAttribution:v}=await cL(n,a,r,i.terminal_statuses,t);return dL({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:g,storage:f,fieldUtilization:y,improvementLedger:h,recordedObservations:o,provenanceCoverage: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 zy(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:w(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ke(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:w(e,"measurementSource"),measurementItem:w(e,"measurementItem"),measurementRevision:w(e,"measurementRevision"),author:w(e,"author"),message:w(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:w(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import lL from"node:fs/promises";import $t 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 Yy=$t.join("runtime","telemetry","events.jsonl"),Jy=$t.join("runtime","telemetry","state.json"),mL=$t.join("runtime","telemetry"),uL=20,By=["status","flush","stats","clear"],Hy=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},xd=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Vy=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},pL=e=>({command:xd(e.event.command,"<unknown>"),eventType:xd(e.event.event_type,"unknown"),eventSchemaVersion:Vy(e.event.schema_version),clientSchemaVersion:Vy(e.client_schema_version)}),fL=()=>({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:{}}),_L=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},hL=e=>{let t=e?.command_resolution;return xd(t,"")||void 0},Xy=(e,t)=>{e[t]=(e[t]??0)+1},gL=(e,t)=>{let n=_L(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=hL(t);r!==void 0&&Xy(e.resolution_counts,r)},yL=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Wy=(e,t)=>{t!==void 0&&e.add(t)},bL=(e,t)=>{let n=pL(t),r=e.get(n.command)??fL();r.count+=1,r.max_attempts=Math.max(r.max_attempts,yL(t.attempts)),Xy(r.event_type_counts,n.eventType),Wy(r.event_schema_versions,n.eventSchemaVersion),Wy(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&gL(r,t.event.payload),e.set(n.command,r)},wL=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((s,i)=>s-i),o=Object.entries(t.resolution_counts).sort((s,i)=>s[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,i)=>s[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,i)=>s-i),client_schema_versions:[...t.client_schema_versions].sort((s,i)=>s-i),...r.length>0?{duration_p50_ms:Hy(r,.5),duration_p95_ms:Hy(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},vL=e=>{let t=(e??"status").trim().toLowerCase();if(By.includes(t))return t;throw xe({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:By,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)},Qy=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Od():e,kL=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Od():Qy(Number.parseInt(t,10))},SL=e=>e===void 0?uL:typeof e=="number"?Qy(e):typeof e=="string"?kL(e):Od(),EL=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},TL=e=>{try{let t=JSON.parse(e);return EL(t)?t:void 0}catch{return}},AL=e=>e===null?[]:e.split(`
48
- `).map(t=>t.trim()).filter(t=>t.length>0),Zy=e=>{let t=AL(e),n=[],r=0;for(let o of t){let s=TL(o);s===void 0?r+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},CL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),RL=e=>{try{let t=JSON.parse(e);return CL(t)?t:{}}catch{return{}}},IL=async e=>{let t=await B(e);return t===null||t.trim().length===0?{}:RL(t)},pi=e=>e??null,fi=async e=>{let t=await T(e),n=$t.join(e,Yy),r=$t.join(e,Jy),o=await B(n),s=Zy(o),i=await IL(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:pi(i.last_attempted_flush_at),last_successful_flush_at:pi(i.last_successful_flush_at),last_failed_flush_at:pi(i.last_failed_flush_at),last_failed_flush_error:pi(i.last_failed_flush_error)}},xL=e=>{let t=new Map;for(let n of e)bL(t,n);return[...t.entries()].map(([n,r])=>wL(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},OL=async(e,t)=>({action:"telemetry",subcommand:"status",status:await fi(t.globalPmRoot),generated_at:S()}),PL=async(e,t)=>{let n=await fi(t.globalPmRoot);await vp(t.globalPmRoot);let r=await fi(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),s=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:s,queue_drained:s,status:r,generated_at:S()}},LL=async(e,t)=>{let n=SL(e.limit),r=await B(t.queuePath),o=Zy(r),s=xL(o.entries),i=s.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:s.length>i.length,stats:i,generated_at:S()}},NL=async(e,t)=>{let n=await T(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 Ie(t.globalPmRoot,n,"telemetry:clear");let o=$t.join(t.globalPmRoot,mL),s=await L(o);return await lL.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:s&&!await L(o),queue_exists_after:await L(t.queuePath),state_exists_after:await L(t.statePath),status:await fi(t.globalPmRoot),generated_at:S()}},FL={status:OL,flush:PL,stats:LL,clear:NL};async function eb(e,t){let n=vL(e.subcommand),r=tt(process.cwd());return FL[n](e,{globalPmRoot:r,queuePath:$t.join(r,Yy),statePath:$t.join(r,Jy)})}import{spawn as yb}from"node:child_process";import{cp as Fd,mkdir as yi,mkdtemp as bb,open as Md,readdir as $d,rm as Gd,symlink as wb}from"node:fs/promises";import{tmpdir as vb}from"node:os";import K 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 tb=20;function ML(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return tb;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?tb:t}function Pd(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let s=kn(r.recorded_at,o.recorded_at);if(s!==0)return s;let i=r.run_id.localeCompare(o.run_id);return i!==0?i:r.kind.localeCompare(o.kind)}),n=ML();return t.length>n?t.slice(t.length-n):t}async function _i(e){await ne({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=Pd([...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 nb=100;function Ld(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 $L(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=nb?n:`${n.slice(0,nb-3)}...`}function rb(e){return e.map((t,n)=>`${n+1}. ${$L(t)}`).join("; ")}function DL(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function UL(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function ob(e,t){let n=DL(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,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 o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let s=[],i=[];for(let a=0;a<e.length;a+=1)UL(e[a],o)&&(i.push(e[a]),s.push(a+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${rb(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:s,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let o=Ld(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${rb(e)}`,d.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7659721c-21f5-55da-8cce-31b290de5bfb")}catch{}})();var gi=20*1024*1024,GL=3e3,jL=1e4,qL=5e3,sb=120,KL=new Set(["locks","extensions","runtime"]),zL=new Set(["history","index","search","extensions","locks","runtime"]),BL=[/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],HL=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,VL=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,WL=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 jd(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 YL(){return jd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",GL)}function JL(){return jd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",jL)}function XL(){return jd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",qL)}function QL(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 ZL(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function qd(e){let t=0,n=0,r=0,o=0;for(let s of e){let i=s.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(r+=1),i.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function eN(e){let t=e??"project";if(!et.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function bi(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(en.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${en.join(", ")}`,d.USAGE)}function tN(e){return nn(e??"source","--workspace-context")}function kb(e,t,n){return n?t:nn(e.workspace_context_mode,"linked test")??t}function Sb(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:bi(e.pm_context_mode)}function Eb(e,t){return e==="auto"?t?"tracker":"schema":e}function nN(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 rN(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 oN(e,t){let n={};if(!e)return n;for(let r of e){let o=br(r,t);if(o)for(let[s,i]of Object.entries(o))n[s]=i}return n}function sN(e,t){if(!e)return[];let n=[];for(let r of e){let o=wr(r,t);o&&n.push(...o)}return[...new Set(n)]}function iN(e){let t=wi(e);return dr(t).some(n=>Na(n)!==null)}function Tb(e){let t=wi(e);return dr(t).some(n=>{let r=Na(n);if(!r)return!1;let o=Tf(r);return o?WL.has(o.subcommand):!1})}function hi(e){if(e)return kf.has(e.subcommand)?Ln(e.args,Sf)?.subcommand:e.subcommand}function ib(e,t){if(e==="npx"||e==="bunx")return ls(t)?.command;if(e==="pnpm")return hi(Ln(t,yf));if(e==="npm")return hi(Ln(t,bf));if(e==="yarn")return hi(Ln(t,wf));if(e==="bun")return hi(Ln(t,vf))}function ab(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function Nd(e){return!e||!Ma(e.command)&&!Ef(e.command)?!1:ds(e.args)==="test-all"}var aN=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])]),cN=new Set(["npx","bunx"]);function Ab(e){let t=e.split(" ").filter(i=>i.length>0),n=Fa(t);if(n.length===0)return!1;let[r,...o]=n,s=aN.get(r);if(s){let i=o.findIndex(a=>s.test(a));return i>=0?Ab(o.slice(i+1).join(" ")):!1}return Ma(r)||$a(r)?ds(o)==="test-all":r==="node"&&o.length>0&&$a(o[0])?ds(o.slice(1))==="test-all":cN.has(r)?Nd(ls(o)):r==="pnpm"?Nd(Da(o)):r==="npm"?Nd(Ua(o)):!1}function Cb(e){let t=wi(e);return dr(t).some(n=>Ab(n))}function Rb(e){if(Cb(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function wi(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function dN(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 lN(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 mN(e){let t=e.split(" ").filter(s=>s.length>0),n=Fa(t);if(n.length===0)return!1;let[r,...o]=n;return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?uN(o):pN(r,o)}function uN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function pN(e,t){return e==="npx"||e==="bunx"?ab(ls(t)?.command):e==="pnpm"||e==="npm"?ab((e==="pnpm"?Da(t):Ua(t))?.command)||ib(e,t)==="vitest":(e==="yarn"||e==="bun")&&ib(e,t)==="vitest"}function Ib(e){let t=wi(e);if(dr(t).some(o=>!dN(o)&&mN(o)&&!lN(o)))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 fN(e){if(Cb(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function _N(e){return e?e.map(hN):[]}function hN(e){let t=e.trim(),n=Ns(t)?Fs(oe(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 Rb(r),Ib(r),{command:r,path:de(n.path),scope:eN(n.scope),timeout_seconds:gN(de(n.timeout_seconds),de(n.timeout)),pm_context_mode:Gs(de(n.pm_context_mode),"--add"),workspace_context_mode:nn(de(n.workspace_context_mode),"--add"),env_set:br(de(n.env_set),"--add"),env_clear:wr(de(n.env_clear),"--add"),shared_host_safe:Us(de(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:rn(de(n.assert_stdout_contains)),assert_stdout_regex:Dn(de(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:rn(de(n.assert_stderr_contains)),assert_stderr_regex:Dn(de(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:js(de(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:qs(de(n.assert_json_field_equals),"--add"),assert_json_field_gte:Ks(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 gN(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(ce(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function yN(e){return e?e.flatMap(t=>{let n=b_(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",d.USAGE);Rb(o),Ib(o)}return n}):[]}function bN(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 o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=oe(n,"--remove"),s=o.path!==void 0?"path":"command",i=o.path??o.command;if(!i?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:s,value:i.trim()}}return{kind:"either",value:n}}):[]}function wN(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 vN(e){try{e.stdin?.end()}catch{}}function xb(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=sb?t:`${t.slice(0,sb-3)}...`}function Ob(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Dd(e){try{process.stderr.write(`${e}
49
- `)}catch{}}function kN(e,t){if(!Ob(t))return null;let n=xb(e.command),r=Date.now();Dd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let s=Date.now()-r;Dd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},JL());return o.unref?.(),o}function SN(e,t,n,r){if(!Ob(r))return;let o=xb(e.command),s=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(" ")}`:"";Dd(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${s}${u} command="${o}"`)}async function cb(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=yb("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 EN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function TN(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 cb(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{cb(r)},YL()),t.forceKillTimer.unref?.()}}function AN(e){return new Promise(t=>{let n=!1,r=null,o=(s,i=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,i)=>{n||(r=setTimeout(()=>{o({code:s,signal:i},!0)},XL()),r.unref?.())}),e.on("close",(s,i)=>{o({code:s,signal:i})})})}function CN(e,t,n,r,o){return yb(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function db(e){let t=await Md(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,gi),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>gi}}finally{await t.close()}}async function RN(e,t,n,r,o,s=process.cwd()){let i=Date.now(),a=await bb(K.join(vb(),"pm-linked-test-output-"));try{let c=K.join(a,"stdout.log"),m=K.join(a,"stderr.log"),[u,p]=await Promise.all([Md(c,"w"),Md(m,"w")]),f;try{f=CN(e,n,u.fd,p.fd,s)}finally{await Promise.all([u.close(),p.close()])}vN(f);let _={heartbeat:kN(r,o),forceKillTimer:null,timedOutTimer:null},g=TN(f,_),y=!1,h;f.on("error",pe=>{h=pe.message}),_.timedOutTimer=setTimeout(()=>{y=!0,g()},t),_.timedOutTimer.unref?.();let{code:b,signal:v}=await AN(f);EN(_);let[k,I]=await Promise.all([db(c),db(m)]),A=k.truncated||I.truncated,N=A?`
50
- [pm linked-test output truncated at ${gi} bytes per stream; the child process continued to completion]
51
- `:"",M={stdout:`${k.text}${N}`,stderr:I.text,exitCode:b,signal:v,timedOut:y,maxBufferExceeded:!1,outputTruncated:A,spawnError:h};return SN(r,M,i,o),M}finally{await Gd(a,{recursive:!0,force:!0})}}function IN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${gi} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function xN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
52
- `);return BL.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>HL.test(n)&&VL.test(n))}function ON(e){return xN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function PN(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function vi(e){let t=PN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function lb(e,t){for(let[n,r]of Object.entries(t.env_set))tn.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)tn.has(n.toUpperCase())||delete e[n]}function LN(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 NN(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function FN(e,t,n){return{env_set:oN(e,"--env-set"),env_clear:sN(t,"--env-clear"),shared_host_safe:n===!0}}async function Hn(e,t,n=!1,r=yi){if(await L(e))try{await si("seed_linked_test",async()=>{if(await r(K.dirname(t),{recursive:!0}),n){await Fd(e,t,{recursive:!0,force:!0});return}await Fd(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&kt(o))return;throw o}}async function mb(e,t,n){await Hn(ye(n.projectPmRoot),ye(e)),await Hn(K.join(n.projectPmRoot,"extensions"),K.join(e,"extensions"),!0),await Hn(ye(n.globalPmRoot),ye(t)),await Hn(K.join(n.globalPmRoot,"extensions"),K.join(t,"extensions"),!0)}async function ub(e,t){if(!await L(e))return;let n=await $d(e,{withFileTypes:!0});for(let r of n){if(KL.has(r.name))continue;let o=K.join(e,r.name),s=K.join(t,r.name);if(r.isDirectory()){await Hn(o,s,!0);continue}r.isFile()&&await Hn(o,s)}}async function Bn(e){if(!await L(e))return 0;let t=0,n=await $d(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||zL.has(r.name))continue;let o=K.join(e,r.name),s;try{s=await $d(o,{withFileTypes:!0})}catch{continue}for(let i of s)i.isFile()&&pl.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function MN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function $N(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let r of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isInteger(o)||o<0)return[];t.push(o);continue}t.push(r)}return t}function pb(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=$N(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let s of r){if(typeof s=="number"){if(!Array.isArray(o)||s>=o.length)return{found:!1,value:void 0};o=o[s];continue}if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,s))return{found:!1,value:void 0};o=o[s]}return{found:!0,value:o}}function DN(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 UN(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?nt(e,t):Object.is(e,t)}function GN(e,t,n){let r=[];r.push(...fb("stdout",t,e.assert_stdout_contains)),r.push(..._b("stdout",t,e.assert_stdout_regex)),r.push(...fb("stderr",n,e.assert_stderr_contains)),r.push(..._b("stderr",n,e.assert_stderr_regex)),r.push(...jN(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(s).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,m]of Object.entries(o)){let u=pb(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=DN(m);UN(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(s)){let u=pb(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 fb(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function _b(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(s){r.push(`${e} regex assertion is invalid: /${o}/ (${s instanceof Error?s.message:String(s)})`)}return r}function jN(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 qN=[{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 KN(e,t){let n=`${e}
53
- ${t}`;for(let r of qN)if(r.regex.test(n))return r.code;return null}function zN(e){return{root:e,schemaProjectPmPath:K.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:K.join(e,"schema","global"),trackerProjectPmPath:K.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:K.join(e,"tracker","global"),workspaceSnapshotRoot:K.join(e,"workspace","project"),workspaceIsolatedRoot:K.join(e,"workspace","isolated")}}function BN(e,t,n){return e.some(r=>kb(r,t,n)==="snapshot")}async function HN(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await yi(K.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await Fd(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(o){let s=K.relative(t,o);return s?!s.split(K.sep).some(i=>n.has(i)):!0}});let r=K.join(t,"node_modules");await L(r)&&await wb(r,K.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function VN(e,t){let n=K.join(e,".agents"),r=K.join(n,"pm");await yi(n,{recursive:!0}),await Gd(r,{recursive:!0,force:!0}),await wb(t,r,process.platform==="win32"?"junction":"dir")}async function WN(e,t=Tr,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 YN(e,t,n){t&&(await mb(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await mb(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await ub(t.projectPmRoot,e.trackerProjectPmPath),await ub(t.globalPmRoot,e.trackerGlobalPmPath)))}function JN(e,t,n){return e.some(r=>{let o=r.command??"",s=o.length>0&&Tb(o),i=n?.autoPmContext===!0&&s?"auto":Sb(r,t,n?.overrideLinkedPmContext===!0);return Eb(i,s)==="tracker"})}async function XN(e,t){return{sourceProjectItemCount:t?await Bn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Bn(t.globalPmRoot):0,schemaProjectItemCount:await Bn(e.schemaProjectPmPath),schemaGlobalItemCount:await Bn(e.schemaGlobalPmPath),trackerProjectItemCount:await Bn(e.trackerProjectPmPath),trackerGlobalItemCount:await Bn(e.trackerGlobalPmPath)}}function QN(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:a,trust:e.trust}}async function ZN(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?bi(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?iN(n):!1,o=r&&n?Tb(n):!1,s=e.options?.autoPmContext===!0&&o,i=s?"auto":Sb(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Eb(i,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await VN(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await Ga(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Ga(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:QN({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function hb(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 eF(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function tF(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return eF(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function nF(e){if(!e.linkedTest.command)return hb(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=fN(e.linkedTest.command);return t?hb(e.linkedTest,e.executionContext,t):null}function rF(e){let t=nF(e);if(t)return t;let n=tF(e);if(n)return n;let r=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,o=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(r||o){let s=rN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),i=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Ud(e.linkedTest,e.executionContext,`${i} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${s}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!nN(e.linkedTest)?Ud(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function oF(e){let t=NN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return lb(n,e.runtimeDirectives),lb(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&LN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[ar]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[ar]="read_only"),n}function sF(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 iF(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 aF(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:MN(e.execution),failure_category:ON(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:IN(e.execution,e.timeoutMs)}}function cF(e){if(e.options?.failOnEmptyTestRun===!0){let n=KN(e.execution.stdout,e.execution.stderr);if(n)return iF({...e,emptyRunSignal:n})}let t=GN(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):sF(e.linkedTest,e.executionContext,e.execution)}async function dF(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await RN(t,n,oF(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?cF({...e,execution:r}):aF({...e,execution:r,timeoutMs:n})}async function Kd(e,t,n){let r=[],o=await bb(K.join(vb(),"pm-linked-test-")),s=zN(o),i=bi(n?.pmContext),a=tN(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=FN(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,p=Cf(),f=JN(e,i,n),_=BN(e,a,n?.overrideLinkedWorkspaceContext===!0),g=await Af(p);try{await WN(s,Tr,f),await yi(s.workspaceIsolatedRoot,{recursive:!0}),await YN(s,u,f),_&&await HN(s,p);let y=await XN(s,u);for(let h=0;h<e.length;h+=1){let b=e[h],v=kb(b,a,n?.overrideLinkedWorkspaceContext===!0),k=await ZN({linkedTest:b,layout:s,counts:y,sourceRoots:u,runLevelPmContextMode:i,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:v,currentSourceRef:g,sourceWorkspaceRoot:p}),I=rF({linkedTest:b,executionContext:k.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:k.linkedOverridePmContextMode,options:n});if(I){r.push(I);continue}r.push(await dF({linkedTest:b,index:h,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:k.executionContext,options:n}))}}finally{await Gd(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function lF(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,s=await U(n,t,r.id_prefix,r.item_format,o);if(!s)throw new l(`Item ${t} not found`,d.NOT_FOUND);let i=await V(s,{schema:r.schema});return{itemId:s.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function mF(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function uF(e,t){let n=[...e];for(let r of t)n.some(o=>mF(o,r))||n.push(r);return n}function pF(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((s,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:o,removed:e.length-o.length}}function fF(e,t,n,r){return pF(uF(e,t),n,r)}function _F(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function hF(e){if(_F(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --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 gF(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:s,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return lF({id:t,pmRoot:r,settings:o,typeToFolder:s});let m=0,u=await ne({pmRoot:r,settings:o,id:t,op:i.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=fF(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(g=>`${g.kind}=${g.value}`),...c.map(g=>`index=${g}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return p.metadata.tests=_.tests,{changedFields:nt(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 yF(e,t){hF(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Ld(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?ob(t,n):void 0,o=e.timeout===void 0?void 0:ce(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:bi(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function bF(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Kd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:tt(process.cwd())}})}function wF(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=qd(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function vF(e){let t=ZL(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=S(),s=Nr(e.options.measure,o);return{run_id:QL("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function kF(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:s,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let m=vF({options:t,runStartedAt:s,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return m;try{return await _i({pmRoot:n,settings:r,itemId:o,author:C(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),m}catch(u){return c.push(`test_result_tracking_failed:${o}:${u instanceof Error?u.message:String(u)}`),m}}function gb(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,o).trim(),i=e.metricBelow.slice(o+1).trim(),a=Number(i);if(o<=0||s.length===0||i.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",d.USAGE);r=jy(t,s,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:qy(t,e.metricDiff)}}async function SF(e,t,n){if(e.acknowledgeLinkedTests===!0)return Rf(t,n,S())}async function ki(e,t,n){let r=xt(),o=E(process.cwd(),n.path);await R(o);let s=await T(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);Nr(t.measure,"validation"),gb(t,[],void 0);let i=O(s,x()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[..._N(a),...yN(c)],p=await Nn(u,C(t.author,s.author_default),S())??[],f=bN(m),_=wN(t.removeIndex),g=await gF({id:e,options:t,pmRoot:o,settings:s,typeToFolder:i.type_to_folder,adds:p,removes:f,removeIndexes:_}),y=yF(t,g.tests),h=await SF(t,o,g.tests),b=t.run===!0?S():void 0,v=await bF({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests}),k=vi(v),I=t.run===!0&&t.failOnSkipped===!0&&v.some(ee=>ee.status==="skipped"),A=wF(t,y.runSelection,v);h&&A.push(`linked_test_trust_acknowledged:${h.acknowledged}`);let N=await kF({options:t,pmRoot:o,settings:s,itemId:g.itemId,runStartedAt:b,runResults:v,failOnSkippedTriggered:I,warnings:A}),M=N?Pd([...g.testRuns,N]):g.testRuns,pe=gb(t,M,N);return{ok:v.every(ee=>ee.status!=="failed")&&I!==!0,id:g.itemId,tests:g.tests,run_results:v,failure_categories:k,selection:y.runSelection?{selector:y.runSelection.selector,requested:y.runSelection.requested,selected_indexes:y.runSelection.selected_indexes,selected_count:y.runSelection.selected_count,skipped_count:y.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:I?!0:void 0,warnings:A.length>0?A:void 0,changed:g.changed,count:g.tests.length,...g.removed>0?{removed:g.removed}:{},...pe}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d3405c0-14e6-51f5-97a1-355438fd0199")}catch{}})();var EF=(e,t)=>{if(e===void 0)return;let n=X(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},TF=e=>{if(e===void 0)return;let t=ce(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},Pb=(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},AF=e=>e instanceof Error?e.message:String(e),CF=()=>{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)}`},RF=e=>e.trim().replaceAll(/\s+/g," "),IF=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),xF=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),OF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},PF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Si=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Lb=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),LF=e=>typeof e=="number"?e:void 0,NF=e=>{let t={assert_stdout_contains:Si(e.assert_stdout_contains),assert_stdout_regex:Si(e.assert_stdout_regex),assert_stderr_contains:Si(e.assert_stderr_contains),assert_stderr_regex:Si(e.assert_stderr_regex),assert_stdout_min_lines:LF(e.assert_stdout_min_lines),assert_json_field_equals:Lb(e.assert_json_field_equals),assert_json_field_gte:Lb(e.assert_json_field_gte)};return JSON.stringify(t)},FF=e=>{let t=zd(e.command);return t!==void 0?`command:${e.scope}:${RF(t)}`:`path:${e.scope}:${zd(e.path)??""}`},Nb=e=>{let t=IF(e.env_set),n=xF(e.env_clear),r=OF(e.pm_context_mode),o=PF(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",i=NF(e);return`${FF(e)}:${t}:${n}:${r}:${o}:${s}:${i}`},MF=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,$F=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},DF=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Ei=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
54
- `)}catch{}},UF=async(e,t,n)=>{let r=[],o=0;for(let s of e){let i=await ki(s.id,{run:!1},{...t,path:n});o+=i.tests.length,r.push({item:s,tests:i.tests})}return{itemTests:r,linkedTests:o}},GF=async e=>{let t=D(e.settings.schema),n=O(e.settings,x()),r=EF(e.options.status,t),o=Pb(e.options.limit,"--limit"),s=Pb(e.options.offset,"--offset")??0,a=(await ae(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(m=>r?m.status===r:!0).sort((m,u)=>m.id.localeCompare(u.id));return{filteredItems:o===void 0?a.slice(s):a.slice(s,s+o),statusFilter:r,limitFilter:o,offsetFilter:s}},jF=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=Nb(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,MF(t.get(o),r.timeout_seconds))}return t},qF=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=Nb(u),f=t.seenTestKeys.has(p);if(!f){t.seenTestKeys.add(p);let _=t.effectiveTimeoutByKey.get(p);n.push(_===void 0?u:{...u,timeout_seconds:_})}return{test:u,key:p,duplicate:f}}),o=n.length>0?await Kd(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],s=0,i=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=o[s];return s+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=$F(i),c=vi(i),m=await BF(e,a,i,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:m,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:i,failure_categories:c}}},KF=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),zF=e=>e?!0:void 0,BF=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=KF(t,r.options);await _i({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:S(),recorded_at:S(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:zF(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${AF(o)}`]}return[]},HF=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},zd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},VF=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:tt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:jF(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:CF(),trackingAttempt:HF(),trackingResumedFrom:zd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),WF=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:vi([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},YF=async(e,t,n)=>{for(let[r,o]of e.entries()){Ei(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let s=await qF(o,t);DF(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),Ei(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}},JF=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=qd(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}`)},XF=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}),QF=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(" "),ZF=async(e,t)=>{let n=E(process.cwd(),t.path);await R(n);let r=await T(n),o=await GF({pmRoot:n,settings:r,options:e}),s=TF(e.timeout),i=S(),a=await UF(o.filteredItems,t,n);return Ei(e,QF({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:s,runStartedAt:i}},eM=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}},Fb=async(e,t)=>{let n=await ZF(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=WF(e,n.linkedTests,n.filteredItems),s=VF({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await YF(n.itemTests,s,r),JF(e,r);let i=eM({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Ei(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),XF({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="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]="863df651-49e0-552f-a7f0-92c3cc9a12a2")}catch{}})();function Mb(){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]="3e5f92c9-c299-592d-a7ab-a6f9998159f0")}catch{}})();var Db=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:Cu().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm init","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm 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"]}],$b=new Map;for(let e of Db){$b.set(e.id,e);for(let t of e.aliases)$b.set(t,e)}function Bd(){return Db.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 RH=[...Ur],IH=[...Gr],tM=new Set(Zn.filter(e=>e.hidden).map(e=>e.alias)),xH=Au("full").filter(e=>!tM.has(e)),OH=$(Xr),PH=$(Qr),LH=$(so),NH=$(mo),FH=$(uo),MH=$(vm),$H=$(km),DH=$(lo),UH=$(ho),GH=$(po),jH=$(fo),qH=$(oo),KH=$(_o),zH=$(Zr),BH=$(eo,!1),HH=$(Lm),VH=$(Xn),WH=$(Qn),YH=$(wo),JH=$(yo),XH=$(ao),QH=$(bo),ZH=$(go),eV=$(vo),tV=$(io),nV=$(co),rV=$(no),oV=$(ko),sV=$(to);var nM=$(So),iV=`${nM} bash zsh fish`,aV=rM(Bd());var cV=$(ro),dV=$(Jn);var lV=Jr.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function rM(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]="1cbb3565-26d8-5657-b724-602658bec852")}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]="72111aa2-52b2-53da-a1c8-07ba53a74944")}catch{}})();var qb=Symbol("pm.active-extension-host-context");function Ne(e){return{fullChangedFields:!0,options:e}}var j=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[qb]=!0,n}run(t,n={}){return Kb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return $f(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return va(await this.list(wa(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,...Ne(ir(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,s={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:s})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,s){return this.runTyped("plan",{...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...s===void 0?{}:{reorderTo:s},options:ir(r,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Ne(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ne(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Ne(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ne(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ne(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ne(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ne(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ne(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},...Ne(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ne(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ne(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ne(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 sM(e={},t={}){return new j(t).context(e)}function iM(e={},t={}){return new j(t).list(e)}function aM(e={},t={}){return new j(t).listAllComplete(e)}function cM(e,t={},n={}){return new j(n).search(e,t)}function dM(e,t={},n={}){return new j(n).get(e,t)}function lM(e={},t={}){return new j(t).next(e)}function mM(e={},t={}){return new j(t).aggregate(e)}function uM(e,t={},n={}){return new j(n).comments(e,t)}function pM(e,t={},n={}){return new j(n).notes(e,t)}function fM(e,t={},n={}){return new j(n).learnings(e,t)}function _M(e,t={},n={}){return new j(n).files(e,t)}function hM(e,t={},n={}){return new j(n).filesDiscover(e,t)}function gM(e,t={},n={}){return new j(n).docs(e,t)}function yM(e,t={},n={}){return new j(n).deps(e,t)}function bM(e,t={},n={},r={}){return new j(r).graph(e,t,n)}function wM(e,t,n={},r={}){return new j(r).append(e,t,n)}function vM(e={},t={}){return new j(t).create(e)}function kM(e,t={},n={}){return new j(n).update(e,t)}function SM(e,t,n={},r={}){return new j(r).reopen(e,t,n)}function EM(e,t,n={},r={}){return new j(r).close(e,t,n)}function TM(e,t={},n={}){return new j(n).claim(e,t)}function AM(e={},t={}){return new j(t).claimNext(e)}function CM(e,t={},n={}){return new j(n).release(e,t)}function RM(e,t={},n={}){return new j(n).copy(e,t)}function IM(e,t={},n={}){return new j(n).delete(e,t)}function xM(e,t,n={},r={}){return new j(r).restore(e,t,n)}function OM(e,t={},n={}){return new j(n).focus(e,t)}function Qe(e,t){let n=w(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}var Ub=Pu(),PM=new oM;function Ti(){da(wl()),la(vl()),ma(kl()),ua(Sl()),pa(El()),fa(Tl()),_a(Al())}async function LM(e,t,n,r){return Lu(()=>t===void 0?Ub.read(()=>Gb(e,n,r)):Ub.write(()=>FM(t,()=>Gb(e,n,r))))}async function Gb(e,t,n){let r=E(t,e.path);if(e.noExtensions)return Ti(),Qa({pmRoot:r},()=>n(null));if(!await L(ye(r)))return Ti(),n(null);let o=null,s;try{let i=await T(r),a=await Wr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Yr({...a,loaded:a.loaded});s={loadResult:a,activationResult:c},da(c.hooks),la(c.commands),ma(c.parsers),ua(c.preflight),pa(c.services),fa(c.renderers),_a(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){Ti(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Qa({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Ti(),s&&await Rl(s.loadResult,s.activationResult).catch(()=>{})}}async function NM(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let s=Wt(e),a=o.registrations.commands.find(m=>Wt(m.action)===s)?.command??o.commands.handlers.find(m=>Wt(m.command)===s)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=await Lo({command:Ia(a),args:ke(n.args??t.args),options:xa(t,n),global:r,pm_root:o.pmRoot,sdk:jf(o.pmRoot,j.forActiveExtensionHost({pmRoot:o.pmRoot,author:typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension"}))});if(!c.handled){let m=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${m}`,d.USAGE)}return c.result}async function FM(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var MM=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function $M(e){let t=Qe(e,"action"),n=Wt(t),r=Ci(Uf,n),o=r?.action??n,s={...e,action:o};return r?.options!==void 0&&(s.options={...r.options,...Wi(e.options)}),o==="package"&&(s.options={...Wi(s.options),vocabulary:"package"}),{action:o,args:s}}function DM(e){return!MM.has(Wt(e))}async function Kb(e){let t=$M(e),n=Aa(t.args),r=DM(t.action),o=w(t.args,"cwd"),s=o??process.cwd();try{return e[qb]===!0||PM.getStore()===!0?await jb(t.action,t.args,n,null):await LM(n,o,s,i=>jb(t.action,t.args,n,i))}finally{r&&Wa()}}function Ci(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ai(e){return w(e.args,"target")??w(e.options,"target")}function Q(e,t=e.options){return e.id??Qe(t,"id")}async function UM(e){let t=gn("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),Va(await at(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function GM(e){let t=Qe(e.args,"query"),n=gn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Va(await pr(t,n,e.global),n)}async function jM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await Pt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function qM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Ge(await Gc(Q(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function KM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await dt(Q(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function zM(e){let t=bs(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")),r_(Q(e),t,e.global)}function zb(e,t){return gf(ny(e.options,t,Me),e.global)}function BM(e){let t=ke(e.options.lookupPath);if(t&&t.length>0)return zb(e,t);let n=Q(e);return e.options.discover===!0?La(n,Ra(e.options),e.global):hf(n,os(e.options),e.global)}function HM(e){return eb({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:Fp(e.args,e.options)},e.global)}function VM(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),ff(e.global,t)}function WM(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);let n=w(e.args,"value")??w(e.options,"value"),r=w(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return Ph(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),r,e.global,w(e.options,"policy")===void 0?n:void 0)}function YM(e){let t=e.options;return Cp(Ap(t),e.global)}function JM(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 XM(e){let t=w(e.args,"subcommand")??Qe(e.options,"subcommand"),n=e.options;return dh({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:QM(e),reorderTo:JM(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function QM(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function ZM(e){let t=w(e.args,"subcommand")??Qe(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:w(e.args,"name")??w(e.options,"name"),author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ke(n)}}function e$(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,a=Ci({list:()=>Xp(t.global),show:()=>Qp(r,t.global),"show-status":()=>Zp(r,t.global),"list-fields":()=>nf(t.global),"show-field":()=>rf(r,t.global),"remove-type":()=>Vp(r,{author:o,force:s},t.global),"remove-field":()=>tf(r,{author:o,force:s},t.global),"remove-status":()=>Jp(r,{author:o,force:s},t.global),"apply-preset":()=>of(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:o,force:s},t.global)},n);return a?a():null}function t$(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return ef(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:ke(i),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:s,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:ke(a),author:r,force:o},t.global)}function n$(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.role??t.options.role;return Yp(n,{role:i===void 0?void 0:ke(i),alias:s,description:w(t.args,"description")??w(t.options,"description"),order:Me(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function r$(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e;return Hp(n,{description:w(t.args,"description")??w(t.options,"description"),defaultStatus:w(t.args,"defaultStatus")??w(t.args,"default_status")??w(t.options,"defaultStatus")??w(t.options,"default_status"),folder:w(t.args,"folder")??w(t.options,"folder"),alias:s,author:r,force:o},t.global)}function o$(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,i=w(t.args,"to")??Qe(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 zp(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:s},t.global)}function s$(e){let t=ZM(e),n=e$(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return o$(t);if(t.subcommand==="add-field")return t$(t);if(t.subcommand==="add-status")return n$(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?sf({minCount:Me(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):r$(t);throw xe({command_path:"schema",token:t.subcommand,allowed:Bp,exit_code:64})}function i$(e){let t=w(e.args,"subcommand")??Qe(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),s=Ci({list:()=>jg(),show:()=>qg(r),lint:()=>Kg(r),apply:()=>zg(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!s)throw xe({command_path:"profile",token:t,allowed:Gg,exit_code:64});return s()}async function a$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await Kf(Q(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function c$(e){let{changedFields:t,runnerOptions:n}=$e(e.args,e.options);return Ge(await J_(Pa(n),e.global),{changedFields:t})}async function d$(e){let{changedFields:t,runnerOptions:n}=$e(e.args,e.options),r=w(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Ge(await n_(Oa(o),e.global),{changedFields:t})}async function l$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options),o=w(r,"target")??Qe(e.args,"target");return Ge(await Jt(Q(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function m$(e){let t=E(process.cwd(),e.global.path),n=await T(t),r=di(D(n.schema)),o=Q(e),s=await vs(o,e.force,e.global,e.options),i=await dt(o,ir(e.options,{status:r,force:e.force},["assignee"]),e.global);return{id:o,action:"start_task",claim:s,update:i}}async function u$(e){let t=E(process.cwd(),e.global.path),n=await T(t),r=Q(e),o=D(n.schema).open_status,s=await dt(r,ir(e.options,{status:o,force:e.force},["assignee"]),e.global),i=await ks(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:s,release:i}}async function p$(e){let t=Q(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await ct(t,n,{...e.options,force:e.force},e.global),o=await ks(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:o}}function f$(e){let t={...e.args,...e.options};return Pp(Qe(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),Dp(t),e.global)}function _$(e){return Gp(E(process.cwd(),e.global.path),{...e.args,...e.options})}var h$={init:e=>Tr(w(e.args,"prefix"),e.global,e.options),context:e=>za(gn("context",e.options),e.global),next:e=>ur(gn("next",e.options),e.global),eval:Ig,events:xg,merge:Og,workspace:Pg,meet:ai,event:ai,remind:ai,list:UM,get:e=>{let t=Q(e);return Ba(t,e.global,gn("get",e.options,[t]))},search:GM,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ke(e.options.status);return Ha(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:Me(e.options.limit,"limit")})},create:jM,copy:qM,focus:e=>qc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:KM,"item-reopen":ty,restore:l$,claim:e=>e.options.next===!0||e.args.next===!0?Jf(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):vs(Q(e),e.force,e.global,e.options),release:e=>ks(Q(e),e.force,e.global,e.options),"start-task":m$,"pause-task":u$,"close-task":p$,close:ey,comments:zM,notes:e=>s_(Q(e),bs(e.options),e.global),learnings:e=>o_(Q(e),bs(e.options),e.global),files:BM,docs:e=>_f(Q(e),os(e.options),e.global),test:e=>ki(Q(e),e.options,e.global),"test-all":e=>Fb(e.options,e.global),telemetry:HM,validate:e=>ms(e.options,e.global,{runUpdate:(t,n,r)=>dt(t,n,r)}),health:VM,assurance:e=>If(e.args,e.options,e.global),contracts:e=>Ty(e.options,e.global),config:WM,activity:YM,aggregate:e=>ja(e.options,e.global),extension:e=>Pn(Ai(e),e.options,e.global),package:e=>Pn(Ai(e),e.options,e.global),install:e=>Pn(Ai(e),{...e.options,install:!0},e.global),upgrade:e=>Nf(Ai(e),e.options,e.global),delete:e=>jc(Q(e),e.options,e.global),deps:e=>Op(Q(e),e.options,e.global),graph:f$,"files-discover":e=>La(Q(e),e.options,e.global),"files-lookup":e=>zb(e,ke(e.options.paths)),history:e=>Lf(Q(e),e.options,e.global),"history-redact":e=>cp(Q(e),e.options,e.global),"history-repair":Jg,"history-compact":Xg,"history-author-acknowledge":_$,plan:XM,schema:s$,profile:i$,stats:e=>Id(e.global,zy(e.options)),append:a$,"update-many":c$,"close-many":d$,gc:e=>Ff(e.global,e.options)};async function jb(e,t,n,r){let o=Ca(t,e);ia(e,o),mu(e,o);let s={action:e,args:t,options:o,id:w(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},i=Ci(h$,e),a=i?await i(s):await NM(e,t,o,n,r);return o.resolvedOutputFormat="json",ku(e,o,a)}var g$={closeManyOptionsFromFlat:Oa,extensionOptionsFromArgs:xa,globalOptions:Aa,mutationListOptions:$p,normalizeActionName:Wt,normalizeCommandPath:Ia,normalizeMcpUpdateOptions:Up,normalizeMcpOptionsArrays:Mp,optionsWithAuthor:Ca,readRequiredString:Qe,readScalarString:Lp,readScalarStringAllowBlank:Np,readStringArray:ke,updateManyOptionsFromFlat:Pa,withAddNoteOption:os,withFilesDiscoveryOptions:Ra,withMutationCompaction:$e};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=g$);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cea03617-5e90-5683-a9d1-289087ed4646")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cc0d4dd1-20e8-59d4-acb5-9f8ed639d35f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f44898af-0809-51e1-a6fb-74716c0971f5")}catch{}})();export{wn as AGENT_PROVENANCE_DIMENSIONS,$u as BASELINE_ITEM_FORMAT_VERSION,zw as BUILTIN_AGENT_PROVENANCE_ADAPTERS,er as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,Ur as BUILTIN_ITEM_TYPE_VALUES,jr as CONFIDENCE_TEXT_VALUES,Du as CURRENT_ITEM_FORMAT_VERSION,Gt as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,pn as ISSUE_SEVERITY_VALUES,sl as ITEM_TYPE_VALUES,Ya as PM_CLI_EXPECTED_ERROR_NAME,Nw as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,Pw as PM_READ_OUTPUT_DIMENSIONS,Lw as PM_READ_OUTPUT_OPTION_FLAGS,oa as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,j as PmClient,un as RISK_VALUES,ov as SEMANTIC_ATTRIBUTION_LIMITS,Gr as STATUS_VALUES,Kw as agentSessionEnvironment,mM as aggregate,Cd as analyzeAgentProvenanceDescriptorCoverage,Uw as analyzeSdkCliParameterCompleteness,wM as append,Mw as applyReadOutputDimensions,Cw as applyReadOutputSessionReferences,Rw as attachReadOutputSessionReceipt,Gw as boundAgentEpisodeIdentity,Ye as canonicalDocument,TM as claim,AM as claimNext,ju as classifyItemFormatVersion,EM as close,uM as comments,sM as context,RM as copy,vM as create,Gf as createPmCliExpectedError,Ow as decodeReadOutputContinuationCursor,IM as deleteItem,yM as deps,Xw as detectAgentIdentity,ev as detectHarnessIdentity,Qw as diagnoseAgentIdentity,gM as docs,Uu as effectiveItemFormatVersion,Mb as emptyImportedDocument,xw as encodeReadOutputContinuationCursor,MP as evaluateSemanticAttributionCoverage,nv as explainSourceTraceability,_M as files,hM as filesDiscover,OM as focus,dM as get,bM as graph,$P as groupHistoryByEpisode,Yf as isAlreadyClaimedError,hs as isPmCliExpectedError,$w as isReadOutputBudgetExceeded,fM as learnings,iM as list,Hw as listAgentProvenanceAdapters,aM as listAllComplete,lM as next,Ww as normalizeAgentProvenanceAdapterValue,Gu as normalizeItemFormatVersion,we as normalizeItemId,X as normalizeStatusInput,pM as notes,S as nowIso,Aw as parseReadOutputSession,cs as parseSourceLineRange,Fo as readAuthorEnvironment,Iw as readOutputSessionRemainingTokens,qa as recordClaimSemanticAttribution,ps as recordFocusSemanticAttribution,Ka as recordReleaseSemanticAttribution,Vw as registerAgentProvenanceAdapters,Bw as registerHarnessSignalDescriptors,CM as release,SM as reopen,jw as resolveAgentSessionContextFromSignals,tv as resolveAuthorIdentity,Ny as resolveHistoryEpisodeGroupIdentity,Fw as resolveReadOutputDimensions,Dw as resolveReadOutputEncoding,sa as resolveReadOutputSurface,rv as resolveSemanticLineageIds,xM as restore,Kb as runAction,qw as runWithAgentSessionContext,Yw as runWithHarnessDetectionSignals,Jw as runWithWorkspaceHarnessSignalDescriptors,cM as search,sv as semanticAttributionAffinity,je as serializeItemDocument,FP as summarizeAgentModelProvenance,Rd as summarizeAgentProvenance,kM as update,ia as validateReadOutputOptions,Zw as writeAuthorEnvironment};
40
+ `}function PI(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Xh(e,t,n){ad(e,"base");let r=ad(t,"ours"),o=ad(n,"theirs"),s=Math.min(r.length,o.length),i=0;for(;i<s&&r[i].eventId===o[i].eventId;)i+=1;if(i===r.length&&i===o.length)return{merged:oi(r),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===o.length)return{merged:oi(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:oi(o),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:o.length-i,entries_total:o.length,reanchored:!1};let a=r.slice(i),c=new Set(a.map(f=>f.eventId)),m=o.slice(i).filter(f=>!c.has(f.eventId)),u=[...a,...m].sort((f,_)=>{if(f.timestamp!==void 0&&_.timestamp!==void 0){let h=kn(f.timestamp,_.timestamp);if(h!==0)return h}else{if(f.timestamp===void 0&&_.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let g=c.has(f.eventId),y=c.has(_.eventId);return g!==y?Number(y)-Number(g):0}),p=PI([...r.slice(0,i),...u]);return{merged:oi(p),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:m.length,entries_total:p.length,reanchored:!0}}var LI=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],NI=["updated_at"];function dn(e,t){return H(e??null)===H(t??null)}function FI(e,t,n){let r=u=>Array.isArray(u)?u:[],o=new Set(r(e).map(u=>H(u))),s=r(t),i=new Set(s.map(u=>H(u))),a=r(n),c=new Set(a.map(u=>H(u))),m=s.filter(u=>{let p=H(u);return!o.has(p)||c.has(p)});for(let u of a){let p=H(u);!i.has(p)&&!o.has(p)&&m.push(u)}return m}function Ar(e){if(typeof e!="object"||e===null||Array.isArray(e))return H(e);let{provenance:t,...n}=e;return H(n)}function MI(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function $I(e,t,n){let r=u=>Array.isArray(u)?u:[],o=new Set(r(e).map(Ar)),s=r(t),i=new Set(s.map(Ar)),a=r(n),c=new Set(a.map(Ar)),m=s.filter(u=>{let p=Ar(u);return!o.has(p)||c.has(p)});for(let u of a){let p=Ar(u);!i.has(p)&&!o.has(p)&&m.push(MI(u))}return m}function DI(e,t){return kn(String(e),String(t))>=0?e:t}function Qh(e,t,n,r){return dn(t,n)?{value:t,from_theirs:!1,conflict:!1}:dn(e,t)?{value:n,from_theirs:!0,conflict:!1}:dn(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function Zh(e,t,n,r,o){let s=Qh(e,t,n,r);if(!s.conflict||o==="preferred_side")return s;let i=H(n).localeCompare(H(t))<0;return{value:i?n:t,from_theirs:i,conflict:!0}}function cd(e){return{...e.metadata}}function dd(e,t,n){try{return Ye(Uo(e,n),n)}catch(r){throw new l(`Item merge input (${t}) is not a readable item document: ${String(r)}`,d.GENERIC_FAILURE)}}function UI(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?$I(e.baseValue,e.oursValue,e.theirsValue):FI(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,dn(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function GI(e){let t=Zh(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:e.baseValue,ours:e.oursValue,theirs:e.theirsValue,retained:t.value,discarded:t.from_theirs?e.oursValue:e.theirsValue})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function jI(e,t,n,r,o){let s=new Set(LI),i=new Set(NI),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(!UI({field:m,baseValue:u,oursValue:p,theirsValue:f,unionFieldSet:s,accumulator:c})){if(i.has(m)){c.merged[m]=DI(p,f);continue}GI({field:m,baseValue:u,oursValue:p,theirsValue:f,preferred:r,conflictResolution:o,accumulator:c})}}return c}function eg(e,t,n,r={}){let o=r.preferred??"ours",s=r.conflictResolution??"preferred_side",i=e.trim().length>0,a=dd(t,"ours",r),c=dd(n,"theirs",r),m=i?dd(e,"base",r):a,u=i?cd(m):{},p=cd(a),f=cd(c),{merged:_,conflictFields:g,fieldsFromTheirs:y,unionFields:h,conflictDecisions:b}=jI(u,p,f,o,s),v=Zh(i?m.body:"",a.body,c.body,o,s);return v.conflict?(g.push("body"),b.push({field:"body",base:i?m.body:"",ours:a.body,theirs:c.body,retained:v.value,discarded:v.from_theirs?a.body:c.body})):v.from_theirs&&y.push("body"),{merged:je({metadata:_,body:v.value},r),conflict_fields:g,fields_from_theirs:y,union_fields:h,conflict_decisions:b,requested_preference:o,conflict_resolution:s}}function ld(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function md(e,t){let n=Do(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 qI(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=H(p);u.set(f,(u.get(f)??0)+1)}return u},o=r(e),s=r(t),i=r(n);for(let[m,u]of o)if((s.get(m)??0)<u||(i.get(m)??0)<u)return null;let a=new Map(s),c=[];for(let m of n){let u=H(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 KI(e,t,n,r,o,s,i){if(!ld(t)||!ld(n))return null;let a=ld(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=o.length>0?`${o}.${u}`:u,f=zI(a,t,n,u,r,p,s,i);f!==void 0&&(c[u]=f)}return c}function tg(e,t,n,r,o,s,i){if(dn(t,n))return t;let a=qI(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(o),a.merged;let c=KI(e,t,n,r,o,s,i);if(c!==null)return c;let m=Qh(e,t,n,r);return m.conflict?s.push(o):m.from_theirs&&i.push(o),m.value}function zI(e,t,n,r,o,s,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 tg(e[r],t[r],n[r],o,s,i,a);if(c){if(u&&dn(e[r],t[r])){a.push(s);return}return u?(i.push(s),o==="theirs"?void 0:t[r]):t[r]}if(!(u&&dn(e[r],n[r])))return u?(i.push(s),o==="theirs"?n[r]:void 0):(a.push(s),n[r])}function ng(e,t,n,r={}){let o=r.preferred??"ours",s=md(e,"base"),i=md(t,"ours"),a=md(n,"theirs"),c=[],m=[],u=tg(s,i,a,o,"",c,m);return{merged:`${JSON.stringify(u??null,null,2)}
41
+ `,conflict_paths:c,paths_from_theirs:m,preferred:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c8046a5-06aa-58f8-b347-e757086082d1")}catch{}})();var rg=["item","history","relationship","json"];function WI(e){let t=e.trim().toLowerCase();if(rg.includes(t))return t;throw new l(`Unknown merge artifact "${e}". Supported values: ${rg.join(", ")}.`,d.USAGE)}function YI(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 ud(e,t){try{return await BI(e,"utf8")}catch{throw new l(`Cannot read merge ${t} file at ${e}.`,d.NOT_FOUND)}}async function JI(e){let t=E(process.cwd(),e.path);return await P(ae(t))?T(t):null}function XI(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function og(e,t){let n=WI(e.artifact),r=YI(e.prefer),o=VI.resolve(e.outputPath??e.oursPath),[s,i,a]=await Promise.all([ud(e.basePath,"base"),ud(e.oursPath,"ours"),ud(e.theirsPath,"theirs")]),c,m,u=[],p={};if(n==="history"){let _=Jh(s,i,a);c=_.merged,p.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=Xh(s,i,a);c=_.merged,p.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await JI(t),g=XI(e.itemPath??o,_),y=kt(x()),h=eg(s,i,a,{format:g,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"stable_value_order"});if(c=h.merged,u.push(...h.conflict_fields),p.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0){let b=Uo(c,{format:g,schema:_?.schema,extensionFieldNames:y}),v=b.metadata,k=[...new Set([...h.fields_from_theirs,...h.union_fields,...h.conflict_decisions.map(I=>I.field)])];m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,mergedFieldHashes:Object.fromEntries(k.map(I=>[I,Rl(H(I==="body"?b.body:v[I]))])),decisions:h.conflict_decisions}}}else{let _=ng(s,i,a,{preferred:r});c=_.merged,u.push(..._.conflict_paths),p.json={paths_from_theirs:_.paths_from_theirs}}if(await HI(o,c,"utf8"),m!==void 0){let _=await df(m);_!==null&&(p.receipt=cr(_))}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:o,requested_preference:r,conflicts:u,...p,guidance:f,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]="c3ec7d9d-f276-5e97-8e97-507925e5d33a")}catch{}})();var QI=4;async function ZI(e){try{return{status:"fulfilled",value:await as(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function ex(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function tx(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.force?e.pendingReceipts:e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>uf(e.gitWorkspaceRoot??process.cwd(),r,{requireExisting:!0}))),n.length}async function sg(e,t){let n=e.dryRun===!0,r=E(process.cwd(),t.path),o=await is(r),s=await lf(o??process.cwd(),{includeLossless:!0,pmRoot:r});if(s.invalid_evidence_count>0)throw new l(`Merge reconciliation refused ${s.invalid_evidence_count} invalid receipt evidence file(s).`,d.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let i=s.receipts,{pendingDecisions:a}=mf(i);if(!n&&e.force!==!0&&a.length>0)throw new l(`Merge reconciliation would accept ${a.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:a.map(A=>`Review receipt ${A.id} for ${A.item_id}: ${A.decisions.map(N=>N.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let c=new Map;for(let A of i){let N=c.get(A.item_id)??[];N.push(A),c.set(A.item_id,N)}let m=Object.fromEntries([...c].map(([A,N])=>[A,{merge:{receipts:N.map(cr)}}])),u=Object.fromEntries([...c].map(([A,N])=>[A,{gitWorkspaceRoot:o,receipts:N}])),p=await cs({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:m,...i.length>0?{mergeReceiptProofById:u}:{}},t),f=new Set(p.streams.map(A=>A.id)),_=[...c.keys()].filter(A=>!f.has(A)),g=await cf(_,QI,A=>ZI({id:A,dryRun:n,options:e,global:t,auditContext:m[A],mergeReceiptProof:u[A]}));ex({receiptOnlyIds:_,results:g,repair:p});let y=await tx({dryRun:n,force:e.force===!0,pendingReceipts:i,repair:p,gitWorkspaceRoot:o}),h=await us({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),b=h.checks.every(A=>A.status==="ok"),v=n?i.length===0:y===i.length,k=p.totals.failed===0&&b&&v,I=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."]:k?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:k,dry_run:n,repair:p,receipts:{pending_before:i.length,reconciled:y,summaries:i.map(cr)},validation:h,guidance:I,generated_at:h.generated_at}}import{createHash as nx}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]="01043e67-99d4-5b68-a1b2-33f35f5cef5f")}catch{}})();var cg=1,dg=/^[A-Za-z0-9_-]+$/,rx=100,ig=1e3;var dq=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function He(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function ox(e){return nx("sha256").update(H({type:He(e.type),author:He(e.author),item:He(e.item),harness:He(e.harness),agent_instance:He(e.agentInstance),provenance:He(e.provenanceFilter)})).digest("hex").slice(0,24)}function ag(e,t){let n={version:cg,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 sx(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===cg,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 ix(e,t){let n=e.trim();if(n.length===0||n.length>4096||!dg.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(!sx(r,t))throw new l("Mutation event cursor does not match this query.",d.USAGE,{code:"event_cursor_query_mismatch"});return r}function ax(e){let t=e??rx;if(!Number.isSafeInteger(t)||t<0||t>ig)throw new l(`Mutation event limit must be an integer from 0 to ${ig}.`,d.USAGE,{code:"invalid_event_limit"});return t}function cx(e,t){let n=e?.trim();if(!n)return{};if(dg.test(n))return{cursor:ix(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 dx(e,t){let n=await ya(e,t);if(n===null){if(!await Ku(e))return{...await zu(e,t),source:"authoritative_history"};n=await ya(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 lx(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 si(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await R(t);let n=ax(e.limit),r=lx(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 o=await T(t),s=o.agent_identity.identity_vocabulary,i=Sp(o.agent_identity.harness_signals),a=Ep({provenance:e.provenanceFilter},i),c=He(e.harness),m=ox(e),{cursor:u,sinceTimestamp:p}=cx(e.since,m),f={...u?{after_ts:u.ts,after_stream_id:u.stream_id,after_stream_offset:u.stream_offset}:p?{since_ts:p}:{},ops:He(e.type),authors:He(e.author),harnesses:c,harness_alias_authors:c?Object.entries(s.aliases).filter(([,y])=>c.includes(y)).map(([y])=>y):void 0,agent_instances:He(e.agentInstance),provenance:[...a].map(([y,h])=>({dimension:y,values:[...h]})),stream_ids:He(e.item),limit:n},_=await dx(t,f),g=_.events.map(y=>({...r==="row"?{cursor:ag(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:Tp(y.entry,s,{itemId:y.stream_id,version:y.stream_offset+1})}:{}}));return{events:g,count:g.length,has_more:_.has_more,cursor_mode:r,..._.events.length===0?{}:{next_cursor:ag(_.events[_.events.length-1],m)},source:_.source,...e.provenanceSummary===!0?{provenance_summary:Ap(_.events.map(y=>y.entry),s,i)}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c7c75b13-7317-5089-9869-7e6e22ed95b2")}catch{}})();var mx="1h",ux="now",px="+1d";function Ft(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function lg(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return ve(n,r)}async function mg(e,t,n,r){let o=lg(e,t,n),s=[];return Ft(s,"start",n.start??ux),n.end!==void 0?Ft(s,"end",n.end):Ft(s,"duration",n.duration??mx),Ft(s,"location",n.location),Ft(s,"timezone",n.timezone),n.allDay===!0&&Ft(s,"all_day","true"),o.event=[s.join(",")],Pt(o,r)}function ug(e,t,n){return mg("Meeting",e,t,n)}function pg(e,t,n){return mg("Event",e,t,n)}function fg(e,t,n){let r=lg("Reminder",e,t),o=[];return Ft(o,"at",t.at??px),Ft(o,"text",t.text??e),r.reminder=[o.join(",")],Pt(r,n)}import Rr from"node:crypto";import{cp as hg,lstat as bx,mkdir as ln,readFile as qn,readdir as fd,rename as bg,rm as hd,writeFile as ai}from"node:fs/promises";import F from"node:path";import{constants as Mt}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 _g=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"}]]),fx=/^[a-z][a-z0-9_]{0,63}$/u,_x=new Map([[Mt.errno.EACCES,"EACCES"],[Mt.errno.EDQUOT,"EDQUOT"],[Mt.errno.EMFILE,"EMFILE"],[Mt.errno.ENFILE,"ENFILE"],[Mt.errno.ENOMEM,"ENOMEM"],[Mt.errno.ENOSPC,"ENOSPC"],[Mt.errno.EPERM,"EPERM"],[Mt.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),hx={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function gx(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&_g.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:_x.get(Math.abs(t.errno))??null}function yx(e,t,n={}){let r=gx(e);if(r===null)return null;if(!fx.test(t))throw new l("Host environment operation labels must be bounded identifiers.",d.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=_g.get(r);return new l(`Host filesystem operation ${t} ${o.summary}.`,d.GENERIC_FAILURE,{code:n.codes?.[o.category]??hx[o.category].code,reason:r,required:o.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[o.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function ii(e,t,n={}){try{return await t()}catch(r){throw yx(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 wg="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var vg=F.join("runtime","workspace-snapshots"),wx=new Set(["checkpoints","locks","runtime","search","transactions"]),vx=/^[a-z0-9][a-z0-9._-]*$/,Cr="sdk-workspace-transaction",pd={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},kg={renameEntry:bg,removeEntry:async e=>{await hd(e,{recursive:!0,force:!0})}},_d=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 qn(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!==Cr||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await _e(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
42
+ `)}};async function Sg(e,t=""){let n=await fd(F.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((s,i)=>s.name.localeCompare(i.name))){if(t.length===0&&wx.has(o.name))continue;let s=F.posix.join(t.replaceAll(F.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${s}`);if(o.isDirectory())r.push(...await Sg(e,s));else if(o.isFile())r.push(s);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${s}`)}return r}async function Eg(e){let t=await Sg(e),n=Rr.createHash("sha256"),r=[],o=0;for(let i of t){let a=await qn(F.join(e,i));r.push(a),o+=a.byteLength,n.update(i),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let s=n.digest("hex");return{manifest:{schema:wg,fingerprint:s,files:t,bytes:o},contents:r}}function gg(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
43
+ `).filter(t=>t.trim().length>0).length}async function kx(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),s=await Promise.all(o.map(async i=>[i,await qn(F.join(e,i))]));for(let[i,a]of s)n.set(i,a)}return n}function gd(e){if(!vx.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 Tg(e,t){return ii(`workspace_snapshot_${e}`,t,{codes:{capacity:pd.capacity.code,permission:pd.permission.code,resource:pd.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 mn(e){return F.join(e,vg)}function Ag(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 Cg(e,t){try{return JSON.parse(await qn(e,"utf8"))}catch(n){throw St(n)?Ag(t):n}}async function yg(e,t,n){try{await hd(e,{recursive:n})}catch(r){throw St(r)?Ag(t):r}}async function Sx(e,t,n=kg){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 Ex(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(s){throw await r.renameEntry(n,t),await r.removeEntry(e),s}await r.removeEntry(n)}async function Tx(e,t){return gd(t),/^[a-f0-9]{64}$/.test(t)?t:(await Cg(F.join(mn(e),"refs",`${t}.json`),t)).fingerprint}async function yd(e,t={}){if(t.name!==void 0&&(gd(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 Eg(e),o=mn(e),s=F.join(o,"objects",n.fingerprint),i=!1;try{i=(await bx(s)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&St(a)))throw a}if(!i){let a=F.join(o,"objects",`.create-${process.pid}-${Rr.randomUUID()}`);await Tg("create_object",async()=>{await ln(F.join(a,"files"),{recursive:!0});for(let[c,m]of n.files.entries()){let u=F.join(a,"files",m);await ln(F.dirname(u),{recursive:!0}),await ai(u,r[c])}await ai(F.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
44
+ `,"utf8"),await ln(F.dirname(s),{recursive:!0})}),i=await Sx(a,s)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=F.join(o,"refs");await ln(c,{recursive:!0});let m=F.join(c,`.ref-${process.pid}-${Rr.randomUUID()}`);await ai(m,`${JSON.stringify(a,null,2)}
45
+ `,"utf8"),await bg(m,F.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:i}}async function Ir(e,t){let n=await Tx(e,t),r=await Cg(F.join(mn(e),"objects",n,"manifest.json"),t);if(r.schema!==wg||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 bd(e){let t=mn(e),n=await fd(F.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&St(o))return[];throw o}),r=await fd(F.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&St(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Ir(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await qn(F.join(t,"refs",o),"utf8"))))}}async function wd(e,t){let n=await Ir(e,t),{manifest:r,contents:o}=await Eg(e),s=new Map(r.files.map((p,f)=>[p,o[f]])),i=await kx(F.join(mn(e),"objects",n.fingerprint,"files"),n.files),a=new Set(r.files),c=new Set(n.files),m=new Set([...a,...c]);for(let p of m){let f=s.get(p),_=i.get(p);f!==void 0&&_!==void 0&&f.equals(_)&&m.delete(p)}let u=r.files.filter(p=>p.startsWith("history/")&&p.endsWith(".jsonl")).map(p=>{let f=gg(s.get(p)),_=gg(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 Rg(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",o=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,i=await be(e,Cr,o,r,!1,!1,s),a=new _d(Vr(e,Cr),r,o);a.start(),await a.refreshNow();let c,m=!1,u=!1;try{let p=await wd(e,t),f=await Ir(e,t),_=await yd(e),g=f.fingerprint,y=mn(e),h=F.join(y,"objects",g,"files"),b=F.dirname(e),v=F.basename(e);c=F.join(b,`.${v}.restore-${Rr.randomUUID()}`);let k=F.join(b,`.${v}.backup-${Rr.randomUUID()}`);await Tg("restore_stage",async()=>{await ln(c,{recursive:!0}),await hg(h,c,{recursive:!0,force:!1}),await ln(F.join(c,"runtime"),{recursive:!0}),await hg(y,F.join(c,vg),{recursive:!0,force:!1})});let I=await Wu({pmRoot:c,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:p.changed_file_count,removed_file_count:p.removed_file_count,removed_item_count:p.removed_item_count,affected_history_stream_count:p.affected_history_stream_count,removed_history_entry_count:p.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:s}),A=F.relative(c,I.historyPath).replaceAll("\\","/");await a.stop(),u=!0;let N=Vr(c,Cr);return await ln(F.dirname(N),{recursive:!0}),await ai(N,await qn(Vr(e,Cr)),{flag:"wx"}),m=!0,await Ex(c,e,k,kg,async()=>{a.start(),u=!1,await a.refreshNow()}),await a.stop(),u=!0,{manifest:f,plan:p,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:A,audit_operation:"workspace_snapshot_restore"}}catch(p){throw c!==void 0&&!m&&await Promise.allSettled([hd(c,{recursive:!0,force:!0})]),p}finally{try{u||await a.stop()}catch{}finally{await i()}}}async function Ig(e,t){gd(t);let n=mn(e);if(!/^[a-f0-9]{64}$/.test(t))return await yg(F.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await bd(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await yg(F.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]="8a3a82a1-9e3d-555f-9111-3c3e19887f75")}catch{}})();function xr(e){let t={...e.args,...e.options};return ve(e.options,t)}function pt(e,t){let n=w(e,t);if(n!==void 0)return n;throw new l(`Missing required parameter: ${t}`,d.USAGE)}function Kn(e){return typeof e=="string"?[e]:ke(e)}function xg(e){return Yh(xr(e),e.global)}function Og(e){let t=xr(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 si({cwd:w(t,"cwd"),pmRoot:w(t,"path"),since:w(t,"since"),type:Kn(t.type),author:Kn(t.author),item:Kn(t.item),limit:t.limit===void 0?void 0:Me(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:Kn(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Kn(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Kn(t.provenanceFilter)}})}function Pg(e){let t=xr(e),n=pt(t,"subcommand");if(n==="install")return Kp({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return sg({dryRun:t.dryRun===!0,author:w(t,"author"),message:w(t,"message"),force:t.force===!0},e.global);if(n==="report")return pf({includeReconciled:t.includeReconciled===!0,cwd:w(t,"cwd")});if(n==="driver")return og({artifact:pt(t,"artifact"),basePath:pt(t,"basePath"),oursPath:pt(t,"oursPath"),theirsPath:pt(t,"theirsPath"),outputPath:w(t,"outputPath")??w(t,"output"),itemPath:w(t,"itemPath"),prefer:w(t,"prefer")},e.global);throw xe({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Lg(e){let t=xr(e),n=pt(t,"subcommand");if(n!=="snapshot")throw xe({command_path:"workspace",token:n,allowed:["snapshot"],display_name:"workspace"});let r=w(t,"snapshotAction")??pt(t,"snapshot_action"),o=E(process.cwd(),e.global.path);if(r==="create")return yd(o,{name:w(t,"name")});if(r==="list")return bd(o);let s=pt(t,"target");if(r==="inspect")return Ir(o,s);if(r==="delete")return Ig(o,s);if(r==="restore")return t.dryRun===!0?wd(o,s):Rg(o,s,{force:t.force===!0,author:w(t,"author"),message:w(t,"message"),lockTtlSeconds:Me(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:Me(t.lockWaitMs,"lockWaitMs")});throw xe({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function ci(e){let t=xr(e),n=pt(t,"title");return e.action==="meet"?ug(n,t,e.global):e.action==="event"?pg(n,t,e.global):fg(n,t,e.global)}import Dx from"node:path";import Ax from"node:fs/promises";import Ng 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]="5c70da27-21f6-5d31-b506-96e1818996d6")}catch{}})();var Cx="templates",Rx=".json",Ix=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,xx=Oo.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),Ox=new Set(xx);function Px(e){let t=e.trim();if(!Ix.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 Fg(e){return Ng.join(e,Cx)}function Mg(e,t){return Ng.join(Fg(e),`${t}${Rx}`)}async function Lx(e){await R(e)}function $g(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function Nx(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(Ox.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(s=>typeof s=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return $g(t)}function Fx(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[o,s]of Object.entries(n)){let i=o.trim();if(i.length===0)throw new l(`Template "${t}" contains an empty option key.`,d.GENERIC_FAILURE);if(typeof s=="string"){r[i]=s;continue}if(Array.isArray(s)&&s.every(a=>typeof a=="string")){r[i]=[...s];continue}throw new l(`Template "${t}" contains invalid value for option "${i}".`,d.GENERIC_FAILURE)}return $g(r)}function Mx(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,o=Fx(r.options,t),s=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:s,updated_at:typeof r.updated_at=="string"?r.updated_at:s,options:o}}async function $x(e,t){let n=await q(Mg(e,t));if(n===null)throw new l(`Template "${t}" not found`,d.NOT_FOUND);return Mx(n,t)}async function vd(e,t,n){let r=E(process.cwd(),n.path);await Lx(r);let o=Px(e),s=Nx(t);if(Object.keys(s).length===0)throw new l("templates save requires at least one create option flag",d.USAGE);let i=S(),a=Mg(r,o),c=i;await P(a)&&(c=(await $x(r,o)).created_at);let m={name:o,created_at:c,updated_at:i,options:s},u=await T(r);return await Ax.mkdir(Fg(r),{recursive:!0}),await Je({pmRoot:r,filePath:a,raw:`${JSON.stringify(m,null,2)}
46
+ `,op:"templates:save",author:C(void 0,u.author_default),lockTtlSeconds:u.locks.ttl_seconds,lockWaitMs:u.locks.wait_ms}),{name:m.name,created_at:m.created_at,updated_at:m.updated_at,path:a,options:m.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f65b4f1f-5501-5829-a04b-d4fbcfb59f5c")}catch{}})();var jg=["list","show","apply","lint"],Ux="schema-types",Gx="schema-statuses",jx="schema-fields";function di(){let e=x();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function qg(){let{profiles:e,warnings:t}=Km(di());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:Wm(n.definition)})),warnings:t,generated_at:S()}}function Kg(e){let t;try{t=Ao(e,di())}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 zg(e){let t;try{t=Ao(e,di())}catch(o){throw new l(o instanceof Error?o.message:String(o),d.USAGE)}let{resolved:n}=t,r=fu(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 qx(e,t){return Dx.join(e,"templates",`${t}.json`)}async function Kx(e,t){let n=await q(qx(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function Dg(e,t,n,r){let o=new Map;for(let s of r.templates){let i=await Kx(e,s.name);i!==void 0&&o.set(s.name,i)}return{typesRaw:await q(st(e,t.files.types,ot.types)),statusesRaw:await q(st(e,t.files.statuses,ot.statuses)),fieldsRaw:await q(st(e,t.files.fields,ot.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function zn(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function Ug(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:zn(t.types.changes),statuses:zn(t.statuses.changes),fields:zn(t.fields.changes),workflows:zn(t.workflows.changes.map(s=>({key:s.type,status:s.status}))),config:zn(t.config.changes),templates:zn(t.templates.changes.map(s=>({key:s.name,status:s.status}))),packages:t.packages,warnings:[...new Set(o)].sort((s,i)=>s.localeCompare(i)),generated_at:S()}}async function zx(e){await R(e)}function Bx(e){try{let t=Ao(e,di());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new l(t instanceof Error?t.message:String(t),d.USAGE)}}async function Bg(e,t,n){let r=E(process.cwd(),n.path);await zx(r);let o=Bx(e),s=o.profile,i=o.warnings,a=t.dryRun===!0,c=await T(r),m=Co(c.schema);if(a){let b=await Dg(r,m,c,s),v=Gg(s,b);return Ug(s,v,!1,!0,[...i])}let u=C(t.author,c.author_default),p=Ju(c),f=!!t.force,_=[...i],g=[],y=async b=>{g.push(await be(r,b,c.locks.ttl_seconds,u,f,p.force_required_for_stale_lock,c.locks.wait_ms))},h;try{await y(Ux),await y(Gx),await y(jx);let b=await Dg(r,m,c,s);if(h=Gg(s,b),h.types.changed){let v=st(r,m.files.types,ot.types);await Je({pmRoot:r,filePath:v,raw:To(h.types.file),op:"profile:apply-types",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let k=new Set(s.types.map(A=>$m(A).name)),I=h.types.file.definitions.filter(A=>k.has(A.name));await Yp(r,I,_,"profile:apply-type-folder"),_.push(...await W({path:v,scope:"project",op:"profile:apply-types"}))}if(h.statuses.changed){let v=st(r,m.files.statuses,ot.statuses);await Je({pmRoot:r,filePath:v,raw:Vm(h.statuses.file),op:"profile:apply-statuses",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await W({path:v,scope:"project",op:"profile:apply-statuses"}))}if(h.fields.changed){let v=st(r,m.files.fields,ot.fields);await Je({pmRoot:r,filePath:v,raw:zm(h.fields.file),op:"profile:apply-fields",author:u,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await W({path:v,scope:"project",op:"profile:apply-fields"}))}if(h.config.changed||h.workflows.changed){for(let v of h.config.changes){if(v.status==="unchanged")continue;let k=Io(v.key);k!==void 0&&xo(c,k,v.value)}c.schema.type_workflows=h.workflows.result,await Ie(r,c,"profile:apply-config")}for(let v of h.templates.changes)v.status!=="unchanged"&&await vd(v.name,{...v.options},n)}finally{for(let b of g.reverse())try{await b()}catch{}}return Ug(s,h,h.changed,!1,_)}function Gg(e,t){try{return _u(e,t)}catch(n){throw new l(n instanceof Error?n.message:String(n),d.USAGE)}}import Vg from"node:fs/promises";import Wg 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 Hx(e,t,n){let r=new Set,o=[];for(let s of e){let i=s.trim();if(i.length===0||r.has(i))continue;r.add(i);let a=t.get(i);if(a===void 0){o.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){o.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return o}function Vx(e,t){let n=[...e].sort((o,s)=>s.entries-o.entries||o.id.localeCompare(s.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function Hg(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return Hx(t.ids,n,t.minEntries)}return Vx(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]="31152621-df59-54a5-a28d-63119e734e6e")}catch{}})();function Wx(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 s=Number.parseInt(n,10);if(!Number.isSafeInteger(s)||s<1||s>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,s-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 o=0;for(let[s,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 ${s+1}.`,d.GENERIC_FAILURE);if(a>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function Yx(e,t){let n=Go(),r=Go();for(let o=0;o<e.length;o+=1){let s=e[o];if(En(n)!==s.before_hash)throw new l(`history-compact detected before-hash drift at entry ${o+1}; run pm history-repair first.`,d.CONFLICT);if(n=qo(n,s.patch,o+1,s.op),En(n)!==s.after_hash)throw new l(`history-compact detected after-hash drift at entry ${o+1}; run pm history-repair first.`,d.CONFLICT);o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function Jx(e,t,n){let r=structuredClone(t),o=[];for(let[s,i]of e.entries()){let a=En(r);r=qo(r,i.patch,n+s+1,i.op),o.push({...i,before_hash:a,after_hash:En(r)})}return{entries:o,finalReplay:r}}async function Xx(e,t,n){let r=e.located?await V(e.located,{schema:t.schema}):null;return r?{loadedItem:r,currentItemRawBeforeLock:r.raw,matchedChainBefore:En(tr(r.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function Qx(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 Zx(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 eO(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=Yx(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=Jx(r,t,e.boundary.compactCount),i=[qe({nowIso:S(),author:e.author,op:"history_compact_baseline",before:Ht(Go()),after:Ht(t),message:Zx(e.boundary)}),...o.entries];return e.dryRun||i.push(qe({nowIso:S(),author:e.author,op:"history_compact",before:Ht(n),after:Ht(n),message:Qx(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function tO(e){return ap({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})=>ip({historyPath:e.historyPath,nextHistoryRaw:Vt(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>W({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function kd(e,t,n){let r=E(process.cwd(),n.path);await R(r);let o=await T(r),s=O(o,x()),i=await cp(r,e,o,s.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 Sn(a,i.id);if(m.length===0)throw new l(`No history entries exist for ${i.id}; nothing to compact.`,d.USAGE);let u=ba(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=Wx(t.before,m),f=p.compactCount>0,_=!!t.dryRun,g=C(t.author,o.author_default),y=[];f||y.push("history_compact_noop_before_boundary");let h=await Xx(i,o,m);h.matchedChainBefore===!1&&y.push("history_compact_item_chain_mismatch");let{rewrittenEntries:b,baselineEntryAdded:v,auditEntryAdded:k}=eO({historyEntries:m,boundary:p,changed:f,dryRun:_,author:g,options:t}),I=ba(b);if(!I.ok)throw new l(`history-compact produced an invalid rewritten chain (${I.errors.join(", ")}).`,d.GENERIC_FAILURE);f&&!_&&y.push(...await tO({pmRoot:r,subject:i,settings:o,typeRegistry:s,historyRawBeforeLock:c,currentItemRawBeforeLock:h.currentItemRawBeforeLock,author:g,force:t.force,loadedItem:h.loadedItem,historyPath:a,rewrittenEntries:b}));let A=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:A},history:{path:a,entries_scanned:m.length,entries_after:b.length,baseline_entry_added:v,audit_entry_added:k,verify_ok:I.ok,verify_errors:I.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:h.matchedChainBefore},warnings:[...new Set(y)].sort((N,M)=>N.localeCompare(M)),generated_at:S()}}var nO=3;function rO(e){let t=Qo(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:Xo(t)}}function Yg(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 oO(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function sO(e){let t=D(e.settings.schema),n=ps(t),r=await ce(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(m=>[m.id,n.classify(m.status)])),s=Wg.join(e.pmRoot,"history"),i=[],a=[];if(!await P(s))return{candidates:i,preselectionErrors:a};let c=(await Vg.readdir(s)).filter(m=>m.endsWith(".jsonl")).sort((m,u)=>m.localeCompare(u));for(let m of c){let u=Wg.join(s,m),p=m.slice(0,-6);try{let f=await Vg.readFile(u,"utf8");await bn({path:u,scope:"project"}),i.push({id:p,entries:oO(f),bucket:o.get(p)??null})}catch(f){a.push({id:p,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:i,preselectionErrors:a}}async function iO(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 kd(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 Jg(e,t){let n=rO(e),r=E(process.cwd(),t.path);await R(r);let o=await T(r),s=O(o,x()),{candidates:i,preselectionErrors:a}=await sO({pmRoot:r,settings:o,typeToFolder:s.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",m=e.minEntries??nO,u=o.history.compact_policy,p=c==="scan"&&e.allOver===void 0&&u.enabled,f=e.allOver??(p?u.max_entries:void 0),_=Hg(i,{ids:n.ids,scope:e.scope,minEntries:m,allOver:f}),g=!!e.dryRun,y=[...a],h={streams_considered:i.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let b of _){let v=await iO({row:b,options:n,dryRun:g,global:t});if(y.push(v.result),!v.selected){h.items_skipped+=1;continue}h.selected+=1,v.compacted&&(h.items_compacted+=1),v.errored&&(h.items_errored+=1)}return{bulk:!0,dry_run:g,mode:c,scope:e.scope??null,criteria:{min_entries:m,all_over:f??null,policy_threshold_applied:p},totals:h,results:y,generated_at: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]="4888a558-7f50-5c28-8e29-fcd19180cbd4")}catch{}})();function Xg(e){let t=e.options.all===!0,n=e.id??w(e.options,"id");return ff(n,t),t?cs(e.options,e.global):as(n,e.options,e.global)}function Qg(e){let t=e.options.ids,n=Qo(t);if(t!==void 0&&n==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:Xo(n),o=Me(e.options.allOver??e.options.all_over,"history-compact allOver"),s=Me(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),i=w(e.options,"scope"),a=[];e.options.closed===!0&&a.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&a.push("all-streams"),(i==="closed"||i==="all-streams")&&a.push(i);let c=[...new Set(a)];if(c.length>1)throw new l("history-compact: closed and all-streams scopes are mutually exclusive.",d.USAGE);let m=c[0];return Yg(e.id,{ids:r,allOver:o,scope:m}),e.id!==void 0?kd(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):Jg({ids:r,scope:m,allOver:o,minEntries:s,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:w(e.options,"author"),message:w(e.options,"message"),force:e.force},e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function li(e){return Ro("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08dcee99-5572-5133-b76a-6a50e4e292e7")}catch{}})();async function Sd(e,t,n,r){let o=t.trim();if(o.length===0)throw new l("pm item reopen requires a non-empty recurrence reason.",d.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let s=E(process.cwd(),r.path),i=D((await T(s)).schema),a=i.open_status,c=li(i),m=n.status??a,u=X(m,i)??m;if(u!==a&&u!==c)throw new l(`Reopen target status must be ${a} or ${c}; received ${m}.`,d.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([a,c])],suggested_retry:`pm item reopen ${e} "${o}" --status ${a}`,suggested_retry_args:["item","reopen",e,o,"--status",a]}});let p=await H_(e,{status:u,unset:["close-reason","resolution","expected-result","actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:p.item,changed_fields:p.changed_fields,warnings:p.warnings,recurrence:p.lifecycle_transition}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="55869854-565d-52d2-8dca-b66aade074bb")}catch{}})();function Zg(e,t){let n=e.id??w(t,"id");if(!n)throw new l("Missing required argument: id",64);return n}function ey(e,t){return w(e.args,"reason")??w(e.args,"text")??w(t,"reason")??w(t,"text")}async function ty(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await dt(Zg(e,r),ey(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function ny(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await Sd(Zg(e,r),ey(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2ef0de1-bc44-5550-862c-f3929334fbef")}catch{}})();function ry(e,t,n){let r;if(typeof e.lines=="string")r=ds(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=ds(`${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 aO=ca("list").properties.outputSession,cO={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:{...aO},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},oy={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},re={type:"string",description:"pm item id, for example pm-abc1."},dO=`Operation name (one of): ${ra.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,lO={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},mO={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function G(e,t=[]){return{...oy,properties:{...oy.properties,...e},required:t}}var uO=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:G({action:{type:"string",enum:[...ra],description:dO},id:re,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."},...cO},["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:G({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:G({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid, options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:G({query:{type:"string"},options:{type:"object"},...mO},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:G({options:{type:"object"},...lO})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:G({id:re,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:G({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId. Set dryRun=true to validate and preview without writes.",inputSchema:G({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:re,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:G({id:re,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:G({id:re,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:G({id:re,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:re,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:G({id:re,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:G({id:re,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:re,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:G({id:re,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:G({id:re,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:G({id:re,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:G({id:re,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:G({id:re,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:G({id:re,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:G({subcommand:{type:"string",enum:[...iu]},id:re,target:re,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:G({id:re,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:G({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:G({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:G({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Schema mutations write workspace config files, not item history.",inputSchema:G({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:[...Gi]},description:`Lifecycle roles for add-status: ${Gi.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:G({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:G({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:G({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],pO={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"},fO=uO.map(e=>{let t=pO[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:ca(t,{properties:n,required:r})}});function sy(){return fO.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="428a19d2-be42-548a-a328-aa0e476b8a71")}catch{}})();var iy=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"]]]),_O=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],hy=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ui=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"]),Or=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"]),gy=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"]]),yy=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"]]),by=new Map([...yy.entries()].flatMap(([e,t])=>ft(t).map(n=>[n,e]))),wy=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],vy=new Map(wy.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),hO=10,gO=20,ay=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."]]),ky=[["init",Jl],["install",Ql],["uninstall",Zl],["explore",em],["manage",im],["describe",tm],["reload",am],["doctor",cm],["catalog",dm],["adopt",lm],["adopt-all",nm],["activate",rm],["deactivate",om],["migrate",sm]],yO=ky.map(([e,t])=>e==="init"?[e,Xl]:[e,t]),bO=[...ky.map(([e,t])=>[`extension ${e}`,t]),...yO.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",ro],["config",Yl],["extension",oo],["package",Jn],["packages",Jn],["install",mm],["create",mo],["item mutate",Om],["item complete",Pm],["item reopen",Lm],["copy",uo],["focus",po],["update",fo],["update-many",_o],["upgrade",um],["calendar",Xn],["cal",Xn],["context",Qn],["ctx",Qn],["get",go],["search",ko],["eval",Fm],["workspace",Et],["workspace snapshot",Et],["workspace snapshot create",Et],["workspace snapshot list",Et],["workspace snapshot inspect",Et],["workspace snapshot restore",Et],["workspace snapshot delete",Et],["next",vo],["aggregate",Zr],["deps",bo],["graph",wo],["guide",yo],["reindex",pm],["history",eo],["history-compact",Hl],["history-redact",zl],["history-repair",Bl],["history-author-acknowledge",to],["merge",Kl],["schema",Vl],["profile",Wl],["plan",no],["restore",hm],["delete",gm],["close",fm],["close-many",so],["append",io],["claim",_m],["release",ym],["start-task",bm],["pause-task",wm],["close-task",vm],["comments",Dl],["notes",Ul],["learnings",Gl],["files",jl],["docs",ql],["test",Em],["test-all",Tm],["telemetry",Am],["test-runs",Cm],["gc",Rm],["stats",ao],["duplicates",co],["validate",Im],["health",lo],["assurance",xm],...Mm,["contracts",So],["completion",Eo],["activity",ho],...[...hy].map(e=>[e,Qr])],Cd=new Map(bO);function wO(e){let t=by.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function cy(e){return ta.includes(e)?pe(e):e.startsWith("extension-")?pe(`extension ${e.slice(10)}`):e.startsWith("package-")?pe(`package ${e.slice(8)}`):e.startsWith("item-")?pe(`item ${e.slice(5)}`):e.startsWith("test-runs-")?pe(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?pe(`templates ${e.slice(10)}`):ui.has(e)?yy.get(e)??pe(e):null}function vO(e,t){return e.command_path===null?!1:ft(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `)||t.startsWith(`${n} `))}function ft(e){return e.split("|").map(t=>pe(t)).filter(t=>t.length>0)}function kO(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let s of ft(o.command_path)){let i=s.split(" ").filter(a=>a.length>0);if(i.length!==0)for(let a=i.length;a>0;a-=1){let c=i.slice(0,a).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,s)=>o.localeCompare(s))}function mi(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Pr(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function SO(e,t){if(!t)return{...e};let r=Pr(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:r}}function Ed(e,t){let r=Pr(e).filter(o=>{let s=o.properties;if(typeof s!="object"||s===null)return!1;let i=s.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:r}}function pe(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Sy(e){return e.replace(/\s+/g,"-")}function Qe(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function dy(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=Qe(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function Td(e,t,n){n&&(e[t]=!0)}function ly(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 EO(e){let t=ly(e.long,"long"),n=ly(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),Td(o,"required",e.required===!0),Td(o,"repeatable",e.repeatable===!0),Td(o,"list",e.list===!0);let s=Qe(e.description);s&&(o.description=s);let i=Qe(e.value_name);i&&(o.value_name=i);let a=[Qe(e.value_type),Qe(e.type),i?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(o.value_type=a),o}function Ey(e){let t=new Map;for(let r of e){let o=pe(r.target_command);if(o.length===0)continue;let s=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},i=`${r.layer}:${r.name}`;s.sourceDedupe.has(i)||(s.sourceDedupe.add(i),s.sources.push({layer:r.layer,name:r.name}));for(let a of r.flags){let c=EO(a);if(!c)continue;let m=`${c.flag}|${c.short??""}`;s.dedupe.has(m)||(s.dedupe.add(m),s.flags.push(c))}t.set(o,s)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((s,i)=>{let a=s.layer.localeCompare(i.layer);return a!==0?a:(s.name??"").localeCompare(i.name??"")})});return n}function TO(e){let t=Ey(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let i=pe(s.command);if(i.length===0)continue;let a=Qe(s.action)??Sy(i),c=Array.isArray(s.arguments)?s.arguments.map(m=>{let u=Qe(m.name);return u?{name:u,required:m.required===!0,variadic:m.variadic===!0,description:Qe(m.description)}:null}).filter(m=>m!==null):[];n.set(i,{command:i,action:a,source:{layer:s.layer,name:s.name},description:Qe(s.description),intent:Qe(s.intent),arguments:c,flags:t.get(i)?.flags??[],examples:dy(s.examples),failure_hints:dy(s.failure_hints)})}let r=new Set;for(let s of e.handlers)r.add(pe(s));for(let s of n.keys())r.add(s);for(let s of t.keys())r.add(s);let o=[];for(let s of[...r].sort((i,a)=>i.localeCompare(a))){let i=n.get(s);o.push(AO(s,i,t.get(s)?.flags??[]))}return o}function AO(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:Sy(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function CO(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let r=t.replace(/-([a-z0-9])/g,(o,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return r.length>0?r:null}function RO(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 IO(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function xO(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=RO(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let s=CO(o);!s||n[s]!==void 0||(n[s]=IO(o,e.action),o.required===!0&&r.push(s))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function OO(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 PO(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((s,i)=>s.localeCompare(i)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let i=`${s.flag}|${s.short??""}`;if(!o.has(i))o.add(i),r.flags.push(s);else{let a=r.flags.find(c=>`${c.flag}|${c.short??""}`===i);a&&OO(a,s)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function LO(e,t=T){let n={mode:vt.extensions.policy.mode,trust_mode:vt.extensions.policy.trust_mode,default_sandbox_profile:vt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=E(process.cwd(),e.path);if(!await P(ae(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),s=await Yr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),i=await Jr({...s,loaded:s.loaded});return{handlers:new Set(i.commands.handlers.map(c=>pe(c.command))),disabledReason:null,commandDefinitions:i.registrations.commands,flagRegistrations:i.registrations.flags,registrations:i.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function NO(e,t={}){let n=new Map;for(let r of na){let o=ui.has(r);if(o&&!t.includePackageOwnedActions)continue;let s=cy(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:s})}if(t.includePackageOwnedActions)for(let r of ui)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:cy(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:pe(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function FO(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?ft(e.command_path):[],r=n.some(i=>t.handlers.has(i)),o=n.map(i=>gy.get(i)).find(i=>typeof i=="string"),s=t.disabledReason===null&&r;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function Ty(e){return Cd.get(e)??Xr}function MO(e){return Or.has(e)?!1:Cd.has(e)}function $O(e){return hy.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function my(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function DO(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function UO(e){let t=new Map;for(let r of e.definitions){let o=my(r.cli_flag);if(!o)continue;let s=r.cli_aliases.map(a=>DO(a)).find(a=>a!==null),i=r.cli_aliases.map(a=>my(a)).filter(a=>a!==null&&a!==o);for(let a of r.commands){let c=t.get(a)??{flags:[],seen:new Set},m=s?{flag:o,short:s}:{flag:o},u=`${m.flag}|${m.short??""}`;c.seen.has(u)||(c.seen.add(u),c.flags.push(m));for(let p of i){let f=`${p}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:p}))}t.set(a,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,Qi(o.flags));return n}function uy(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let s=`${o.flag}|${o.short??""}`;r.has(s)||(r.add(s),n.push(o))}return Qi(n)}function GO(e,t,n,r){return e.map(o=>{let s=MO(o),i=s?Ty(o):[],a=n.get($O(o))??[],c=t.get(o),m=uy(i,a),u=uy(m,c?.flags??[]),p=i.length>0&&(c?.flags.length??0)>0?"mixed":s?"core":"extension";return{command:o,flags:u,...r?{canonical_command:Ad(o),visibility:Au(Ad(o)),positionals:Fl(o)?.slots??[],flag_invocations:Tu(o,u)}:{},provider:p,extension_sources:c?.sources}}).sort((o,s)=>o.command.localeCompare(s.command))}function jO(e,t=Zn){let n=new Set(e),r=new Map;for(let o of wy){let s=o.aliases.filter(i=>n.has(i));r.set(o.canonical,{canonical:o.canonical,aliases:s,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let s=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};s.aliases.includes(o.alias)||s.aliases.push(o.alias),s.contracts.push(o),r.set(o.canonical,s)}return[...r.values()].map(({contracts:o,...s})=>o.length===0?s:{...s,contracts:o}).sort((o,s)=>o.canonical.localeCompare(s.canonical))}function qO(){return{create_string_options:hu,create_repeatable_options:Oo,update_string_options:gu,update_repeatable_options:yu,list_string_options:xl,search_string_options:Ol,calendar_string_options:Pl,context_string_options:Ll,activity_string_options:Nl}}function py(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=_n(e,"create",n),o=[...new Set(r.required)].sort((a,c)=>a.localeCompare(c)),s=[...new Set(o.map(a=>ye("create",a)))].sort((a,c)=>a.localeCompare(c)),i=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:o,required_flags:s,required_type_options:i,policy_errors:[...new Set(r.errors)].sort((a,c)=>a.localeCompare(c))}}function KO(e){let t={},n={};for(let r of[...e.types].sort((o,s)=>o.localeCompare(s))){let o=e.by_type[r];t[r]=py(o,"strict"),n[r]=py(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function zO(e,t){let n=Pr(e);if(n.length===0)return e;let r=!1,o=n.map(s=>{let i=s.properties;if(typeof i!="object"||i===null)return s;let a=i.action;return typeof a!="object"||a===null||a.const!=="create"?s:(r=!0,{...s,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function BO(e){let t=mi(e.action)!==void 0||mi(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,s=e.flagsOnly===!0,i=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,m=mi(e.action),u=mi(e.command),p=!r&&!c&&!o&&!s&&!i&&!m&&!u;return{selectedAction:m,selectedCommand:u,summary:r,schemaOnly:o,flagsOnly:s,availabilityOnly:i,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:p,omitUnfilteredCommandFlags:p,omitUnfilteredCommanderAliases:p||u!==void 0&&!c}}function HO(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 VO(e,t=T){try{return await t(e)}catch{return structuredClone(vt)}}async function WO(e,t){let n=await VO(t),r=await LO(e),o=O(n,r.registrations??x()),s=We(n.schema),i=TO(r);return{settings:n,runtimeProbe:r,typeRegistry:o,statusRegistry:D(n.schema),runtimeFieldRegistry:s,runtimeFieldFlagMap:UO(s),createRequiredOptionContracts:KO(o),extensionContracts:i,mergedExtensionContracts:PO(i),extensionFlagMap:Ey(r.flagRegistrations)}}function fy(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ui.has(e.selectedAction)||e.selectedCommand!==void 0&&Or.has(e.selectedCommand))}function YO(e,t){let n=NO(t,{includePackageOwnedActions:fy(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(cu);return n.filter(o=>!r.has(o.action))}return fy(e)&&e.selectedCommand!==void 0&&Or.has(e.selectedCommand)&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:wO(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function JO(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 XO(e,t){return[...new Set([...ta.filter(n=>!Or.has(n)),...[...Cd.keys()].filter(n=>!Or.has(n)),...e.flatMap(n=>n.command_path?ft(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>pe(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function QO(e,t){let n=t.slice(0,hO),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),s=t.slice(0,gO),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: ${o}.`,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:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function ZO(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 eP(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 tP(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let r=t.filter(s=>s.startsWith(`${e.selectedCommand} `));if(r.length>0)throw QO(e.selectedCommand,r);let o=gy.get(e.selectedCommand);throw o?ZO(e.selectedCommand,o):eP(e.selectedCommand)}function nP(e,t){let n=YO(e,t.mergedExtensionContracts);JO(e,n);let r=XO(n,t.mergedExtensionContracts);tP(e,r);let o=e.selectedCommand?by.get(e.selectedCommand):void 0,s=e.selectedCommand?n.filter(m=>o?m.action===o:vO(m,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.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?s.filter(m=>m.action===e.selectedAction):s,a=[...new Map(i.map(m=>FO(m,t.runtimeProbe)).map(m=>[o?m.action:`${m.action}|${m.command_path??""}`,m])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(m=>m.invocable):a;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:s,scopedActionDescriptors:i,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(m=>m.action))]}}function rP(e){return new Set(Pr(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function oP(e){let t=pu,n=Pr(t),r=rP(t),o=e.filter(s=>!r.has(s.action)).map(s=>xO(s));return o.length>0?{...t,oneOf:[...n,...o]}:t}function _y(e,t,n){let r=new Set(t.actionDescriptors.map(s=>s.action)),o=e.selectedAction?SO(n,e.selectedAction):e.selectedCommand?Ed(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):Ed(n,r);return e.runtimeOnly&&!e.selectedAction?Ed(o,new Set(t.actions)):o}function sP(e,t,n){let r=oP(t.mergedExtensionContracts),s=!e.flagsOnly&&!e.availabilityOnly?zO(_y(e,n,r),t.createRequiredOptionContracts):_y(e,n,r);return{mergedSchema:r,filteredSchema:s}}function iP(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?kO(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function aP(e,t){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let n=new Set(Zn.filter(r=>r.hidden&&r.lifecycle==="deprecated").map(r=>r.alias));return t.filter(r=>!n.has(r))}function Ad(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":vy.get(t)??t}var cP=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"]]),dP=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function lP(e,t){let n=ay.get(e)??(e.includes(" ")?void 0:ay.get(Ad(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(m=>ft(m.command).includes(e));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let o=e.split(" "),s=o.at(-1),i=o.slice(0,-1).join(" "),a=cP.get(s),c=dP.get(e)??i;return{intent:a===void 0||i.length===0?`Run ${e}.`:`${a} ${c}.`,intent_source:"generated"}}function mP(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(pe))].filter(s=>s.length>0).sort((s,i)=>s.localeCompare(i)).map(s=>{let i=oa(s,{generateFallback:!0}),a=s.split(" ")[0],c=vy.get(a)??(a.startsWith("list-")?"list":a.startsWith("history-")?"history":a),m=new Set([...Ty(s).map(f=>f.flag),...t.filter(f=>ft(f.command).includes(s)).flatMap(f=>f.flags.map(_=>_.flag))]),u=(iy.get(s)??iy.get(c)??_O).filter(f=>m.has(f)),p=lP(s,t);return{command:s,intent:p.intent,...o||p.intent_source!=="command"?{intent_source:p.intent_source}:{},...u.length>0?{flags:u}:{},default_max_estimated_tokens:i.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...i.default_max_estimated_tokens_by_format}}:{}}})}function uP(e){return e.map(t=>({budget:oa(t,{generateFallback:!0}),envelope:Iu(t)}))}function pP(e){let t=new Map;for(let n of e){let r=wu(n),o=r===void 0?[d.SUCCESS,d.GENERIC_FAILURE,d.USAGE,d.NOT_FOUND,d.CONFLICT,d.DEPENDENCY_FAILED]:r.exit_codes,s=o.join(","),i=t.get(s)??{commands:[],exit_codes:o};i.commands.push(n),t.set(s,i)}return[...t.values()]}function fP(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>ft(r.command).includes(e.selectedCommand));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>ft(o.command).some(s=>r.has(s)))}return t.extensionContracts}function _P(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 hP(e,t,n){let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,s])=>[o,[...new Set(s.map(i=>`--${i.cli_flag}`))].sort((i,a)=>i.localeCompare(a))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...eu],services:[...tu],policy_modes:[...nu],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...su],trust_modes:[...ru],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...ou],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...al],create_modes:[...cl],close_validation_modes:[...dl],workflow_enforcement_modes:[...ll]},e.relationship_kind_contracts=[...gl,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,s)=>o.kind.localeCompare(s.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function gP(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 yP(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=GO(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let s=new Set(r);e.list_projections=Object.entries(Pu).filter(([i])=>s.has(i)).map(([i,a])=>({command:i,default:a,brief_fields:[...Ou],compact_fields:[...xu]}))}e.command_aliases=o}}function bP(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=qO();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function wP(e,t,n,r){e.command_summaries=mP(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...du],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(pe))].filter(o=>ia(o)!==void 0).sort((o,s)=>o.localeCompare(s)).map(o=>({command:o,modes:[...mu(o).keys()]}))}:{}},e.grammar_contracts={nouns:Kt.nouns,shared_verbs:Kt.shared_verbs,scope_before_verb:Kt.scope_before_verb,visible_top_level_ceiling:Kt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Kt.ceiling_raise_requires_pm_item,positional_shape_budget:Kt.positional_shape_budget,positional_shape_count:new Set(Xi.map(({slots:o})=>$l(o))).size,positional_action_count:Ji.length,positional_action_parents:[...new Set(Ji.map(({parent:o})=>o))].sort((o,s)=>o.localeCompare(s)),...r.includePositionalSignatures?{positional_signatures:Xi}:{}}}async function Ay(e,t){let n=BO(e);HO(n);let r=E(process.cwd(),t.path),o=await WO(t,r),s=nP(n,o),i=sP(n,o,s),a=iP(n,s),c=aP(n,a),m=_P(n,i,s,c),u=fP(n,o,c),p=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&wP(m,c,u,{includeFormatBudgets:p,includeIntentProvenance:p,includePositionalSignatures:p,includeProjectionModeMatrix:p}),n.summary)return m;let f=jO(s.commandCatalog);return n.flagsOnly&&!n.fullOutput||hP(m,o,n),gP(m,n,i,u),yP(m,n,o,c,f),bP(m,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(m.assurance_contracts={measurement_source_kinds:[...xp],gate_triggers:[...Ip]}),n.fullOutput&&m.grammar_contracts&&(m.grammar_contracts.destinations=Ml),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(m.mcp_tools=sy(),m.context_intents=vu(),m.read_output_dimensions=sa,m.error_codes=Eu,m.command_output_contracts=uP(c),m.diagnostic_output_contracts=lu,m.command_exit_contracts={vocabulary:bu,command_sets:pP(c)}),m}import rL from"node:fs/promises";import zy 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 pi(e,t,n,r,o,s="min"){let i=o==="min"?e-t:t-e,a=s==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return i<0||i===0&&r!==null&&a<0}function vP(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,s=null,i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let m=c.trim();if(m==="")continue;r+=1;let u;try{u=JSON.parse(m)}catch{continue}if(u===null||typeof u!="object"||!("ts"in u)||typeof u.ts!="string")continue;let p=u.ts,f=Date.parse(p);Number.isNaN(f)||(pi(f,i,p,o,"min")&&(i=f,o=p),pi(f,a,p,s,"max","max")&&(a=f,s=p))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:s}}function Cy(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:_,raw:g})=>vP(_,g)),s=0,i=0,a=null,c=null,m=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let _ of o){if(s+=_.lines,i+=_.bytes,_.oldest_ts!==null){let g=Date.parse(_.oldest_ts);pi(g,m,_.id,a?.id??null,"min")&&(m=g,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let g=Date.parse(_.newest_ts);pi(g,u,_.id,c?.id??null,"max")&&(u=g,c={id:_.id,ts:_.newest_ts})}}let p=r===0?[]:[...o].sort((_,g)=>g.bytes-_.bytes||_.id.localeCompare(g.id)).slice(0,r),f=r===0?[]:[...o].sort((_,g)=>g.lines-_.lines||_.id.localeCompare(g.id)).slice(0,r);return{total_streams:e.length,total_lines:s,total_bytes:i,largest_by_bytes:p,deepest_by_lines:f,oldest_entry:a,newest_entry:c}}import{createHash as SP}from"node:crypto";import{execFile as EP}from"node:child_process";import xy from"node:path";import{promisify as TP}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 Ry=1;function kP(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 Rd(e){if(e===null)return{format_version:Ry,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!==Ry||!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(!kP(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]="c2e1edc9-c454-5cfa-85c8-e9fb0a76a296")}catch{}})();var AP=TP(EP),CP=50,Iy=1e3,RP=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Oy(e){let t=e.trim().toLowerCase();if(!RP.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 IP(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 Lr(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 xP(e){let t=e??CP;if(!Number.isSafeInteger(t)||t<0||t>Iy)throw new l(`Improvement observation limit must be an integer from 0 to ${Iy}.`,d.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Py(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 OP(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=Oy(n.metric),o=IP(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new l("Target-directed observations require a finite threshold.",d.USAGE,{code:"invalid_improvement_observation"});let s=await LP(e,n.revision),i=Lr(n.source,"source"),a=Lr(n.itemId,"itemId"),c=Lr(n.unit,"unit"),m=Lr(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,r,i??"manual",a??"workspace"].join(":")),u={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Py(n.observedAt??S(),"observedAt"),...s,author:C(n.author,t.author_default),...a===void 0?{}:{item_id:a},...i===void 0?{}:{source:i},...m===void 0?{}:{idempotency_key:m}};return{id:SP("sha256").update(H(u)).digest("hex").slice(0,24),...u}}function PP(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new l(`Improvement observation retry key already records a different value for ${t.metric}.`,d.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new l(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,d.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function LP(e,t){let n=Lr(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await AP("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:_l(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function NP(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function Ly(e,t={}){let n=E(process.cwd(),t.path);await R(n);let r=await T(n),o=await OP(n,r,e),s=xy.join(n,"improvement-ledger.json"),i=await Yu({pmRoot:n,filePath:s,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:a=>{let c=Rd(a),m=PP(c,o);return m?{raw:a,result:m}:(c.observations.push(o),c.observations.sort((u,p)=>u.observed_at.localeCompare(p.observed_at)||u.metric.localeCompare(p.metric)||u.id.localeCompare(p.id)),{raw:`${H(c)}
47
+ `,result:o})}});return{changed:i.changed,observation:i.result,ledger_path:"improvement-ledger.json"}}async function Ny(e={}){let t=E(e.cwd??process.cwd(),e.pmRoot);await R(t);let n=e.metric===void 0?void 0:Oy(e.metric),r=e.since===void 0?void 0:Py(e.since,"since"),o=xP(e.limit),i=Rd(await q(xy.join(t,"improvement-ledger.json"))).observations.filter(c=>(n===void 0||c.metric===n)&&(e.itemId===void 0||c.item_id===e.itemId)&&(r===void 0||c.observed_at>=r)),a=new Map;for(let c of i){let m=a.get(c.metric)??[];m.push(c),a.set(c.metric,m)}return{observations:[...i].reverse().slice(0,o),total:i.length,truncated:i.length>o,trends:[...a].map(([,c])=>NP(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 Fy(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 FP(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function MP(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function Id(e=er,t=wn){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function $P(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function xd(e,t=wn,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let s of t){let i=`${o.agent_harness}\0${s}`,a=r.get(i)??{harness:o.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};a.entries+=1;let c=o.agent_provenance?.[s];c!=null&&c.value.length>0?a.observed+=1:c===null?a.unavailable+=1:a.legacy_missing+=1,r.set(i,a)}return[...r.values()].map(o=>{let s=o.observed+o.unavailable;return{...o,coverage:s===0?null:o.observed/s,inert:s>=n&&o.observed===0}}).sort((o,s)=>o.harness.localeCompare(s.harness)||o.dimension.localeCompare(s.dimension))}function DP(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let m of["role","topic"]){let u=`${c.agent_harness}\0${m}`,p=o.get(u)??{harness:c.agent_harness,dimension:m,entries:0,observed:0,by_source:{},coverage:0};p.entries+=1;let f=c.agent_provenance?.[m];f?.value&&(p.observed+=1,p.by_source[f.source]=(p.by_source[f.source]??0)+1),o.set(u,p)}let s=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([m],[u])=>m.localeCompare(u)))})).sort((c,m)=>c.harness.localeCompare(m.harness)||c.dimension.localeCompare(m.dimension)),i=s.filter(c=>c.entries>=r),a=i.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:i.length>0&&a.length===0,minimum_coverage:n,minimum_entries:r,rows:s,failures:a}}function UP(e){let t=[...e].sort((s,i)=>s.ts.localeCompare(i.ts)||s.author.localeCompare(i.author)||s.op.localeCompare(i.op)||s.before_hash.localeCompare(i.before_hash)||s.after_hash.localeCompare(i.after_hash)),n=new Map,r=new Map;for(let s of t){let i=s.agent_episode,a=Fy(s),c=`${a.source}:${a.id}`,m=n.get(c);if(m){m.entries.push(s);continue}let u={id:a.id,...i?.label===void 0?{}:{label:i.label},...i?.parent_id===void 0?{}:{parent_id:i.parent_id},source:a.source,entries:[s],children:[]};n.set(c,u),i!==void 0&&r.set(a.id,u)}let o=[];for(let s of n.values()){let i=s.parent_id?r.get(s.parent_id):void 0;i&&FP(s,i,r)?i.children.push(s):o.push(s)}return MP(o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f0e89b0b-ccd1-5dbb-afad-119d5a98590a")}catch{}})();var GP=1e4,My=1e5,jP=1e3,qP=30,KP=["append","comment","docs","file","learning","note","test_run"];function zP(e){let t=e??GP;if(!Number.isSafeInteger(t)||t<1||t>My)throw new l(`History analytics event limit must be an integer from 1 to ${My}.`,d.USAGE,{code:"invalid_history_analytics_limit"});return t}function $y(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 BP(e){let t=e?.trim();if(!t)return new Date(Date.now()-qP*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new l("History analytics --since duration must be positive.",d.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*s).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new 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 Dy(e,t){let n=zP(t.eventLimit),r=BP(t.since),o=[],s=r,i=!1;for(;o.length<n;){let a=await si({pmRoot:e,since:s,limit:Math.min(jP,n-o.length),full:!0}),c=a.events.map(m=>({item_id:m.item_id,entry:m.entry}));if(o.push(...c),i=a.has_more,s=a.next_cursor,!a.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:i,...i?{next_cursor:s}:{},source:"history_event_index"}}}function HP(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function VP(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 WP(e){return KP.some(t=>e.startsWith(t))}function Uy(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 YP(e,t,n){let r=new Map,o=new Map,s=new Map;for(let i of t){let a=HP(i.entry,e),c=VP(i.entry),m=o.get(i.item_id)===!0,u=c===void 0?m:n.has(c);if(c!==void 0&&o.set(i.item_id,u),!a)continue;let p=Uy(r,a);p.events+=1,WP(i.entry.op)?p.annotationEvents+=1:p.stateEvents+=1,c!==void 0&&!m&&u?(p.closes+=1,s.set(i.item_id,a)):c!==void 0&&m&&!u&&(p.reopens+=1)}return{buckets:r,lastCloseValue:s}}function JP(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of o){let i=t.get(s);i&&(Uy(e,i).defectEscapes+=1)}}}function XP(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function QP(e,t,n,r,o,s){let{buckets:i,lastCloseValue:a}=YP(e,t,r);return JP(i,a,n),{dimension:e,status:i.size===0?"unavailable":"available",rows:[...i].map(([c,m])=>XP(c,m,o,s)).sort((c,m)=>m.events-c.events||c.value.localeCompare(m.value))}}function ZP(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),s=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(s)?1:Math.max(1,(s-o)/864e5)}function eL(e,t,n){let r=Id(t),o=xd(e,wn,n),s=o.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),i=r.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:r,observations:o,inert:s,undeclared:i,warnings:[...s.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...i.map(a=>`provenance_dimension_undeclared:${a}`)]}}function Gy(e,t=er,n={}){let r=$y(n.minimumSample);return{...eL(e.events.map(o=>o.entry),t,r),window:e.receipt}}function jy(e,t,n,r={}){let o=$y(r.minimumSample),s=ZP(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(i=>QP(i,e.events,t,n,o,s)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var tL=32;function nL(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let s=o.slice(0,o.indexOf("=")).trim();r.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Nr(e,t){let n=nL(e).map(o=>{let[s,...i]=o.split(","),a=s.indexOf("="),c=s.slice(0,a).trim(),m=s.slice(a+1).trim(),u=Number(m);if(a<=0||c.length===0||m.length===0||!Number.isFinite(u))throw new l(`Invalid --measure "${o}"; expected name=value[,unit=...][,threshold=...]`,d.USAGE);let p,f;for(let _ of i){let g=_.indexOf("="),y=_.slice(0,g).trim(),h=_.slice(g+1).trim();if(y==="unit"&&h.length>0)p=h;else if(y==="threshold"&&h.length>0&&Number.isFinite(Number(h)))f=Number(h);else throw new l(`Invalid --measure attribute "${_}"`,d.USAGE)}return{name:c,value:u,unit:p,threshold:f,recorded_at:t}});return[...new Map(n.map(o=>[o.name,o])).values()].sort((o,s)=>o.name.localeCompare(s.name)).slice(0,tL)}function qy(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function Ky(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,i)=>i.recorded_at.localeCompare(s.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b56db1fc-d989-5d18-8b29-336a03f1e525")}catch{}})();function oL(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function sL(e,t,n,r,o){let s=mr(e,"type",r),i=new Set(s.rows.map(f=>f.key)),a=t.filter(f=>!i.has(f)),m=(o?[...s.rows,...a.map(f=>({label:f,key:f,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(f=>({type:f.key??f.label,total:f.total,open:f.buckets.open,in_progress:f.buckets.in_progress,blocked:f.buckets.blocked,draft:f.buckets.draft,closed:f.buckets.closed,canceled:f.buckets.canceled,other:f.buckets.other})),u=oL([...n]);for(let f of e)u[f.status]+=1;let p=Object.fromEntries(Object.entries(u).filter(([,f])=>o||f>0));return{byType:m,byStatus:p,omitted:o?0:a.length+Object.values(u).filter(f=>f===0).length}}function iL(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function aL(e){let t=zy.join(e,"history");if(!await P(t))return[];await bn({path:t,scope:"project"});let n=(await rL.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,s)=>o.localeCompare(s)),r=[];for(let o of n){let s=zy.join(t,o),i=await q(s);i!==null&&(await bn({path:s,scope:"project"}),r.push({id:o.slice(0,-6),raw:i}))}return r}async function cL(e,t){let n=[],r=S();for(let o of Nr(t.observe,r))n.push(await Ly({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function dL(e,t,n){let r={};return t.byAssignee&&(r.assignee=mr(e,"assignee",n)),t.byTag&&(r.tag=mr(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=mr(e,"priority",n)),r}async function lL(e,t,n,r,o){let s={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},i=o.provenanceCoverage||o.fleetAttribution?await Dy(e,s):void 0;return{provenanceCoverage:o.provenanceCoverage&&i?Gy(i,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:o.fleetAttribution&&i?jy(i,t,r,s):void 0}}function mL(e,t,n,r,o){let s=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...s?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:S()}}async function Od(e,t={}){let n=E(process.cwd(),e.path);await R(n);let r=await T(n),o=await cL(e,t),s=O(r,x()),i=D(r.schema),a=t.fieldUtilization?await tp(n,r.item_format,s.type_to_folder,void 0,r.schema):await ce(n,r.item_format,s.type_to_folder,void 0,r.schema);await Zu({pmRoot:n,settings:r,itemIds:a.map(k=>k.id),commandLabel:"stats"});let c=ps(i),m=sL(a,s.types,i.definitions.map(k=>k.id),c,t.includeEmpty===!0),u=await aL(n),p=0;for(let k of u)p+=iL(k.raw);let f=t.storage?Cy(u):void 0,_=t.metadataCoverage?Pf(a,c):void 0,g=dL(a,t,c),y=t.fieldUtilization?Lf(a):void 0,h=t.measurements===!0||o.length>0?await Ny({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:b,fleetAttribution:v}=await lL(n,a,r,i.terminal_statuses,t);return mL({items:a.length,history_streams:u.length,history_entries:p},m.byType,m.byStatus,m.omitted,{metadataCoverage:_,breakdowns:g,storage:f,fieldUtilization:y,improvementLedger:h,recordedObservations:o,provenanceCoverage: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 By(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:w(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ke(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:w(e,"measurementSource"),measurementItem:w(e,"measurementItem"),measurementRevision:w(e,"measurementRevision"),author:w(e,"author"),message:w(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:w(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import uL from"node:fs/promises";import $t 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 Jy=$t.join("runtime","telemetry","events.jsonl"),Xy=$t.join("runtime","telemetry","state.json"),pL=$t.join("runtime","telemetry"),fL=20,Hy=["status","flush","stats","clear"],Vy=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Pd=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Wy=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},_L=e=>({command:Pd(e.event.command,"<unknown>"),eventType:Pd(e.event.event_type,"unknown"),eventSchemaVersion:Wy(e.event.schema_version),clientSchemaVersion:Wy(e.client_schema_version)}),hL=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),gL=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},yL=e=>{let t=e?.command_resolution;return Pd(t,"")||void 0},Qy=(e,t)=>{e[t]=(e[t]??0)+1},bL=(e,t)=>{let n=gL(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=yL(t);r!==void 0&&Qy(e.resolution_counts,r)},wL=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Yy=(e,t)=>{t!==void 0&&e.add(t)},vL=(e,t)=>{let n=_L(t),r=e.get(n.command)??hL();r.count+=1,r.max_attempts=Math.max(r.max_attempts,wL(t.attempts)),Qy(r.event_type_counts,n.eventType),Yy(r.event_schema_versions,n.eventSchemaVersion),Yy(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&bL(r,t.event.payload),e.set(n.command,r)},kL=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((s,i)=>s-i),o=Object.entries(t.resolution_counts).sort((s,i)=>s[0].localeCompare(i[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,i)=>s[0].localeCompare(i[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,i)=>s-i),client_schema_versions:[...t.client_schema_versions].sort((s,i)=>s-i),...r.length>0?{duration_p50_ms:Vy(r,.5),duration_p95_ms:Vy(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},SL=e=>{let t=(e??"status").trim().toLowerCase();if(Hy.includes(t))return t;throw xe({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Hy,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Ld=()=>{throw new l("--limit must be a positive integer",d.USAGE)},Zy=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Ld():e,EL=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Ld():Zy(Number.parseInt(t,10))},TL=e=>e===void 0?fL:typeof e=="number"?Zy(e):typeof e=="string"?EL(e):Ld(),AL=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},CL=e=>{try{let t=JSON.parse(e);return AL(t)?t:void 0}catch{return}},RL=e=>e===null?[]:e.split(`
48
+ `).map(t=>t.trim()).filter(t=>t.length>0),eb=e=>{let t=RL(e),n=[],r=0;for(let o of t){let s=CL(o);s===void 0?r+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},IL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xL=e=>{try{let t=JSON.parse(e);return IL(t)?t:{}}catch{return{}}},OL=async e=>{let t=await q(e);return t===null||t.trim().length===0?{}:xL(t)},fi=e=>e??null,_i=async e=>{let t=await T(e),n=$t.join(e,Jy),r=$t.join(e,Xy),o=await q(n),s=eb(o),i=await OL(r);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:r,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:fi(i.last_attempted_flush_at),last_successful_flush_at:fi(i.last_successful_flush_at),last_failed_flush_at:fi(i.last_failed_flush_at),last_failed_flush_error:fi(i.last_failed_flush_error)}},PL=e=>{let t=new Map;for(let n of e)vL(t,n);return[...t.entries()].map(([n,r])=>kL(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},LL=async(e,t)=>({action:"telemetry",subcommand:"status",status:await _i(t.globalPmRoot),generated_at:S()}),NL=async(e,t)=>{let n=await _i(t.globalPmRoot);await kp(t.globalPmRoot);let r=await _i(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),s=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:s,queue_drained:s,status:r,generated_at:S()}},FL=async(e,t)=>{let n=TL(e.limit),r=await q(t.queuePath),o=eb(r),s=PL(o.entries),i=s.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:s.length>i.length,stats:i,generated_at:S()}},ML=async(e,t)=>{let n=await T(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 Ie(t.globalPmRoot,n,"telemetry:clear");let o=$t.join(t.globalPmRoot,pL),s=await P(o);return await uL.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:s&&!await P(o),queue_exists_after:await P(t.queuePath),state_exists_after:await P(t.statePath),status:await _i(t.globalPmRoot),generated_at:S()}},$L={status:LL,flush:NL,stats:FL,clear:ML};async function tb(e,t){let n=SL(e.subcommand),r=nt(process.cwd());return $L[n](e,{globalPmRoot:r,queuePath:$t.join(r,Jy),statePath:$t.join(r,Xy)})}import{spawn as wb}from"node:child_process";import{cp as $d,mkdir as bi,mkdtemp as vb,open as Dd,readdir as Ud,rm as Fr,symlink as kb}from"node:fs/promises";import{tmpdir as Sb}from"node:os";import z 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 nb=20;function DL(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return nb;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?nb:t}function Nd(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let s=kn(r.recorded_at,o.recorded_at);if(s!==0)return s;let i=r.run_id.localeCompare(o.run_id);return i!==0?i:r.kind.localeCompare(o.kind)}),n=DL();return t.length>n?t.slice(t.length-n):t}async function hi(e){await ne({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=Nd([...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 rb=100;function Fd(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 UL(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=rb?n:`${n.slice(0,rb-3)}...`}function ob(e){return e.map((t,n)=>`${n+1}. ${UL(t)}`).join("; ")}function GL(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 jL(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function sb(e,t){let n=GL(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,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 o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",d.USAGE);let s=[],i=[];for(let a=0;a<e.length;a+=1)jL(e[a],o)&&(i.push(e[a]),s.push(a+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${ob(e)}`,d.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:s,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let o=Fd(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${ob(e)}`,d.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="99ce92bb-ed45-5327-b148-b5bb26a0bf05")}catch{}})();var yi=20*1024*1024,qL=3e3,KL=1e4,zL=5e3,ib=120,BL=new Set(["locks","extensions","runtime"]),HL=new Set(["history","index","search","extensions","locks","runtime"]),VL=[/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],WL=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,YL=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,JL=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 qd(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function XL(){return qd("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",qL)}function QL(){return qd("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",KL)}function ZL(){return qd("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",zL)}function eN(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 tN(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function Kd(e){let t=0,n=0,r=0,o=0;for(let s of e){let i=s.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(r+=1),i.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function nN(e){let t=e??"project";if(!tt.includes(t))throw new l(`Invalid scope "${e}"`,d.USAGE);return t}function wi(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(en.includes(t))return t;throw new l(`Invalid --pm-context value "${e}". Expected one of: ${en.join(", ")}`,d.USAGE)}function rN(e){return nn(e??"source","--workspace-context")}function Eb(e,t,n){return n?t:nn(e.workspace_context_mode,"linked test")??t}function Tb(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:wi(e.pm_context_mode)}function Ab(e,t){return e==="auto"?t?"tracker":"schema":e}function oN(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 sN(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 iN(e,t){let n={};if(!e)return n;for(let r of e){let o=br(r,t);if(o)for(let[s,i]of Object.entries(o))n[s]=i}return n}function aN(e,t){if(!e)return[];let n=[];for(let r of e){let o=wr(r,t);o&&n.push(...o)}return[...new Set(n)]}function cN(e){let t=vi(e);return dr(t).some(n=>Ma(n)!==null)}function Cb(e){let t=vi(e);return dr(t).some(n=>{let r=Ma(n);if(!r)return!1;let o=Af(r);return o?JL.has(o.subcommand):!1})}function gi(e){if(e)return Sf.has(e.subcommand)?Ln(e.args,Ef)?.subcommand:e.subcommand}function ab(e,t){if(e==="npx"||e==="bunx")return ms(t)?.command;if(e==="pnpm")return gi(Ln(t,bf));if(e==="npm")return gi(Ln(t,wf));if(e==="yarn")return gi(Ln(t,vf));if(e==="bun")return gi(Ln(t,kf))}function cb(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function Md(e){return!e||!Da(e.command)&&!Tf(e.command)?!1:ls(e.args)==="test-all"}var dN=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])]),lN=new Set(["npx","bunx"]);function Rb(e){let t=e.split(" ").filter(i=>i.length>0),n=$a(t);if(n.length===0)return!1;let[r,...o]=n,s=dN.get(r);if(s){let i=o.findIndex(a=>s.test(a));return i>=0?Rb(o.slice(i+1).join(" ")):!1}return Da(r)||Ua(r)?ls(o)==="test-all":r==="node"&&o.length>0&&Ua(o[0])?ls(o.slice(1))==="test-all":lN.has(r)?Md(ms(o)):r==="pnpm"?Md(Ga(o)):r==="npm"?Md(ja(o)):!1}function Ib(e){let t=vi(e);return dr(t).some(n=>Rb(n))}function xb(e){if(Ib(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',d.USAGE)}function vi(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function mN(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 uN(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 pN(e){let t=e.split(" ").filter(s=>s.length>0),n=$a(t);if(n.length===0)return!1;let[r,...o]=n;return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?fN(o):_N(r,o)}function fN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function _N(e,t){return e==="npx"||e==="bunx"?cb(ms(t)?.command):e==="pnpm"||e==="npm"?cb((e==="pnpm"?Ga(t):ja(t))?.command)||ab(e,t)==="vitest":(e==="yarn"||e==="bun")&&ab(e,t)==="vitest"}function Ob(e){let t=vi(e);if(dr(t).some(o=>!mN(o)&&pN(o)&&!uN(o)))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 hN(e){if(Ib(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function gN(e){return e?e.map(yN):[]}function yN(e){let t=e.trim(),n=Fs(t)?Ms(oe(e,"--add"),"--add"):{command:t},r=le(n.command);if(!r)throw new l("--add requires command=<value> or a bare command (path=<value> is optional metadata)",d.USAGE);return xb(r),Ob(r),{command:r,path:le(n.path),scope:nN(n.scope),timeout_seconds:bN(le(n.timeout_seconds),le(n.timeout)),pm_context_mode:js(le(n.pm_context_mode),"--add"),workspace_context_mode:nn(le(n.workspace_context_mode),"--add"),env_set:br(le(n.env_set),"--add"),env_clear:wr(le(n.env_clear),"--add"),shared_host_safe:Gs(le(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:rn(le(n.assert_stdout_contains)),assert_stdout_regex:Dn(le(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:rn(le(n.assert_stderr_contains)),assert_stderr_regex:Dn(le(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:qs(le(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Ks(le(n.assert_json_field_equals),"--add"),assert_json_field_gte:zs(le(n.assert_json_field_gte),"--add"),note:le(n.note)}}function le(e){let t=e?.trim();return t&&t.length>0?t:void 0}function bN(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(de(n,"timeout_seconds"));if(r<=0)throw new l("--add timeout_seconds must be a positive integer",d.USAGE);return r}function wN(e){return e?e.flatMap(t=>{let n=w_(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new l("--add-json requires a non-empty command string",d.USAGE);xb(o),Ob(o)}return n}):[]}function vN(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 o=n.slice(r[0].length).trim();if(!o)throw new l("--remove requires a non-empty command=<value> or path=<value>",d.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new l("--remove structured selectors require command=<value> or path=<value>",d.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=oe(n,"--remove"),s=o.path!==void 0?"path":"command",i=o.path??o.command;if(!i?.trim())throw new l("--remove requires command=<value> and/or path=<value>",d.USAGE);return{kind:s,value:i.trim()}}return{kind:"either",value:n}}):[]}function kN(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 SN(e){try{e.stdin?.end()}catch{}}function Pb(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=ib?t:`${t.slice(0,ib-3)}...`}function Lb(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Gd(e){try{process.stderr.write(`${e}
49
+ `)}catch{}}function EN(e,t){if(!Lb(t))return null;let n=Pb(e.command),r=Date.now();Gd(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let s=Date.now()-r;Gd(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},QL());return o.unref?.(),o}function TN(e,t,n,r){if(!Lb(r))return;let o=Pb(e.command),s=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(" ")}`:"";Gd(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${m} elapsed_ms=${s}${u} command="${o}"`)}async function db(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=wb("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 AN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function CN(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 db(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{db(r)},XL()),t.forceKillTimer.unref?.()}}function RN(e){return new Promise(t=>{let n=!1,r=null,o=(s,i=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,i)=>{n||(r=setTimeout(()=>{o({code:s,signal:i},!0)},ZL()),r.unref?.())}),e.on("close",(s,i)=>{o({code:s,signal:i})})})}function IN(e,t,n,r,o){return wb(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function lb(e){let t=await Dd(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,yi),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>yi}}finally{await t.close()}}async function xN(e,t,n,r,o,s=process.cwd()){let i=Date.now(),a=await vb(z.join(Sb(),"pm-linked-test-output-"));try{let c=z.join(a,"stdout.log"),m=z.join(a,"stderr.log"),[u,p]=await Promise.all([Dd(c,"w"),Dd(m,"w")]),f;try{f=IN(e,n,u.fd,p.fd,s)}finally{await Promise.all([u.close(),p.close()])}SN(f);let _={heartbeat:EN(r,o),forceKillTimer:null,timedOutTimer:null},g=CN(f,_),y=!1,h;f.on("error",fe=>{h=fe.message}),_.timedOutTimer=setTimeout(()=>{y=!0,g()},t),_.timedOutTimer.unref?.();let{code:b,signal:v}=await RN(f);AN(_);let[k,I]=await Promise.all([lb(c),lb(m)]),A=k.truncated||I.truncated,N=A?`
50
+ [pm linked-test output truncated at ${yi} bytes per stream; the child process continued to completion]
51
+ `:"",M={stdout:`${k.text}${N}`,stderr:I.text,exitCode:b,signal:v,timedOut:y,maxBufferExceeded:!1,outputTruncated:A,spawnError:h};return TN(r,M,i,o),M}finally{await Fr(a,{recursive:!0,force:!0})}}function ON(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${yi} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function PN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
52
+ `);return VL.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>WL.test(n)&&YL.test(n))}function LN(e){return PN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function NN(){return{infra_collision:0,trust_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function ki(e){let t=NN();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function mb(e,t){for(let[n,r]of Object.entries(t.env_set))tn.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)tn.has(n.toUpperCase())||delete e[n]}function FN(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 MN(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function $N(e,t,n){return{env_set:iN(e,"--env-set"),env_clear:aN(t,"--env-clear"),shared_host_safe:n===!0}}async function Hn(e,t,n=!1,r=bi){if(await P(e))try{await ii("seed_linked_test",async()=>{if(await r(z.dirname(t),{recursive:!0}),n){await $d(e,t,{recursive:!0,force:!0});return}await $d(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&St(o))return;throw o}}async function ub(e,t,n){await Hn(ae(n.projectPmRoot),ae(e)),await Hn(z.join(n.projectPmRoot,"extensions"),z.join(e,"extensions"),!0),await Hn(ae(n.globalPmRoot),ae(t)),await Hn(z.join(n.globalPmRoot,"extensions"),z.join(t,"extensions"),!0)}async function pb(e,t){if(!await P(e))return;let n=await Ud(e,{withFileTypes:!0});for(let r of n){if(BL.has(r.name))continue;let o=z.join(e,r.name),s=z.join(t,r.name);if(r.isDirectory()){await Hn(o,s,!0);continue}r.isFile()&&await Hn(o,s)}}async function fb(e,t){let n=await q(ae(e));if(n===null||await P(wa(e)))return;let r=await T(t);await Fr(wa(t),{force:!0}),await Fr(ae(t),{force:!0}),await Je({pmRoot:t,filePath:ae(t),raw:n,op:"settings:write",author:C(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function Bn(e){if(!await P(e))return 0;let t=0,n=await Ud(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||HL.has(r.name))continue;let o=z.join(e,r.name),s;try{s=await Ud(o,{withFileTypes:!0})}catch{continue}for(let i of s)i.isFile()&&fl.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function DN(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function UN(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let r of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isInteger(o)||o<0)return[];t.push(o);continue}t.push(r)}return t}function _b(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=UN(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let s of r){if(typeof s=="number"){if(!Array.isArray(o)||s>=o.length)return{found:!1,value:void 0};o=o[s];continue}if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,s))return{found:!1,value:void 0};o=o[s]}return{found:!0,value:o}}function GN(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 jN(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?rt(e,t):Object.is(e,t)}function qN(e,t,n){let r=[];r.push(...hb("stdout",t,e.assert_stdout_contains)),r.push(...gb("stdout",t,e.assert_stdout_regex)),r.push(...hb("stderr",n,e.assert_stderr_contains)),r.push(...gb("stderr",n,e.assert_stderr_regex)),r.push(...KN(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(s).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,m]of Object.entries(o)){let u=_b(a,c);if(!u.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let p=GN(m);jN(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(s)){let u=_b(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 hb(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function gb(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(s){r.push(`${e} regex assertion is invalid: /${o}/ (${s instanceof Error?s.message:String(s)})`)}return r}function KN(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 zN=[{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 BN(e,t){let n=`${e}
53
+ ${t}`;for(let r of zN)if(r.regex.test(n))return r.code;return null}function HN(e){return{root:e,schemaProjectPmPath:z.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:z.join(e,"schema","global"),trackerProjectPmPath:z.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:z.join(e,"tracker","global"),workspaceSnapshotRoot:z.join(e,"workspace","project"),workspaceIsolatedRoot:z.join(e,"workspace","isolated")}}function VN(e,t,n){return e.some(r=>Eb(r,t,n)==="snapshot")}async function WN(e,t){let n=new Set([".agents",".git",".nyc_output",".turbo","coverage","node_modules"]);await bi(z.dirname(e.workspaceSnapshotRoot),{recursive:!0}),await $d(t,e.workspaceSnapshotRoot,{recursive:!0,force:!0,filter(o){let s=z.relative(t,o);return s?!s.split(z.sep).some(i=>n.has(i)):!0}});let r=z.join(t,"node_modules");await P(r)&&await kb(r,z.join(e.workspaceSnapshotRoot,"node_modules"),process.platform==="win32"?"junction":"dir")}async function YN(e,t){let n=z.join(e,".agents"),r=z.join(n,"pm");await bi(n,{recursive:!0}),await Fr(r,{recursive:!0,force:!0}),await kb(t,r,process.platform==="win32"?"junction":"dir")}async function JN(e,t=Tr,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 XN(e,t,n){t&&(await ub(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),n&&(await ub(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await pb(t.projectPmRoot,e.trackerProjectPmPath),await pb(t.globalPmRoot,e.trackerGlobalPmPath),await fb(t.projectPmRoot,e.trackerProjectPmPath),await fb(t.globalPmRoot,e.trackerGlobalPmPath)))}function QN(e,t,n){return e.some(r=>{let o=r.command??"",s=o.length>0&&Cb(o),i=n?.autoPmContext===!0&&s?"auto":Tb(r,t,n?.overrideLinkedPmContext===!0);return Ab(i,s)==="tracker"})}async function ZN(e,t){return{sourceProjectItemCount:t?await Bn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Bn(t.globalPmRoot):0,schemaProjectItemCount:await Bn(e.schemaProjectPmPath),schemaGlobalItemCount:await Bn(e.schemaGlobalPmPath),trackerProjectItemCount:await Bn(e.trackerProjectPmPath),trackerGlobalItemCount:await Bn(e.trackerGlobalPmPath)}}function eF(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:a,trust:e.trust}}async function tF(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?wi(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?cN(n):!1,o=r&&n?Cb(n):!1,s=e.options?.autoPmContext===!0&&o,i=s?"auto":Tb(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Ab(i,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await YN(e.layout.workspaceSnapshotRoot,c);let m=e.options?.pmRoot?await qa(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await qa(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:eF({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:m})}}function yb(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function jd(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 nF(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function rF(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return nF(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function oF(e){if(!e.linkedTest.command)return yb(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=hN(e.linkedTest.command);return t?yb(e.linkedTest,e.executionContext,t):null}function sF(e){let t=oF(e);if(t)return t;let n=rF(e);if(n)return n;let r=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,o=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(r||o){let s=sN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),i=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return jd(e.linkedTest,e.executionContext,`${i} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${s}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!oN(e.linkedTest)?jd(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function iF(e){let t=MN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return mb(n,e.runtimeDirectives),mb(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&FN(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[ar]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[ar]="read_only"),n}function aF(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 cF(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 dF(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:DN(e.execution),failure_category:LN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:ON(e.execution,e.timeoutMs)}}function lF(e){if(e.options?.failOnEmptyTestRun===!0){let n=BN(e.execution.stdout,e.execution.stderr);if(n)return cF({...e,emptyRunSignal:n})}let t=qN(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?jd(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):aF(e.linkedTest,e.executionContext,e.execution)}async function mF(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await xN(t,n,iF(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?lF({...e,execution:r}):dF({...e,execution:r,timeoutMs:n})}async function zd(e,t,n){let r=[],o=await vb(z.join(Sb(),"pm-linked-test-")),s=HN(o),i=wi(n?.pmContext),a=rN(n?.workspaceContext),c=n?.progress===!0?"always":"auto",m=$N(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,p=Rf(),f=QN(e,i,n),_=VN(e,a,n?.overrideLinkedWorkspaceContext===!0),g=await Cf(p);try{await JN(s,Tr,f),await bi(s.workspaceIsolatedRoot,{recursive:!0}),await XN(s,u,f),_&&await WN(s,p);let y=await ZN(s,u);for(let h=0;h<e.length;h+=1){let b=e[h],v=Eb(b,a,n?.overrideLinkedWorkspaceContext===!0),k=await tF({linkedTest:b,layout:s,counts:y,sourceRoots:u,runLevelPmContextMode:i,options:n,requestedWorkspaceContextMode:a,workspaceContextMode:v,currentSourceRef:g,sourceWorkspaceRoot:p}),I=sF({linkedTest:b,executionContext:k.executionContext,runLevelPmContextMode:i,linkedOverridePmContextMode:k.linkedOverridePmContextMode,options:n});if(I){r.push(I);continue}r.push(await mF({linkedTest:b,index:h,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:m,progressMode:c,executionContext:k.executionContext,options:n}))}}finally{await Fr(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}async function uF(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,s=await U(n,t,r.id_prefix,r.item_format,o);if(!s)throw new l(`Item ${t} not found`,d.NOT_FOUND);let i=await V(s,{schema:r.schema});return{itemId:s.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function pF(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function fF(e,t){let n=[...e];for(let r of t)n.some(o=>pF(o,r))||n.push(r);return n}function _F(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((s,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:o,removed:e.length-o.length}}function hF(e,t,n,r){return _F(fF(e,t),n,r)}function gF(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function yF(e){if(gF(e)&&e.run!==!0)throw new l("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",d.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --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 bF(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:s,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return uF({id:t,pmRoot:r,settings:o,typeToFolder:s});let m=0,u=await ne({pmRoot:r,settings:o,id:t,op:i.length>0?"tests_add":"tests_remove",author:C(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(p){let f=p.metadata.tests??[],_=hF(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(g=>`${g.kind}=${g.value}`),...c.map(g=>`index=${g}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return p.metadata.tests=_.tests,{changedFields:rt(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 wF(e,t){yF(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:Fd(e.onlyIndex),onlyLast:e.onlyLast},r=e.run===!0?sb(t,n):void 0,o=e.timeout===void 0?void 0:de(e.timeout,"timeout");if(o!==void 0&&o<=0)throw new l("Test timeout must be a positive number",d.USAGE);return{defaultTimeoutSeconds:o,pmContextMode:wi(e.pmContext),runSelection:r,testsToRun:r?.selected??t}}async function vF(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await zd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:nt(process.cwd())}})}function kF(e,t,n){let r=[];if(t&&t.selector!==null&&r.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let o=Kd(n);r.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return r}function SF(e){let t=tN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=S(),s=Nr(e.options.measure,o);return{run_id:eN("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function EF(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:s,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let m=SF({options:t,runStartedAt:s,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return m;try{return await hi({pmRoot:n,settings:r,itemId:o,author:C(t.author,r.author_default),message:`Track test run summary (${m.run_id})`,entry:m}),m}catch(u){return c.push(`test_result_tracking_failed:${o}:${u instanceof Error?u.message:String(u)}`),m}}function bb(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,o).trim(),i=e.metricBelow.slice(o+1).trim(),a=Number(i);if(o<=0||s.length===0||i.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",d.USAGE);r=qy(t,s,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Ky(t,e.metricDiff)}}async function TF(e,t,n){if(e.acknowledgeLinkedTests===!0)return If(t,n,S())}async function Si(e,t,n){let r=xt(),o=E(process.cwd(),n.path);await R(o);let s=await T(o);if((t.measure?.length??0)>0&&t.run!==!0)throw new l("--measure requires --run",d.USAGE);Nr(t.measure,"validation"),bb(t,[],void 0);let i=O(s,x()),a=await r.resolveList(t.add,"--add"),c=await r.resolveList(t.addJson,"--add-json"),m=await r.resolveList(t.remove,"--remove"),u=[...gN(a),...wN(c)],p=await Nn(u,C(t.author,s.author_default),S())??[],f=vN(m),_=kN(t.removeIndex),g=await bF({id:e,options:t,pmRoot:o,settings:s,typeToFolder:i.type_to_folder,adds:p,removes:f,removeIndexes:_}),y=wF(t,g.tests),h=await TF(t,o,g.tests),b=t.run===!0?S():void 0,v=await vF({options:t,runOptions:y,pmRoot:o,untrustedLinkedTestsPolicyEnabled:s.testing.allow_untrusted_linked_tests}),k=ki(v),I=t.run===!0&&t.failOnSkipped===!0&&v.some(ee=>ee.status==="skipped"),A=kF(t,y.runSelection,v);h&&A.push(`linked_test_trust_acknowledged:${h.acknowledged}`);let N=await EF({options:t,pmRoot:o,settings:s,itemId:g.itemId,runStartedAt:b,runResults:v,failOnSkippedTriggered:I,warnings:A}),M=N?Nd([...g.testRuns,N]):g.testRuns,fe=bb(t,M,N);return{ok:v.every(ee=>ee.status!=="failed")&&I!==!0,id:g.itemId,tests:g.tests,run_results:v,failure_categories:k,selection:y.runSelection?{selector:y.runSelection.selector,requested:y.runSelection.requested,selected_indexes:y.runSelection.selected_indexes,selected_count:y.runSelection.selected_count,skipped_count:y.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:I?!0:void 0,warnings:A.length>0?A:void 0,changed:g.changed,count:g.tests.length,...g.removed>0?{removed:g.removed}:{},...fe}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d3405c0-14e6-51f5-97a1-355438fd0199")}catch{}})();var AF=(e,t)=>{if(e===void 0)return;let n=X(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new l(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,d.USAGE)}return n},CF=e=>{if(e===void 0)return;let t=de(e,"timeout");if(t<=0)throw new l("timeout must be a positive number",d.USAGE);return t},Nb=(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},RF=e=>e instanceof Error?e.message:String(e),IF=()=>{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)}`},xF=e=>e.trim().replaceAll(/\s+/g," "),OF=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),PF=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),LF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},NF=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Ei=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Fb=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),FF=e=>typeof e=="number"?e:void 0,MF=e=>{let t={assert_stdout_contains:Ei(e.assert_stdout_contains),assert_stdout_regex:Ei(e.assert_stdout_regex),assert_stderr_contains:Ei(e.assert_stderr_contains),assert_stderr_regex:Ei(e.assert_stderr_regex),assert_stdout_min_lines:FF(e.assert_stdout_min_lines),assert_json_field_equals:Fb(e.assert_json_field_equals),assert_json_field_gte:Fb(e.assert_json_field_gte)};return JSON.stringify(t)},$F=e=>{let t=Bd(e.command);return t!==void 0?`command:${e.scope}:${xF(t)}`:`path:${e.scope}:${Bd(e.path)??""}`},Mb=e=>{let t=OF(e.env_set),n=PF(e.env_clear),r=LF(e.pm_context_mode),o=NF(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",i=MF(e);return`${$F(e)}:${t}:${n}:${r}:${o}:${s}:${i}`},DF=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,UF=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},GF=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Ti=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
54
+ `)}catch{}},jF=async(e,t,n)=>{let r=[],o=0;for(let s of e){let i=await Si(s.id,{run:!1},{...t,path:n});o+=i.tests.length,r.push({item:s,tests:i.tests})}return{itemTests:r,linkedTests:o}},qF=async e=>{let t=D(e.settings.schema),n=O(e.settings,x()),r=AF(e.options.status,t),o=Nb(e.options.limit,"--limit"),s=Nb(e.options.offset,"--offset")??0,a=(await ce(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(m=>r?m.status===r:!0).sort((m,u)=>m.id.localeCompare(u.id));return{filteredItems:o===void 0?a.slice(s):a.slice(s,s+o),statusFilter:r,limitFilter:o,offsetFilter:s}},KF=e=>{let t=new Map;for(let{tests:n}of e)for(let r of n){let o=Mb(r);if(!t.has(o)){t.set(o,r.timeout_seconds);continue}t.set(o,DF(t.get(o),r.timeout_seconds))}return t},zF=async(e,t)=>{let n=[],r=e.tests.map(u=>{let p=Mb(u),f=t.seenTestKeys.has(p);if(!f){t.seenTestKeys.add(p);let _=t.effectiveTimeoutByKey.get(p);n.push(_===void 0?u:{...u,timeout_seconds:_})}return{test:u,key:p,duplicate:f}}),o=n.length>0?await zd(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],s=0,i=r.map(({test:u,key:p,duplicate:f})=>{if(!f){let _=o[s];return s+=1,_}return{command:u.command,path:u.path,status:"skipped",error:`Duplicate linked test skipped (key=${p}).`}}),a=UF(i),c=ki(i),m=await VF(e,a,i,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:m,failureCategories:c,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:i,failure_categories:c}}},BF=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),HF=e=>e?!0:void 0,VF=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=BF(t,r.options);await hi({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:S(),recorded_at:S(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:HF(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}})}catch(o){return[`test_result_tracking_failed:${e.item.id}:${RF(o)}`]}return[]},WF=()=>{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},Bd=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},YF=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:nt(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:KF(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:C(e.options.author,e.settings.author_default),trackingRunId:IF(),trackingAttempt:WF(),trackingResumedFrom:Bd(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),JF=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:ki([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},XF=async(e,t,n)=>{for(let[r,o]of e.entries()){Ti(t.options,`item ${r+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);let s=await zF(o,t);GF(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),Ti(t.options,`item ${r+1}/${e.length} end id=${o.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}},QF=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=Kd(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}`)},ZF=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}),eM=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(" "),tM=async(e,t)=>{let n=E(process.cwd(),t.path);await R(n);let r=await T(n),o=await qF({pmRoot:n,settings:r,options:e}),s=CF(e.timeout),i=S(),a=await jF(o.filteredItems,t,n);return Ti(e,eM({...o,linkedTests:a.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:s,runStartedAt:i}},nM=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}},$b=async(e,t)=>{let n=await tM(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=JF(e,n.linkedTests,n.filteredItems),s=YF({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await XF(n.itemTests,s,r),QF(e,r);let i=nM({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Ti(e,`end status=${i.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),ZF({ok:i.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:i.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="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]="863df651-49e0-552f-a7f0-92c3cc9a12a2")}catch{}})();function Db(){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]="3e5f92c9-c299-592d-a7ab-a6f9998159f0")}catch{}})();var Gb=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:Ru().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm init","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm 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"]}],Ub=new Map;for(let e of Gb){Ub.set(e.id,e);for(let t of e.aliases)Ub.set(t,e)}function Hd(){return Gb.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 OH=[...Gr],PH=[...jr],rM=new Set(Zn.filter(e=>e.hidden).map(e=>e.alias)),LH=Cu("full").filter(e=>!rM.has(e)),NH=$(Qr),FH=$(Zr),MH=$(io),$H=$(uo),DH=$(po),UH=$(km),GH=$(Sm),jH=$(mo),qH=$(go),KH=$(fo),zH=$(_o),BH=$(so),HH=$(ho),VH=$(eo),WH=$(to,!1),YH=$(Nm),JH=$(Xn),XH=$(Qn),QH=$(vo),ZH=$(bo),eV=$(co),tV=$(wo),nV=$(yo),rV=$(ko),oV=$(ao),sV=$(lo),iV=$(ro),aV=$(So),cV=$(no);var oM=$(Eo),dV=`${oM} bash zsh fish`,lV=sM(Hd());var mV=$(oo),uV=$(Jn);var pV=Xr.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function sM(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]="1cbb3565-26d8-5657-b724-602658bec852")}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]="72111aa2-52b2-53da-a1c8-07ba53a74944")}catch{}})();var zb=Symbol("pm.active-extension-host-context");function Ne(e){return{fullChangedFields:!0,options:e}}var j=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[zb]=!0,n}run(t,n={}){return Bb({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Df(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Sa(await this.list(ka(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,...Ne(ir(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,s={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:s})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,s){return this.runTyped("plan",{...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...s===void 0?{}:{reorderTo:s},options:ir(r,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Ne(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ne(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Ne(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ne(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ne(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ne(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ne(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ne(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},...Ne(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ne(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ne(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ne(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 aM(e={},t={}){return new j(t).context(e)}function cM(e={},t={}){return new j(t).list(e)}function dM(e={},t={}){return new j(t).listAllComplete(e)}function lM(e,t={},n={}){return new j(n).search(e,t)}function mM(e,t={},n={}){return new j(n).get(e,t)}function uM(e={},t={}){return new j(t).next(e)}function pM(e={},t={}){return new j(t).aggregate(e)}function fM(e,t={},n={}){return new j(n).comments(e,t)}function _M(e,t={},n={}){return new j(n).notes(e,t)}function hM(e,t={},n={}){return new j(n).learnings(e,t)}function gM(e,t={},n={}){return new j(n).files(e,t)}function yM(e,t={},n={}){return new j(n).filesDiscover(e,t)}function bM(e,t={},n={}){return new j(n).docs(e,t)}function wM(e,t={},n={}){return new j(n).deps(e,t)}function vM(e,t={},n={},r={}){return new j(r).graph(e,t,n)}function kM(e,t,n={},r={}){return new j(r).append(e,t,n)}function SM(e={},t={}){return new j(t).create(e)}function EM(e,t={},n={}){return new j(n).update(e,t)}function TM(e,t,n={},r={}){return new j(r).reopen(e,t,n)}function AM(e,t,n={},r={}){return new j(r).close(e,t,n)}function CM(e,t={},n={}){return new j(n).claim(e,t)}function RM(e={},t={}){return new j(t).claimNext(e)}function IM(e,t={},n={}){return new j(n).release(e,t)}function xM(e,t={},n={}){return new j(n).copy(e,t)}function OM(e,t={},n={}){return new j(n).delete(e,t)}function PM(e,t,n={},r={}){return new j(r).restore(e,t,n)}function LM(e,t={},n={}){return new j(n).focus(e,t)}function Ze(e,t){let n=w(e,t);if(!n)throw new l(`Missing required argument: ${t}`,64);return n}var jb=Lu(),NM=new iM;function Ai(){la(vl()),ma(kl()),ua(Sl()),pa(El()),fa(Tl()),_a(Al()),ha(Cl())}async function FM(e,t,n,r){return Nu(()=>t===void 0?jb.read(()=>qb(e,n,r)):jb.write(()=>$M(t,()=>qb(e,n,r))))}async function qb(e,t,n){let r=E(t,e.path);if(e.noExtensions)return Ai(),ec({pmRoot:r},()=>n(null));if(!await P(ae(r)))return Ai(),n(null);let o=null,s;try{let i=await T(r),a=await Yr({pmRoot:r,settings:i,cwd:t,noExtensions:!1}),c=await Jr({...a,loaded:a.loaded});s={loadResult:a,activationResult:c},la(c.hooks),ma(c.commands),ua(c.parsers),pa(c.preflight),fa(c.services),_a(c.renderers),ha(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:a.loaded}}catch(i){Ai(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await ec({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Ai(),s&&await Il(s.loadResult,s.activationResult).catch(()=>{})}}async function MM(e,t,n,r,o){if(!o)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let s=Wt(e),a=o.registrations.commands.find(m=>Wt(m.action)===s)?.command??o.commands.handlers.find(m=>Wt(m.command)===s)?.command;if(!a)throw new l(`Unsupported native pm action: ${e}`,d.USAGE);let c=await No({command:Oa(a),args:ke(n.args??t.args),options:Pa(t,n),global:r,pm_root:o.pmRoot,sdk:qf(o.pmRoot,j.forActiveExtensionHost({pmRoot:o.pmRoot,author:typeof r.author=="string"&&r.author.trim()?r.author.trim():"pm-extension"}))});if(!c.handled){let m=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new l(`Unsupported native pm action: ${e}${m}`,d.USAGE)}return c.result}async function $M(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var DM=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function UM(e){let t=Ze(e,"action"),n=Wt(t),r=Ri(Gf,n),o=r?.action??n,s={...e,action:o};return r?.options!==void 0&&(s.options={...r.options,...Yi(e.options)}),o==="package"&&(s.options={...Yi(s.options),vocabulary:"package"}),{action:o,args:s}}function GM(e){return!DM.has(Wt(e))}async function Bb(e){let t=UM(e),n=Ra(t.args),r=GM(t.action),o=w(t.args,"cwd"),s=o??process.cwd();try{return e[zb]===!0||NM.getStore()===!0?await Kb(t.action,t.args,n,null):await FM(n,o,s,i=>Kb(t.action,t.args,n,i))}finally{r&&Ja()}}function Ri(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ci(e){return w(e.args,"target")??w(e.options,"target")}function Q(e,t=e.options){return e.id??Ze(t,"id")}async function jM(e){let t=gn("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),Ya(await ct(w(e.args,"status")??w(t,"status"),t,e.global),t)}async function qM(e){let t=Ze(e.args,"query"),n=gn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),Ya(await pr(t,n,e.global),n)}async function KM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await Pt(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function zM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Ge(await qc(Q(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function BM(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await lt(Q(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function HM(e){let t=ws(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),o_(Q(e),t,e.global)}function Hb(e,t){return yf(ry(e.options,t,Me),e.global)}function VM(e){let t=ke(e.options.lookupPath);if(t&&t.length>0)return Hb(e,t);let n=Q(e);return e.options.discover===!0?Fa(n,xa(e.options),e.global):gf(n,ss(e.options),e.global)}function WM(e){return tb({subcommand:w(e.args,"subcommand")??w(e.options,"subcommand"),limit:Mp(e.args,e.options)},e.global)}function YM(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),_f(e.global,t)}function JM(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);let n=w(e.args,"value")??w(e.options,"value"),r=w(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options;return Lh(w(e.args,"scope")??w(e.options,"scope")??"project",t,w(e.args,"key")??w(e.options,"key"),r,e.global,w(e.options,"policy")===void 0?n:void 0)}function XM(e){let t=e.options;return Rp(Cp(t),e.global)}function QM(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 ZM(e){let t=w(e.args,"subcommand")??Ze(e.options,"subcommand"),n=e.options;return lh({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:e$(e),reorderTo:QM(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function e$(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function t$(e){let t=w(e.args,"subcommand")??Ze(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:w(e.args,"name")??w(e.options,"name"),author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ke(n)}}function n$(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,a=Ri({list:()=>Qp(t.global),show:()=>Zp(r,t.global),"show-status":()=>ef(r,t.global),"list-fields":()=>rf(t.global),"show-field":()=>of(r,t.global),"remove-type":()=>Wp(r,{author:o,force:s},t.global),"remove-field":()=>nf(r,{author:o,force:s},t.global),"remove-status":()=>Xp(r,{author:o,force:s},t.global),"apply-preset":()=>sf(w(t.args,"typePreset")??w(t.options,"typePreset"),{author:o,force:s},t.global)},n);return a?a():null}function r$(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return tf(n,{type:w(t.args,"fieldType")??w(t.options,"fieldType"),commands:i===void 0?void 0:ke(i),description:w(t.args,"description")??w(t.options,"description"),cliFlag:w(t.args,"cliFlag")??w(t.options,"cliFlag"),alias:s,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:ke(a),author:r,force:o},t.global)}function o$(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e,i=t.args.role??t.options.role;return Jp(n,{role:i===void 0?void 0:ke(i),alias:s,description:w(t.args,"description")??w(t.options,"description"),order:Me(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function s$(e){let{ctx:t,name:n,author:r,force:o,aliases:s}=e;return Vp(n,{description:w(t.args,"description")??w(t.options,"description"),defaultStatus:w(t.args,"defaultStatus")??w(t.args,"default_status")??w(t.options,"defaultStatus")??w(t.options,"default_status"),folder:w(t.args,"folder")??w(t.options,"folder"),alias:s,author:r,force:o},t.global)}function i$(e){let{ctx:t,subcommand:n,name:r,author:o,force:s}=e,i=w(t.args,"to")??Ze(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 Bp(m,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:s},t.global)}function a$(e){let t=t$(e),n=n$(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return i$(t);if(t.subcommand==="add-field")return r$(t);if(t.subcommand==="add-status")return o$(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?af({minCount:Me(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):s$(t);throw xe({command_path:"schema",token:t.subcommand,allowed:Hp,exit_code:64})}function c$(e){let t=w(e.args,"subcommand")??Ze(e.options,"subcommand"),n=t.trim().toLowerCase(),r=w(e.args,"name")??w(e.options,"name"),s=Ri({list:()=>qg(),show:()=>Kg(r),lint:()=>zg(r),apply:()=>Bg(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:w(e.args,"author")??w(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!s)throw xe({command_path:"profile",token:t,allowed:jg,exit_code:64});return s()}async function d$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options);return Ge(await zf(Q(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function l$(e){let{changedFields:t,runnerOptions:n}=$e(e.args,e.options);return Ge(await X_(Na(n),e.global),{changedFields:t})}async function m$(e){let{changedFields:t,runnerOptions:n}=$e(e.args,e.options),r=w(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Ge(await r_(La(o),e.global),{changedFields:t})}async function u$(e){let{changedFields:t,idOnly:n,runnerOptions:r}=$e(e.args,e.options),o=w(r,"target")??Ze(e.args,"target");return Ge(await Jt(Q(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function p$(e){let t=E(process.cwd(),e.global.path),n=await T(t),r=li(D(n.schema)),o=Q(e),s=await ks(o,e.force,e.global,e.options),i=await lt(o,ir(e.options,{status:r,force:e.force},["assignee"]),e.global);return{id:o,action:"start_task",claim:s,update:i}}async function f$(e){let t=E(process.cwd(),e.global.path),n=await T(t),r=Q(e),o=D(n.schema).open_status,s=await lt(r,ir(e.options,{status:o,force:e.force},["assignee"]),e.global),i=await Ss(r,e.force,e.global,e.options);return{id:r,action:"pause_task",update:s,release:i}}async function _$(e){let t=Q(e),n=w(e.args,"reason")??w(e.args,"text")??w(e.options,"reason")??w(e.options,"text"),r=await dt(t,n,{...e.options,force:e.force},e.global),o=await Ss(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:r,release:o}}function h$(e){let t={...e.args,...e.options};return Lp(Ze(t,"subcommand"),w(t,"id")??e.id,w(t,"target"),Up(t),e.global)}function g$(e){return jp(E(process.cwd(),e.global.path),{...e.args,...e.options})}var y$={init:e=>Tr(w(e.args,"prefix"),e.global,e.options),context:e=>Ha(gn("context",e.options),e.global),next:e=>ur(gn("next",e.options),e.global),eval:xg,events:Og,merge:Pg,workspace:Lg,meet:ci,event:ci,remind:ci,list:jM,get:e=>{let t=Q(e);return Va(t,e.global,gn("get",e.options,[t]))},search:qM,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ke(e.options.status);return Wa(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:Me(e.options.limit,"limit")})},create:KM,copy:zM,focus:e=>zc(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:BM,"item-reopen":ny,restore:u$,claim:e=>e.options.next===!0||e.args.next===!0?Xf(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):ks(Q(e),e.force,e.global,e.options),release:e=>Ss(Q(e),e.force,e.global,e.options),"start-task":p$,"pause-task":f$,"close-task":_$,close:ty,comments:HM,notes:e=>i_(Q(e),ws(e.options),e.global),learnings:e=>s_(Q(e),ws(e.options),e.global),files:VM,docs:e=>hf(Q(e),ss(e.options),e.global),test:e=>Si(Q(e),e.options,e.global),"test-all":e=>$b(e.options,e.global),telemetry:WM,validate:e=>us(e.options,e.global,{runUpdate:(t,n,r)=>lt(t,n,r)}),health:YM,assurance:e=>xf(e.args,e.options,e.global),contracts:e=>Ay(e.options,e.global),config:JM,activity:XM,aggregate:e=>Ka(e.options,e.global),extension:e=>Pn(Ci(e),e.options,e.global),package:e=>Pn(Ci(e),e.options,e.global),install:e=>Pn(Ci(e),{...e.options,install:!0},e.global),upgrade:e=>Ff(Ci(e),e.options,e.global),delete:e=>Kc(Q(e),e.options,e.global),deps:e=>Pp(Q(e),e.options,e.global),graph:h$,"files-discover":e=>Fa(Q(e),e.options,e.global),"files-lookup":e=>Hb(e,ke(e.options.paths)),history:e=>Nf(Q(e),e.options,e.global),"history-redact":e=>dp(Q(e),e.options,e.global),"history-repair":Xg,"history-compact":Qg,"history-author-acknowledge":g$,plan:ZM,schema:a$,profile:c$,stats:e=>Od(e.global,By(e.options)),append:d$,"update-many":l$,"close-many":m$,gc:e=>Mf(e.global,e.options)};async function Kb(e,t,n,r){let o=Ia(t,e);aa(e,o),uu(e,o);let s={action:e,args:t,options:o,id:w(t,"id"),force:t.force===!0||o.force===!0,global:n,activeExtensions:r},i=Ri(y$,e),a=i?await i(s):await MM(e,t,o,n,r);return o.resolvedOutputFormat="json",Su(e,o,a)}var b$={closeManyOptionsFromFlat:La,extensionOptionsFromArgs:Pa,globalOptions:Ra,mutationListOptions:Dp,normalizeActionName:Wt,normalizeCommandPath:Oa,normalizeMcpUpdateOptions:Gp,normalizeMcpOptionsArrays:$p,optionsWithAuthor:Ia,readRequiredString:Ze,readScalarString:Np,readScalarStringAllowBlank:Fp,readStringArray:ke,updateManyOptionsFromFlat:Na,withAddNoteOption:ss,withFilesDiscoveryOptions:xa,withMutationCompaction:$e};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=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]="cea03617-5e90-5683-a9d1-289087ed4646")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cc0d4dd1-20e8-59d4-acb5-9f8ed639d35f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f44898af-0809-51e1-a6fb-74716c0971f5")}catch{}})();export{wn as AGENT_PROVENANCE_DIMENSIONS,Du as BASELINE_ITEM_FORMAT_VERSION,Hw as BUILTIN_AGENT_PROVENANCE_ADAPTERS,er as BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,Gr as BUILTIN_ITEM_TYPE_VALUES,qr as CONFIDENCE_TEXT_VALUES,Uu as CURRENT_ITEM_FORMAT_VERSION,Gt as DEPENDENCY_KIND_VALUES,d as EXIT_CODE,pn as ISSUE_SEVERITY_VALUES,il as ITEM_TYPE_VALUES,Xa as PM_CLI_EXPECTED_ERROR_NAME,Mw as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,Nw as PM_READ_OUTPUT_DIMENSIONS,Fw as PM_READ_OUTPUT_OPTION_FLAGS,sa as PM_READ_OUTPUT_SURFACE_CONTRACTS,l as PmCliError,j as PmClient,un as RISK_VALUES,iv as SEMANTIC_ATTRIBUTION_LIMITS,jr as STATUS_VALUES,Bw as agentSessionEnvironment,pM as aggregate,Id as analyzeAgentProvenanceDescriptorCoverage,jw as analyzeSdkCliParameterCompleteness,kM as append,Dw as applyReadOutputDimensions,Iw as applyReadOutputSessionReferences,xw as attachReadOutputSessionReceipt,qw as boundAgentEpisodeIdentity,Ye as canonicalDocument,CM as claim,RM as claimNext,qu as classifyItemFormatVersion,AM as close,fM as comments,aM as context,xM as copy,SM as create,jf as createPmCliExpectedError,Lw as decodeReadOutputContinuationCursor,OM as deleteItem,wM as deps,Zw as detectAgentIdentity,nv as detectHarnessIdentity,ev as diagnoseAgentIdentity,bM as docs,Gu as effectiveItemFormatVersion,Db as emptyImportedDocument,Pw as encodeReadOutputContinuationCursor,DP as evaluateSemanticAttributionCoverage,ov as explainSourceTraceability,gM as files,yM as filesDiscover,LM as focus,mM as get,vM as graph,UP as groupHistoryByEpisode,Jf as isAlreadyClaimedError,gs as isPmCliExpectedError,Uw as isReadOutputBudgetExceeded,hM as learnings,cM as list,Ww as listAgentProvenanceAdapters,dM as listAllComplete,uM as next,Jw as normalizeAgentProvenanceAdapterValue,ju as normalizeItemFormatVersion,we as normalizeItemId,X as normalizeStatusInput,_M as notes,S as nowIso,Rw as parseReadOutputSession,ds as parseSourceLineRange,Mo as readAuthorEnvironment,Ow as readOutputSessionRemainingTokens,za as recordClaimSemanticAttribution,fs as recordFocusSemanticAttribution,Ba as recordReleaseSemanticAttribution,Yw as registerAgentProvenanceAdapters,Vw as registerHarnessSignalDescriptors,IM as release,TM as reopen,Kw as resolveAgentSessionContextFromSignals,rv as resolveAuthorIdentity,Fy as resolveHistoryEpisodeGroupIdentity,$w as resolveReadOutputDimensions,Gw as resolveReadOutputEncoding,ia as resolveReadOutputSurface,sv as resolveSemanticLineageIds,PM as restore,Bb as runAction,zw as runWithAgentSessionContext,Xw as runWithHarnessDetectionSignals,Qw as runWithWorkspaceHarnessSignalDescriptors,lM as search,av as semanticAttributionAffinity,je as serializeItemDocument,$P as summarizeAgentModelProvenance,xd as summarizeAgentProvenance,EM as update,aa as validateReadOutputOptions,tv as writeAuthorEnvironment};
55
55
  //# sourceMappingURL=sdk-core.js.map