@unbrained/pm-cli 2026.8.5 → 2026.8.6

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 (188) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +14 -0
  3. package/dist/cli/main.js +12 -37
  4. package/dist/cli/register-setup.d.ts +1 -1
  5. package/dist/cli/register-setup.js +46 -20
  6. package/dist/cli-bundle/bundle-manifest.json +391 -391
  7. package/dist/cli-bundle/chunks/append-XAJ5Z4XS.js +2 -0
  8. package/dist/cli-bundle/chunks/{chunk-2WFXWAYX.js → chunk-343QETLI.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-RKAVWO3O.js → chunk-3KFVGGRE.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-VCKLFEUN.js → chunk-3ZJRFYY2.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-UZBWIUYD.js → chunk-4AVFKHHC.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-BPELKUQD.js → chunk-4OVGQW22.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-54FNT7U2.js → chunk-5PBP2ZP3.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-NY4T3JWN.js → chunk-5ZKQPA44.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-4YUBDMQM.js → chunk-A3XQ7VPU.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-OPVH7SKD.js → chunk-AJE3AHPD.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-V3774P7D.js → chunk-AOBDLU4T.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-VN5VITU3.js → chunk-AYRUGRNS.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-HWRRMBJO.js → chunk-BP6EMEDP.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-ZYHOB3SN.js → chunk-C3YABSJK.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-43HQQI6S.js → chunk-CA3BURYF.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-E2RKBKWB.js → chunk-D7I3TUGV.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-4VN6GS4U.js → chunk-DQGJ2RWT.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-YSO3YFZ4.js → chunk-DWOAOZHZ.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-Q35VBGOQ.js → chunk-E7BFPLUZ.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-LKDGK44W.js → chunk-F4NREH3G.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-OMXVBQ2N.js → chunk-FDBRXV25.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-3FTILRJ2.js → chunk-GU3TSEHD.js} +2 -2
  29. package/dist/cli-bundle/chunks/chunk-HS7OVAUN.js +164 -0
  30. package/dist/cli-bundle/chunks/{chunk-OTHLDSFP.js → chunk-JFZIS6JF.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-7A5OT5J2.js → chunk-JQ4NZ5EB.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-BXQLRKWF.js → chunk-L6LGKJX3.js} +2 -2
  33. package/dist/cli-bundle/chunks/{chunk-CSI3WS5I.js → chunk-M357ZCOR.js} +2 -2
  34. package/dist/cli-bundle/chunks/{chunk-5ZBOIPGP.js → chunk-M4VEE3FK.js} +2 -2
  35. package/dist/cli-bundle/chunks/{chunk-7C4PTJG6.js → chunk-MCS73BKB.js} +2 -2
  36. package/dist/cli-bundle/chunks/{chunk-A62CYISG.js → chunk-MDTH7SAE.js} +2 -2
  37. package/dist/cli-bundle/chunks/{chunk-HNFD72UK.js → chunk-OXY3SJ3N.js} +2 -2
  38. package/dist/cli-bundle/chunks/{chunk-L3AZOELJ.js → chunk-PECV7L5T.js} +2 -2
  39. package/dist/cli-bundle/chunks/{chunk-DXDREUXT.js → chunk-Q3VOP62W.js} +2 -2
  40. package/dist/cli-bundle/chunks/{chunk-UP7DTVMD.js → chunk-QJ7C3JIW.js} +2 -2
  41. package/dist/cli-bundle/chunks/{chunk-42E7YPLG.js → chunk-R6LSRGPS.js} +2 -2
  42. package/dist/cli-bundle/chunks/{chunk-MHK6LIWE.js → chunk-R6RKEYYW.js} +2 -2
  43. package/dist/cli-bundle/chunks/{chunk-UN66FZRO.js → chunk-RAFUN7IX.js} +3 -3
  44. package/dist/cli-bundle/chunks/chunk-RUAU5OSH.js +2 -0
  45. package/dist/cli-bundle/chunks/chunk-SD3YXU2U.js +56 -0
  46. package/dist/cli-bundle/chunks/{chunk-SSF4PIUR.js → chunk-SV3YQ4RY.js} +2 -2
  47. package/dist/cli-bundle/chunks/{chunk-V3EUXXOF.js → chunk-SVV3DQES.js} +2 -2
  48. package/dist/cli-bundle/chunks/{chunk-45G53IU4.js → chunk-SXECIECW.js} +2 -2
  49. package/dist/cli-bundle/chunks/chunk-T45OHXDW.js +8 -0
  50. package/dist/cli-bundle/chunks/{chunk-PMXJEU3F.js → chunk-TPKDJ5WL.js} +2 -2
  51. package/dist/cli-bundle/chunks/{chunk-M72BKL5Q.js → chunk-UVVXHGYS.js} +2 -2
  52. package/dist/cli-bundle/chunks/{chunk-WRL4KNDL.js → chunk-V663653R.js} +19 -19
  53. package/dist/cli-bundle/chunks/{chunk-R546TPDE.js → chunk-WSI5KZQJ.js} +2 -2
  54. package/dist/cli-bundle/chunks/{chunk-6MSQJOTG.js → chunk-XPOQQJTX.js} +2 -2
  55. package/dist/cli-bundle/chunks/{chunk-XCEZYMNI.js → chunk-YCCDXBNU.js} +2 -2
  56. package/dist/cli-bundle/chunks/{chunk-LN2WFEU4.js → chunk-ZFBWCKYF.js} +2 -2
  57. package/dist/cli-bundle/chunks/close-DI66JMSB.js +2 -0
  58. package/dist/cli-bundle/chunks/close-many-VFKT6U3O.js +2 -0
  59. package/dist/cli-bundle/chunks/comments-E73HIEZJ.js +2 -0
  60. package/dist/cli-bundle/chunks/copy-WBYVLCPC.js +2 -0
  61. package/dist/cli-bundle/chunks/{create-XLKTXTUF.js → create-TG67IVFI.js} +2 -2
  62. package/dist/cli-bundle/chunks/delete-6XKUVVQN.js +2 -0
  63. package/dist/cli-bundle/chunks/{deps-ITTY3GIC.js → deps-AJUGP2OH.js} +2 -2
  64. package/dist/cli-bundle/chunks/{docs-W4OSRTYR.js → docs-QOCLDRKJ.js} +2 -2
  65. package/dist/cli-bundle/chunks/{files-EOK4AZI4.js → files-3ST5TY64.js} +2 -2
  66. package/dist/cli-bundle/chunks/focus-R2AWS63Y.js +2 -0
  67. package/dist/cli-bundle/chunks/{history-compact-7UGTMLL3.js → history-compact-7BJFML4S.js} +2 -2
  68. package/dist/cli-bundle/chunks/{history-redact-4DZRMD6Z.js → history-redact-WJN3HYXR.js} +2 -2
  69. package/dist/cli-bundle/chunks/{history-repair-UPOSZW5R.js → history-repair-XDNZUB7F.js} +2 -2
  70. package/dist/cli-bundle/chunks/{learnings-GMRNCBS3.js → learnings-SZMUPVNA.js} +2 -2
  71. package/dist/cli-bundle/chunks/{profile-2MUUMHRE.js → profile-KL53JIAC.js} +2 -2
  72. package/dist/cli-bundle/chunks/{register-list-query-LR3SQ5ZF.js → register-list-query-QH7ONPKU.js} +2 -2
  73. package/dist/cli-bundle/chunks/{register-mutation-SUOHFVWM.js → register-mutation-OCRQNZK4.js} +3 -3
  74. package/dist/cli-bundle/chunks/{register-operations-ARRRKOVN.js → register-operations-HIBJXRGB.js} +2 -2
  75. package/dist/cli-bundle/chunks/register-setup-QWBQ6HBS.js +2 -0
  76. package/dist/cli-bundle/chunks/restore-FXA5QPM7.js +2 -0
  77. package/dist/cli-bundle/chunks/{schema-FJ4EA3XF.js → schema-QJ27OTRV.js} +2 -2
  78. package/dist/cli-bundle/chunks/update-7GBO4SXG.js +2 -0
  79. package/dist/cli-bundle/chunks/update-many-VF6ZKQUO.js +2 -0
  80. package/dist/cli-bundle/focused-chunks/{chunk-B7LJWAZE.js → chunk-27DK4A5O.js} +2 -2
  81. package/dist/cli-bundle/focused-chunks/{chunk-SV3O7TSH.js → chunk-4JC3AOGS.js} +2 -2
  82. package/dist/cli-bundle/focused-chunks/{chunk-G6ETT4QK.js → chunk-6KDHXURF.js} +2 -2
  83. package/dist/cli-bundle/focused-chunks/{chunk-PG2RIZBX.js → chunk-74CWP3A4.js} +2 -2
  84. package/dist/cli-bundle/focused-chunks/{chunk-Y4LDYLLT.js → chunk-7AZDTGPA.js} +2 -2
  85. package/dist/cli-bundle/focused-chunks/chunk-7YTZ7A4E.js +2 -0
  86. package/dist/cli-bundle/focused-chunks/{chunk-A7BJ5SS6.js → chunk-CL3NB7VW.js} +2 -2
  87. package/dist/cli-bundle/focused-chunks/chunk-EAXXF2HW.js +4 -0
  88. package/dist/cli-bundle/focused-chunks/{chunk-UIL2M2NA.js → chunk-EYO4F74Z.js} +2 -2
  89. package/dist/cli-bundle/focused-chunks/{chunk-7J5TUBUJ.js → chunk-GEYU23YS.js} +2 -2
  90. package/dist/cli-bundle/focused-chunks/{chunk-WEM2E2PE.js → chunk-GIERI4YU.js} +2 -2
  91. package/dist/cli-bundle/focused-chunks/{chunk-WVIVUWVL.js → chunk-GSW2Y7VZ.js} +2 -2
  92. package/dist/cli-bundle/focused-chunks/{chunk-VLYOEYML.js → chunk-LKQXXO62.js} +2 -2
  93. package/dist/cli-bundle/focused-chunks/{chunk-MJ7HWSFK.js → chunk-MBBMTDD3.js} +2 -2
  94. package/dist/cli-bundle/focused-chunks/{chunk-PIMMYG7Q.js → chunk-ME4XVOBJ.js} +2 -2
  95. package/dist/cli-bundle/focused-chunks/{chunk-IPWSFADF.js → chunk-N7QN3NE6.js} +2 -2
  96. package/dist/cli-bundle/focused-chunks/{chunk-W7BJEWHX.js → chunk-QL5H3AQH.js} +2 -2
  97. package/dist/cli-bundle/focused-chunks/chunk-TQMFQYXR.js +29 -0
  98. package/dist/cli-bundle/focused-chunks/{chunk-RUR5I3TK.js → chunk-XNVXIQ4B.js} +2 -2
  99. package/dist/cli-bundle/focused-chunks/{chunk-FGKY4MBE.js → chunk-YHDCGUIW.js} +2 -2
  100. package/dist/cli-bundle/focused-chunks/{chunk-QVHKCI4T.js → chunk-YLPZHWX7.js} +2 -2
  101. package/dist/cli-bundle/main.js +13 -13
  102. package/dist/cli-bundle/sdk-authoring.js +1 -1
  103. package/dist/cli-bundle/sdk-contracts.js +1 -1
  104. package/dist/cli-bundle/sdk-core.js +25 -25
  105. package/dist/cli-bundle/sdk-governance.js +1 -1
  106. package/dist/cli-bundle/sdk-graph.js +1 -1
  107. package/dist/cli-bundle/sdk-merge.js +1 -1
  108. package/dist/cli-bundle/sdk-query.js +1 -1
  109. package/dist/cli-bundle/sdk-runtime.js +1 -1
  110. package/dist/cli-bundle/sdk-testing.js +1 -1
  111. package/dist/cli-bundle/sdk.js +1 -1
  112. package/dist/core/extensions/activation-summary.d.ts +4 -0
  113. package/dist/core/extensions/activation-summary.js +5 -2
  114. package/dist/core/extensions/contribution-inventory.d.ts +1 -0
  115. package/dist/core/extensions/contribution-inventory.js +35 -2
  116. package/dist/core/extensions/extension-hook-runtime.js +5 -3
  117. package/dist/core/extensions/extension-types.d.ts +18 -1
  118. package/dist/core/extensions/extension-types.js +2 -2
  119. package/dist/core/extensions/loader.js +5 -13
  120. package/dist/core/extensions/preflight-ownership.d.ts +5 -0
  121. package/dist/core/extensions/preflight-ownership.js +42 -0
  122. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  123. package/dist/sdk/cli-contracts/flag-contracts.js +8 -2
  124. package/dist/sdk/cli-contracts/runtime-contracts.js +4 -3
  125. package/dist/sdk/cli-contracts.d.ts +1 -1
  126. package/dist/sdk/cli-contracts.js +3 -3
  127. package/dist/sdk/compose.d.ts +2 -2
  128. package/dist/sdk/compose.js +7 -2
  129. package/dist/sdk/define.d.ts +3 -1
  130. package/dist/sdk/define.js +3 -8
  131. package/dist/sdk/extension/install-sources.d.ts +43 -5
  132. package/dist/sdk/extension/install-sources.js +36 -2
  133. package/dist/sdk/extension/migrations.d.ts +114 -0
  134. package/dist/sdk/extension/migrations.js +175 -0
  135. package/dist/sdk/extension/scaffold.js +14 -9
  136. package/dist/sdk/extension/source-resolution.d.ts +50 -0
  137. package/dist/sdk/extension/source-resolution.js +66 -0
  138. package/dist/sdk/extension.d.ts +5 -1
  139. package/dist/sdk/extension.js +24 -26
  140. package/dist/sdk/governance/health.js +11 -2
  141. package/dist/sdk/index.d.ts +6 -2
  142. package/dist/sdk/index.js +8 -4
  143. package/dist/sdk/package-migrations.d.ts +10 -0
  144. package/dist/sdk/package-migrations.js +21 -0
  145. package/dist/sdk/runtime.d.ts +2 -0
  146. package/dist/sdk/runtime.js +6 -2
  147. package/docs/COMMANDS.md +9 -0
  148. package/docs/EXTENSIONS.md +2 -2
  149. package/docs/EXTENSION_LIFECYCLE.md +46 -0
  150. package/docs/README.md +1 -0
  151. package/docs/RELEASING.md +33 -20
  152. package/docs/SDK.md +31 -3
  153. package/marketplace.json +2 -2
  154. package/package.json +3 -3
  155. package/packages/pm-beads/package.json +1 -1
  156. package/packages/pm-calendar/package.json +1 -1
  157. package/packages/pm-command-kit/package.json +1 -1
  158. package/packages/pm-digital-twin/package.json +1 -1
  159. package/packages/pm-governance-audit/package.json +1 -1
  160. package/packages/pm-guide-shell/package.json +1 -1
  161. package/packages/pm-kanban/package.json +1 -1
  162. package/packages/pm-lifecycle-hooks/package.json +1 -1
  163. package/packages/pm-linked-test-adapters/package.json +1 -1
  164. package/packages/pm-search-advanced/package.json +1 -1
  165. package/packages/pm-templates/package.json +1 -1
  166. package/packages/pm-todos/package.json +1 -1
  167. package/packages/pm-vcs/package.json +1 -1
  168. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  169. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  170. package/sdk/public-surface.json +218 -20
  171. package/dist/cli-bundle/chunks/append-VXXGOXSG.js +0 -2
  172. package/dist/cli-bundle/chunks/chunk-EGJ4JTUG.js +0 -55
  173. package/dist/cli-bundle/chunks/chunk-FPBQHMFT.js +0 -8
  174. package/dist/cli-bundle/chunks/chunk-GE4KCSZP.js +0 -164
  175. package/dist/cli-bundle/chunks/chunk-YEWNL576.js +0 -2
  176. package/dist/cli-bundle/chunks/close-VZ3OQPN5.js +0 -2
  177. package/dist/cli-bundle/chunks/close-many-SB4TI27P.js +0 -2
  178. package/dist/cli-bundle/chunks/comments-BIF3Q4KY.js +0 -2
  179. package/dist/cli-bundle/chunks/copy-6AI5Z57X.js +0 -2
  180. package/dist/cli-bundle/chunks/delete-ZY2VHQTP.js +0 -2
  181. package/dist/cli-bundle/chunks/focus-DLBNWL7L.js +0 -2
  182. package/dist/cli-bundle/chunks/register-setup-O6AYP6NP.js +0 -2
  183. package/dist/cli-bundle/chunks/restore-ZVCVHTB5.js +0 -2
  184. package/dist/cli-bundle/chunks/update-YHV52CSS.js +0 -2
  185. package/dist/cli-bundle/chunks/update-many-M6YHVNXM.js +0 -2
  186. package/dist/cli-bundle/focused-chunks/chunk-BIMTMOS7.js +0 -4
  187. package/dist/cli-bundle/focused-chunks/chunk-GJ2TG2CW.js +0 -28
  188. package/dist/cli-bundle/focused-chunks/chunk-N5XU5UVK.js +0 -2
@@ -1,20 +1,20 @@
1
- import{a as vt}from"./chunk-E2RKBKWB.js";import{b as Wo}from"./chunk-UZBWIUYD.js";import{a as Bo}from"./chunk-OMXVBQ2N.js";import{a as qo}from"./chunk-4VN6GS4U.js";import{f as Eo}from"./chunk-54FNT7U2.js";import{c as Cn,l as Go,m as En,n as In,u as zo}from"./chunk-EGJ4JTUG.js";import{e as wo,j as Ie,l as $o,m as Uo,n as kt}from"./chunk-VCKLFEUN.js";import{oa as Io,qa as An}from"./chunk-6MSQJOTG.js";import{b as zi,c as Hi,d as Vi,e as Ki,g as Yi,l as Xi,m as Ji,o as Qi,p as Zi}from"./chunk-LN2WFEU4.js";import{B as bo,x as yo}from"./chunk-SSF4PIUR.js";import{A as xn,B as Mo,C as Do,D as Fo,E as jo,P as Sn,q as Oo,r as No,s as bn,u as wn,v as kn,w as vn,x as Lo,y as Po,z as Tn}from"./chunk-HWRRMBJO.js";import{d as Ro}from"./chunk-YSO3YFZ4.js";import{i as Ao}from"./chunk-L3AZOELJ.js";import{j as To,o as xo,p as So,q as Co}from"./chunk-RKAVWO3O.js";import{a as ko,d as vo,e as wt}from"./chunk-UP7DTVMD.js";import{A as gn,Aa as _o,B as kr,Ba as le,C as vr,Ca as po,D as Tr,Da as fo,E as xr,Ea as go,F as Sr,Fa as ho,G as Cr,H as Er,I as Ir,J as Ar,K as Rr,L as Or,M as Nr,N as Lr,O as Pr,P as Mr,Q as Dr,R as Fr,S as jr,T as $r,U as Ur,V as Gr,W as qr,X as Br,Y as Wr,Z as zr,_ as Hr,c as fn,ca as Vr,da as Kr,e as er,ea as Yr,f as tr,fa as Xr,g as nr,ga as Jr,h as sr,ha as Qr,i as ir,ia as Zr,j as rr,ja as eo,k as or,ka as to,l as ar,la as no,m as cr,ma as so,n as dr,na as io,o as lr,p as ur,q as mr,qa as ro,r as _r,ra as oo,s as pr,sa as hn,t as fr,ta as ao,u as gr,v as hr,va as yn,w as yr,wa as co,x as br,xa as lo,ya as uo,z as wr,za as mo}from"./chunk-YEWNL576.js";import{B as _n,C as Mi,Ea as Gi,Fa as qi,Ga as Bi,Ha as Wi,M as Di,R as Fi,T as ji,W as pn,Y as $i,wa as Ui,x as Oi}from"./chunk-A62CYISG.js";import{a as mn}from"./chunk-5ZBOIPGP.js";import{f as un,i as Ei,j as Be}from"./chunk-42E7YPLG.js";import{$a as ri,$c as pt,A as g,Aa as Xs,Ad as pi,Af as N,Bb as an,Be as qe,Bf as Ri,C as h,Cb as cn,Da as V,Db as dn,E as P,Ec as mt,Ga as Js,Ia as ge,Ie as Si,Kd as fi,La as R,Lf as Ni,Mf as Li,Na as Q,Nc as Z,Nf as Pi,Oa as O,Oc as ci,Oe as ln,Of as bt,Pc as di,Pf as Ee,Qa as Qs,R as k,Ra as Zs,Rc as li,Sa as dt,Sf as ye,T as Ws,Ua as ei,Va as sn,Vb as lt,Wa as rn,Xa as ti,Xb as ut,Xc as ui,Ya as ni,Yc as _t,Za as si,_a as ii,a as de,ab as oi,ad as ft,ae as gi,b as x,c as $,d as se,da as nn,dd as Ce,g as $s,gd as gt,ha as zs,ib as on,ie as hi,la as Hs,lc as W,lf as ht,ma as Vs,mf as Ci,na as Ks,oa as Ys,p as Us,qf as yt,r as Gs,re as yi,se as bi,t as qs,te as wi,uc as Se,ud as mi,ue as ki,ve as vi,wc as X,we as Ti,wf as Ii,x as Bs,xe as he,y as ct,yc as ai,yd as _i,ye as xi,z as Ge,zd as ee,zf as Ai}from"./chunk-GE4KCSZP.js";(function(){try{var e=typeof window<"u"?window:typeof 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 Ho(e,t,n){return[...await pi(Zs(e,t),t).catch(()=>[])].reverse().find(r=>r.patch.some(o=>o.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]="9c3fc3ab-ba84-5f6d-a05c-bc452ae26c15")}catch{}})();var Vo="no_available_next_item";function Al(e){return e instanceof h&&e.context?.code==="already_claimed_by"}async function Rl(e,t,n,s={}){let i=R(process.cwd(),n.path);if(!await x(O(i)))throw new h(`Tracker is not initialized at ${i}. Run pm init first.`,g.NOT_FOUND);let r=await N(i),o=Z(r.schema),a=ee(s.author,r.author_default),c=_i(a),d=null,l=!1,u=[],m=await ye({pmRoot:i,settings:r,id:e,op:"claim",author:a,message:s.message,force:t,skipNoop:!0,async mutate(_){let f=_.metadata.assignee??"",y=_.metadata.claim_principal?.trim()||f;if(d=f.trim().length>0?f:null,li(_.metadata.status,o)&&!t)throw new h(`Cannot claim terminal item ${_.metadata.id} without --force`,g.CONFLICT);if(d!==null&&y!==c){if(s.ifAvailable===!0)return l=!0,u.push(`claim_skipped_held_by:${d}`),{changedFields:[]};if(!t){let v=await Ho(i,_.metadata.id,f);throw new h(`Item ${_.metadata.id} is already ${v}. Use --force to take over, or --if-available to skip without failing.`,g.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."]})}u.push(`claim_takeover:${d}->${a}`)}return _.metadata.assignee=a,_.metadata.claim_principal=c,{changedFields:["assignee","claim_principal"],warnings:u}}});return{item:m.item,claimed_by:l&&d!==null?d:a,previous_assignee:d,forced:t,...l?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function bb(e,t,n={},s={}){let i=Ol(n.maxAttempts),r=await N(R(process.cwd(),t.path)),o={...n,author:ee(n.author,r.author_default)},a=await Io({...s,callerAuthor:o.author,limit:String(i)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return Nl(c.slice(0,i),e,t,o)}function Ol(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new h("--max-attempts must be an integer from 1 to 100",g.USAGE);return t}async function Nl(e,t,n,s={},i=Rl){let r=0;for(let a of e){r+=1;try{let c=await i(a.id,t,n,s),d={...c,recommendation:a,attempts:r,available:!0};if(!c.skipped)return d}catch(c){if(!Al(c))throw c}}if(s.ifAvailable===!0)return{available:!1,item:null,claimed_by:ee(s.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:r,warnings:[Vo]};let o=r===0;throw new h(o?"No actionable items matched the selection filters":"No actionable item remained available to claim",o?g.NOT_FOUND:g.CONFLICT,{code:Vo,why:o?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[o?"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 wb(e,t,n,s={}){let i=R(process.cwd(),n.path);if(!await x(O(i)))throw new h(`Tracker is not initialized at ${i}. Run pm init first.`,g.NOT_FOUND);let r=await N(i),o=ee(s.author,r.author_default),a=s.ownershipReleaseBypass===!0,c=null,d;try{d=await ye({pmRoot:i,settings:r,id:e,op:"release",author:o,message:s.message,force:t,bypassAssigneeConflict:a,mutate(l){return c=l.metadata.assignee??null,!c&&!l.metadata.claim_principal?{changedFields:[]}:(delete l.metadata.assignee,delete l.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(l){Eo(l,{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{item:d.item,released_by:o,previous_assignee:c,forced:t}}import Rn from"node:fs/promises";import Ko 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]="a6c0aa24-501a-5e76-a669-91d125634cf1")}catch{}})();var Ll=1440*60*1e3,Pl=new Set(["committed","compensated"]);function Ml(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Dl(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function Fl(e,t,n,s,i){let r=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(r))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=s-r;return Pl.has(t)?o>i?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function jl(e,t,n,s){let i=s.hooks?.onRead?await s.hooks.onRead(e):[],r=Dl(await Rn.readFile(e,"utf8")),o=Fl(t,r.status,r.updatedAt,s.nowMs,s.retentionMs);return o.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),o.remove&&!s.dryRun&&(await Rn.rm(e,{force:!0}),s.hooks?.onWrite&&i.push(...await s.hooks.onWrite(e))),{decision:o,warnings:i}}async function Yo(e,t){let{dryRun:n,hooks:s}=t,i=t.now??Date.now(),r=Math.max(0,t.retentionDays)*Ll,o=Ko.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Rn.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(Ml(d,"ENOENT"))return a;throw d}for(let d of c){let l=Ko.join(o,d),u=`transactions/sdk/${d}`,m=await jl(l,u,d,{dryRun:n,hooks:s,nowMs:i,retentionMs:r});a.warnings.push(...m.warnings),a.scanned+=1;let{decision:_}=m;if(!_.remove){a.retained.push(u),a.entries.push(_.entry);continue}a.removed.push(u),a.entries.push(_.entry)}return a}import Ae from"node:fs/promises";import Ct from"node:path";import Tt from"node:fs/promises";import On 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]="8cc32963-26eb-5e08-bffb-2d8da152a43f")}catch{}})();var $l=864e5;function xt(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Ul(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function Gl(e,t){let n;try{n=await Tt.readdir(e,{withFileTypes:!0})}catch(i){if(xt(i,"ENOENT"))return[];throw i}let s=[];for(let i of n)if(i.isDirectory()){let r=On.join(e,i.name),o;try{o=await Tt.readdir(r)}catch(a){xt(a,"ENOENT")||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of o)a.endsWith(".json")&&s.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&s.push(i.name);return s.sort()}async function Xo(e,t){let{dryRun:n,hooks:s}=t,i=t.now??Date.now(),r=Math.max(0,t.retentionDays)*$l,o=On.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await Gl(o,a.warnings);for(let d of c){let l=On.join(o,d),u=`checkpoints/${d}`;a.scanned+=1,s?.onRead&&a.warnings.push(...await s.onRead(l));let m;try{m=await Tt.readFile(l,"utf8")}catch(b){if(xt(b,"ENOENT")){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let _=Ul(m),p=_===null?Number.NaN:Date.parse(_);if(!Number.isFinite(p)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:_,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=i-p,y={file:u,created_at:_,age_seconds:Math.floor(f/1e3),stale:f>r,reason:f>r?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await Tt.unlink(l)}catch(b){if(!xt(b,"ENOENT")){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}s?.onWrite&&a.warnings.push(...await s.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}import We from"node:fs/promises";import St 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]="a026943f-1a46-526b-bfaa-435025c65c2a")}catch{}})();function ql(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:s,owner:i,created_at:r,ttl_seconds:o}=n;return typeof s!="string"||typeof i!="string"||typeof r!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:s,owner:i,created_at:r,ttl_seconds:o}}function ze(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Jo(e,t,n){let s=ql(t);if(s===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(s.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:s.id,owner:s.owner,created_at:s.created_at,ttl_seconds:s.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let r=n-i,o=Math.floor(r/1e3),a=r>s.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:s.id,owner:s.owner,created_at:s.created_at,ttl_seconds:s.ttl_seconds,age_seconds:o,stale:a,reason:a?"expired":"active"}}}async function Qo(e,t){let n=t??Date.now(),s=St.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},r;try{r=(await We.readdir(s)).filter(a=>a.endsWith(".lock")).sort()}catch(o){if(ze(o,"ENOENT"))return i;throw o}for(let o of r){let a;try{a=await We.readFile(St.join(s,o),"utf8")}catch(d){if(ze(d,"ENOENT"))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=Jo(o,a,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function Zo(e,t){let{dryRun:n,hooks:s}=t,i=t.now??Date.now(),r=St.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},a;try{a=(await We.readdir(r)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if(ze(c,"ENOENT"))return o;throw c}for(let c of a){o.scanned+=1;let d=St.join(r,c),l=`locks/${c}`;if(s?.onRead){let _=await s.onRead(d);o.warnings.push(..._)}let u;try{u=await We.readFile(d,"utf8")}catch(_){if(ze(_,"ENOENT")){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${c}`),o.retained.push(l),o.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=Jo(c,u,i);if(m.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="active"){o.retained.push(l),o.entries.push(m.entry);continue}if(!n){try{await We.unlink(d)}catch(_){if(!ze(_,"ENOENT")){o.warnings.push(`lock_remove_failed:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}}if(s?.onWrite){let _=await s.onWrite(d);o.warnings.push(..._)}}o.removed.push(l),o.entries.push(m.entry)}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]="0973a87f-2b63-5fa1-9624-82897d181f71")}catch{}})();var He=["index","embeddings","runtime","locks","checkpoints","transactions"],Bl=1440*60*1e3,Wl=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];function ea(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function zl(e,t,n){let s=t.relativePath,i=Ct.join(e,s),r=await X({path:i,scope:"project"});try{let o=await Ae.stat(i);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...r,`not_a_file:${s}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...r,`not_a_directory:${s}`]};if(n)return{removed:!0,warnings:r};t.kind==="file"?await Ae.unlink(i):await Ae.rm(i,{recursive:!0,force:!0});let a=await Se({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...r,...a]}}catch(o){if(ea(o,"ENOENT"))return{removed:!1,warnings:r};throw o}}async function Hl(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],s=[],i=[],r=[],o=Date.now()-Bl;for(let a of n){let c=Ct.join(e,a.relativePath);if(!await x(c))continue;let d=(await Ae.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=Ct.posix.join(a.relativePath,l),m=Ct.join(c,l);r.push(...await X({path:m,scope:"project"}));let _=await Ae.stat(m).catch(p=>{if(!ea(p,"ENOENT"))throw p});if(_){if(_.mtimeMs>o){i.push(u);continue}s.push(u),!t&&(await Ae.rm(m,{recursive:!0,force:!0}),r.push(...await Se({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:s,retained:i,warnings:r}}function Vl(e){if(!e||e.length===0)return[...He];let t=e.flatMap(s=>s.split(",")).map(s=>s.trim().toLowerCase()).filter(s=>s.length>0);if(t.length===0)throw new h(`--scope requires at least one value (${He.join(",")})`,g.USAGE);let n=new Set;for(let s of t){if(!He.includes(s))throw new h(`Invalid --scope value "${s}". Expected one or more of: ${He.join(", ")}`,g.USAGE);n.add(s)}return He.filter(s=>n.has(s))}function Kl(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),s=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&s&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function Bb(e,t={}){let n=R(process.cwd(),e.path);if(!await x(O(n)))throw new h(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let s=await N(n),i=t.dryRun===!0,r=Vl(t.scope),o=Wl.filter(p=>r.includes(p.scope)),a=[],c=[],d=[];for(let p of o){let f=await zl(n,p,i);f.removed?a.push(p.relativePath):c.push(p.relativePath),d.push(...f.warnings)}if(r.includes("runtime")){let p=await Hl(n,i);a.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(r.includes("locks")){let p=await Zo(n,{dryRun:i,hooks:{onRead:f=>X({path:f,scope:"project"}),onWrite:f=>Se({path:f,scope:"project",op:"gc:lock_remove"})}});a.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),l={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(r.includes("transactions")){let p=s.checkpoints.retention_days,f=await Yo(n,{dryRun:i,retentionDays:p,hooks:{onRead:y=>X({path:y,scope:"project"}),onWrite:y=>Se({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),u={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length,retention_days:p}}let m;if(r.includes("checkpoints")){let p=s.checkpoints.retention_days,f=await Xo(n,{dryRun:i,retentionDays:p,hooks:{onRead:y=>X({path:y,scope:"project"}),onWrite:y=>Se({path:y,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),m={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length,retention_days:p}}d.push(...await ai({mode:i?"gc:dry-run":"gc",total_items:o.length}));let _=Kl({dryRun:i,scopes:r,removed:a});return{ok:d.length===0,dry_run:i,scope:r,removed:a,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:_,generated_at:k()}}import Et from"node:fs/promises";import It 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]="364a8999-58e2-58c9-bfa6-acd8c42ec471")}catch{}})();var Yl="2026-07-15T06:22:12.276Z",Xl=Date.parse(Yl),Jl=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],ta=e=>typeof e=="string"?e:"",na=e=>{let t=e??{},n=ta(t.author).trim().toLowerCase(),s=Number(["","unknown"].includes(n)),i=+(Date.parse(ta(t.ts))>=Xl);return Jl[s][i]};function sa(e,t,n=20,s=new Set,i=!1){let r=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,_]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(_)}catch{continue}d+=1;let f=na(p);if(f!=="attributed"){if(l+=1,f==="actionable_unknown"&&s.has(`${e}:${m+1}`)){u+=1;continue}a[f]+=1,i&&f==="actionable_unknown"&&o.push({item_id:e,line:m+1}),r.length<c&&r.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:r,samples_truncated:a.legacy_unknown+a.actionable_unknown>r.length,actionable_events:o}}var Yb=(e,t,n=20,s=new Set)=>sa(e,t,n,s);function Ql(e){let t=new Set;for(let n of e.split(/\r?\n/)){let s;try{s=JSON.parse(n)}catch{continue}let r=(typeof s=="object"&&s!==null&&typeof s.context=="object"&&s.context!==null?s.context:{}).author_acknowledgment;if(!(typeof r!="object"||r===null||!Array.isArray(r.events)))for(let o of r.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Ve=async(e,t=20,n=!1)=>{let s=It.join(e,"history"),i;try{i=(await Et.readdir(s)).filter(b=>b.endsWith(".jsonl")).sort((b,v)=>b.localeCompare(v))}catch{i=[]}let r=new Set,o=[],a=[],c=0,d=0,l=0,u=0,m=0,_=0,p="_workspace.jsonl",f=new Set;if(i.includes(p))try{f=Ql(await Et.readFile(It.join(s,p),"utf8"))}catch{f=new Set}for(let b of i){let v;try{v=await Et.readFile(It.join(s,b),"utf8")}catch{continue}let E=b.slice(0,-6),S=sa(E,v,t-o.length,f,n);c+=1,d+=S.checked_events,l+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,_+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&r.add(E),o.push(...S.samples),n&&a.push(...S.actionable_events)}let y=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:_,affected_item_ids:[...r].sort((b,v)=>b.localeCompare(v)),samples:o,samples_truncated:y>o.length,...n?{actionable_events:a}:{}}};async function Xb(e,t){let n=t.reviewer.trim(),s=t.attributed_author.trim(),i=t.reason.trim(),r=t.events??[];if(+(t.all_actionable===!0)+ +(r.length>0)>1)throw new TypeError("Author acknowledgment accepts either explicit events or all_actionable, not both.");let a=t.all_actionable===!0?(await Ve(e,0,!0)).actionable_events:r;if([a.length>0,n.length>0,n.toLowerCase()!=="unknown",s.length>0,s.toLowerCase()!=="unknown",i.length>0].includes(!1))throw new TypeError("Author acknowledgment requires events, reviewer, attributed_author, and reason.");let d=[...new Map(a.map(m=>[`${m.item_id}:${m.line}`,{item_id:m.item_id,line:m.line}])).values()].sort((m,_)=>m.item_id.localeCompare(_.item_id)||m.line-_.line);for(let m of d){if([/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1))throw new TypeError(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`);let p;try{let y=(await Et.readFile(It.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];p=JSON.parse(y??"")}catch{throw new TypeError(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`)}if(na(p)!=="actionable_unknown")throw new TypeError(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`)}let l=await N(e),u=await yt({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:d,attributed_author:s}},message:i,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms});return{acknowledged:d.length,history_path:u.historyPath}}import{execFile as Zl}from"node:child_process";import{randomUUID as eu}from"node:crypto";import{readdir as tu,readFile as nu}from"node:fs/promises";import Ke from"node:path";import{promisify as su}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]="c4721ede-e557-5720-a9c2-4b2b344cc6cc")}catch{}})();var iu=su(Zl);async function Nn(e){try{let{stdout:t}=await iu("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}function ia(e){return`${e}.json`}function ow(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,preferred:e.preferred,decisions:e.decisions.map(t=>({field:t.field,retained_hash:dn(an(t.retained)),discarded_hash:dn(an(t.discarded))}))}}async function aw(e){let t=await Nn(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),s=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,i=Ke.basename(s,Ke.extname(s)),r={version:1,id:eu(),item_path:s.replaceAll("\\","/"),item_id:i,preferred:e.preferred,fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:k()};return await de(t),await se(Ke.join(t,ia(r.id)),`${JSON.stringify(r,null,2)}
2
- `),r}async function Ye(e,t={}){let n=await Nn(e);if(n===null||!await x(n))return[];let s=[],i;try{i=await tu(n)}catch{return[]}for(let r of i.sort((o,a)=>o.localeCompare(a)))if(r.endsWith(".json"))try{let o=JSON.parse(await nu(Ke.join(n,r),"utf8"));o.version===1&&(t.includeReconciled||o.state==="pending")&&s.push(o)}catch{}return s.sort((r,o)=>r.created_at.localeCompare(o.created_at))}async function cw(e,t){let n=await Nn(e);n!==null&&await se(Ke.join(n,ia(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:k()},null,2)}
3
- `)}async function dw(e){let t=await Ye(e.cwd??process.cwd(),e);return{ok:!0,count:t.length,receipts:t,generated_at:k()}}import re from"node:fs/promises";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]="6a350683-275b-5d4d-ae02-45798b115f89")}catch{}})();var ru=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:"pm validate --check-history-drift --fix-hints",summary:"Historical mutations lack attributable authorship. Configure PM_AUTHOR, pass global --author, or set author_default so future audit events are attributable."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_unknown_author_events",command:"pm config project set author_default <stable-agent-id>",summary:"Historical mutations lack attributable authorship. Set a stable default or use invocation-wide --author for future events; existing audit history remains append-only."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function ou(e){if(typeof e!="string")return;let t=e.trim();for(let n of ru)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Ln(e){let t={};for(let n of e){let s=ou(n);s!==void 0&&!Object.prototype.hasOwnProperty.call(t,s.code)&&(t[s.code]=s.command)}return t}function ra(e){return Object.values(Ln(e))}import{execFile as au}from"node:child_process";import{realpath as cu}from"node:fs/promises";import oa from"node:path";import{promisify as du}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]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var lu=du(au),uu=32*1024*1024,mu=1e4,_u=["search/eval-queries.json"];function Pn(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function pu(e){return`'${e.replaceAll("'","'\\''")}'`}async function fu(e,t=cu){return t(e).catch(()=>oa.resolve(e))}async function At(e){let t=await Ie(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await fu(e),s=Pn(oa.relative(t,n));if(s.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=wo.map(r=>`${s}/${Pn(r)}`);try{let{stdout:r}=await lu("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:uu,windowsHide:!0,timeout:mu}),o=new Set(_u.map(d=>`${s}/${d}`)),a=[...new Set(r.split("\0").filter(d=>d.length>0&&!o.has(Pn(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:s,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>pu(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:s,tracked_paths:[],tracked_path_count:0,remediation_command: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]="6d814d40-522c-5bcc-b404-7e6511cf999a")}catch{}})();var gu=new Set(Bi),ca=25,Xe=8,hu=z.join("runtime","telemetry","events.jsonl"),yu=z.join("runtime","telemetry","state.json"),bu=2500,wu=500,da=qi-3,ku=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function la(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("stale_in_progress_items:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function ua(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Oe(e){return e.trim().toLowerCase()}function Fn(e,t){let n=Oe(e),s=Oe(t);return n.startsWith("builtin-")?!0:s==="beads"||s==="todos"}async function Un(e){try{return(await re.stat(e)).isDirectory()}catch{return!1}}async function vu(e){let t=(await re.readdir(e,{withFileTypes:!0})).filter(s=>s.isDirectory()),n=await Promise.all(t.map(s=>re.readdir(z.join(e,s.name),{withFileTypes:!0})));return new Set(n.flatMap(s=>s.filter(i=>i.isFile()).filter(i=>ge.some(r=>i.name.endsWith(r))).map(i=>z.parse(i.name).name)))}async function Tu(e,t,n,s){let i=await X({path:e,scope:"project"}),r=t!=="_workspace"&&!s.has(t);if(!n.enabled&&!r)return{warnings:i,overThreshold:!1,classification:"live"};let o;try{o=await re.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(r){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function xu(e,t,n){let s=z.join(e,"history");if(!await Un(s))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await re.readdir(s)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),o=t.enabled?t.max_entries:null,a=[],c=[],d=[],l=[];for(let u of i){let m=z.join(s,u),_=u.slice(0,-6),p=await Tu(m,_,t,n);a.push(...p.warnings),p.classification==="tombstone"&&d.push(_),p.classification==="orphaned"&&l.push(_),p.overThreshold&&c.push(_)}return{count:i.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:o,tombstones:d,orphaned:l}}function jn(e,t){return z.relative(e,t).replaceAll("\\","/")}async function ma(e,t){let n=[...new Set(Object.values(t))].sort((i,r)=>i.localeCompare(r)),s=[];for(let i of n){let r=z.join(e,i),o=[];try{o=await re.readdir(r)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT")continue;continue}for(let a of o)ge.some(c=>a.toLowerCase().endsWith(c))&&s.push(z.join(r,a))}return s.sort((i,r)=>jn(e,i).localeCompare(jn(e,r))),s}function Su(e){return!(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")}async function Cu(e,t,n){let s=await ma(e,t),i=[],r=[],o=[],a=[],c=mt(W());for(let d of s){let l=jn(e,d),u;try{u=await re.readFile(d,"utf8")}catch{i.push(l);continue}let m=Ce(u);if(m){r.push({path:l,...m});continue}try{let _=gt(u,{format:Qs(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:_t(_.metadata)})}catch{o.push(l)}}return{paths:s,unreadable:i,conflictMarkers:r,parseFailures:o,formatVersions:a}}async function Eu(e){let t=z.join(e,"history"),n=[],s=[],i=[],r=[];try{r=(await re.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,a)=>o.localeCompare(a))}catch(o){Su(o)&&n.push("history")}for(let o of r){let a=o.slice(0,-6),c;try{c=await re.readFile(z.join(t,o),"utf8")}catch{n.push(a);continue}let d=Ce(c);if(d){s.push({id:a,...d});continue}c.split(/\r?\n/).forEach((l,u)=>{if(l.trim())try{JSON.parse(l)}catch{i.push({id:a,line:u+1})}})}return{files:r,unreadable:n,conflictMarkers:s,invalidJson:i}}async function Iu(e,t,n,s){let i=await Cu(e,t,n),r=await Eu(e),o=pt(i.formatVersions),a=await At(e),c=await Ie(e),d=c===null?null:await kt(c),l=c===null?[]:await Ye(c),u=d?.status==="missing"&&d.missing_keys.length===5&&d.drifted_keys.length===0,m=[...i.unreadable.map(p=>`integrity_item_unreadable:${p}`),...i.conflictMarkers.map(p=>`integrity_item_conflict_marker:${p.path}:L${p.line}`),...i.parseFailures.map(p=>`integrity_item_parse_failed:${p}`),...r.unreadable.map(p=>`integrity_history_unreadable:${p}`),...r.conflictMarkers.map(p=>`integrity_history_conflict_marker:${p.id}:L${p.line}`),...r.invalidJson.map(p=>`integrity_history_invalid_json:${p.id}:L${p.line}`),...o.outdated.map(p=>`integrity_item_outdated_format_version:${p}`),...o.ahead.map(p=>`integrity_item_ahead_format_version:${p}`),...a.tracked_path_count>0?[`tracked_runtime_cache_files:${a.tracked_path_count}`]:[],...d!==null&&d.status!=="ok"?[`merge_driver_configuration_${u?"missing":"drift"}:${d.missing_keys.length+d.drifted_keys.length}`]:[],...l.length>0?[`merge_decisions_unreviewed:${l.length}`]:[]],_=[...new Set(m)].sort((p,f)=>p.localeCompare(f));return{check:{name:"integrity",status:_.length===0?"ok":"warn",details:{checked_item_files:i.paths.length,checked_history_streams:r.files.length,counts:{item_unreadable:i.unreadable.length,item_conflict_markers:i.conflictMarkers.length,item_parse_failures:i.parseFailures.length,history_unreadable:r.unreadable.length,history_conflict_markers:r.conflictMarkers.length,history_invalid_json:r.invalidJson.length,item_outdated_format_version:o.outdated.length,item_ahead_format_version:o.ahead.length,tracked_runtime_cache_files:a.tracked_path_count,merge_driver_configuration:d===null||d.status==="ok"?0:d.missing_keys.length+d.drifted_keys.length,pending_merge_decisions:l.length},item_unreadable:i.unreadable,item_conflict_markers:i.conflictMarkers,item_parse_failures:i.parseFailures,item_outdated_format_version:o.outdated,item_ahead_format_version:o.ahead,history_unreadable:r.unreadable,history_conflict_markers:r.conflictMarkers,history_invalid_json:r.invalidJson,tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command},merge_driver_configuration:d===null?null:{...d,required:s},pending_merge_decision_items:[...new Set(l.map(p=>p.item_id))].sort((p,f)=>p.localeCompare(f))}},warnings:_}}function Au(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function Ru(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:Au(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Ou(e,t){let n=P(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Nu(e){let n=P(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function Lu(e){return P(e.reason)??P(e.error)??P(e.message)}function Mn(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let s=(e.name??"").localeCompare(t.name??"");return s!==0?s:(e.id??"").localeCompare(t.id??"")}function Pu(e){let t=[],n=[],s=[];e.forEach((r,o)=>{let a=Ou(r.definition,o),c=Nu(r.definition);if(c==="applied"){t.push({layer:r.layer,name:r.name,id:a,status:c});return}if(c==="failed"){s.push({layer:r.layer,name:r.name,id:a,status:c,reason:Lu(r.definition)});return}n.push({layer:r.layer,name:r.name,id:a,status:c})}),t.sort(Mn),n.sort(Mn),s.sort(Mn);let i=[...s.map(r=>`extension_migration_failed:${r.layer}:${r.name}:${r.id}`),...n.map(r=>`extension_migration_pending:${r.layer}:${r.name}:${r.id}`)];return{summary:{applied:t,pending:n,failed:s,applied_count:t.length,pending_count:n.length,failed_count:s.length},warnings:i}}function _a(e,t,n,s,i,r,o,a,c){let d=[...new Set(e)].sort((y,b)=>y.localeCompare(b)),l=[...new Set(d.map(y=>ua(y)))].sort((y,b)=>y.localeCompare(b)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,m=c.length>0,_=m?"partial":"full",p=[],f=Go(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return f&&p.push(f),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(s.failed_count>0||s.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${$s.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:s.failed_count,migration_pending_count:s.pending_count,managed_state_warning_count:i,managed_extension_entries_count:r,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:_,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function Mu(e,t,n){let s=await lt({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),i=s.loaded.map(w=>Ru(w)),r=await ut({...s,loaded:s.loaded}),[o,a]=await Promise.all([Cn(s.roots.project),Cn(s.roots.global)]),c=Pu(r.registrations.migrations),d={failed:r.failed,warnings:r.warnings,hook_counts:r.hook_counts,command_override_count:r.command_override_count,command_handler_count:r.command_handler_count,parser_override_count:r.parser_override_count,preflight_override_count:r.preflight_override_count,service_override_count:r.service_override_count,renderer_override_count:r.renderer_override_count,registration_counts:r.registration_counts,registrations:r.registrations,migration_status:c.summary,managed_extensions:{project:{path:o.path,count:o.state.entries.length,entries:o.state.entries},global:{path:a.path,count:a.state.entries.length,entries:a.state.entries}}},l=new Set(o.state.entries.map(w=>Oe(w.name))),u=new Set(a.state.entries.map(w=>Oe(w.name))),m=[...new Map(s.loaded.filter(w=>!(w.layer==="project"?l:u).has(Oe(w.name))).map(w=>[`${w.layer}:${w.name}`,{layer:w.layer,name:w.name,directory:w.directory}])).values()].sort((w,A)=>{let q=`${w.layer}:${w.name}`,D=`${A.layer}:${A.name}`;return q.localeCompare(D)}),_=m.map(w=>`${w.layer}:${w.name}`).sort((w,A)=>w.localeCompare(A)),p=m.filter(w=>Fn(w.name,w.directory)).map(w=>`${w.layer}:${w.name}`).sort((w,A)=>w.localeCompare(A)),f=m.filter(w=>!Fn(w.name,w.directory)).map(w=>`${w.layer}:${w.name}`).sort((w,A)=>w.localeCompare(A)),y=f.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${f.length}`]:[],b=[...s.warnings,...d.warnings,...c.warnings,...o.warnings,...a.warnings,...y],v=En(b),E=In(),S=_a(b,s.failed.length,r.failed.length,c.summary,o.warnings.length+a.warnings.length,o.state.entries.length+a.state.entries.length,_,p,f);return{check:{name:"extensions",status:b.length===0?"ok":"warn",details:{...s,loaded:i,warnings:b,activation:d,triage:S,capability_contract:E,capability_guidance:v}},warnings:b}}function Du(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function ie(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function Fu(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function Rt(e,t){let n=ie(e,t);return{...n,sample:n.sample.map(s=>Fu(s))}}function L(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(s=>typeof s=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function ju(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var $u={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:L(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:L(e.missing_required,t),missing_optional:L(e.missing_optional,t),missing:L(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:L(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:Rt(e.discovered,t),effective:Rt(e.effective,t),loaded:Rt(e.loaded,t),failed:ie(e.failed,t),warnings:L(e.warnings,t),activation:{failed:ie(n.failed,t),warnings:L(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:ju(n.migration_status)},triage:e.triage,capability_contract:e.capability_contract,capability_guidance:ie(e.capability_guidance,t)}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:L(n.affected_item_ids,t),samples:ie(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:L(e.item_unreadable,t),item_conflict_markers:ie(e.item_conflict_markers,t),item_parse_failures:L(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:L(n.tracked_paths,t)},history_unreadable:L(e.history_unreadable,t),history_conflict_markers:ie(e.history_conflict_markers,t),history_invalid_json:ie(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>({checked_items:e.checked_items,counts:e.counts,drifted_items:L(e.drifted_items,t),missing_streams:L(e.missing_streams,t),unreadable_streams:L(e.unreadable_streams,t),hash_mismatches:L(e.hash_mismatches,t),chain_mismatches:L(e.chain_mismatches,t),skipped:e.skipped}),vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:L(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:L(e.stale_items_after,t),skipped:e.skipped})};function pa(e,t){let n=$u[e.name];return n?n(e.details,t):e.details}function Uu(e){let t=L(e.warnings,Xe);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,details:pa(n,Xe)})),warnings:t.sample,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:Xe},generated_at:e.generated_at}}function aa(e){return e.details.skipped===!0}function Gu(e){let t=L(e.warnings,Xe),n=e.checks.filter(aa).map(s=>s.name);return{ok:e.ok,checks:e.checks.filter(s=>!aa(s)).map(s=>({name:s.name,status:s.status,details:{}})),warning_count:t.count,warnings:t.sample,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:Xe,omitted_checks:n},generated_at:e.generated_at}}function $n(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Du(e,ca);return{values:n.values,truncated:n.truncated,total:e.length}}function Re(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function qu(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return gu.has(e)?e:null}function Ot(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function fa(e){let t=0,n=0,s=0,i=0,r=0;for(let o of e.split(`
4
- `)){let a=o.trim();if(a.length!==0){s+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,r=Math.max(r,d),d>=da&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:s,highRetryEntries:i,maxAttempts:r}}function Bu(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Wu(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function zu(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await ga(n)}}function Hu(e,t,n){let s=[];if(t.invalidRows>0&&s.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return s;let i=n.last_successful_flush_at,r=n.last_failed_flush_at,o=r&&(!i||r>i),a=!i,c=t.validEntries>=wu;return(o||a||c)&&s.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&s.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),s}function Vu(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function Ku(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Gi?[`telemetry_schema_version_behind:${t}`]:[]}function Yu(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,s=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!i&&(!s||i>=s)?[`telemetry_otel_export_failing:${n}`]:[]}function Xu(){return{telemetry_disabled:Re("PM_TELEMETRY_DISABLED")||Re("PM_NO_TELEMETRY"),pm_no_telemetry:Re("PM_NO_TELEMETRY"),telemetry_otel_disabled:Re("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:Re("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:qu()}}function Ju(e,t){return e.telemetry.enabled&&t.validEntries>0}function Qu(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function ga(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(bu)});return{probe_url:Ot(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let s of ku){let i=n.headers.get(s)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:Ot(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function Zu(e,t){let n=Q(process.cwd()),s=z.join(n,hu),i=z.join(n,yu),r=await $(s),o=r!==null,a=r?Buffer.byteLength(r,"utf8"):0,c=r?fa(r):Bu(),d=await $(i),{runtimeState:l,stateParseFailed:u}=Wu(d),m=e.telemetry.endpoint.trim(),_=Ot(m),p=await zu(e,t.checkTelemetry),f=[];u&&f.push("telemetry_state_invalid_json"),f.push(...Hu(e,c,l),...Vu(p),...Ku(p),...Yu(e,l));let y=Ju(e,c),b=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:f.length===0?"ok":"warn",details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:_,global_pm_root:n,queue_path:s,queue_exists:o,queue_entries:c.validEntries,queue_draining:Qu(y,f),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:a,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:da,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:b,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:Xu()}},warnings:f}}async function em(e){let t;try{t=await Qo(e)}catch(s){let i=s instanceof Error?s.message:String(s);return{check:{name:"locks",status:"warn",details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function tm(e,t){let n="metadata",{missingStreams:s,unreadableStreams:i,hashMismatches:r,chainMismatches:o,driftedItems:a}=await vt(e,t,{cacheHitVerification:n}),c=[...s.map(d=>`history_drift_missing_stream:${d}`),...i.map(d=>`history_drift_unreadable_stream:${d}`),...r.map(d=>`history_drift_hash_mismatch:${d}`),...o.map(d=>`history_drift_chain_mismatch:${d}`)];return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,cache_hit_verification:n,drifted_items:a,counts:{drifted:a.length,missing_streams:s.length,unreadable_streams:i.length,hash_mismatches:r.length,chain_mismatches:o.length},missing_streams:s,unreadable_streams:i,hash_mismatches:r,chain_mismatches:o}},warnings:c}}function nm(e,t){let n=Oi(e),s=Mi(n.settings),i=Di(n.settings,t),r=s.active?Fi(s.active.name,s.active.model):null;return{runtimeDefaults:n,providerResolution:s,vectorStoreResolution:i,runtimeEmbeddingIdentity:r,semanticRuntimeAvailable:!!(s.active&&i.active)}}function sm(){return{refreshed:[],skipped:[],warnings:[]}}async function im(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?sm():$i(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function rm(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&ji(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function om(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,s)=>n.localeCompare(s))}function am(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function ha(e,t){let n=t.providerResolution.active?.name??null,s=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:_n(n,e.search?.provider??null),vector_store_active:s,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:_n(s,e.vector_store?.adapter??null)}}function cm(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function dm(e,t,n){return e.enabled&&n.length>0&&t}async function lm(e,t,n,s,i){let r=nm(t,e),o=await pn(e),a=r.semanticRuntimeAvailable?An(n,o.entries):[],c=await im({pmRoot:e,snapshot:r,refreshPolicy:s,staleBefore:a}),d=await pn(e),l=r.semanticRuntimeAvailable?An(n,d.entries):[],u=!r.runtimeDefaults.auto_ollama_defaults_applied,m=rm({strictVectorizationWarnings:u,semanticRuntimeAvailable:r.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:r.runtimeEmbeddingIdentity}),_=om({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:r.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=$n(a,i),f=$n(l,i),y=dm(s,r.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:_.length===0?"ok":"warn",details:{semantic_runtime_available:r.semanticRuntimeAvailable,compatibility_mode_auto_defaults:r.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:r.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:r.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:r.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:cm(s),...ha(t,r),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:r.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:ca,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:y,refresh_skipped_reason:am(s,r.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:f.total,stale_items_after:f.values,stale_items_after_truncated:f.truncated}},warnings:_}}function um(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function mm(e){let t=e.checkOnly===!0,n=e.noRefresh===!0||t,s=e.refreshVectors===!0;if(s&&t)throw new h("--check-only cannot be combined with --refresh-vectors",g.USAGE);if(s&&e.noRefresh===!0)throw new h("--no-refresh cannot be combined with --refresh-vectors",g.USAGE);return{enabled:s||!n,checkOnly:t,noRefresh:n,refreshVectors:s}}var _m=new Set(["extensions","locks","search"]);function pm(e){let t=new Set(Gs.filter(i=>i.length>0)),n=new Set,s=new Set(Object.values(qs));for(let i of e.folders)t.has(i)&&!s.has(i)||(t.delete(i),n.add(i));for(let i of _m)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,r)=>i.localeCompare(r)),optionalDirs:[...n].sort((i,r)=>i.localeCompare(r)),optionalDirSet:n}}async function fm(e,t,n){let{requiredDirs:s,optionalDirs:i,optionalDirSet:r}=pm(t),o=[],a=[],c=[];for(let d of[...s,...i]){let l=z.join(e,d);c.push(...await X({path:l,scope:"project"})),!await Un(l)&&(r.has(d)?a.push(d):o.push(d))}return{requiredDirs:s,optionalDirs:i,missingRequiredDirs:o,missingOptionalDirs:a,missingDirs:n?[...o,...a]:[...o],hookWarnings:c}}function ya(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,s=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||s)&&e.full!==!0,skipDrift:(e.skipDrift===!0||s)&&e.full!==!0,skipVectors:(e.skipVectors===!0||s)&&e.full!==!0}}async function gm(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Pi(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):Ee(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Dn(e){return{check:{name:e,status:"ok",details:{skipped:!0}},warnings:[]}}function hm(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function ym(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function bm(e){return{name:"settings_values",status:e.length===0?"ok":"warn",details:{warnings:e}}}var Gn=e=>e.unknown_event_count??0,qn=e=>e.actionable_unknown_event_count??Gn(e);function wm(e,t,n,s,i){let r=Gn(s),o=qn(s),a=r>0,c=o>0,d=i.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!c&&!d?"ok":"warn",details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...a?{author_attribution:s}:{},...d?{stale_in_progress:i}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function ba(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function km(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function vm(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function Tm(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historySummary.over_threshold.map(t=>`history_stream_over_compact_threshold:${t}`),...e.authorAttributionWarnings,...e.staleInProgressWarnings],locks:e.locksCheck.warnings,integrity:e.integrityCheck.warnings,history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function xm(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-repair --all";if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function Sm(e){for(let t of e.checks){let n=Ln(e.remediationSources[t.name]);xm({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}function wa(e,t,n){return n?Gu(e):t.brief===!0?Uu(e):e}async function ek(e,t={}){let n=R(process.cwd(),e.path),s=O(n);if(!await x(s))throw new h(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let{settings:i,warnings:r}=await Ai(n),o=[...new Set(r)],a=V(i,W()),c=t.strictDirectories===!0,d=mm(t),l=await fm(n,a,c),u=um(i),m=await Zu(i,{checkTelemetry:t.checkTelemetry===!0}),_=await Mu(n,i,!!e.noExtensions),p=ya(t),f=[],y=await gm({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:p,itemReadWarnings:f}),b=y,v=[...new Set(f)],E=p.skipDrift?{warnings:[]}:await ht({pmRoot:n,settings:i,itemIds:y.map(tn=>tn.id),commandLabel:"health"}),S=await xu(n,i.history.compact_policy,await vu(n)),w=await Ve(n,20,t.verboseAuthorEvents===!0),A=qn(w),q=A>0?[`history_unknown_author_events:${A}`]:[],D=ba(await Ui(n,y,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),j=await em(n),Y=p.skipIntegrity?Dn("integrity"):await Iu(n,a.type_to_folder,i.schema,t.requireMergeDrivers===!0),ce=p.skipDrift?Dn("history_drift"):await tm(n,b),T=p.skipVectors?Dn("vectorization"):await lm(n,i,b,d,t.verboseStaleItems===!0),B=[hm(s,i,o),ym(l,c),bm(u),m.check,_.check,wm(y,i,S,w,D.scan),j.check,Y.check,ce.check,T.check],js=km({directoryState:l,normalizedSettingsReadWarnings:o,settingWarnings:u,normalizedItemReadWarnings:v,telemetryCheck:m,extensionCheck:_,historyPolicyWarnings:E.warnings,historySummary:S,authorAttributionWarnings:q,staleInProgressWarnings:D.warnings,locksCheck:j,integrityCheck:Y,historyDriftCheck:ce,vectorizationCheck:T});Sm({checks:B,remediationSources:Tm({directoryState:l,normalizedSettingsReadWarnings:o,settingWarnings:u,telemetryCheck:m,extensionCheck:_,historySummary:S,authorAttributionWarnings:q,staleInProgressWarnings:D.warnings,locksCheck:j,integrityCheck:Y,historyDriftCheck:ce,vectorizationCheck:T}),historyDriftedCount:vm(ce),overThresholdCount:S.over_threshold.length});let Il={ok:js.filter(tn=>!la(tn,t.requireMergeDrivers===!0)).length===0,checks:B,warnings:js,generated_at:k()};return wa(Il,t,p.summaryMode)}var tk={buildExtensionHealthTriageSummary:_a,buildCapabilityContractMetadata:In,buildStaleInProgressHealthSummary:ba,buildVectorizationProviderDetails:ha,collectUnknownCapabilityGuidance:En,isAdvisoryHealthWarning:la,isDirectory:Un,isExpectedUnmanagedExtension:Fn,listItemDocumentPaths:ma,normalizeEndpointForDisplay:Ot,normalizeExtensionNameForMatch:Oe,parseTelemetryQueue:fa,probeTelemetryEndpointHealth:ga,projectHealthResult:wa,resolveActionableUnknownAuthorEventCount:qn,resolveHealthSkipPolicy:ya,resolveUnknownAuthorEventCount:Gn,selectStaleItemDetail:$n,summarizeHealthCheckDetails:pa,summarizeExtensionList:Rt,summarizeRecordList:ie,summarizeStringList:L,telemetryEnvFlagEnabled:Re,warningCode:ua};import Ne from"node:fs/promises";import Le from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function Cm(e,t){let n=[...new Set(Object.values(t))],s=[];return await Promise.all(n.map(async i=>{let r;try{r=await Ne.readdir(Le.join(e,i))}catch{return}for(let o of r)for(let a of ge)if(o.toLowerCase().endsWith(a)){s.push({relativePath:`${i}/${o}`,id:o.slice(0,-a.length)});break}})),s.sort((i,r)=>i.relativePath.localeCompare(r.relativePath))}function Em(e,t){let{id:n,relativePath:s,liveItemIds:i,out:r}=e,o=Ce(t);if(o){r.conflictMarkers.push({id:n,path:s,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=null,c=t.split(/\r?\n/).map((d,l)=>({content:d.trim(),number:l+1})).filter(d=>d.content.length>0);for(let d of c)try{let l=JSON.parse(d.content);if(typeof l!="object"||l===null||Array.isArray(l))throw new TypeError("history entry must be an object");a=l}catch{r.unparseable.push({id:n,path:s,line:d.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&i.has(n)&&r.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(r.repairReconciliations+=1))}function Bn(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function Im(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},s;try{s=await Ne.readdir(Le.join(e,"history"))}catch{return n}for(let i of s.sort((r,o)=>r.localeCompare(o))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let r;try{r=await Ne.readFile(Le.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Bn("history stream",o)});continue}Em({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},r)}return n}function ka(e){let t=Ce(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function Am(e){let t=[],n=0,s=null;try{s=await $(O(e))}catch(r){n+=1,t.push({path:"settings.json",detail:Bn("configuration file",r)})}if(s!==null){n+=1;let r=ka(s);r!==null&&t.push({path:"settings.json",detail:r})}let i;try{i=await Ne.readdir(Le.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let r of i.sort((o,a)=>o.localeCompare(a))){if(!r.endsWith(".json"))continue;n+=1;let o;try{o=await Ne.readFile(Le.join(e,"schema",r),"utf8")}catch(c){t.push({path:`schema/${r}`,detail:Bn("configuration file",c)});continue}let a=ka(o);a!==null&&t.push({path:`schema/${r}`,detail:a})}return{scanned:n,unparseable:t}}async function va(e,t,n,s={}){let i=await Cm(e,n),r=new Set(i.map(u=>u.id)),o=new Map;for(let u of i){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((_,p)=>_.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Le.join(e,u.relativePath);return gt(await Ne.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:s.schema,extensionFieldNames:s.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await Im(e,r),l=await Am(e);return{item_files_on_disk:i.length,item_ids_on_disk:r.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c4d45cf-6b97-5151-a325-db09d31962a7")}catch{}})();var Rm=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Wn=new Set(["--pm-path","--path","--author"]),Om={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},Nm=new Set(["-p","--package"]),Lm=new Set(["-c","--call"]),zn=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Hn=new Set(["-C","--prefix","--userconfig","--cache"]),Ta=new Set(["--cwd"]),xa=new Set(["--cwd"]),Pm=new Set(["exec","x"]),Sa=new Set(["run","run-script"]),Ca=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Pe(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function Nt(e){let t=Lt(e.split(" ").filter(r=>r.length>0));if(t.length===0)return null;let[n,...s]=t;if(Je(n)||Qe(n))return s;if(n==="node"&&s[0]&&Qe(s[0]))return s.slice(1);let i=n==="npx"||n==="bunx"?be(s):n==="pnpm"?Mt(s):n==="npm"?Dt(s):null;return i&&(Je(i.command)||Kn(i.command))?i.args:null}var Vn=(e,t="pm")=>{let n=t.trim().toLowerCase(),s=n.length;for(;s>0&&n[s-1]==="-";)s-=1;let i=n.slice(0,s);if(i.length===0)return[];let r=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of Pe(r)){let c=Nt(a),d=c?Yn(c):null,l=d&&Rm.has(d.subcommand)?Dm(d.remaining,Om[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&o.add(l)}return[...o].sort((a,c)=>a.localeCompare(c))};function Lt(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Pt(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Wn.has(n)){t+=2;continue}t+=1;continue}return n}}function Je(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function Mm(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let s=t.indexOf("@",n+1);return s===-1?t:t.slice(0,s)}function Kn(e){let t=Mm(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Qe(e){return e==="dist/cli.js"||e==="./dist/cli.js"||e.endsWith("/dist/cli.js")}function be(e){let t=0;for(;t<e.length;){let s=e[t];if(s==="--"){t+=1;break}if(!s.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(s);if(i){let r=i[1];return r?{command:r,args:e.slice(t+1)}:null}if(Lm.has(s)){t+=1;break}t+=Nm.has(s)&&!s.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function ue(e,t){let n=0;for(;n<e.length;){let s=e[n];if(s==="--"){n+=1;continue}if(s.startsWith("-")){if(s.includes("=")){n+=1;continue}if(t.has(s)){n+=2;continue}n+=1;continue}return{subcommand:s,args:e.slice(n+1)}}return null}function Mt(e){let t=ue(e,zn);return t?.subcommand!=="dlx"?null:be(t.args)}function Dt(e){let t=ue(e,Hn);return!t||!Pm.has(t.subcommand)?null:be(t.args)}function Yn(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Wn.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Dm(e,t=new Set){for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="--")return e[n+1];if(!s.startsWith("-"))return s;!s.includes("=")&&(Wn.has(s)||t.has(s))&&(n+=1)}}import ns from"node:fs/promises";import{realpathSync as Bm}from"node:fs";import{execFile as Wm}from"node:child_process";import H from"node:path";import{promisify as zm}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]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var Fm=["metadata","resolution"],Xn=["metadata","resolution","estimates","lifecycle"],jm="completed";function Jn(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Ea(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Ia(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let s=Ea(n.close_reason)??jm;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:s,command:`pm update ${n.id} --resolution ${Jn(s)}`,gate:"resolution"})}return t}function Aa(e){let t=[];for(let n of e){let s=Ea(n.resolution);s!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:s,command:`pm update ${n.id} --close-reason ${Jn(s)}`,gate:"metadata"})}return t}function Ra(e,t){return e.map(n=>{let s=Ii(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(s),command:`pm update ${n.id} --estimate ${s}`,gate:"estimates"}})}function Oa(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function Na(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let s=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${s} ${n.item_id} --remove ${Jn(n.path)}`})}return t}function La(e){let t=(e??[]).flatMap(s=>s.split(",")).map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new h(`--fix-scope values must not be empty. Supported values: ${Xn.join(", ")}.`,g.USAGE);return new Set(Fm)}let n=new Set;for(let s of t){let i=s.toLowerCase().replaceAll("-","_");if(Xn.includes(i)){n.add(i);continue}throw new h(`Unknown --fix-scope value "${s}". Supported values: ${Xn.join(", ")}.`,g.USAGE)}return n}function Pa(e,t){let n=[],s=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?s.push(i):n.push(i);return{applicable:n,gated:s}}function Ze(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var $m=/^([A-Z][A-Z0-9]*-\d+)\b/;function Um(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=$m.exec(t);return n?n[1]:null}function Ma(e){return typeof e=="string"&&e.trim().length>0}function Da(e){let t=new Map;for(let s of e){if(typeof s.title!="string"||Ma(s.duplicate_of))continue;let i=Um(s.title);if(i===null)continue;let r=t.get(i);r||(r=[],t.set(i,r)),r.some(o=>o.id===s.id)||r.push({id:s.id,title:s.title,parent:Ma(s.parent)?s.parent.trim():null})}let n=[];for(let[s,i]of t){if(i.length<2)continue;let r=new Set(i.map(c=>c.id.toLowerCase())),o=i.filter(c=>c.parent===null||!r.has(c.parent.toLowerCase()));if(o.length<2)continue;let a=[...o].sort((c,d)=>c.id.localeCompare(d.id));n.push({code:s,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return n.sort((s,i)=>s.code.localeCompare(i.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function Fa(e){let t=new Map;for(let s of e){let i=t.get(s.item_type);i||(i=new Map,t.set(s.item_type,i)),i.set(s.field,(i.get(s.field)??0)+1)}let n={};for(let s of[...t.keys()].sort((i,r)=>i.localeCompare(r))){let i=t.get(s),r={};for(let o of[...i.keys()].sort((a,c)=>a.localeCompare(c)))r[o]=i.get(o);n[s]=r}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]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var ja=3;function $a(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Ua(e,t,n=ja){let s=Number.isFinite(n)&&n>=1?Math.floor(n):ja,i=new Map;for(let r of t){let o=$a(r);if(o.length===0)continue;let a=i.get(o);a?a.push(r):i.set(o,[r])}return e.map(r=>{let o=(i.get($a(r))??[]).filter(a=>a!==r).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:r,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:r,classification:"moved",candidates:o.slice(0,s),candidates_truncated:o.length>s}})}function Ga(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function Gm(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function qa(e){return`${e.item_id} ${e.link_kind}`}function Ba(e,t){let n=new Map;for(let s of e){let i=n.get(s.path);i?(i.classification=Gm(i.classification,s.classification),i.owners.set(qa(s),s)):n.set(s.path,{classification:s.classification,owners:new Map([[qa(s),s]])})}return[...n.entries()].sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>({path:s,classification:i.classification,items:[...i.owners.values()].map(r=>{let o=t(r.item_id);return{id:r.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:r.link_kind}}).sort((r,o)=>{let a=r.id.localeCompare(o.id);return a!==0?a:r.field.localeCompare(o.field)})}))}function qm(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Wa(e){let t=[];for(let n of e)for(let s of n.items)t.push(`${n.path}:${n.classification} owner=${s.id} status=${s.status} field=${s.field} title="${qm(s.title)}"`);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]="f8048210-9e9f-585b-b0df-a34eca521cc3")}catch{}})();var Hm=["src","tests","docs"],Vm=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],Km=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),Ym=["resolution","expected_result","actual_result"],Xm=["default","tracked-all","tracked-all-strict"],za=["core","strict","custom"],jt=["off","warn","error"];var Zn=["author","acceptance_criteria","estimated_minutes","close_reason"],Xa=[...Zn,"reviewer","risk","confidence","sprint","release"],ss=Array.from(new Set(Xa)),Jm={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"},Qm={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},Zm={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},e_={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},t_={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},n_=32*1024*1024,s_=1e4,Ja=40,ae=5,i_=4096,r_=255,o_=zm(Wm);function Qa(e){let t={};for(let[n,s]of Object.entries(e))Array.isArray(s)||(t[n]=typeof s=="object"&&s!==null?Qa(s):s);return t}function a_(e){return{...e,checks:e.checks.map(t=>({...t,details:Qa(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function we(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Ha(e){return we(e).replace(/\/+$/,"")}function J(e){let t=P(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Ut(e,t){return ft(e,t)??e}function et(e,t){return t.terminal_statuses.has(Ut(e,t))}function me(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ft(e,t){return e.length!==t.length?!1:e.every((n,s)=>n===t[s])}function c_(e){let t=me(Bs),n={blocked_reason:me(ct.blocked_reason),resolution:me(ct.resolution),actual_result:me(ct.actual_result)},s=me(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:me(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:me(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:me(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:s,stale_blocker_reason_pattern_source:Ft(s,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Ft(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Ft(i.resolution,n.resolution)?"default":"settings",actual_result:Ft(i.actual_result,n.actual_result)?"default":"settings"}}}function Za(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(za.includes(t))return t;throw new h(`Unknown --metadata-profile value "${e}". Supported values: ${za.join(", ")}.`,g.USAGE)}function ec(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(jt.includes(t))return t;throw new h(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${jt.join(", ")}.`,g.USAGE)}function tc(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(jt.includes(t))return t;throw new h(`Unknown --parent-cycle-severity value "${e}". Supported values: ${jt.join(", ")}.`,g.USAGE)}function d_(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>Jm[n]).filter(n=>n!==void 0).sort((n,s)=>n.localeCompare(s))}function l_(e,t,n){let s=d_(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Zn],configured_custom_fields:s,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Xa],configured_custom_fields:s,fallback_to_core:!1,warnings:[]}:s.length>0?{profile:e,profile_source:t,required_fields:s,configured_custom_fields:s,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Zn],configured_custom_fields:s,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var u_=new Set(["acceptance_criteria","estimated_minutes"]);function nc(e,t,n,s){return!s&&u_.has(t)&&et(e.status,n)?!1:t==="author"?!P(e.author):t==="acceptance_criteria"?!P(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ut(e.status,n)===n.close_status&&!P(e.close_reason):t==="reviewer"?!P(e.reviewer):t==="risk"?!P(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!P(e.confidence):t==="sprint"?!P(e.sprint):!P(e.release)}function sc(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new h(`Unknown --scan-mode value "${e}". Supported values: ${Xm.join(", ")}.`,g.USAGE)}function ic(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return H.resolve(t);let n=H.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return H.dirname(H.dirname(n));let i=H.resolve(process.cwd()),r=Va(n),o=Va(i),a=H.relative(r,o);return a.length===0||!a.startsWith("..")&&!H.isAbsolute(a)?n:i}function Va(e){try{return Bm.native(e)}catch{return H.resolve(e)}}function rc(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function is(e,t,n){let s=t.length>0?H.join(e,t):e,i;try{i=await ns.readdir(s,{withFileTypes:!0})}catch(r){if(rc(r,["ENOENT"]))return;throw r}for(let r of i){if(r.name.startsWith("."))continue;let o=t.length>0?H.join(t,r.name):r.name;if(r.isDirectory()){if(Km.has(r.name))continue;await is(e,o,n);continue}r.isFile()&&n.push(we(o))}}async function es(e){let t=[];for(let n of Hm)await is(e,n,t);for(let n of Vm){let s=H.join(e,n);try{(await ns.stat(s)).isFile()&&t.push(we(n))}catch{}}return[...new Set(t)].sort((n,s)=>n.localeCompare(s))}async function oc(e){try{let{stdout:t}=await o_("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:n_,windowsHide:!0,timeout:s_}),n=t.split("\0").map(s=>we(s)).filter(s=>s.length>0);return[...new Set(n)].sort((s,i)=>s.localeCompare(i))}catch{return null}}function m_(e,t){let n=new Set,s=Ha(Us);s.length>0&&n.add(s);let i=Ha(H.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((r,o)=>r.localeCompare(o))}function Ka(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function __(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let s=await oc(e);if(s)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:s,candidateTotal:s.length,candidateScanned:s.length};let i=await es(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await es(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function M(e,t=ae){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function _e(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=M(e,Ja);return{values:n.values,truncated:n.truncated,total:e.length}}var p_={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},f_={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function g_(e){let t=e.missing_fields.map(n=>`${p_[n]} "${f_[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function ac(e,t){let n=e.details?.missing_resolution_remediation_hints,s=Array.isArray(n)&&n.length>0,i=s?n.filter(o=>typeof o=="string"):ra(t);if(i.length===0)return;let r=s&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...r?{fix_hints_truncated:!0}:{}}}function cc(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var h_="validate_metadata_duplicate_issue_codes";function dc(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:ae,s=e.slice(0,n);return{rows:s.map(r=>({code:r.code,count:r.count,ids:r.ids,titles:r.titles,remediation_hint:`Items ${r.ids.join(", ")} share issue code "${r.code}"; rename or merge so each logical code maps to one item.`})),truncated:s.length<e.length,warnings:[`${h_}:${e.length}`]}}function y_(){return Object.fromEntries(ss.map(e=>[e,[]]))}function b_(e,t,n){let s=y_();for(let i of e)for(let r of ss)nc(i,r,t,n)&&s[r].push(i.id);return s}function w_(e,t,n){let s=[...e.warnings];for(let i of e.required_fields){let r=t[i];r.length>0&&s.push(`${Qm[i]}:${r.length}`)}return s.push(...n),s}function lc(e,t){let n={};for(let s of e.required_fields){let i=t[s],r=i?i.length:0,o=Zm[s];r>0&&o&&(n[o]=r)}return n}function uc(e,t,n){let s=[];for(let i of e.required_fields){let r=t[i];if(r)for(let o of r){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";s.push({item_type:c,field:i})}}return s}function k_(e,t,n,s){for(let i of t.required_fields){let r=n[i];if(!r||r.length===0)continue;let o=e_[i],a=t_[i];if(!o||!a)continue;let c=M(r,s?r.length:ae);e[o]=c.values,e[a]=c.truncated}}function mc(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let s=t.close_reason;return s?s.map(i=>({id:i,resolution:P(n.get(i)?.resolution)})):[]}function _c(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let s=t.estimated_minutes;return s?s.map(i=>({id:i,type:P(n.get(i)?.type)})):[]}function v_(e,t,n,s){let i=new Map(e.map(y=>[y.id,y])),r=t.profile==="strict",o=b_(e,n,r),a=Da(e),c=dc(a,s),d=w_(t,o,c.warnings),l=lc(t,o),u=uc(t,o,i),m=Fa(u),_={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...ss],counts:l,missing_by_type:m,duplicate_issue_codes_count:a.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(_.configured_custom_required_fields=[...t.configured_custom_fields]),k_(_,t,o,s);let p=mc(t,o,i),f=_c(t,o,i);return{check:{name:"metadata",status:d.length===0?"ok":"warn",details:_},warnings:d,closeReasonBackfillRows:p,estimateBackfillRows:f}}function T_(e,t,n){let s=new Set(t.terminal_done_statuses);s.add(t.close_status);let i=e.filter(m=>s.has(Ut(m.status,t))),r=[],o=[];for(let m of i){let _=Ym.filter(p=>!P(m[p]));_.length!==0&&(r.push({id:m.id,missing_fields:_}),o.push({id:m.id,missing_fields:_,close_reason:P(m.close_reason)}))}let a=r.length>0?[`validate_resolution_missing_fields:${r.length}`]:[],c=n?Number.POSITIVE_INFINITY:ae,d=M(r.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=r.map(m=>g_(m)),u=M(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",details:{checked_closed_items:i.length,missing_resolution_items:r.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function pc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fc(e,t="pm",n=on()){let s=new Set(e.map(r=>r.id)),i=[...e].sort((r,o)=>r.id.localeCompare(o.id));return new Map(i.map(r=>{let o=new Set,a=J(r.blocked_by);a&&s.has(a)&&o.add(a),(r.dependencies??[]).filter(d=>{let l=J(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>J(d.id)).filter(d=>d!==void 0&&s.has(d)).forEach(d=>o.add(d));let c=J(r.definition_of_ready);return hc(c??"",t).filter(d=>s.has(d)).forEach(d=>o.add(d)),[r.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function gc(e,t,n){let s=Ao(e,n?l=>et(l,n):void 0),i=s.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),r=s.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:ae,a=M(i,o),c=M(r,o),d=M(s.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",details:{checked_items:e.length,dangling_reference_count:i.length+r.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:r.length,legacy_closed_dangling_reference_count:s.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:s.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function hc(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),s=new RegExp(`(?:^|[^a-z0-9-])(${pc(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(s)].map(i=>i[1].toLowerCase()))].sort((i,r)=>i.localeCompare(r))}function rs(e){let t=0,n=new Map,s=new Map,i=[],r=new Set,o=[],a=l=>{n.set(l,t),s.set(l,t),t+=1,i.push(l),r.add(l);for(let m of e.get(l)??[])n.has(m)?r.has(m)&&s.set(l,Math.min(s.get(l),n.get(m))):(a(m),s.set(l,Math.min(s.get(l),s.get(m))));if(s.get(l)!==n.get(l))return;let u=[];for(;i.length>0;){let m=i.pop();if(r.delete(m),u.push(m),m===l)break}u.sort((m,_)=>m.localeCompare(_)),o.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return o.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function os(e,t){let n=e[0];if(e.length===1)return[n,n];let s=new Set(e),i=[n],r=new Set([n]),o=a=>{let c=(t.get(a)??[]).filter(d=>s.has(d));for(let d of c){if(d===n&&i.length>1)return i.push(n),!0;if(!r.has(d)){if(r.add(d),i.push(d),o(d))return!0;i.pop(),r.delete(d)}}return!1};return o(n)?[...i]:[...e,n]}function yc(e,t="pm"){let n=fc(e,t),s=rs(n),i=[...new Set(s.flat())].sort((o,a)=>o.localeCompare(a)),r=s.map(o=>os(o,n).join("->"));return{cycle_count:s.length,cycle_item_ids:i,cycle_sample_paths:r}}function bc(e,t=on()){let n=new Map(e.map(r=>[r.id.toLowerCase(),r.id])),s=new Map(e.map(r=>[r.id,[]]));return[...e].sort((r,o)=>r.id.localeCompare(o.id)).forEach(r=>{let o=s.get(r.id),a=J(r.parent),c=a?n.get(a.toLowerCase()):void 0;c&&o.push(c),(r.dependencies??[]).forEach(d=>{let l=t.resolve(d.kind);if(!l?.hierarchy)return;let u=n.get(d.id.toLowerCase());u&&(l.hierarchyDirection==="source_parent"?s.get(u).push(r.id):o.push(u))})}),s.forEach((r,o)=>{s.set(o,[...new Set(r)].sort((a,c)=>a.localeCompare(c)))}),s}function wc(e){let t=bc(e),n=rs(t),s=[...new Set(n.flat())].sort((r,o)=>r.localeCompare(o)),i=n.map(r=>os(r,t).join("->"));return{cycle_count:n.length,cycle_item_ids:s,cycle_sample_paths:i}}function kc(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function $t(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function vc(e,t){let n=$t(e).split("/").filter(Boolean),s=$t(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<s.length&&n[i]===s[i];)i+=1;return i}function x_(e,t){let n=$t(t),s=$t(e),i=t.endsWith("/")?t:`${t}/`,r=e.startsWith(i),o=n.length>0&&n===s,a=vc(e,t);return!r&&!o&&a===0?null:r?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function S_(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function C_(e,t,n){let s=t==="docs_unowned"?"docs":"files",i;return n.flatMap(r=>(s==="docs"?r.docs??[]:r.files??[]).map(o=>({item:r,link:o}))).forEach(({item:r,link:o})=>{if(o.scope!=="project")return;let a=we(o.path);if(a.length===0||a===e)return;let c=x_(e,a);c!==null&&S_(i,r,c.score)&&(i={item:r,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function Tc(e,t){return e.map(n=>{let s=kc(n),i=s==="docs_unowned"?"docs":"files",r=C_(n,s,t),o=r?.id??"<id>";return{path:n,classification:s,owner_candidate:r,remediation_hint:`pm ${i} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function xc(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function E_(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,s])=>{let i=J(e[n]);return i?s.some(r=>i.toLowerCase().includes(r)):!1}).map(([n])=>n).sort((n,s)=>n.localeCompare(s))}function I_(e,t,n,s,i){let r=J(t.parent),o=r?n.get(s.get(r.toLowerCase())??r):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!et(o.status,i)}}function A_(e,t,n,s){let i=J(e.blocked_by),r=J(e.blocked_reason),o=r?.toLowerCase(),a=Ut(e.status,n),c=[];return t.has(a)?(!i&&!r&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&s.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),r&&c.push("non_blocked_status_has_blocked_reason"),c)}function R_(e,t,n,s){let i=new Map(e.map(c=>[c.id,c])),r=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!et(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=E_(c,s);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=J(c.parent),u=l?i.get(r.get(l.toLowerCase())??l):void 0;if(u&&et(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(I_(c,u,i,r,n))),t){let m=A_(c,o,n,s);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((_,p)=>_.localeCompare(p))})}}return a}function O_(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function Ya(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function N_(e,t,n,s,i,r){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=Ya("validate_lifecycle_dependency_cycles",n,i),c=Ya("validate_hierarchy_parent_cycle",s,r);return[...o,...a?[a]:[],...c?[c]:[]]}function Sc(e){let t=we(e);return t.length>i_||t.split(/[\\/]/).some(n=>n.length>r_)}async function L_(e,t){let n=H.isAbsolute(t)?t:H.resolve(e,t);if(Sc(n))return!1;try{let s=await ns.stat(n);return!s.isFile()&&!s.isDirectory()}catch(s){return rc(s,["ENOENT","ENOTDIR"])}}async function P_(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},s=e.flatMap(i=>[...(i.files??[]).map(r=>({item:i,artifact:r,link_kind:"files"})),...(i.docs??[]).map(r=>({item:i,artifact:r,link_kind:"docs"}))]);for(let{item:i,artifact:r,link_kind:o}of s){if(r.scope!=="project")continue;if(qo(r.path)){n.remoteLinkedPaths.add(r.path.trim());continue}let a=we(r.path);a.length!==0&&(n.linkedProjectPaths.add(a),await L_(t,r.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:o})))}return n}function M_(e,t,n,s,i,r){let o=s==="tracked-all-strict",a=o&&!i,c=i||o,d=c?[]:m_(t,n),l=d.length===0?[]:e.candidateFiles.filter(_=>Ka(_,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(_=>!Ka(_,d)),m={};if(l.length>0){let _=_e(l,r);m.pm_internals={count:l.length,paths:_.values,paths_truncated:_.truncated,paths_total:_.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function Cc(e,t,n,s,i,r,o,a="pm"){let c=R_(e,t,i,r);O_(c);let d=yc(c.activeItems,a),l=wc(e),u=N_(c,t,n,s,d.cycle_count,l.cycle_count),m=o?Number.POSITIVE_INFINITY:ae,_=M(c.closureLikeRows.map(w=>`${w.id}:${w.fields.join(",")}`),m),p=M(c.terminalParentRows.map(w=>`${w.id}:${w.parent_id}:${w.parent_status}`),m),f=M(c.staleBlockerRows.map(w=>`${w.id}:${w.status}:${w.reasons.join(",")}`),m),y=M(d.cycle_item_ids,m),b=M(d.cycle_sample_paths,m),v=M(l.cycle_item_ids,m),E=M(l.cycle_sample_paths,m);return{check:{name:"lifecycle",status:d.cycle_count>0&&n==="error"||l.cycle_count>0&&s==="error"?"error":u.length===0?"ok":"warn",details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:_.values,active_closure_like_metadata_rows_truncated:_.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:p.values,active_terminal_parent_rows_truncated:p.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:f.values,stale_blocker_rows_truncated:f.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:y.values,dependency_cycle_item_ids_truncated:y.truncated,dependency_cycle_sample_paths:b.values,dependency_cycle_sample_paths_truncated:b.truncated,parent_cycle_severity_policy:s,parent_cycle_count:l.cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:v.values,parent_cycle_item_ids_truncated:v.truncated,parent_cycle_sample_paths:E.values,parent_cycle_sample_paths_truncated:E.truncated,stale_blocker_reason_patterns:[...r.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:r.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...r.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:r.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...r.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:r.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...r.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:r.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function Ec(e,t,n,s,i,r){let o=await P_(e,t),a=new Map(e.map(T=>[T.id,T])),c=[...new Set(o.missingLinkedPaths)].sort((T,B)=>T.localeCompare(B)),d=await __(t,s),l=M_(d,n,t,s,i,r),u=l.candidateFiles.filter(T=>!o.linkedProjectPaths.has(T)),m=Tc(u,e),_=Ua(c,l.candidateFiles),p=new Map(_.map(T=>[T.path,T.classification])),f=_.filter(T=>T.classification==="moved").length,y=o.staleLinkRows.map(T=>({...T,classification:p.get(T.path)??"deleted"})).sort((T,B)=>T.item_id.localeCompare(B.item_id)||T.path.localeCompare(B.path)||T.link_kind.localeCompare(B.link_kind)),b=[];l.strictModeForcesPmInternals&&b.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&b.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&b.push(`validate_files_orphaned_paths:${u.length}`);let v=[...o.remoteLinkedPaths].sort((T,B)=>T.localeCompare(B)),E=_e(v,r),S=_e(c,r),w=_e(u,r),A=_e(m.map(T=>`${T.path}:${T.classification}:owner_candidate=${T.owner_candidate?.id??"unowned"}`),r),q=r?m:_e(xc(m),!1).values,D=_e(Ga(_),r),j=y.map(T=>({item_id:T.item_id,path:T.path,link_kind:T.link_kind,classification:T.classification})),Y=Ba(j,T=>{let B=a.get(T);return B?{type:B.type,title:B.title,status:B.status}:void 0}),ce=r?Y:_e(Wa(Y),!1).values;return{check:{name:"files",status:b.length===0?"ok":"warn",details:{workspace_root:t,scan_mode_requested:d.requestedMode,scan_mode_applied:d.appliedMode,strict_tracked_all_mode:l.strictTrackedAllMode,strict_mode_forces_pm_internals:l.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:l.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:r?"full":"summary",file_list_summary_limit:Ja,candidate_scan_source:d.source,include_pm_internals:l.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:l.pmInternalCandidatePrefixes,pm_internal_excluded_count:l.excludedPmInternalPaths.length,excluded_total:l.excludedPmInternalPaths.length,excluded_by_reason:l.excludedByReason,linked_project_paths:o.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:E.total,remote_linked_paths:E.values,remote_linked_paths_truncated:E.truncated,candidate_total_raw:d.candidateTotal,candidate_scanned_raw:d.candidateScanned,candidate_total:l.candidateFiles.length,candidate_scanned:l.candidateFiles.length,scanned_candidate_files:l.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:S.total,missing_linked_paths:S.values,missing_linked_paths_truncated:S.truncated,missing_linked_paths_moved_count:f,missing_linked_paths_deleted_count:c.length-f,missing_linked_path_classifications:D.values,missing_linked_path_classifications_truncated:D.truncated,missing_linked_path_rows_count:Y.length,missing_linked_path_rows:ce,orphaned_paths_count:u.length,orphaned_paths_total:w.total,orphaned_paths:w.values,orphaned_paths_truncated:w.truncated,orphaned_path_classifications:A.values,orphaned_path_classifications_truncated:A.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:q}},warnings:b,staleLinkPruneRows:y}}async function D_(e,t,n){let{missingStreams:s,unreadableStreams:i,hashMismatches:r,chainMismatches:o,driftedItems:a}=await vt(e,t),c=[];s.length>0&&c.push(`validate_history_drift_missing_streams:${s.length}`),i.length>0&&c.push(`validate_history_drift_unreadable_streams:${i.length}`),r.length>0&&c.push(`validate_history_drift_hash_mismatches:${r.length}`),o.length>0&&c.push(`validate_history_drift_chain_mismatches:${o.length}`);let d=n?Number.POSITIVE_INFINITY:ae,l=M(a,d);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,drifted_items_count:a.length,drifted_items:l.values,drifted_items_truncated:l.truncated,counts:{missing_streams:s.length,unreadable_streams:i.length,hash_mismatches:r.length,chain_mismatches:o.length}}},warnings:c}}function F_(e,t,n){let s=n.trim().replaceAll(/\s+/g," "),i=s.length>120?`${s.slice(0,117)}...`:s;return`${e}:${t}:${i}`}function Ic(e,t,n){let s=new Set(e.map(y=>y.id.toLowerCase())),i=0,r=0,o=new Set,a=[],c=e.flatMap(y=>(y.tests??[]).map(b=>({item:y,linkedTest:b})));for(let{item:y,linkedTest:b}of c){if(typeof b.command!="string"||b.command.trim().length===0)continue;i+=1;let v=Vn(b.command,t);if(v.length!==0){r+=v.length;for(let E of v)o.add(E),s.has(E.toLowerCase())||a.push(F_(y.id,E,b.command))}}let d=[...new Set(a)].sort((y,b)=>y.localeCompare(b)),l=[...new Set(d.map(y=>y.split(":")[1]??""))].filter(y=>y.length>0).sort((y,b)=>y.localeCompare(b)),u=d.length>0?[`validate_command_references_stale_pm_ids:${d.length}`]:[],m=n?Number.POSITIVE_INFINITY:ae,_=M(d,m),p=M(l,m),f=M([...o].sort((y,b)=>y.localeCompare(b)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",details:{checked_items:e.length,linked_commands_scanned:i,referenced_pm_ids_count:r,unique_referenced_pm_ids_count:o.size,unique_referenced_pm_ids:f.values,unique_referenced_pm_ids_truncated:f.truncated,stale_pm_id_references_count:d.length,stale_pm_ids_count:l.length,stale_pm_ids:p.values,stale_pm_ids_truncated:p.truncated,stale_pm_id_reference_rows:_.values,stale_pm_id_reference_rows_truncated:_.truncated}},warnings:u}}function j_(e,t){let n=pt(e.map(c=>({ref:c.id,version:_t(c)}))),s=[];n.outdated.length>0&&s.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&s.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:ae,r=M(n.outdated,i),o=M(n.ahead,i);return{check:{name:"format_version",status:n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok",details:{checked_items:e.length,current_format_version:ui,outdated_items_count:n.outdated.length,outdated_items:r.values,outdated_items_truncated:r.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:s}}var ts="pm validate auto-fix";async function Ac(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let s={message:ts};if(e.kind==="set_resolution"?s.resolution=e.value:e.kind==="set_close_reason"?s.closeReason=e.value:e.kind==="set_estimate"?s.estimatedMinutes=e.value:e.kind==="reparent"?s.parent=e.parent_id:s.unset=["parent"],!n.runUpdate)throw new h("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.USAGE);await n.runUpdate(e.item_id,s,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Qn(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Rc(e,t,n){let s=[],i=[],r=new Map;for(let o of e.filter(a=>Qn(a)===null))try{await Ac(o,t,n),s.push(o)}catch(a){i.push({fix:o,error:a})}for(let o of e.filter(a=>Qn(a)!==null)){let a=Qn(o),c=r.get(a);c?c.push(o):r.set(a,[o])}for(let o of r.values()){let a=o[0];if(!a)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await Wo(a.item_id,{remove:c,message:ts},t):await Bo(a.item_id,{remove:c,message:ts},t),s.push(...o)}catch(d){i.push(...o.map(l=>({fix:l,error:d})))}}return{applied:s,failed:i}}var sv={applyValidateFix:Ac,applyValidateFixes:Rc,attachValidateFixHints:ac,buildCommandReferencesCheck:Ic,buildDependencyReferencesCheck:gc,buildCloseReasonBackfillRows:mc,buildFilesCheck:Ec,buildLifecycleCheck:Cc,buildLifecycleDependencyGraph:fc,buildLifecycleParentGraph:bc,buildEstimateBackfillRows:_c,buildMetadataCounts:lc,buildMissingFieldOccurrences:uc,buildOrphanedPathRows:Tc,classifyOrphanedPath:kc,collectDefaultProjectFileCandidates:es,collectTrackedGitFileCandidates:oc,detectLifecycleDependencyCycles:yc,detectLifecycleParentCycles:wc,escapeRegExp:pc,extractItemIds:hc,findLifecycleDependencyCycleComponents:rs,isMetadataFieldMissing:nc,linkedArtifactPathExceedsFilesystemLimits:Sc,listFilesRecursive:is,resolveDependencyCycleSeverity:ec,resolveParentCycleSeverity:tc,resolveFileScanMode:sc,resolveLifecycleDependencyCycleSamplePath:os,resolveRequestedChecks:cc,resolveValidateMetadataProfile:Za,resolveWorkspaceRoot:ic,sharedDirectoryPrefixLength:vc,summarizeOrphanedPathRows:xc,summarizeDuplicateIssueCodes:dc,toMeaningfulString:J};async function $_(e,t,n,s){let i=await va(e,new Set(t.map(m=>m.id)),n,{schema:s.schema,extensionFieldNames:mt(W())}),r=[];i.unreadable_item_files.length>0&&r.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&r.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&r.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&r.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&r.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&r.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let o=r.length,a=await At(e);a.tracked_path_count>0&&r.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Uo(e,$o(s));c.status==="drift"&&r.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Ie(e),l=d===null?null:await kt(d);l!==null&&l.status!=="ok"&&r.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=d===null?[]:await Ye(d);return u.length>0&&r.push(`validate_merge_decisions_unreviewed:${u.length}`),{check:{name:"storage_integrity",status:o>0?"error":r.length>0?"warn":"ok",details:{...i,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:u.length,pending_merge_decision_items:[...new Set(u.map(m=>m.item_id))].sort((m,_)=>m.localeCompare(_)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:r}}function oe(e,t,n){n&&ac(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function U_(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,s=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let i=v_(e.items,e.metadataPolicy,e.statusRegistry,s);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,oe(t,i,n)}if(e.requestedChecks.has("resolution")){let i=T_(e.items,e.statusRegistry,s);t.resolutionBackfillRows=i.resolutionBackfillRows,oe(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=Cc(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,s,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,oe(t,i,n),oe(t,gc(e.items,s,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await Ec(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=i.staleLinkPruneRows,oe(t,i,n)}return e.requestedChecks.has("command_references")&&oe(t,Ic(e.items,e.settings.id_prefix,s),n),e.requestedChecks.has("history_drift")&&oe(t,await D_(e.pmRoot,e.items,s),n),e.requestedChecks.has("format_version")&&oe(t,j_(e.items,s),n),e.requestedChecks.has("storage_integrity")&&oe(t,await $_(e.pmRoot,e.items,V(e.settings,W()).type_to_folder,e.settings),n),t}function G_(e,t,n){let s=[];return e.autoFix===!0&&(s.push(...Aa(t.closeReasonBackfillRows)),s.push(...Ia(t.resolutionBackfillRows)),s.push(...Ra(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),s.push(...Oa(t.terminalParentFixRows))),e.pruneMissing===!0&&s.push(...Na(t.staleLinkPruneRows)),s}async function q_(e,t,n,s,i,r){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=G_(e,t,n),{applicable:a,gated:c}=Pa(o,s),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await Rc(a,i,r);l.push(...m.applied.map(Ze)),u.push(...m.failed.map(({fix:_,error:p})=>({...Ze(_),error:p instanceof Error?p.message:String(p)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...s].sort((m,_)=>m.localeCompare(_)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(Ze),applied_fixes:l,gated_fixes:c.map(m=>({...Ze(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function iv(e,t,n={}){fi(e.counts===!0,e.full===!0,"--counts");let s=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!s)throw new h("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new h("--fix-scope requires --auto-fix.",g.USAGE);let i=La(e.fixScope),r=R(process.cwd(),t.path);if(!await x(O(r)))throw new h(`Tracker is not initialized at ${r}. Run pm init first.`,g.NOT_FOUND);let o=await N(r),a=Z(o.schema),c=V(o,W()),d=[],l=await Ee(r,o.item_format,c.type_to_folder,d,o.schema),u=cc(e);if(u.has("history_drift")){let j=await Ve(r);j.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${j.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",_=Za(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),p=l_(_,m,o.validation.metadata_required_fields),f=c_(o),y=ec(e.dependencyCycleSeverity),b=tc(e.parentCycleSeverity),v=sc(e.scanMode),E=ic(r),S=await U_({requestedChecks:u,options:e,global:t,pmRoot:r,workspaceRoot:E,settings:o,items:l,statusRegistry:a,metadataPolicy:p,lifecyclePatternPolicy:f,dependencyCycleSeverity:y,parentCycleSeverity:b,fileScanMode:v,initialWarnings:[...new Set(d)]}),w=s?await q_(e,S,o,i,t,n):void 0,A=[...new Set(S.warnings)].sort((j,Y)=>j.localeCompare(Y)),D={ok:!S.checks.some(j=>j.status==="error"),has_warnings:A.length>0,checks:S.checks,warnings:A,...w!==void 0?{fixes:w}:{},generated_at:k(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?D:{...a_(D),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32223457-5f57-5049-99cf-c5d766413fb6")}catch{}})();var B_="1h",W_="now",z_="+1d";function pe(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Oc(e,t,n){return{type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message}}async function Nc(e,t,n,s){let i=Oc(e,t,n),r=[];return pe(r,"start",n.start??W_),n.end!==void 0?pe(r,"end",n.end):pe(r,"duration",n.duration??B_),pe(r,"location",n.location),pe(r,"timezone",n.timezone),n.allDay===!0&&pe(r,"all_day","true"),i.event=[r.join(",")],Sn(i,s)}function av(e,t,n){return Nc("Meeting",e,t,n)}function cv(e,t,n){return Nc("Event",e,t,n)}function dv(e,t,n){let s=Oc("Reminder",e,t),i=[];return pe(i,"at",t.at??z_),pe(i,"text",t.text??e),s.reminder=[i.join(",")],Sn(s,n)}import nt from"node:crypto";import{cp as Lc,lstat as H_,mkdir as ke,readFile as Me,readdir as as,rename as Dc,rm as ds,writeFile as Gt}from"node:fs/promises";import C 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]="3e32be7c-f8a4-547d-8c19-456b4567982e")}catch{}})();var Fc="https://schema.unbrained.dev/pm/workspace-snapshot/v1",jc=C.join("runtime","workspace-snapshots"),V_=new Set(["checkpoints","locks","runtime","search","transactions"]),K_=/^[a-z0-9][a-z0-9._-]*$/,tt="sdk-workspace-transaction",$c={renameEntry:Dc,removeEntry:async e=>{await ds(e,{recursive:!0,force:!0})}},cs=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,s){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(s*1e3/3))}start(){this.timer=setInterval(()=>{this.refresh===void 0&&(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))},this.intervalMs),this.timer.unref()}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()}async renew(){let t=JSON.parse(await Me(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!==tt||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await se(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
5
- `)}};async function Uc(e,t=""){let n=await as(C.join(e,t),{withFileTypes:!0}),s=[];for(let i of n.sort((r,o)=>r.name.localeCompare(o.name))){if(t.length===0&&V_.has(i.name))continue;let r=C.posix.join(t.replaceAll(C.sep,"/"),i.name);if(i.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${r}`);if(i.isDirectory())s.push(...await Uc(e,r));else if(i.isFile())s.push(r);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${r}`)}return s}async function Gc(e){let t=await Uc(e),n=nt.createHash("sha256"),s=[],i=0;for(let o of t){let a=await Me(C.join(e,o));s.push(a),i+=a.byteLength,n.update(o),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let r=n.digest("hex");return{manifest:{schema:Fc,fingerprint:r,files:t,bytes:i},contents:s}}function Pc(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
6
- `).filter(t=>t.trim().length>0).length}async function Y_(e,t){let n=new Map;for(let s=0;s<t.length;s+=32){let i=t.slice(s,s+32),r=await Promise.all(i.map(async o=>[o,await Me(C.join(e,o))]));for(let[o,a]of r)n.set(o,a)}return n}function ls(e){if(!K_.test(e))throw new h("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",g.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"}})}function qc(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function ve(e){return C.join(e,jc)}function Bc(e){return new h(`Unknown workspace snapshot: ${e}`,g.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 Wc(e,t){try{return JSON.parse(await Me(e,"utf8"))}catch(n){throw qc(n,"ENOENT")?Bc(t):n}}async function Mc(e,t,n){try{await ds(e,{recursive:n})}catch(s){throw qc(s,"ENOENT")?Bc(t):s}}async function X_(e,t,n=$c){try{return await n.renameEntry(e,t),!1}catch(s){if(!(s instanceof Error&&"code"in s&&(s.code==="EEXIST"||s.code==="ENOTEMPTY")))throw s;return await n.removeEntry(e),!0}}async function J_(e,t,n,s,i){await s.renameEntry(t,n);try{await s.renameEntry(e,t),await i?.()}catch(r){throw await s.renameEntry(n,t),await s.removeEntry(e),r}await s.removeEntry(n)}async function Q_(e,t){return ls(t),/^[a-f0-9]{64}$/.test(t)?t:(await Wc(C.join(ve(e),"refs",`${t}.json`),t)).fingerprint}async function Z_(e,t={}){if(t.name!==void 0&&(ls(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new h("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",g.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:s}=await Gc(e),i=ve(e),r=C.join(i,"objects",n.fingerprint),o=!1;try{o=(await H_(r)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="ENOENT"))throw a}if(!o){let a=C.join(i,"objects",`.create-${process.pid}-${nt.randomUUID()}`);await ke(C.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let l=C.join(a,"files",d);await ke(C.dirname(l),{recursive:!0}),await Gt(l,s[c])}await Gt(C.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
7
- `,"utf8"),await ke(C.dirname(r),{recursive:!0}),o=await X_(a,r)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=C.join(i,"refs");await ke(c,{recursive:!0});let d=C.join(c,`.ref-${process.pid}-${nt.randomUUID()}`);await Gt(d,`${JSON.stringify(a,null,2)}
8
- `,"utf8"),await Dc(d,C.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:o}}async function us(e,t){let n=await Q_(e,t),s=await Wc(C.join(ve(e),"objects",n,"manifest.json"),t);if(s.schema!==Fc||s.fingerprint!==n)throw new h(`Snapshot manifest identity mismatch: ${t}`,g.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 s}async function ep(e){let t=ve(e),n=await as(C.join(t,"objects")).catch(i=>{if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i}),s=await as(C.join(t,"refs")).catch(i=>{if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i});return{objects:await Promise.all(n.filter(i=>/^[a-f0-9]{64}$/.test(i)).sort().map(i=>us(e,i))),references:await Promise.all(s.filter(i=>i.endsWith(".json")).sort().map(async i=>JSON.parse(await Me(C.join(t,"refs",i),"utf8"))))}}async function tp(e,t){let n=await us(e,t),{manifest:s,contents:i}=await Gc(e),r=new Map(s.files.map((u,m)=>[u,i[m]])),o=await Y_(C.join(ve(e),"objects",n.fingerprint,"files"),n.files),a=new Set(s.files),c=new Set(n.files),d=new Set([...a,...c]);for(let u of d){let m=r.get(u),_=o.get(u);m!==void 0&&_!==void 0&&m.equals(_)&&d.delete(u)}let l=s.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let m=Pc(r.get(u)),_=Pc(o.get(u));return{path:u,current_entries:m,target_entries:_,removed_entries:Math.max(0,m-_)}}).filter(u=>u.removed_entries>0).sort((u,m)=>u.path.localeCompare(m.path));return{target_fingerprint:n.fingerprint,current_fingerprint:s.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!a.has(u)).length,removed_item_count:[...a].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:l.length,removed_history_entry_count:l.reduce((u,m)=>u+m.removed_entries,0),affected_history_streams:l,changes_authoritative_state:s.fingerprint!==n.fingerprint}}async function np(e,t,n={}){if(n.force!==!0)throw new h("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",g.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 s=n.author?.trim()||"pm-sdk",i=n.lockTtlSeconds??60,r=n.lockWaitMs??5e3,o=await Ci(e,tt,i,s,!1,!1,r),a=new cs(dt(e,tt),s,i);a.start();let c,d=!1,l=!1;try{let u=await tp(e,t),m=await us(e,t),_=await Z_(e),p=m.fingerprint,f=ve(e),y=C.join(f,"objects",p,"files"),b=C.dirname(e),v=C.basename(e);c=C.join(b,`.${v}.restore-${nt.randomUUID()}`);let E=C.join(b,`.${v}.backup-${nt.randomUUID()}`);await ke(c,{recursive:!0}),await Lc(y,c,{recursive:!0,force:!1}),await ke(C.join(c,"runtime"),{recursive:!0}),await Lc(f,C.join(c,jc),{recursive:!0,force:!1});let S=await yt({pmRoot:c,op:"workspace_snapshot_restore",author:s,message:n.message??`Restore workspace snapshot ${p}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:p,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:u.changed_file_count,removed_file_count:u.removed_file_count,removed_item_count:u.removed_item_count,affected_history_stream_count:u.affected_history_stream_count,removed_history_entry_count:u.removed_history_entry_count},lockTtlSeconds:i,lockWaitMs:r}),w=C.relative(c,S.historyPath).replaceAll("\\","/");await a.stop(),l=!0;let A=dt(c,tt);return await ke(C.dirname(A),{recursive:!0}),await Gt(A,await Me(dt(e,tt)),{flag:"wx"}),d=!0,await J_(c,e,E,$c,async()=>{a.start(),l=!1}),await a.stop(),l=!0,{manifest:m,plan:u,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:w,audit_operation:"workspace_snapshot_restore"}}catch(u){throw c!==void 0&&!d&&await Promise.allSettled([ds(c,{recursive:!0,force:!0})]),u}finally{try{l||await a.stop()}catch{}finally{await o()}}}async function wv(e,t){return(await np(e,t,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function kv(e,t){ls(t);let n=ve(e);if(!/^[a-f0-9]{64}$/.test(t))return await Mc(C.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:s}=await ep(e);if(s.some(i=>i.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Mc(C.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]="3b72f4a5-9e0b-5f8e-8ee9-e45cd83d6f92")}catch{}})();var sp=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),ip=new Set(["--add","--body","--comment","--dep","--description","--doc","--field","--file","--learning","--note","--remove","--test","--type-option"]),rp=new Set(["append","comments","create","docs","files","learnings","notes","test","update"]),op=["--allow-","--check-","--dry-run","--explain","--filter-","--full","--has-","--include-","--json","--no-","--only","--quiet","--require-","--runtime-only","--schema-only","--stream","--strict-","--summary","--today","--verbose"];function ap(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:t.endsWith("-file")?["argv","file"]:ip.has(t)&&rp.has(e)?["argv","stdin"]:["argv"]}function cp(e){let t=e.value_name!==void 0||e.value_type==="string"||e.value_type==="number"||e.list===!0||e.repeatable===!0,n=e.flag==="--stdin"||e.flag==="--stdin-json"||op.some(s=>e.flag.startsWith(s));return t||!n}function dp(e,t){let n=cp(t),s=ap(e,t.flag),i=t.description??sp[t.flag]??`${n?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:i,takes_value:n,value_required:n,...n?{value_name:t.value_name??"value"}:{},value_type:n?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:s,...s.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{}}}function zc(e,t){return t.map(n=>dp(e,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]="6fc2cd04-2fe4-5a0e-944d-fab0f86509e2")}catch{}})();var lp=new Set(["claim","close","context","create","get","help","list","next","plan","release","search","update","validate"]),up=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),ms=Object.freeze([...he.map(e=>({command:e,tier:lp.has(e)?"core":up.has(e)?"standard":"full"})),{command:"completion-statuses",tier:"internal"},{command:"completion-tags",tier:"internal"},{command:"completion-types",tier:"internal"},{command:"test-runs-worker",tier:"internal"}]),Hc={core:0,standard:1,full:2,internal:3},mp=new Map(ms.map(({command:e,tier:t})=>[e,t]));function Vc(e,t="standard"){return mp.get(e.trim().toLowerCase())??t}function _p(e){let t=Hc[e];return ms.filter(n=>n.tier!=="internal"&&Hc[n.tier]<=t).map(n=>n.command)}var pp=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function Sv(e,t){if(t==="full")return[...e];let n=new Set(_p(t));return e.filter(s=>{let i=pp[s];return i!==void 0&&n.has(i)})}var Cv=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),Ev=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function Iv(){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_VISIBILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier |","| --- | --- |",...ms.map(({command:t,tier:n})=>`| \`${t}\` | ${n} |`),""].join(`
9
- `)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="479dd590-7f54-54ae-bbaf-8f183fd6b6b4")}catch{}})();var fp=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],gp=new Map(fp.map(e=>[e.exit_code,e.class]));function Kc(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function Yc(e){let t=new Set,n=e.map(s=>{let i=s.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(i))throw new TypeError(`Invalid pm error code: ${JSON.stringify(s.code)}`);if(t.has(i))throw new TypeError(`Duplicate pm error code: ${i}`);t.add(i);let r=Kc(s.sources),o=Kc(s.emitting_commands);if(![1,2,3,4,5].includes(s.exit_code)||s.meaning.trim().length===0||s.recovery.trim().length===0||r.length===0||o.length===0||gp.get(s.exit_code)!==s.class)throw new TypeError(`Invalid pm error code contract: ${i}`);return Object.freeze({...s,code:i,meaning:s.meaning.trim(),recovery:s.recovery.trim(),sources:r,emitting_commands:o})});return Object.freeze(n.sort((s,i)=>s.code.localeCompare(i.code)))}function Rv(e,t){let n=e.trim(),s=t.find(i=>i.code===n);if(!s)throw new TypeError(`Unknown pm error code "${n}"`);return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a568064-a103-5b19-969d-6e58fc0cc5b7")}catch{}})();var Xc=Yc([{code:"acceptance_criteria_semicolon_forbidden",meaning:"Acceptance criteria semicolon forbidden condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"]},{code:"already_claimed_by",meaning:"Already claimed by condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"ambiguous_list_all",meaning:"Ambiguous list all condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-list-query.ts"],emitting_commands:["*"]},{code:"ambiguous_option_combination",meaning:"Ambiguous option combination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"annotation_flag_like_value",meaning:"Annotation flag like value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"]},{code:"annotation_message_without_text",meaning:"Annotation message without text condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"]},{code:"append_empty_body",meaning:"Append empty body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"]},{code:"body_file_conflicts_with_body",meaning:"Body file conflicts with body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"]},{code:"body_file_missing_path",meaning:"Body file missing path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"]},{code:"body_file_unreadable",meaning:"Body file unreadable condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"]},{code:"bundle_integrity_torn_install",meaning:"Bundle integrity torn install condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/bundle-integrity.ts"],emitting_commands:["*"]},{code:"capability_undeclared",meaning:"Capability undeclared condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"capability_unused",meaning:"Capability unused condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"child_projection_item_bound_exceeded",meaning:"Child projection item bound exceeded condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-children.ts"],emitting_commands:["*"]},{code:"close_reason_required",meaning:"Close reason required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"]},{code:"close_through_update",meaning:"Close through update condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"close_validation_missing_fields",meaning:"Close validation missing fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"collected_zero_items",meaning:"Collected zero items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"command_failed",meaning:"Command failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"command_namespace",meaning:"Command namespace condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"]},{code:"command_override_conflict",meaning:"Command override conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"config_duplicate",meaning:"Config duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"config_key_unknown",meaning:"Config key unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"config_value_invalid",meaning:"Config value invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"conflicting_lifecycle_owner",meaning:"Conflicting lifecycle owner condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-operations.ts"],emitting_commands:["*"]},{code:"context_takes_no_item_argument",meaning:"Context takes no item argument condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"core_item_field_requires_dedicated_flag",meaning:"Core item field requires dedicated flag condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"create_positional_type_without_title",meaning:"Create positional type without title condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts"],emitting_commands:["*"]},{code:"dependency_edge_not_allowed",meaning:"Dependency edge not allowed condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"]},{code:"duplicate_command",meaning:"Duplicate command condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"duplicate_edge",meaning:"Duplicate edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"]},{code:"duplicate_sweep_cost_limit",meaning:"Duplicate sweep cost limit condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/similarity.ts"],emitting_commands:["*"]},{code:"duplicate_target_circular",meaning:"Duplicate target circular condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_is_duplicate",meaning:"Duplicate target is duplicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_missing",meaning:"Duplicate target missing condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_self",meaning:"Duplicate target self condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"empty_surface",meaning:"Empty surface condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"event_cursor_query_mismatch",meaning:"Event cursor query mismatch condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"event_index_unavailable",meaning:"Event index unavailable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"extension_command_activation_failed",meaning:"Extension command activation failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/commander-usage.ts"],emitting_commands:["*"]},{code:"extension_dependency_name_unsafe",meaning:"Extension dependency name unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"extension_dependency_spec_invalid",meaning:"Extension dependency spec invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"extension_dependency_version_unsafe",meaning:"Extension dependency version unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"extension_install_soft_failed",meaning:"Extension install soft failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"]},{code:"extension_install_source_contains_destination",meaning:"Extension install source contains destination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-runtime.ts"],emitting_commands:["*"]},{code:"extension_item_field_reserved",meaning:"Extension item field reserved condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"extension_item_field_type_conflict",meaning:"Extension item field type conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"extension_item_field_unknown",meaning:"Extension item field unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_failed",meaning:"Extension mutation guard failed condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_invalid_decision",meaning:"Extension mutation guard invalid decision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_invalid_denial",meaning:"Extension mutation guard invalid denial condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_timed_out",meaning:"Extension mutation guard timed out condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_update_health_partial_coverage",meaning:"Extension update health partial coverage condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"field_duplicate",meaning:"Field duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"field_invalid",meaning:"Field invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"field_mcp_input_collision",meaning:"Field mcp input collision condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"github_source_entry_unbuilt",meaning:"Github source entry unbuilt condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/shared.ts"],emitting_commands:["*"]},{code:"history_author_acknowledge_selector_required",meaning:"History author acknowledge selector required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-history-author.ts"],emitting_commands:["*"]},{code:"history_drift_chain_mismatch",meaning:"History drift chain mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_drift_hash_mismatch",meaning:"History drift hash mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_drift_missing_stream",meaning:"History drift missing stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_drift_unreadable_stream",meaning:"History drift unreadable stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_merge_conflict_markers_detected",meaning:"History merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"]},{code:"history_stream_over_compact_threshold",meaning:"History stream over compact threshold condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_target_out_of_range",meaning:"History target out of range condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"]},{code:"history_unknown_author_events",meaning:"History unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"init_existing_settings_requires_force",meaning:"Init existing settings requires force condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"init_gitignore_unwritable",meaning:"Init gitignore unwritable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace.ts"],emitting_commands:["*"]},{code:"init_id_prefix_conflict",meaning:"Init id prefix conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"init_id_prefix_path_like",meaning:"Init id prefix path like condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"integrity_history_conflict_marker",meaning:"Integrity history conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_history_invalid_json",meaning:"Integrity history invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_history_unreadable",meaning:"Integrity history unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_ahead_format_version",meaning:"Integrity item ahead format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_conflict_marker",meaning:"Integrity item conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_outdated_format_version",meaning:"Integrity item outdated format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_parse_failed",meaning:"Integrity item parse failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_unreadable",meaning:"Integrity item unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"invalid_argument_value",meaning:"Invalid argument value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts"],emitting_commands:["*","create"]},{code:"invalid_command_usage",meaning:"Invalid command usage condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"invalid_event_cursor",meaning:"Invalid event cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_event_follow_interval",meaning:"Invalid event follow interval condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_event_limit",meaning:"Invalid event limit condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_event_since",meaning:"Invalid event since condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_provenance_predicate",meaning:"Invalid provenance predicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"]},{code:"invalid_query_cursor",meaning:"Invalid query cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/pagination.ts"],emitting_commands:["*"]},{code:"invalid_workspace_snapshot_target",meaning:"Invalid workspace snapshot target condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"item_document_invalid",meaning:"Item document invalid condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"]},{code:"item_document_roundtrip_failed",meaning:"Item document roundtrip failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"]},{code:"item_id_collision",meaning:"Item id collision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"]},{code:"item_not_found",meaning:"Item not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"likely_duplicate",meaning:"Likely duplicate condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/similarity.ts"],emitting_commands:["*"]},{code:"linked_test_value_not_quoted",meaning:"Linked test value not quoted condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"list_source_incomplete",meaning:"List source incomplete condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/list.ts"],emitting_commands:["list"]},{code:"local_package_archive_unsafe",meaning:"Local package archive unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"local_source_not_found_bare_name",meaning:"Local source not found bare name condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"lock_conflict",meaning:"Lock conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"locks_stale_count",meaning:"Locks stale count condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"locks_unreadable",meaning:"Locks unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"malformed_plan_step_evidence",meaning:"Malformed plan step evidence condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"manifest_capabilities_absent",meaning:"Manifest capabilities absent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"merge_conflict_markers_detected",meaning:"Merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"]},{code:"merge_git_config_unwritable",meaning:"Merge git config unwritable condition.",stability:"stable",exit_code:5,class:"dependency_failed",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"]},{code:"merge_root_not_found",meaning:"Merge root not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"]},{code:"missing_directory",meaning:"Missing directory condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"missing_lifecycle_target",meaning:"Missing lifecycle target condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension.ts"],emitting_commands:["*"]},{code:"missing_required_argument",meaning:"Missing required argument condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","core/telemetry/observability.ts","sdk/history-redact.ts","sdk/invocation-author.ts"],emitting_commands:["*"]},{code:"missing_required_option",meaning:"Missing required option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"]},{code:"module_import_failed",meaning:"Module import failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"multi_target_github_install_ambiguous",meaning:"Multi target github install ambiguous condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"]},{code:"mutation_author_required",meaning:"Mutation author required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"]},{code:"mutation_secret_guard_blocked",meaning:"Mutation secret guard blocked condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"]},{code:"no_matching_tests",meaning:"No matching tests condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_projects_matched_filters",meaning:"No projects matched filters condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_test_files_found",meaning:"No test files found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_tests_found",meaning:"No tests found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_update_fields",meaning:"No update fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"npm_package_not_found",meaning:"Npm package not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"ownership_conflict",meaning:"Ownership conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"],emitting_commands:["*"]},{code:"ownership_dependency_bypass_restricted_options",meaning:"Ownership dependency bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"ownership_metadata_bypass_restricted_options",meaning:"Ownership metadata bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"package_spec_empty",meaning:"Package spec empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_name_empty",meaning:"Profile name empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_name_not_normalized",meaning:"Profile name not normalized condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_summary_empty",meaning:"Profile summary empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_title_empty",meaning:"Profile title empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"redundant_edge",meaning:"Redundant edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"]},{code:"reindex_already_running",meaning:"Reindex already running condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/reindex.ts"],emitting_commands:["*"]},{code:"reserved_item_field",meaning:"Reserved item field condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"schema_migration_input_required",meaning:"Schema migration input required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/migration-gates.ts"],emitting_commands:["*"]},{code:"settings_read_fs_error",meaning:"Settings read fs error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"settings_read_invalid_json",meaning:"Settings read invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"settings_read_invalid_schema",meaning:"Settings read invalid schema condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"settings_read_merge_failed",meaning:"Settings read merge failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"status_duplicate",meaning:"Status duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"status_invalid",meaning:"Status invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"stdin_json_invalid",meaning:"Stdin json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"]},{code:"stdin_json_unknown_key",meaning:"Stdin json unknown key condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"]},{code:"structured_event_immutable",meaning:"Structured event immutable condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"]},{code:"structured_event_input_conflict",meaning:"Structured event input conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"structured_event_json_empty",meaning:"Structured event json empty condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"structured_event_json_invalid",meaning:"Structured event json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"structured_event_since_invalid",meaning:"Structured event since invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"telemetry_endpoint_probe_failed",meaning:"Telemetry endpoint probe failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_endpoint_probe_http_status",meaning:"Telemetry endpoint probe http status condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_otel_export_failing",meaning:"Telemetry otel export failing condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_queue_high_retries",meaning:"Telemetry queue high retries condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_queue_invalid_rows",meaning:"Telemetry queue invalid rows condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_queue_pending",meaning:"Telemetry queue pending condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_schema_version_behind",meaning:"Telemetry schema version behind condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_state_invalid_json",meaning:"Telemetry state invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"template_type_unknown",meaning:"Template type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"terminal_plan_mutation",meaning:"Terminal plan mutation condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"terminal_state_conflict",meaning:"Terminal state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"tracked_runtime_cache_files",meaning:"Tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"tracker_not_initialized",meaning:"Tracker not initialized condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"tracker_root_missing",meaning:"Tracker root missing condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"]},{code:"tracker_root_not_directory",meaning:"Tracker root not directory condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"]},{code:"type_duplicate",meaning:"Type duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"type_invalid",meaning:"Type invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"unknown_command",meaning:"Unknown command condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"]},{code:"unknown_context_intent",meaning:"Unknown context intent condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-intent-contracts.ts"],emitting_commands:["*"]},{code:"unknown_error",meaning:"Unknown error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"unknown_field",meaning:"Unknown field condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"]},{code:"unknown_field_projection",meaning:"Unknown field projection condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts"],emitting_commands:["get","list"]},{code:"unknown_item_type",meaning:"Unknown item type condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"]},{code:"unknown_lifecycle_action",meaning:"Unknown lifecycle action condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension.ts"],emitting_commands:["*"]},{code:"unknown_option",meaning:"Unknown option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"unknown_plan_template",meaning:"Unknown plan template condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"unknown_provenance_dimension",meaning:"Unknown provenance dimension condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"]},{code:"unknown_status",meaning:"Unknown status condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"]},{code:"unknown_subcommand",meaning:"Unknown subcommand condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts","cli/register-operations.ts","sdk/runtime-extended-actions.ts","sdk/telemetry.ts"],emitting_commands:["*"]},{code:"unsupported_update_option",meaning:"Unsupported update option condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"validate_command_references_stale_pm_ids",meaning:"Validate command references stale pm ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_files_missing_linked_paths",meaning:"Validate files missing linked paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_files_orphaned_paths",meaning:"Validate files orphaned paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_files_tracked_all_strict_forces_pm_internals",meaning:"Validate files tracked all strict forces pm internals condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_format_version_ahead_items",meaning:"Validate format version ahead items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_format_version_outdated_items",meaning:"Validate format version outdated items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_hierarchy_parent_cycle",meaning:"Validate hierarchy parent cycle condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_hierarchy_parent_cycle_error",meaning:"Validate hierarchy parent cycle error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_chain_mismatches",meaning:"Validate history drift chain mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_hash_mismatches",meaning:"Validate history drift hash mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_missing_streams",meaning:"Validate history drift missing streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_unreadable_streams",meaning:"Validate history drift unreadable streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_unknown_author_events",meaning:"Validate history unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_active_closure_like_metadata",meaning:"Validate lifecycle active closure like metadata condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_active_terminal_parent",meaning:"Validate lifecycle active terminal parent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_dependency_cycles",meaning:"Validate lifecycle dependency cycles condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_dependency_cycles_error",meaning:"Validate lifecycle dependency cycles error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_stale_blockers",meaning:"Validate lifecycle stale blockers condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_merge_fence_drift",meaning:"Validate merge fence drift condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_custom_profile_missing_required_fields",meaning:"Validate metadata custom profile missing required fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_duplicate_issue_codes",meaning:"Validate metadata duplicate issue codes condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_acceptance_criteria",meaning:"Validate metadata missing acceptance criteria condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_close_reason",meaning:"Validate metadata missing close reason condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_confidence",meaning:"Validate metadata missing confidence condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_estimate",meaning:"Validate metadata missing estimate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_release",meaning:"Validate metadata missing release condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_reviewer",meaning:"Validate metadata missing reviewer condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_risk",meaning:"Validate metadata missing risk condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_sprint",meaning:"Validate metadata missing sprint condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_resolution_missing_fields",meaning:"Validate resolution missing fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_duplicate_item_ids",meaning:"Validate storage duplicate item ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_history_conflict_markers",meaning:"Validate storage history conflict markers condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_resurrected_items",meaning:"Validate storage resurrected items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_tracked_runtime_cache_files",meaning:"Validate storage tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_unparseable_config",meaning:"Validate storage unparseable config condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_unparseable_history",meaning:"Validate storage unparseable history condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_unreadable_items",meaning:"Validate storage unreadable items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"vectorization_embedding_identity_changed",meaning:"Vectorization embedding identity changed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"vectorization_stale_items_remaining",meaning:"Vectorization stale items remaining condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"workflow_duplicate_type",meaning:"Workflow duplicate type condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_status_unknown",meaning:"Workflow status unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_transition_malformed",meaning:"Workflow transition malformed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_type_empty",meaning:"Workflow type empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_type_unknown",meaning:"Workflow type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workspace_history_state_conflict",meaning:"Workspace history state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"]},{code:"workspace_root_pm_path",meaning:"Workspace root pm path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_force_required",meaning:"Workspace snapshot force required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_manifest_mismatch",meaning:"Workspace snapshot manifest mismatch condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_name_reserved_fingerprint",meaning:"Workspace snapshot name reserved fingerprint condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_not_found",meaning:"Workspace snapshot not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"wrong_item_type",meaning:"Wrong item type condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]}]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af86d275-63a8-5205-a8b3-154efdbd8e2a")}catch{}})();var hp=["mutation_receipt","entity","collection","diagnostic","stream"],yp=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),bp=new Set(["close-many","update-many"]),wp=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),kp=new Set(["aggregate","deps","graph","health","stats","validate"]);function st(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!hp.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function Jc(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return bp.has(n)?st({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):yp.has(n)?st({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):wp.has(n)?st({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):kp.has(n)?st({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):st({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var vp=he.map(e=>Jc(e)),Tp=new Map(vp.map(e=>[e.command,e]));function Qc(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=t.split(" "),s=Tp.get(n);return s?{...s,command:t}:Jc(t)}function xp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sp(e){return xp(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function Mv(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!Sp(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="89c1ac6d-c217-54ea-8728-5a58762f86d9")}catch{}})();var Cp={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:{type:"integer",minimum:1,description:"Universal estimated-token ceiling for a read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."}},Zc={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},F={type:"string",description:"pm item id, for example pm-abc1."},Ep=`Operation name (one of): ${qe.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,Ip={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."}},Ap={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 I(e,t=[]){return{...Zc,properties:{...Zc.properties,...e},required:t}}var Rp=[{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:I({action:{type:"string",enum:[...qe],description:Ep},id:F,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."},...Cp},["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:I({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:I({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:I({query:{type:"string"},options:{type:"object"},...Ap},["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:I({options:{type:"object"},...Ip})},{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:I({id:F,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.",inputSchema:I({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"}})},{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:I({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:I({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:F,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:I({id:F,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:I({id:F,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:I({id:F,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:I({id:F,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:I({id:F,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:I({id:F,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:I({id:F,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:I({id:F,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:I({id:F,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:I({id:F,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:I({id:F,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:I({id:F,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:I({id:F,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:I({subcommand:{type:"string",enum:[...xi]},id:F,target:F,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:I({id:F,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:I({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:I({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:I({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:I({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:[...nn]},description:`Lifecycle roles for add-status: ${nn.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:I({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:I({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:I({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."}})}],Op={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"},Np=Rp.map(e=>{let t=Op[e.name];if(!t)return e;let n=e.inputSchema.properties,s=e.inputSchema.required.map(String);return{...e,inputSchema:yo(t,{properties:n,required:s})}});function ed(){return Np.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(s=>String(s)).sort((s,i)=>s.localeCompare(i)):[];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]="d13ab001-705f-5443-9394-401069aa43fb")}catch{}})();var Lp=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"]]]),Pp=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],ud=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Bt=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"]),it=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"]),md=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"]]),_d=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"]]),pd=new Map([..._d.entries()].flatMap(([e,t])=>Te(t).map(n=>[n,e]))),fd=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],Mp=new Map(fd.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),Dp=10,Fp=20,td=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["claim","Claim work."],["close","Close work."],["comments","Manage comments."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["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."],["learnings","Manage learnings."],["list","List work."],["next","Pick next work."],["notes","Manage notes."],["ops","Run operations."],["package","Manage packages."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["stats","Show stats."],["telemetry","Manage telemetry."],["test","Run linked tests."],["update","Update work."],["upgrade","Upgrade packages."],["validate","Validate data."],["workspace","Manage portable workspace primitives."]]),gd=[["init",wr],["install",vr],["uninstall",Tr],["explore",xr],["manage",Ar],["describe",Sr],["reload",Rr],["doctor",Or],["catalog",Nr],["adopt",Lr],["adopt-all",Cr],["activate",Er],["deactivate",Ir]],jp=gd.map(([e,t])=>e==="init"?[e,kr]:[e,t]),$p=[...gd.map(([e,t])=>[`extension ${e}`,t]),...jp.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",hr],["config",yr],["extension",br],["package",gn],["packages",gn],["install",Pr],["create",no],["item mutate",so],["item complete",io],["update",ro],["update-many",oo],["upgrade",Mr],["calendar",hn],["cal",hn],["context",yn],["ctx",yn],["get",co],["search",fo],["eval",_o],["workspace",le],["workspace snapshot",le],["workspace snapshot create",le],["workspace snapshot list",le],["workspace snapshot inspect",le],["workspace snapshot restore",le],["workspace snapshot delete",le],["next",po],["aggregate",nr],["deps",uo],["graph",mo],["guide",lo],["reindex",Dr],["history",cr],["history-compact",_r],["history-redact",lr],["history-repair",ur],["history-author-acknowledge",mr],["merge",dr],["schema",pr],["profile",fr],["plan",gr],["restore",Gr],["delete",qr],["close",Fr],["close-many",jr],["append",$r],["claim",Ur],["release",Br],["start-task",Wr],["pause-task",zr],["close-task",Hr],["comments",sr],["notes",ir],["learnings",rr],["files",or],["docs",ar],["test",Vr],["test-all",Kr],["telemetry",Yr],["test-runs",Xr],["gc",Jr],["stats",Qr],["duplicates",Zr],["validate",to],["health",eo],["contracts",go],["completion",ho],["activity",ao],...[...ud].map(e=>[e,tr])],gs=new Map($p);function Up(e){let t=pd.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function nd(e){return he.includes(e)?K(e):e.startsWith("extension-")?K(`extension ${e.slice(10)}`):e.startsWith("package-")?K(`package ${e.slice(8)}`):e.startsWith("test-runs-")?K(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?K(`templates ${e.slice(10)}`):Bt.has(e)?_d.get(e)??K(e):null}function Gp(e,t){return e.command_path===null?!1:Te(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `))}function Te(e){return e.split("|").map(t=>K(t)).filter(t=>t.length>0)}function qp(e,t){let n=new Set(t),s=new Set;for(let i of e)if(i.command_path)for(let r of Te(i.command_path)){let o=r.split(" ").filter(a=>a.length>0);if(o.length!==0)for(let a=o.length;a>0;a-=1){let c=o.slice(0,a).join(" ");if(n.has(c)){s.add(c);break}}}return[...s].sort((i,r)=>i.localeCompare(r))}function qt(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function rt(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function Bp(e,t){if(!t)return{...e};let s=rt(e).filter(i=>{let r=i.properties;if(typeof r!="object"||r===null)return!1;let o=r.action;return typeof o!="object"||o===null?!1:o.const===t});return{...e,oneOf:s}}function _s(e,t){let s=rt(e).filter(i=>{let r=i.properties;if(typeof r!="object"||r===null)return!1;let o=r.action;if(typeof o!="object"||o===null)return!1;let a=o.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:s}}function K(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function sd(e){return e.replace(/\s+/g,"-")}function te(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function id(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let s of e){let i=te(s);!i||n.has(i)||(n.add(i),t.push(i))}return t}function ps(e,t,n){n&&(e[t]=!0)}function rd(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 Wp(e){let t=rd(e.long,"long"),n=rd(e.short,"short"),s=t??n;if(!s)return null;let i={flag:s};n&&t&&(i.short=n),ps(i,"required",e.required===!0),ps(i,"repeatable",e.repeatable===!0),ps(i,"list",e.list===!0);let r=te(e.description);r&&(i.description=r);let o=te(e.value_name);o&&(i.value_name=o);let a=[te(e.value_type),te(e.type),o?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(i.value_type=a),i}function hd(e){let t=new Map;for(let s of e){let i=K(s.target_command);if(i.length===0)continue;let r=t.get(i)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},o=`${s.layer}:${s.name}`;r.sourceDedupe.has(o)||(r.sourceDedupe.add(o),r.sources.push({layer:s.layer,name:s.name}));for(let a of s.flags){let c=Wp(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;r.dedupe.has(d)||(r.dedupe.add(d),r.flags.push(c))}t.set(i,r)}let n=new Map;for(let[s,i]of t.entries())n.set(s,{flags:i.flags,sources:i.sources.sort((r,o)=>{let a=r.layer.localeCompare(o.layer);return a!==0?a:(r.name??"").localeCompare(o.name??"")})});return n}function zp(e){let t=hd(e.flagRegistrations),n=new Map;for(let r of e.commandDefinitions){let o=K(r.command);if(o.length===0)continue;let a=te(r.action)??sd(o),c=Array.isArray(r.arguments)?r.arguments.map(d=>{let l=te(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:te(d.description)}:null}).filter(d=>d!==null):[];n.set(o,{command:o,action:a,source:{layer:r.layer,name:r.name},description:te(r.description),intent:te(r.intent),arguments:c,flags:t.get(o)?.flags??[],examples:id(r.examples),failure_hints:id(r.failure_hints)})}let s=new Set;for(let r of e.handlers)s.add(K(r));for(let r of n.keys())s.add(r);for(let r of t.keys())s.add(r);let i=[];for(let r of[...s].sort((o,a)=>o.localeCompare(a))){let o=n.get(r);if(o){i.push({...o,flags:o.flags.length>0?o.flags:t.get(r)?.flags??[]});continue}i.push({command:r,action:sd(r),source:null,description:null,intent:null,arguments:[],flags:t.get(r)?.flags??[],examples:[],failure_hints:[]})}return i}function Hp(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let s=t.replace(/-([a-z0-9])/g,(i,r)=>r.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return s.length>0?s:null}function Vp(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 Kp(e,t){let n=e.value_type??"boolean",s=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",i=e.repeatable===!0||e.list===!0;return{type:i?"array":s,...i?{items:{type:s}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function Yp(e){let t=e.command.split("|").map(i=>i.trim()).filter(i=>i.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},s=["action"];for(let i of e.arguments)n[i.name]=Vp(i,e.action),i.required&&s.push(i.name);for(let i of e.flags){let r=Hp(i);!r||n[r]!==void 0||(n[r]=Kp(i,e.action),i.required===!0&&s.push(r))}return{type:"object",properties:n,required:s,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function Xp(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 Jp(e){let t=new Map;for(let n of e){let s=t.get(n.action);if(!s){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}s.command=[...new Set([s.command,n.command])].sort((r,o)=>r.localeCompare(o)).join("|"),s.arguments=s.arguments.length>=n.arguments.length?s.arguments:n.arguments;let i=new Set(s.flags.map(r=>`${r.flag}|${r.short??""}`));for(let r of n.flags){let o=`${r.flag}|${r.short??""}`;if(!i.has(o))i.add(o),s.flags.push(r);else{let a=s.flags.find(c=>`${c.flag}|${c.short??""}`===o);a&&Xp(a,r)}}s.examples=[...new Set([...s.examples,...n.examples])],s.failure_hints=[...new Set([...s.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,s)=>n.action.localeCompare(s.action))}async function Qp(e,t=N){let n={mode:Ge.extensions.policy.mode,trust_mode:Ge.extensions.policy.trust_mode,default_sandbox_profile:Ge.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let s=R(process.cwd(),e.path);if(!await x(O(s)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let i=await t(s),r=await lt({pmRoot:s,settings:i,cwd:process.cwd(),noExtensions:!1}),o=await ut({...r,loaded:r.loaded});return{handlers:new Set(o.commands.handlers.map(c=>K(c.command))),disabledReason:null,commandDefinitions:o.registrations.commands,flagRegistrations:o.registrations.flags,registrations:o.registrations,policyState:{mode:r.policy.mode,trust_mode:r.policy.trust_mode,default_sandbox_profile:r.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function Zp(e,t={}){let n=new Map;for(let s of qe){let i=Bt.has(s);if(i&&!t.includePackageOwnedActions)continue;let r=nd(s);n.set(s,{action:s,provider:i?"extension":"core",requires_extension:i,command_path:r})}if(t.includePackageOwnedActions)for(let s of Bt)n.has(s)||n.set(s,{action:s,provider:"extension",requires_extension:!0,command_path:nd(s)});for(let s of e)n.has(s.action)||n.set(s.action,{action:s.action,provider:"extension",requires_extension:!0,command_path:K(s.command)});return[...n.values()].sort((s,i)=>(s.action??"").localeCompare(i.action??""))}function ef(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?Te(e.command_path):[],s=n.some(o=>t.handlers.has(o)),i=n.map(o=>md.get(o)).find(o=>typeof o=="string"),r=t.disabledReason===null&&s;return{action:e.action,invocable:r,available:r,requires_extension:!0,provider:"extension",disabled_reason:r?null:t.disabledReason??(i?`optional_package_not_installed:${i}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:s,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function yd(e){return gs.get(e)??er}function tf(e){return it.has(e)?!1:gs.has(e)}function nf(e){return ud.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function od(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function sf(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function rf(e){let t=new Map;for(let s of e.definitions){let i=od(s.cli_flag);if(!i)continue;let r=s.cli_aliases.map(a=>sf(a)).find(a=>a!==null),o=s.cli_aliases.map(a=>od(a)).filter(a=>a!==null&&a!==i);for(let a of s.commands){let c=t.get(a)??{flags:[],seen:new Set},d=r?{flag:i,short:r}:{flag:i},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of o){let m=`${u}|`;c.seen.has(m)||(c.seen.add(m),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[s,i]of t.entries())n.set(s,fn(i.flags));return n}function ad(e,t){let n=[],s=new Set;for(let i of[...e,...t]){let r=`${i.flag}|${i.short??""}`;s.has(r)||(s.add(r),n.push(i))}return fn(n)}function of(e,t,n,s){return e.map(i=>{let r=tf(i),o=r?yd(i):[],a=n.get(nf(i))??[],c=t.get(i),d=ad(o,a),l=ad(d,c?.flags??[]),u=o.length>0&&(c?.flags.length??0)>0?"mixed":r?"core":"extension";return{command:i,flags:l,...s?{canonical_command:fs(i),visibility:Vc(fs(i)),flag_invocations:zc(i,l)}:{},provider:u,extension_sources:c?.sources}}).sort((i,r)=>i.command.localeCompare(r.command))}function af(e){let t=new Set(e);return fd.map(n=>({canonical:n.canonical,aliases:n.aliases.filter(s=>t.has(s))})).filter(n=>t.has(n.canonical)&&n.aliases.length>0)}function cf(){return{create_string_options:Xi,create_repeatable_options:Ji,update_string_options:Qi,update_repeatable_options:Zi,list_string_options:zi,search_string_options:Hi,calendar_string_options:Vi,context_string_options:Ki,activity_string_options:Yi}}function cd(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 s=Js(e,"create",n),i=[...new Set(s.required)].sort((a,c)=>a.localeCompare(c)),r=[...new Set(i.map(a=>Xs("create",a)))].sort((a,c)=>a.localeCompare(c)),o=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:i,required_flags:r,required_type_options:o,policy_errors:[...new Set(s.errors)].sort((a,c)=>a.localeCompare(c))}}function df(e){let t={},n={};for(let s of[...e.types].sort((i,r)=>i.localeCompare(r))){let i=e.by_type[s];t[s]=cd(i,"strict"),n[s]=cd(i,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function lf(e,t){let n=rt(e);if(n.length===0)return e;let s=!1,i=n.map(r=>{let o=r.properties;if(typeof o!="object"||o===null)return r;let a=o.action;return typeof a!="object"||a===null||a.const!=="create"?r:(s=!0,{...r,"x-create-required-options":t})});return s?{...e,oneOf:i}:e}function uf(e){let t=qt(e.action)!==void 0||qt(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,s=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,i=e.schemaOnly===!0,r=e.flagsOnly===!0,o=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=qt(e.action),l=qt(e.command),u=!s&&!c&&!i&&!r&&!o&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:s,schemaOnly:i,flagsOnly:r,availabilityOnly:o,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u}}function mf(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new h("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",g.USAGE)}async function _f(e,t=N){try{return await t(e)}catch{return structuredClone(Ge)}}async function pf(e,t){let n=await _f(t),s=await Qp(e),i=V(n,s.registrations??W()),r=di(n.schema),o=zp(s);return{settings:n,runtimeProbe:s,typeRegistry:i,statusRegistry:Z(n.schema),runtimeFieldRegistry:r,runtimeFieldFlagMap:rf(r),createRequiredOptionContracts:df(i),extensionContracts:o,mergedExtensionContracts:Jp(o),extensionFlagMap:hd(s.flagRegistrations)}}function dd(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Bt.has(e.selectedAction)||e.selectedCommand!==void 0&&it.has(e.selectedCommand))}function ff(e,t){let n=Zp(t,{includePackageOwnedActions:dd(e)});return dd(e)&&e.selectedCommand!==void 0&&it.has(e.selectedCommand)&&!n.some(s=>s.command_path===e.selectedCommand)&&n.push({action:Up(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function gf(e,t){let n=new Set(t.map(s=>s.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new h(`Unknown action: "${e.selectedAction}".`,g.USAGE)}function hf(e,t){return[...new Set([...he.filter(n=>!it.has(n)),...[...gs.keys()].filter(n=>!it.has(n)),...e.flatMap(n=>n.command_path?Te(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>K(n)).filter(n=>n.length>0).sort((n,s)=>n.localeCompare(s))}function yf(e,t){let n=t.slice(0,Dp),s=t.length-n.length,i=s>0?`${n.join(", ")}, and ${s} more`:n.join(", "),r=t.slice(0,Fp),o=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new h(`Command "${e}" is a command namespace. Choose a concrete child command: ${i}.`,g.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:o,nextSteps:[`Retry with a child command, for example: ${o[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:r.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function bf(e,t){return new h(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,g.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 wf(e){return new h(`Unknown command: "${e}".`,g.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 kf(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let s=t.filter(r=>r.startsWith(`${e.selectedCommand} `));if(s.length>0)throw yf(e.selectedCommand,s);let i=md.get(e.selectedCommand);throw i?bf(e.selectedCommand,i):wf(e.selectedCommand)}function vf(e,t){let n=ff(e,t.mergedExtensionContracts);gf(e,n);let s=hf(n,t.mergedExtensionContracts);kf(e,s);let i=e.selectedCommand?pd.get(e.selectedCommand):void 0,r=e.selectedCommand?n.filter(d=>i?d.action===i:Gp(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!r.some(d=>d.action===e.selectedAction))throw new h(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,g.USAGE);let o=e.selectedAction?r.filter(d=>d.action===e.selectedAction):r,a=[...new Map(o.map(d=>ef(d,t.runtimeProbe)).map(d=>[i?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:s,commandScopedDescriptors:r,scopedActionDescriptors:o,selectedPackageOwnedAction:i,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function Tf(e){return new Set(rt(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let s=n.action;if(typeof s!="object"||s===null)return null;let i=s.const;return typeof i=="string"?i:null}).filter(t=>t!==null))}function xf(e){let t=bo,n=rt(t),s=Tf(t),i=e.filter(r=>!s.has(r.action)).map(r=>Yp(r));return i.length>0?{...t,oneOf:[...n,...i]}:t}function ld(e,t,n){let s=new Set(t.actionDescriptors.map(r=>r.action)),i=e.selectedAction?Bp(n,e.selectedAction):e.selectedCommand?_s(n,new Set(t.scopedActionDescriptors.map(r=>r.action))):_s(n,s);return e.runtimeOnly&&!e.selectedAction?_s(i,new Set(t.actions)):i}function Sf(e,t,n){let s=xf(t.mergedExtensionContracts),r=!e.flagsOnly&&!e.availabilityOnly?lf(ld(e,n,s),t.createRequiredOptionContracts):ld(e,n,s);return{mergedSchema:s,filteredSchema:r}}function Cf(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?qp(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Ef(e,t){return t}function If(e){let t=e.split(" ")[0];return td.get(e)??td.get(t)??"Inspect flags."}function fs(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":t==="ctx"?"context":t==="packages"?"package":Mp.get(t)??t}function Af(e){let t=new Map;for(let s of e){let i=s.split(" ")[0],r=fs(i),o=t.get(r)??new Set;o.add(i),t.set(r,o)}return[...t.keys()].filter(s=>s.length>0).sort((s,i)=>s.localeCompare(i)).map(s=>{let i=ln(s,{generateFallback:!0}),r=new Set(yd(s).map(c=>c.flag)),o=(Lp.get(s)??Pp).filter(c=>r.has(c)),a=[...t.get(s)].filter(c=>c!==s).sort((c,d)=>c.localeCompare(d));return{command:s,...a.length>0?{aliases:a}:{},intent:If(s),...o.length>0?{flags:o}:{},default_max_estimated_tokens:i.default_max_estimated_tokens}})}function Rf(e){return e.map(t=>({budget:ln(t,{generateFallback:!0}),envelope:Qc(t)}))}function Of(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(s=>Te(s.command).includes(e.selectedCommand));if(e.selectedAction){let s=new Set(n);return t.extensionContracts.filter(i=>Te(i.command).some(r=>s.has(r)))}return t.extensionContracts}function Nf(e,t,n,s){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?[]:s,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function Lf(e,t){e.runtime_schema={statuses:t.statusRegistry.definitions.map(n=>n.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()].map(([n,s])=>[n,[...new Set(s.map(i=>`--${i.cli_flag}`))].sort((i,r)=>i.localeCompare(r))]))},e.extension_contracts={capabilities:[...yi],services:[...bi],policy_modes:[...wi],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Ti],trust_modes:[...ki],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...vi],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Hs],create_modes:[...Vs],close_validation_modes:[...Ks],workflow_enforcement_modes:[...Ys]}}function Pf(e,t,n,s){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=s;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=s}}function Mf(e,t,n,s,i){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=of(s,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let r=new Set(s);e.list_projections=Object.entries(Co).filter(([o])=>r.has(o)).map(([o,a])=>({command:o,default:a,brief_fields:[...So],compact_fields:[...xo]}))}i.length>0&&(e.command_aliases=i)}}function Df(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=cf();return}e.commander_aliases_omitted_reason="unfiltered_default_brief"}}async function Qv(e,t){let n=uf(e);mf(n);let s=R(process.cwd(),t.path),i=await pf(t,s),r=vf(n,i),o=Sf(n,i,r),a=Cf(n,r),c=Ef(n,a),d=Nf(n,o,r,c);if(n.summary)return d.command_summaries=Af(c),d.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Si],allows_unbounded_opt_out:!0},d;let l=af(a),u=Of(n,i,c);return n.flagsOnly&&!n.fullOutput||Lf(d,i),Pf(d,n,o,u),Mf(d,n,i,c,l),Df(d,n),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=ed(),d.context_intents=hi(),d.read_output_dimensions=gi,d.error_codes=Xc,d.command_output_contracts=Rf(c)),d}import jf from"node:fs/promises";import wd 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 Wt(e,t,n,s,i,r="min"){let o=i==="min"?e-t:t-e,a=r==="min"?n.localeCompare(s??n):(s??n).localeCompare(n);return o<0||o===0&&s!==null&&a<0}function Ff(e,t){let n=Buffer.byteLength(t,"utf8"),s=0,i=null,r=null,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;s+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,m=Date.parse(u);Number.isNaN(m)||(Wt(m,o,u,i,"min")&&(o=m,i=u),Wt(m,a,u,r,"max","max")&&(a=m,r=u))}return{id:e,bytes:n,lines:s,oldest_ts:i,newest_ts:r}}function bd(e,t){let n=t?.topN??5,s=Math.max(0,Math.floor(n)),i=e.map(({id:_,raw:p})=>Ff(_,p)),r=0,o=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let _ of i){if(r+=_.lines,o+=_.bytes,_.oldest_ts!==null){let p=Date.parse(_.oldest_ts);Wt(p,d,_.id,a?.id??null,"min")&&(d=p,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let p=Date.parse(_.newest_ts);Wt(p,l,_.id,c?.id??null,"max")&&(l=p,c={id:_.id,ts:_.newest_ts})}}let u=s===0?[]:[...i].sort((_,p)=>p.bytes-_.bytes||_.id.localeCompare(p.id)).slice(0,s),m=s===0?[]:[...i].sort((_,p)=>p.lines-_.lines||_.id.localeCompare(p.id)).slice(0,s);return{total_streams:e.length,total_lines:r,total_bytes:o,largest_by_bytes:u,deepest_by_lines:m,oldest_entry:a,newest_entry:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e8916552-697e-565c-91e1-4829ecb584af")}catch{}})();function $f(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function Uf(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function Gf(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function qf(e){let t=wd.join(e,"history");if(!await x(t))return[];await X({path:t,scope:"project"});let n=(await jf.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,r)=>i.localeCompare(r)),s=[];for(let i of n){let r=wd.join(t,i),o=await $(r);o!==null&&(await X({path:r,scope:"project"}),s.push({id:i.slice(0,-6),raw:o}))}return s}async function hT(e,t={}){let n=R(process.cwd(),e.path);if(!await x(O(n)))throw new h(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let s=await N(n),i=V(s,W()),r=Z(s.schema),o=t.fieldUtilization?await Ee(n,s.item_format,i.type_to_folder,void 0,s.schema):await bt(n,s.item_format,i.type_to_folder,void 0,s.schema);await ht({pmRoot:n,settings:s,itemIds:o.map(b=>b.id),commandLabel:"stats"});let a=$f(i.types),c=Uf(r.definitions.map(b=>b.id));for(let b of o)a[b.type]+=1,c[b.status]+=1;let d=await qf(n),l=0;for(let b of d)l+=Gf(b.raw);let u=t.storage?bd(d):void 0,m=ko(r),_=t.metadataCoverage?vo(o,m):void 0,p={};t.byAssignee&&(p.assignee=wt(o,"assignee",m)),t.byTag&&(p.tag=wt(o,"tag",m,{tagPrefix:t.tagPrefix})),t.byPriority&&(p.priority=wt(o,"priority",m));let f=Object.keys(p).length>0,y=t.fieldUtilization?To(o):void 0;return{totals:{items:o.length,history_streams:d.length,history_entries:l},by_type:a,by_status:c,..._?{metadata_coverage:_}:{},...f?{breakdowns:p}:{},...u?{storage:u}:{},...y?{field_utilization:y}:{},generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6152efa9-8338-57f0-b3de-5707befed019")}catch{}})();async function kT(e,t={}){let n=await Ro({pmRoot:R(process.cwd(),e.path),...t.status===void 0?{}:{statuses:t.status.flatMap(s=>s.split(",").map(i=>i.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(s=>{let i=s.id;return{...s,canonical_id:i,close_command:`pm close <duplicate-id> --duplicate-of ${i}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import Bf from"node:fs/promises";import fe 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]="150c6ff7-cfb5-542f-bd3d-3c8088d1086a")}catch{}})();var Sd=fe.join("runtime","telemetry","events.jsonl"),Cd=fe.join("runtime","telemetry","state.json"),Wf=fe.join("runtime","telemetry"),zf=20,kd=["status","flush","stats","clear"],vd=(e,t)=>{let n=Math.ceil(t*e.length),s=Math.min(e.length-1,Math.max(0,n-1));return e[s]},hs=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Td=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},Hf=e=>({command:hs(e.event.command,"<unknown>"),eventType:hs(e.event.event_type,"unknown"),eventSchemaVersion:Td(e.event.schema_version),clientSchemaVersion:Td(e.client_schema_version)}),Vf=()=>({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:{}}),Kf=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},Yf=e=>{let t=e?.command_resolution;return hs(t,"")||void 0},Ed=(e,t)=>{e[t]=(e[t]??0)+1},Xf=(e,t)=>{let n=Kf(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let s=Yf(t);s!==void 0&&Ed(e.resolution_counts,s)},Jf=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,xd=(e,t)=>{t!==void 0&&e.add(t)},Qf=(e,t)=>{let n=Hf(t),s=e.get(n.command)??Vf();s.count+=1,s.max_attempts=Math.max(s.max_attempts,Jf(t.attempts)),Ed(s.event_type_counts,n.eventType),xd(s.event_schema_versions,n.eventSchemaVersion),xd(s.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&Xf(s,t.event.payload),e.set(n.command,s)},Zf=(e,t)=>{let n=t.ok_count+t.error_count,s=[...t.finish_durations_ms].sort((r,o)=>r-o),i=Object.entries(t.resolution_counts).sort((r,o)=>r[0].localeCompare(o[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((r,o)=>r[0].localeCompare(o[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((r,o)=>r-o),client_schema_versions:[...t.client_schema_versions].sort((r,o)=>r-o),...s.length>0?{duration_p50_ms:vd(s,.5),duration_p95_ms:vd(s,.95),duration_max_ms:s[s.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...i.length>0?{command_resolution_counts:Object.fromEntries(i)}:{}}},eg=e=>{let t=(e??"status").trim().toLowerCase();if(kd.includes(t))return t;throw new h(`Unknown pm telemetry subcommand "${e}". Allowed: ${kd.join(", ")}`,g.USAGE,{code:"unknown_subcommand",examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},ys=()=>{throw new h("--limit must be a positive integer",g.USAGE)},Id=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?ys():e,tg=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?ys():Id(Number.parseInt(t,10))},ng=e=>e===void 0?zf:typeof e=="number"?Id(e):typeof e=="string"?tg(e):ys(),sg=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},ig=e=>{try{let t=JSON.parse(e);return sg(t)?t:void 0}catch{return}},rg=e=>e===null?[]:e.split(`
10
- `).map(t=>t.trim()).filter(t=>t.length>0),Ad=e=>{let t=rg(e),n=[],s=0;for(let i of t){let r=ig(i);r===void 0?s+=1:n.push(r)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:s,entries:n}},og=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ag=e=>{try{let t=JSON.parse(e);return og(t)?t:{}}catch{return{}}},cg=async e=>{let t=await $(e);return t===null||t.trim().length===0?{}:ag(t)},zt=e=>e??null,Ht=async e=>{let t=await N(e),n=fe.join(e,Sd),s=fe.join(e,Cd),i=await $(n),r=Ad(i),o=await cg(s);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:s,queue_rows_total:r.rows_total,queue_entries:r.valid_entries,queue_invalid_rows:r.invalid_rows,queue_size_bytes:Buffer.byteLength(i??"","utf8"),last_attempted_flush_at:zt(o.last_attempted_flush_at),last_successful_flush_at:zt(o.last_successful_flush_at),last_failed_flush_at:zt(o.last_failed_flush_at),last_failed_flush_error:zt(o.last_failed_flush_error)}},dg=e=>{let t=new Map;for(let n of e)Qf(t,n);return[...t.entries()].map(([n,s])=>Zf(n,s)).sort((n,s)=>s.count-n.count||n.command.localeCompare(s.command))},lg=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Ht(t.globalPmRoot),generated_at:k()}),ug=async(e,t)=>{let n=await Ht(t.globalPmRoot);await Wi(t.globalPmRoot);let s=await Ht(t.globalPmRoot),i=Math.max(0,n.queue_entries-s.queue_entries),r=s.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:s.queue_entries,queue_entries_drained:i,queue_progressed:i>0,queue_empty:r,queue_drained:r,status:s,generated_at:k()}},mg=async(e,t)=>{let n=ng(e.limit),s=await $(t.queuePath),i=Ad(s),r=dg(i.entries),o=r.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:r.length,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_rows_total:i.rows_total,truncated:r.length>o.length,stats:o,generated_at:k()}},_g=async(e,t)=>{let n=await N(t.globalPmRoot),s=[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="",s&&await Ri(t.globalPmRoot,n,"telemetry:clear");let i=fe.join(t.globalPmRoot,Wf),r=await x(i);return await Bf.rm(i,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:s,runtime_dir_removed:r&&!await x(i),queue_exists_after:await x(t.queuePath),state_exists_after:await x(t.statePath),status:await Ht(t.globalPmRoot),generated_at:k()}},pg={status:lg,flush:ug,stats:mg,clear:_g};async function NT(e,t){let n=eg(e.subcommand),s=Q(process.cwd());return pg[n](e,{globalPmRoot:s,queuePath:fe.join(s,Sd),statePath:fe.join(s,Cd)})}(function(){try{var e=typeof window<"u"?window:typeof 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 fg=32;function gg(e){let t=[];for(let n of e??[]){let s=[];for(let i of n.split(",")){let r=i.slice(0,i.indexOf("=")).trim();s.length>0&&r!=="unit"&&r!=="threshold"&&(t.push(s.join(",")),s=[]),s.push(i)}t.push(s.join(","))}return t}function bs(e,t){let n=gg(e).map(i=>{let[r,...o]=i.split(","),a=r.indexOf("="),c=r.slice(0,a).trim(),d=r.slice(a+1).trim(),l=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(l))throw new h(`Invalid --measure "${i}"; expected name=value[,unit=...][,threshold=...]`,g.USAGE);let u,m;for(let _ of o){let p=_.indexOf("="),f=_.slice(0,p).trim(),y=_.slice(p+1).trim();if(f==="unit"&&y.length>0)u=y;else if(f==="threshold"&&y.length>0&&Number.isFinite(Number(y)))m=Number(y);else throw new h(`Invalid --measure attribute "${_}"`,g.USAGE)}return{name:c,value:l,unit:u,threshold:m,recorded_at:t}});return[...new Map(n.map(i=>[i.name,i])).values()].sort((i,r)=>i.name.localeCompare(r.name)).slice(0,fg)}function Rd(e,t,n){return e.flatMap(s=>(s.measurements??[]).filter(i=>i.name===t&&i.value<n).map(i=>({...i,run_id:s.run_id})))}function Od(e,t){let n=e.flatMap(r=>r.measurements??[]).filter(r=>r.name===t).sort((r,o)=>o.recorded_at.localeCompare(r.recorded_at)),s=n[0],i=n[1];return{name:t,latest:s?.value??null,previous:i?.value??null,delta:s!==void 0&&i!==void 0?s.value-i.value:null,unit:s?.unit}}import{spawn as Xd}from"node:child_process";import{cp as Dd,mkdir as kg,mkdtemp as Jd,open as Ts,readdir as xs,rm as Qd}from"node:fs/promises";import{tmpdir as Zd}from"node:os";import G 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 Nd=20;function hg(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return Nd;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?Nd:t}function ws(e){let t=[...e].filter(s=>s.run_id.trim().length>0&&s.started_at.trim().length>0&&s.finished_at.trim().length>0&&s.recorded_at.trim().length>0).sort((s,i)=>{let r=Ws(s.recorded_at,i.recorded_at);if(r!==0)return r;let o=s.run_id.localeCompare(i.run_id);return o!==0?o:s.kind.localeCompare(i.kind)}),n=hg();return t.length>n?t.slice(t.length-n):t}async function Vt(e){await ye({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=ws([...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 Ld=100;function ks(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new h(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,g.USAGE);return n}function yg(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Ld?n:`${n.slice(0,Ld-3)}...`}function Pd(e){return e.map((t,n)=>`${n+1}. ${yg(t)}`).join("; ")}function bg(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 wg(e,t){let n=e.command?.toLowerCase()??"",s=e.path?.toLowerCase()??"";return n.includes(t)||s.includes(t)}function Md(e,t){let n=bg(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((i,r)=>r+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new h(`Combine at most one linked-test selector per run: ${n.map(i=>`--${i}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,g.USAGE);let s=n[0];if(e.length===0)throw new h(`--${s} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,g.USAGE);if(s==="match"){let i=t.match.trim().toLowerCase();if(i.length===0)throw new h("--match requires a non-empty substring to match against linked-test command/path values",g.USAGE);let r=[],o=[];for(let a=0;a<e.length;a+=1)wg(e[a],i)&&(o.push(e[a]),r.push(a+1));if(o.length===0)throw new h(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Pd(e)}`,g.USAGE);return{selector:"match",requested:t.match,selected:o,selected_indexes:r,selected_count:o.length,skipped_count:e.length-o.length}}if(s==="only-index"){let i=ks(t.onlyIndex);if(i>e.length)throw new h(`--only-index ${i} is out of range: this item has ${e.length} linked test(s). Available entries: ${Pd(e)}`,g.USAGE);return{selector:"only-index",requested:String(i),selected:[e[i-1]],selected_indexes:[i],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]="7d05534b-3cf7-506c-8626-4bd4a42cbc80")}catch{}})();var Yt=20*1024*1024,vg=3e3,Tg=1e4,xg=5e3,Fd=120,Sg=new Set(["locks","extensions","runtime"]),Cg=new Set(["history","index","search","extensions","locks","runtime"]),Eg=[/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],Ig=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,Ag=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,Rg=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 Es(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let s=Number.parseInt(n,10);return!Number.isFinite(s)||s<=0?t:s}function Og(){return Es("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",vg)}function Ng(){return Es("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",Tg)}function Lg(){return Es("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",xg)}function Pg(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 Mg(e){let t=0,n=0,s=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"){n+=1;continue}s+=1}return{passed:t,failed:n,skipped:s}}function Is(e){let t=0,n=0,s=0,i=0;for(let r of e){let o=r.execution_context;!o||o.is_pm_command!==!0||(t+=1,o.is_pm_tracker_read_command===!0&&(n+=1),o.mismatch_detected===!0&&(s+=1),o.auto_pm_context_applied===!0&&(i+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:s,auto_remediated:i}}function Dg(e){let t=e??"project";if(!zs.includes(t))throw new h(`Invalid scope "${e}"`,g.USAGE);return t}function Xt(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(wn.includes(t))return t;throw new h(`Invalid --pm-context value "${e}". Expected one of: ${wn.join(", ")}`,g.USAGE)}function Fg(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Xt(e.pm_context_mode)}function jg(e,t){return e==="auto"?t?"tracker":"schema":e}function $g(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 Ug(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:s}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&s==="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 Gg(e,t){let n={};if(!e)return n;for(let s of e){let i=kn(s,t);if(i)for(let[r,o]of Object.entries(i))n[r]=o}return n}function qg(e,t){if(!e)return[];let n=[];for(let s of e){let i=vn(s,t);i&&n.push(...i)}return[...new Set(n)]}function Bg(e){let t=Jt(e);return Pe(t).some(n=>Nt(n)!==null)}function Wg(e){let t=Jt(e);return Pe(t).some(n=>{let s=Nt(n);if(!s)return!1;let i=Yn(s);return i?Rg.has(i.subcommand):!1})}function Kt(e){if(e)return Sa.has(e.subcommand)?ue(e.args,Ca)?.subcommand:e.subcommand}function jd(e,t){if(e==="npx"||e==="bunx")return be(t)?.command;if(e==="pnpm")return Kt(ue(t,zn));if(e==="npm")return Kt(ue(t,Hn));if(e==="yarn")return Kt(ue(t,Ta));if(e==="bun")return Kt(ue(t,xa))}function $d(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function vs(e){return!e||!Je(e.command)&&!Kn(e.command)?!1:Pt(e.args)==="test-all"}var zg=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])]),Hg=new Set(["npx","bunx"]);function el(e){let t=e.split(" ").filter(o=>o.length>0),n=Lt(t);if(n.length===0)return!1;let[s,...i]=n,r=zg.get(s);if(r){let o=i.findIndex(a=>r.test(a));return o>=0?el(i.slice(o+1).join(" ")):!1}return Je(s)||Qe(s)?Pt(i)==="test-all":s==="node"&&i.length>0&&Qe(i[0])?Pt(i.slice(1))==="test-all":Hg.has(s)?vs(be(i)):s==="pnpm"?vs(Mt(i)):s==="npm"?vs(Dt(i)):!1}function tl(e){let t=Jt(e);return Pe(t).some(n=>el(n))}function nl(e){if(tl(e))throw new h('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',g.USAGE)}function Jt(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function Vg(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 Kg(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 Yg(e){let t=e.split(" ").filter(r=>r.length>0),n=Lt(t);if(n.length===0)return!1;let[s,...i]=n;return s==="vitest"||s.endsWith("/vitest")||s.endsWith("/vitest.mjs")?!0:s==="node"?Xg(i):Jg(s,i)}function Xg(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function Jg(e,t){return e==="npx"||e==="bunx"?$d(be(t)?.command):e==="pnpm"||e==="npm"?$d((e==="pnpm"?Mt(t):Dt(t))?.command)||jd(e,t)==="vitest":(e==="yarn"||e==="bun")&&jd(e,t)==="vitest"}function sl(e){let t=Jt(e);if(Pe(t).some(i=>!Vg(i)&&Yg(i)&&!Kg(i)))throw new h('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".',g.USAGE)}function Qg(e){if(tl(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function Zg(e){return e?e.map(eh):[]}function eh(e){let t=e.trim(),n=Oo(t)?No(un(e,"--add"),"--add"):{command:t},s=U(n.command);if(!s)throw new h("--add requires command=<value> or a bare command (path=<value> is optional metadata)",g.USAGE);return nl(s),sl(s),{command:s,path:U(n.path),scope:Dg(n.scope),timeout_seconds:th(U(n.timeout_seconds),U(n.timeout)),pm_context_mode:Po(U(n.pm_context_mode),"--add"),env_set:kn(U(n.env_set),"--add"),env_clear:vn(U(n.env_clear),"--add"),shared_host_safe:Lo(U(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Tn(U(n.assert_stdout_contains)),assert_stdout_regex:xn(U(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Tn(U(n.assert_stderr_contains)),assert_stderr_regex:xn(U(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Mo(U(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Do(U(n.assert_json_field_equals),"--add"),assert_json_field_gte:Fo(U(n.assert_json_field_gte),"--add"),note:U(n.note)}}function U(e){let t=e?.trim();return t&&t.length>0?t:void 0}function th(e,t){if(e&&t&&e!==t)throw new h("--add timeout and timeout_seconds must match when both are provided",g.USAGE);let n=e??t;if(n===void 0)return;let s=Math.floor(Be(n,"timeout_seconds"));if(s<=0)throw new h("--add timeout_seconds must be a positive integer",g.USAGE);return s}function nh(e){return e?e.flatMap(t=>{let n=jo(t,"--add-json");for(let s of n){let i=s.command;if(!i)throw new h("--add-json requires a non-empty command string",g.USAGE);nl(i),sl(i)}return n}):[]}function sh(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new h("--remove requires command or path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:path|command)\s*[:=]/i.test(n)||n.startsWith("```")){let s=un(n,"--remove"),i=s.path??s.command;if(!i?.trim())throw new h("--remove requires command=<value> and/or path=<value>",g.USAGE);return i.trim()}return n}):[]}function ih(e){try{e.stdin?.end()}catch{}}function il(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=Fd?t:`${t.slice(0,Fd-3)}...`}function rl(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Ss(e){try{process.stderr.write(`${e}
11
- `)}catch{}}function rh(e,t){if(!rl(t))return null;let n=il(e.command),s=Date.now();Ss(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let i=setInterval(()=>{let r=Date.now()-s;Ss(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${r} command="${n}"`)},Ng());return i.unref?.(),i}function oh(e,t,n,s){if(!rl(s))return;let i=il(e.command),r=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 d=t.exitCode===null?"null":String(t.exitCode),l=c.length>0?` ${c.join(" ")}`:"";Ss(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${d} elapsed_ms=${r}${l} command="${i}"`)}async function Ud(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Xd("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 ah(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function ch(e,t){let n=!1;return async()=>{if(n)return;n=!0;let s=e.pid;if(!s||s<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await Ud(s);return}try{process.kill(-s,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{Ud(s)},Og()),t.forceKillTimer.unref?.()}}function dh(e){return new Promise(t=>{let n=!1,s=null,i=(r,o=!1)=>{n||(n=!0,s&&(clearTimeout(s),s=null),o&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(r))};e.on("exit",(r,o)=>{n||(s=setTimeout(()=>{i({code:r,signal:o},!0)},Lg()),s.unref?.())}),e.on("close",(r,o)=>{i({code:r,signal:o})})})}function lh(e,t,n,s){return Xd(e,{cwd:process.cwd(),env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,s]})}async function Gd(e){let t=await Ts(e,"r");try{let n=(await t.stat()).size,s=Math.min(n,Yt),i=Buffer.alloc(s);return s>0&&await t.read(i,0,s,0),{text:i.toString("utf8"),truncated:n>Yt}}finally{await t.close()}}async function uh(e,t,n,s,i){let r=Date.now(),o=await Jd(G.join(Zd(),"pm-linked-test-output-"));try{let a=G.join(o,"stdout.log"),c=G.join(o,"stderr.log"),[d,l]=await Promise.all([Ts(a,"w"),Ts(c,"w")]),u;try{u=lh(e,n,d.fd,l.fd)}finally{await Promise.all([d.close(),l.close()])}ih(u);let m={heartbeat:rh(s,i),forceKillTimer:null,timedOutTimer:null},_=ch(u,m),p=!1,f;u.on("error",q=>{f=q.message}),m.timedOutTimer=setTimeout(()=>{p=!0,_()},t),m.timedOutTimer.unref?.();let{code:y,signal:b}=await dh(u);ah(m);let[v,E]=await Promise.all([Gd(a),Gd(c)]),S=v.truncated||E.truncated,w=S?`
1
+ import{a as vt}from"./chunk-D7I3TUGV.js";import{b as Ho}from"./chunk-4AVFKHHC.js";import{a as zo}from"./chunk-FDBRXV25.js";import{a as Wo}from"./chunk-DQGJ2RWT.js";import{f as Io}from"./chunk-5PBP2ZP3.js";import{B as Vo,c as En,m as qo,n as Cn,o as In,r as Bo}from"./chunk-SD3YXU2U.js";import{e as ko,j as Ie,l as Uo,m as Go,n as kt}from"./chunk-3ZJRFYY2.js";import{oa as Ao,qa as An}from"./chunk-XPOQQJTX.js";import{b as zi,c as Hi,d as Vi,e as Ki,g as Yi,l as Xi,m as Ji,o as Qi,p as Zi}from"./chunk-ZFBWCKYF.js";import{B as wo,x as bo}from"./chunk-SV3YQ4RY.js";import{A as xn,B as Do,C as Fo,D as jo,E as $o,P as Sn,q as No,r as Lo,s as bn,u as wn,v as kn,w as vn,x as Po,y as Mo,z as Tn}from"./chunk-BP6EMEDP.js";import{d as Oo}from"./chunk-DWOAOZHZ.js";import{i as Ro}from"./chunk-PECV7L5T.js";import{j as xo,o as So,p as Eo,q as Co}from"./chunk-3KFVGGRE.js";import{a as vo,d as To,e as wt}from"./chunk-QJ7C3JIW.js";import{$ as Vr,A as gn,Aa as _o,B as kr,Ba as po,C as vr,Ca as le,D as Tr,Da as fo,E as xr,Ea as go,F as Sr,Fa as ho,G as Er,Ga as yo,H as Cr,I as Ir,J as Ar,K as Rr,L as Or,M as Nr,N as Lr,O as Pr,P as Mr,Q as Dr,R as Fr,S as jr,T as $r,U as Ur,V as Gr,W as qr,X as Br,Y as Wr,Z as zr,_ as Hr,c as fn,da as Kr,e as er,ea as Yr,f as tr,fa as Xr,g as nr,ga as Jr,h as sr,ha as Qr,i as ir,ia as Zr,j as rr,ja as eo,k as or,ka as to,l as ar,la as no,m as cr,ma as so,n as dr,na as io,o as lr,oa as ro,p as ur,q as mr,r as _r,ra as oo,s as pr,sa as ao,t as fr,ta as hn,u as gr,ua as co,v as hr,w as yr,wa as yn,x as br,xa as lo,ya as uo,z as wr,za as mo}from"./chunk-RUAU5OSH.js";import{B as _n,C as Mi,Ea as Gi,Fa as qi,Ga as Bi,Ha as Wi,M as Di,R as Fi,T as ji,W as pn,Y as $i,wa as Ui,x as Oi}from"./chunk-MDTH7SAE.js";import{a as mn}from"./chunk-M4VEE3FK.js";import{f as un,i as Ci,j as Be}from"./chunk-R6LSRGPS.js";import{$a as ri,$c as pt,A as g,Aa as Xs,Ad as pi,Af as N,Bb as an,Be as qe,Bf as Ri,C as h,Cb as cn,Da as V,Db as dn,E as P,Ec as mt,Ga as Js,Ia as ge,Ie as Si,Kd as fi,La as R,Lf as Ni,Mf as Li,Na as Q,Nc as Z,Nf as Pi,Oa as O,Oc as ci,Oe as ln,Of as bt,Pc as di,Pf as Ce,Qa as Qs,R as k,Ra as Zs,Rc as li,Sa as dt,Sf as ye,T as Ws,Ua as ei,Va as sn,Vb as lt,Wa as rn,Xa as ti,Xb as ut,Xc as ui,Ya as ni,Yc as _t,Za as si,_a as ii,a as de,ab as oi,ad as ft,ae as gi,b as x,c as $,d as se,da as nn,dd as Ee,g as $s,gd as gt,ha as zs,ie as hi,jb as on,la as Hs,lc as W,lf as ht,ma as Vs,mf as Ei,na as Ks,oa as Ys,p as Us,qf as yt,r as Gs,re as yi,se as bi,t as qs,te as wi,uc as Se,ud as mi,ue as ki,ve as vi,wc as X,we as Ti,wf as Ii,x as Bs,xe as he,y as ct,yc as ai,yd as _i,ye as xi,z as Ge,zd as ee,zf as Ai}from"./chunk-HS7OVAUN.js";(function(){try{var e=typeof window<"u"?window:typeof 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 Ko(e,t,n){return[...await pi(Zs(e,t),t).catch(()=>[])].reverse().find(r=>r.patch.some(o=>o.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]="9c3fc3ab-ba84-5f6d-a05c-bc452ae26c15")}catch{}})();var Yo="no_available_next_item";function Ol(e){return e instanceof h&&e.context?.code==="already_claimed_by"}async function Nl(e,t,n,s={}){let i=R(process.cwd(),n.path);if(!await x(O(i)))throw new h(`Tracker is not initialized at ${i}. Run pm init first.`,g.NOT_FOUND);let r=await N(i),o=Z(r.schema),a=ee(s.author,r.author_default),c=_i(a),d=null,l=!1,u=[],m=await ye({pmRoot:i,settings:r,id:e,op:"claim",author:a,message:s.message,force:t,skipNoop:!0,async mutate(_){let f=_.metadata.assignee??"",y=_.metadata.claim_principal?.trim()||f;if(d=f.trim().length>0?f:null,li(_.metadata.status,o)&&!t)throw new h(`Cannot claim terminal item ${_.metadata.id} without --force`,g.CONFLICT);if(d!==null&&y!==c){if(s.ifAvailable===!0)return l=!0,u.push(`claim_skipped_held_by:${d}`),{changedFields:[]};if(!t){let v=await Ko(i,_.metadata.id,f);throw new h(`Item ${_.metadata.id} is already ${v}. Use --force to take over, or --if-available to skip without failing.`,g.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."]})}u.push(`claim_takeover:${d}->${a}`)}return _.metadata.assignee=a,_.metadata.claim_principal=c,{changedFields:["assignee","claim_principal"],warnings:u}}});return{item:m.item,claimed_by:l&&d!==null?d:a,previous_assignee:d,forced:t,...l?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function kb(e,t,n={},s={}){let i=Ll(n.maxAttempts),r=await N(R(process.cwd(),t.path)),o={...n,author:ee(n.author,r.author_default)},a=await Ao({...s,callerAuthor:o.author,limit:String(i)},t),c=[a.recommended,...a.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return Pl(c.slice(0,i),e,t,o)}function Ll(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new h("--max-attempts must be an integer from 1 to 100",g.USAGE);return t}async function Pl(e,t,n,s={},i=Nl){let r=0;for(let a of e){r+=1;try{let c=await i(a.id,t,n,s),d={...c,recommendation:a,attempts:r,available:!0};if(!c.skipped)return d}catch(c){if(!Ol(c))throw c}}if(s.ifAvailable===!0)return{available:!1,item:null,claimed_by:ee(s.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:r,warnings:[Yo]};let o=r===0;throw new h(o?"No actionable items matched the selection filters":"No actionable item remained available to claim",o?g.NOT_FOUND:g.CONFLICT,{code:Yo,why:o?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[o?"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 vb(e,t,n,s={}){let i=R(process.cwd(),n.path);if(!await x(O(i)))throw new h(`Tracker is not initialized at ${i}. Run pm init first.`,g.NOT_FOUND);let r=await N(i),o=ee(s.author,r.author_default),a=s.ownershipReleaseBypass===!0,c=null,d;try{d=await ye({pmRoot:i,settings:r,id:e,op:"release",author:o,message:s.message,force:t,bypassAssigneeConflict:a,mutate(l){return c=l.metadata.assignee??null,!c&&!l.metadata.claim_principal?{changedFields:[]}:(delete l.metadata.assignee,delete l.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(l){Io(l,{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{item:d.item,released_by:o,previous_assignee:c,forced:t}}import Rn from"node:fs/promises";import Xo 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]="a6c0aa24-501a-5e76-a669-91d125634cf1")}catch{}})();var Ml=1440*60*1e3,Dl=new Set(["committed","compensated"]);function Fl(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function jl(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function $l(e,t,n,s,i){let r=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(r))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=s-r;return Dl.has(t)?o>i?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function Ul(e,t,n,s){let i=s.hooks?.onRead?await s.hooks.onRead(e):[],r=jl(await Rn.readFile(e,"utf8")),o=$l(t,r.status,r.updatedAt,s.nowMs,s.retentionMs);return o.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),o.remove&&!s.dryRun&&(await Rn.rm(e,{force:!0}),s.hooks?.onWrite&&i.push(...await s.hooks.onWrite(e))),{decision:o,warnings:i}}async function Jo(e,t){let{dryRun:n,hooks:s}=t,i=t.now??Date.now(),r=Math.max(0,t.retentionDays)*Ml,o=Xo.join(e,"transactions","sdk"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Rn.readdir(o)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(Fl(d,"ENOENT"))return a;throw d}for(let d of c){let l=Xo.join(o,d),u=`transactions/sdk/${d}`,m=await Ul(l,u,d,{dryRun:n,hooks:s,nowMs:i,retentionMs:r});a.warnings.push(...m.warnings),a.scanned+=1;let{decision:_}=m;if(!_.remove){a.retained.push(u),a.entries.push(_.entry);continue}a.removed.push(u),a.entries.push(_.entry)}return a}import Ae from"node:fs/promises";import Et from"node:path";import Tt from"node:fs/promises";import On 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]="8cc32963-26eb-5e08-bffb-2d8da152a43f")}catch{}})();var Gl=864e5;function xt(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function ql(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function Bl(e,t){let n;try{n=await Tt.readdir(e,{withFileTypes:!0})}catch(i){if(xt(i,"ENOENT"))return[];throw i}let s=[];for(let i of n)if(i.isDirectory()){let r=On.join(e,i.name),o;try{o=await Tt.readdir(r)}catch(a){xt(a,"ENOENT")||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let a of o)a.endsWith(".json")&&s.push(`${i.name}/${a}`)}else i.name.endsWith(".json")&&s.push(i.name);return s.sort()}async function Qo(e,t){let{dryRun:n,hooks:s}=t,i=t.now??Date.now(),r=Math.max(0,t.retentionDays)*Gl,o=On.join(e,"checkpoints"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await Bl(o,a.warnings);for(let d of c){let l=On.join(o,d),u=`checkpoints/${d}`;a.scanned+=1,s?.onRead&&a.warnings.push(...await s.onRead(l));let m;try{m=await Tt.readFile(l,"utf8")}catch(b){if(xt(b,"ENOENT")){a.scanned-=1;continue}a.warnings.push(`checkpoint_unreadable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let _=ql(m),p=_===null?Number.NaN:Date.parse(_);if(!Number.isFinite(p)){a.warnings.push(`checkpoint_unparseable:${d}`),a.retained.push(u),a.entries.push({file:u,created_at:_,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=i-p,y={file:u,created_at:_,age_seconds:Math.floor(f/1e3),stale:f>r,reason:f>r?"expired":"active"};if(!y.stale){a.retained.push(u),a.entries.push(y);continue}if(!n){try{await Tt.unlink(l)}catch(b){if(!xt(b,"ENOENT")){a.warnings.push(`checkpoint_remove_failed:${d}`),a.retained.push(u),a.entries.push(y);continue}}s?.onWrite&&a.warnings.push(...await s.onWrite(l))}a.removed.push(u),a.entries.push(y)}return a}import We from"node:fs/promises";import St 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]="a026943f-1a46-526b-bfaa-435025c65c2a")}catch{}})();function Wl(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:s,owner:i,created_at:r,ttl_seconds:o}=n;return typeof s!="string"||typeof i!="string"||typeof r!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:s,owner:i,created_at:r,ttl_seconds:o}}function ze(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Zo(e,t,n){let s=Wl(t);if(s===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(s.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:s.id,owner:s.owner,created_at:s.created_at,ttl_seconds:s.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let r=n-i,o=Math.floor(r/1e3),a=r>s.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:s.id,owner:s.owner,created_at:s.created_at,ttl_seconds:s.ttl_seconds,age_seconds:o,stale:a,reason:a?"expired":"active"}}}async function ea(e,t){let n=t??Date.now(),s=St.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},r;try{r=(await We.readdir(s)).filter(a=>a.endsWith(".lock")).sort()}catch(o){if(ze(o,"ENOENT"))return i;throw o}for(let o of r){let a;try{a=await We.readFile(St.join(s,o),"utf8")}catch(d){if(ze(d,"ENOENT"))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=Zo(o,a,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function ta(e,t){let{dryRun:n,hooks:s}=t,i=t.now??Date.now(),r=St.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},a;try{a=(await We.readdir(r)).filter(d=>d.endsWith(".lock")).sort()}catch(c){if(ze(c,"ENOENT"))return o;throw c}for(let c of a){o.scanned+=1;let d=St.join(r,c),l=`locks/${c}`;if(s?.onRead){let _=await s.onRead(d);o.warnings.push(..._)}let u;try{u=await We.readFile(d,"utf8")}catch(_){if(ze(_,"ENOENT")){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${c}`),o.retained.push(l),o.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=Zo(c,u,i);if(m.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}if(m.detail==="active"){o.retained.push(l),o.entries.push(m.entry);continue}if(!n){try{await We.unlink(d)}catch(_){if(!ze(_,"ENOENT")){o.warnings.push(`lock_remove_failed:${c}`),o.retained.push(l),o.entries.push(m.entry);continue}}if(s?.onWrite){let _=await s.onWrite(d);o.warnings.push(..._)}}o.removed.push(l),o.entries.push(m.entry)}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]="0973a87f-2b63-5fa1-9624-82897d181f71")}catch{}})();var He=["index","embeddings","runtime","locks","checkpoints","transactions"],zl=1440*60*1e3,Hl=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];function na(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function Vl(e,t,n){let s=t.relativePath,i=Et.join(e,s),r=await X({path:i,scope:"project"});try{let o=await Ae.stat(i);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...r,`not_a_file:${s}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...r,`not_a_directory:${s}`]};if(n)return{removed:!0,warnings:r};t.kind==="file"?await Ae.unlink(i):await Ae.rm(i,{recursive:!0,force:!0});let a=await Se({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...r,...a]}}catch(o){if(na(o,"ENOENT"))return{removed:!1,warnings:r};throw o}}async function Kl(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],s=[],i=[],r=[],o=Date.now()-zl;for(let a of n){let c=Et.join(e,a.relativePath);if(!await x(c))continue;let d=(await Ae.readdir(c)).filter(l=>l.startsWith(a.prefix)).sort();for(let l of d){let u=Et.posix.join(a.relativePath,l),m=Et.join(c,l);r.push(...await X({path:m,scope:"project"}));let _=await Ae.stat(m).catch(p=>{if(!na(p,"ENOENT"))throw p});if(_){if(_.mtimeMs>o){i.push(u);continue}s.push(u),!t&&(await Ae.rm(m,{recursive:!0,force:!0}),r.push(...await Se({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:s,retained:i,warnings:r}}function Yl(e){if(!e||e.length===0)return[...He];let t=e.flatMap(s=>s.split(",")).map(s=>s.trim().toLowerCase()).filter(s=>s.length>0);if(t.length===0)throw new h(`--scope requires at least one value (${He.join(",")})`,g.USAGE);let n=new Set;for(let s of t){if(!He.includes(s))throw new h(`Invalid --scope value "${s}". Expected one or more of: ${He.join(", ")}`,g.USAGE);n.add(s)}return He.filter(s=>n.has(s))}function Xl(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),s=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&s&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function zb(e,t={}){let n=R(process.cwd(),e.path);if(!await x(O(n)))throw new h(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let s=await N(n),i=t.dryRun===!0,r=Yl(t.scope),o=Hl.filter(p=>r.includes(p.scope)),a=[],c=[],d=[];for(let p of o){let f=await Vl(n,p,i);f.removed?a.push(p.relativePath):c.push(p.relativePath),d.push(...f.warnings)}if(r.includes("runtime")){let p=await Kl(n,i);a.push(...p.removed),c.push(...p.retained),d.push(...p.warnings)}let l;if(r.includes("locks")){let p=await ta(n,{dryRun:i,hooks:{onRead:f=>X({path:f,scope:"project"}),onWrite:f=>Se({path:f,scope:"project",op:"gc:lock_remove"})}});a.push(...p.removed),c.push(...p.retained),d.push(...p.warnings),l={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(r.includes("transactions")){let p=s.checkpoints.retention_days,f=await Jo(n,{dryRun:i,retentionDays:p,hooks:{onRead:y=>X({path:y,scope:"project"}),onWrite:y=>Se({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),u={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length,retention_days:p}}let m;if(r.includes("checkpoints")){let p=s.checkpoints.retention_days,f=await Qo(n,{dryRun:i,retentionDays:p,hooks:{onRead:y=>X({path:y,scope:"project"}),onWrite:y=>Se({path:y,scope:"project",op:"gc:checkpoint_remove"})}});a.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),m={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length,retention_days:p}}d.push(...await ai({mode:i?"gc:dry-run":"gc",total_items:o.length}));let _=Xl({dryRun:i,scopes:r,removed:a});return{ok:d.length===0,dry_run:i,scope:r,removed:a,retained:c,warnings:d,...l?{locks:l}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:_,generated_at:k()}}import Ct from"node:fs/promises";import It 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]="364a8999-58e2-58c9-bfa6-acd8c42ec471")}catch{}})();var Jl="2026-07-15T06:22:12.276Z",Ql=Date.parse(Jl),Zl=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],sa=e=>typeof e=="string"?e:"",ia=e=>{let t=e??{},n=sa(t.author).trim().toLowerCase(),s=Number(["","unknown"].includes(n)),i=+(Date.parse(sa(t.ts))>=Ql);return Zl[s][i]};function ra(e,t,n=20,s=new Set,i=!1){let r=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[m,_]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(_)}catch{continue}d+=1;let f=ia(p);if(f!=="attributed"){if(l+=1,f==="actionable_unknown"&&s.has(`${e}:${m+1}`)){u+=1;continue}a[f]+=1,i&&f==="actionable_unknown"&&o.push({item_id:e,line:m+1}),r.length<c&&r.push({item_id:e,line:m+1})}}return{checked_events:d,unknown_event_count:l,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:r,samples_truncated:a.legacy_unknown+a.actionable_unknown>r.length,actionable_events:o}}var Jb=(e,t,n=20,s=new Set)=>ra(e,t,n,s);function eu(e){let t=new Set;for(let n of e.split(/\r?\n/)){let s;try{s=JSON.parse(n)}catch{continue}let r=(typeof s=="object"&&s!==null&&typeof s.context=="object"&&s.context!==null?s.context:{}).author_acknowledgment;if(!(typeof r!="object"||r===null||!Array.isArray(r.events)))for(let o of r.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Ve=async(e,t=20,n=!1)=>{let s=It.join(e,"history"),i;try{i=(await Ct.readdir(s)).filter(b=>b.endsWith(".jsonl")).sort((b,v)=>b.localeCompare(v))}catch{i=[]}let r=new Set,o=[],a=[],c=0,d=0,l=0,u=0,m=0,_=0,p="_workspace.jsonl",f=new Set;if(i.includes(p))try{f=eu(await Ct.readFile(It.join(s,p),"utf8"))}catch{f=new Set}for(let b of i){let v;try{v=await Ct.readFile(It.join(s,b),"utf8")}catch{continue}let C=b.slice(0,-6),S=ra(C,v,t-o.length,f,n);c+=1,d+=S.checked_events,l+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,_+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&r.add(C),o.push(...S.samples),n&&a.push(...S.actionable_events)}let y=u+m;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:_,affected_item_ids:[...r].sort((b,v)=>b.localeCompare(v)),samples:o,samples_truncated:y>o.length,...n?{actionable_events:a}:{}}};async function Qb(e,t){let n=t.reviewer.trim(),s=t.attributed_author.trim(),i=t.reason.trim(),r=t.events??[];if(+(t.all_actionable===!0)+ +(r.length>0)>1)throw new TypeError("Author acknowledgment accepts either explicit events or all_actionable, not both.");let a=t.all_actionable===!0?(await Ve(e,0,!0)).actionable_events:r;if([a.length>0,n.length>0,n.toLowerCase()!=="unknown",s.length>0,s.toLowerCase()!=="unknown",i.length>0].includes(!1))throw new TypeError("Author acknowledgment requires events, reviewer, attributed_author, and reason.");let d=[...new Map(a.map(m=>[`${m.item_id}:${m.line}`,{item_id:m.item_id,line:m.line}])).values()].sort((m,_)=>m.item_id.localeCompare(_.item_id)||m.line-_.line);for(let m of d){if([/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1))throw new TypeError(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`);let p;try{let y=(await Ct.readFile(It.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];p=JSON.parse(y??"")}catch{throw new TypeError(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`)}if(ia(p)!=="actionable_unknown")throw new TypeError(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`)}let l=await N(e),u=await yt({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:d,attributed_author:s}},message:i,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms});return{acknowledged:d.length,history_path:u.historyPath}}import{execFile as tu}from"node:child_process";import{randomUUID as nu}from"node:crypto";import{readdir as su,readFile as iu}from"node:fs/promises";import Ke from"node:path";import{promisify as ru}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]="c4721ede-e557-5720-a9c2-4b2b344cc6cc")}catch{}})();var ou=ru(tu);async function Nn(e){try{let{stdout:t}=await ou("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}function oa(e){return`${e}.json`}function cw(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,preferred:e.preferred,decisions:e.decisions.map(t=>({field:t.field,retained_hash:dn(an(t.retained)),discarded_hash:dn(an(t.discarded))}))}}async function dw(e){let t=await Nn(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),s=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,i=Ke.basename(s,Ke.extname(s)),r={version:1,id:nu(),item_path:s.replaceAll("\\","/"),item_id:i,preferred:e.preferred,fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:k()};return await de(t),await se(Ke.join(t,oa(r.id)),`${JSON.stringify(r,null,2)}
2
+ `),r}async function Ye(e,t={}){let n=await Nn(e);if(n===null||!await x(n))return[];let s=[],i;try{i=await su(n)}catch{return[]}for(let r of i.sort((o,a)=>o.localeCompare(a)))if(r.endsWith(".json"))try{let o=JSON.parse(await iu(Ke.join(n,r),"utf8"));o.version===1&&(t.includeReconciled||o.state==="pending")&&s.push(o)}catch{}return s.sort((r,o)=>r.created_at.localeCompare(o.created_at))}async function lw(e,t){let n=await Nn(e);n!==null&&await se(Ke.join(n,oa(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:k()},null,2)}
3
+ `)}async function uw(e){let t=await Ye(e.cwd??process.cwd(),e);return{ok:!0,count:t.length,receipts:t,generated_at:k()}}import re from"node:fs/promises";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]="6a350683-275b-5d4d-ae02-45798b115f89")}catch{}})();var au=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:"pm validate --check-history-drift --fix-hints",summary:"Historical mutations lack attributable authorship. Configure PM_AUTHOR, pass global --author, or set author_default so future audit events are attributable."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_unknown_author_events",command:"pm config project set author_default <stable-agent-id>",summary:"Historical mutations lack attributable authorship. Set a stable default or use invocation-wide --author for future events; existing audit history remains append-only."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function cu(e){if(typeof e!="string")return;let t=e.trim();for(let n of au)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Ln(e){let t={};for(let n of e){let s=cu(n);s!==void 0&&!Object.prototype.hasOwnProperty.call(t,s.code)&&(t[s.code]=s.command)}return t}function aa(e){return Object.values(Ln(e))}import{execFile as du}from"node:child_process";import{realpath as lu}from"node:fs/promises";import ca from"node:path";import{promisify as uu}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]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var mu=uu(du),_u=32*1024*1024,pu=1e4,fu=["search/eval-queries.json"];function Pn(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function gu(e){return`'${e.replaceAll("'","'\\''")}'`}async function hu(e,t=lu){return t(e).catch(()=>ca.resolve(e))}async function At(e){let t=await Ie(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await hu(e),s=Pn(ca.relative(t,n));if(s.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=ko.map(r=>`${s}/${Pn(r)}`);try{let{stdout:r}=await mu("git",["ls-files","-z","--",...i.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:_u,windowsHide:!0,timeout:pu}),o=new Set(fu.map(d=>`${s}/${d}`)),a=[...new Set(r.split("\0").filter(d=>d.length>0&&!o.has(Pn(d))))].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>a.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:s,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(d=>gu(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:s,tracked_paths:[],tracked_path_count:0,remediation_command: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]="34fc99f6-45e5-53f2-96eb-767d50ed449c")}catch{}})();var yu=new Set(Bi),la=25,Xe=8,bu=z.join("runtime","telemetry","events.jsonl"),wu=z.join("runtime","telemetry","state.json"),ku=2500,vu=500,ua=qi-3,Tu=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function ma(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("stale_in_progress_items:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function _a(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Oe(e){return e.trim().toLowerCase()}function Fn(e,t){let n=Oe(e),s=Oe(t);return n.startsWith("builtin-")?!0:s==="beads"||s==="todos"}async function Un(e){try{return(await re.stat(e)).isDirectory()}catch{return!1}}async function xu(e){let t=(await re.readdir(e,{withFileTypes:!0})).filter(s=>s.isDirectory()),n=await Promise.all(t.map(s=>re.readdir(z.join(e,s.name),{withFileTypes:!0})));return new Set(n.flatMap(s=>s.filter(i=>i.isFile()).filter(i=>ge.some(r=>i.name.endsWith(r))).map(i=>z.parse(i.name).name)))}async function Su(e,t,n,s){let i=await X({path:e,scope:"project"}),r=t!=="_workspace"&&!s.has(t);if(!n.enabled&&!r)return{warnings:i,overThreshold:!1,classification:"live"};let o;try{o=await re.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let a="live";if(r){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{a=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function Eu(e,t,n){let s=z.join(e,"history");if(!await Un(s))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await re.readdir(s)).filter(u=>u.endsWith(".jsonl")).sort((u,m)=>u.localeCompare(m)),o=t.enabled?t.max_entries:null,a=[],c=[],d=[],l=[];for(let u of i){let m=z.join(s,u),_=u.slice(0,-6),p=await Su(m,_,t,n);a.push(...p.warnings),p.classification==="tombstone"&&d.push(_),p.classification==="orphaned"&&l.push(_),p.overThreshold&&c.push(_)}return{count:i.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...l.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:o,tombstones:d,orphaned:l}}function jn(e,t){return z.relative(e,t).replaceAll("\\","/")}async function pa(e,t){let n=[...new Set(Object.values(t))].sort((i,r)=>i.localeCompare(r)),s=[];for(let i of n){let r=z.join(e,i),o=[];try{o=await re.readdir(r)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT")continue;continue}for(let a of o)ge.some(c=>a.toLowerCase().endsWith(c))&&s.push(z.join(r,a))}return s.sort((i,r)=>jn(e,i).localeCompare(jn(e,r))),s}function Cu(e){return!(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")}async function Iu(e,t,n){let s=await pa(e,t),i=[],r=[],o=[],a=[],c=mt(W());for(let d of s){let l=jn(e,d),u;try{u=await re.readFile(d,"utf8")}catch{i.push(l);continue}let m=Ee(u);if(m){r.push({path:l,...m});continue}try{let _=gt(u,{format:Qs(d),schema:n,extensionFieldNames:c});a.push({ref:l,version:_t(_.metadata)})}catch{o.push(l)}}return{paths:s,unreadable:i,conflictMarkers:r,parseFailures:o,formatVersions:a}}async function Au(e){let t=z.join(e,"history"),n=[],s=[],i=[],r=[];try{r=(await re.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,a)=>o.localeCompare(a))}catch(o){Cu(o)&&n.push("history")}for(let o of r){let a=o.slice(0,-6),c;try{c=await re.readFile(z.join(t,o),"utf8")}catch{n.push(a);continue}let d=Ee(c);if(d){s.push({id:a,...d});continue}c.split(/\r?\n/).forEach((l,u)=>{if(l.trim())try{JSON.parse(l)}catch{i.push({id:a,line:u+1})}})}return{files:r,unreadable:n,conflictMarkers:s,invalidJson:i}}async function Ru(e,t,n,s){let i=await Iu(e,t,n),r=await Au(e),o=pt(i.formatVersions),a=await At(e),c=await Ie(e),d=c===null?null:await kt(c),l=c===null?[]:await Ye(c),u=d?.status==="missing"&&d.missing_keys.length===5&&d.drifted_keys.length===0,m=[...i.unreadable.map(p=>`integrity_item_unreadable:${p}`),...i.conflictMarkers.map(p=>`integrity_item_conflict_marker:${p.path}:L${p.line}`),...i.parseFailures.map(p=>`integrity_item_parse_failed:${p}`),...r.unreadable.map(p=>`integrity_history_unreadable:${p}`),...r.conflictMarkers.map(p=>`integrity_history_conflict_marker:${p.id}:L${p.line}`),...r.invalidJson.map(p=>`integrity_history_invalid_json:${p.id}:L${p.line}`),...o.outdated.map(p=>`integrity_item_outdated_format_version:${p}`),...o.ahead.map(p=>`integrity_item_ahead_format_version:${p}`),...a.tracked_path_count>0?[`tracked_runtime_cache_files:${a.tracked_path_count}`]:[],...d!==null&&d.status!=="ok"?[`merge_driver_configuration_${u?"missing":"drift"}:${d.missing_keys.length+d.drifted_keys.length}`]:[],...l.length>0?[`merge_decisions_unreviewed:${l.length}`]:[]],_=[...new Set(m)].sort((p,f)=>p.localeCompare(f));return{check:{name:"integrity",status:_.length===0?"ok":"warn",details:{checked_item_files:i.paths.length,checked_history_streams:r.files.length,counts:{item_unreadable:i.unreadable.length,item_conflict_markers:i.conflictMarkers.length,item_parse_failures:i.parseFailures.length,history_unreadable:r.unreadable.length,history_conflict_markers:r.conflictMarkers.length,history_invalid_json:r.invalidJson.length,item_outdated_format_version:o.outdated.length,item_ahead_format_version:o.ahead.length,tracked_runtime_cache_files:a.tracked_path_count,merge_driver_configuration:d===null||d.status==="ok"?0:d.missing_keys.length+d.drifted_keys.length,pending_merge_decisions:l.length},item_unreadable:i.unreadable,item_conflict_markers:i.conflictMarkers,item_parse_failures:i.parseFailures,item_outdated_format_version:o.outdated,item_ahead_format_version:o.ahead,history_unreadable:r.unreadable,history_conflict_markers:r.conflictMarkers,history_invalid_json:r.invalidJson,tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command},merge_driver_configuration:d===null?null:{...d,required:s},pending_merge_decision_items:[...new Set(l.map(p=>p.item_id))].sort((p,f)=>p.localeCompare(f))}},warnings:_}}function Ou(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function Nu(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:Ou(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Lu(e,t){let n=P(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Pu(e){let n=P(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function Mu(e){return P(e.reason)??P(e.error)??P(e.message)}function Mn(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let s=(e.name??"").localeCompare(t.name??"");return s!==0?s:(e.id??"").localeCompare(t.id??"")}function Du(e){let t=[],n=[],s=[];e.forEach((r,o)=>{let a=Lu(r.definition,o),c=Pu(r.definition);if(c==="applied"){t.push({layer:r.layer,name:r.name,id:a,status:c});return}if(c==="failed"){s.push({layer:r.layer,name:r.name,id:a,status:c,reason:Mu(r.definition)});return}n.push({layer:r.layer,name:r.name,id:a,status:c})}),t.sort(Mn),n.sort(Mn),s.sort(Mn);let i=[...s.map(r=>`extension_migration_failed:${r.layer}:${r.name}:${r.id}`),...n.map(r=>`extension_migration_pending:${r.layer}:${r.name}:${r.id}`)];return{summary:{applied:t,pending:n,failed:s,applied_count:t.length,pending_count:n.length,failed_count:s.length},warnings:i}}function fa(e,t,n,s,i,r,o,a,c){let d=[...new Set(e)].sort((y,b)=>y.localeCompare(b)),l=[...new Set(d.map(y=>_a(y)))].sort((y,b)=>y.localeCompare(b)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,m=c.length>0,_=m?"partial":"full",p=[],f=qo(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return f&&p.push(f),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(s.failed_count>0||s.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${$s.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:s.failed_count,migration_pending_count:s.pending_count,managed_state_warning_count:i,managed_extension_entries_count:r,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:_,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function Fu(e,t,n){let s=await lt({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),i=s.loaded.map(w=>Nu(w)),r=await ut({...s,loaded:s.loaded}),[o,a]=await Promise.all([En(s.roots.project),En(s.roots.global)]);await Bo(e,r.registrations.migrations);let c=Du(r.registrations.migrations),d={failed:r.failed,warnings:r.warnings,hook_counts:r.hook_counts,command_override_count:r.command_override_count,command_handler_count:r.command_handler_count,parser_override_count:r.parser_override_count,preflight_override_count:r.preflight_override_count,service_override_count:r.service_override_count,renderer_override_count:r.renderer_override_count,registration_counts:r.registration_counts,registrations:r.registrations,migration_status:c.summary,managed_extensions:{project:{path:o.path,count:o.state.entries.length,entries:o.state.entries},global:{path:a.path,count:a.state.entries.length,entries:a.state.entries}}},l=new Set(o.state.entries.map(w=>Oe(w.name))),u=new Set(a.state.entries.map(w=>Oe(w.name))),m=[...new Map(s.loaded.filter(w=>!(w.layer==="project"?l:u).has(Oe(w.name))).map(w=>[`${w.layer}:${w.name}`,{layer:w.layer,name:w.name,directory:w.directory}])).values()].sort((w,A)=>{let q=`${w.layer}:${w.name}`,D=`${A.layer}:${A.name}`;return q.localeCompare(D)}),_=m.map(w=>`${w.layer}:${w.name}`).sort((w,A)=>w.localeCompare(A)),p=m.filter(w=>Fn(w.name,w.directory)).map(w=>`${w.layer}:${w.name}`).sort((w,A)=>w.localeCompare(A)),f=m.filter(w=>!Fn(w.name,w.directory)).map(w=>`${w.layer}:${w.name}`).sort((w,A)=>w.localeCompare(A)),y=f.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${f.length}`]:[],b=[...s.warnings,...d.warnings,...c.warnings,...o.warnings,...a.warnings,...y],v=Cn(b),C=In(),S=fa(b,s.failed.length,r.failed.length,c.summary,o.warnings.length+a.warnings.length,o.state.entries.length+a.state.entries.length,_,p,f);return{check:{name:"extensions",status:b.length===0?"ok":"warn",details:{...s,loaded:i,warnings:b,activation:d,triage:S,...c.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:C,capability_guidance:v}},warnings:b}}function ju(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function ie(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function $u(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function Rt(e,t){let n=ie(e,t);return{...n,sample:n.sample.map(s=>$u(s))}}function L(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(s=>typeof s=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function Uu(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var Gu={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:L(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:L(e.missing_required,t),missing_optional:L(e.missing_optional,t),missing:L(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:L(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:Rt(e.discovered,t),effective:Rt(e.effective,t),loaded:Rt(e.loaded,t),failed:ie(e.failed,t),warnings:L(e.warnings,t),activation:{failed:ie(n.failed,t),warnings:L(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:Uu(n.migration_status)},triage:e.triage,capability_contract:e.capability_contract,capability_guidance:ie(e.capability_guidance,t)}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:L(n.affected_item_ids,t),samples:ie(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:L(e.item_unreadable,t),item_conflict_markers:ie(e.item_conflict_markers,t),item_parse_failures:L(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:L(n.tracked_paths,t)},history_unreadable:L(e.history_unreadable,t),history_conflict_markers:ie(e.history_conflict_markers,t),history_invalid_json:ie(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>({checked_items:e.checked_items,counts:e.counts,drifted_items:L(e.drifted_items,t),missing_streams:L(e.missing_streams,t),unreadable_streams:L(e.unreadable_streams,t),hash_mismatches:L(e.hash_mismatches,t),chain_mismatches:L(e.chain_mismatches,t),skipped:e.skipped}),vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:L(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:L(e.stale_items_after,t),skipped:e.skipped})};function ga(e,t){let n=Gu[e.name];return n?n(e.details,t):e.details}function qu(e){let t=L(e.warnings,Xe);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,details:ga(n,Xe)})),warnings:t.sample,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:Xe},generated_at:e.generated_at}}function da(e){return e.details.skipped===!0}function Bu(e){let t=L(e.warnings,Xe),n=e.checks.filter(da).map(s=>s.name);return{ok:e.ok,checks:e.checks.filter(s=>!da(s)).map(s=>({name:s.name,status:s.status,details:{}})),warning_count:t.count,warnings:t.sample,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:Xe,omitted_checks:n},generated_at:e.generated_at}}function $n(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ju(e,la);return{values:n.values,truncated:n.truncated,total:e.length}}function Re(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Wu(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return yu.has(e)?e:null}function Ot(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function ha(e){let t=0,n=0,s=0,i=0,r=0;for(let o of e.split(`
4
+ `)){let a=o.trim();if(a.length!==0){s+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,r=Math.max(r,d),d>=ua&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:s,highRetryEntries:i,maxAttempts:r}}function zu(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Hu(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function Vu(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await ya(n)}}function Ku(e,t,n){let s=[];if(t.invalidRows>0&&s.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return s;let i=n.last_successful_flush_at,r=n.last_failed_flush_at,o=r&&(!i||r>i),a=!i,c=t.validEntries>=vu;return(o||a||c)&&s.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&s.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),s}function Yu(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function Xu(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Gi?[`telemetry_schema_version_behind:${t}`]:[]}function Ju(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,s=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!i&&(!s||i>=s)?[`telemetry_otel_export_failing:${n}`]:[]}function Qu(){return{telemetry_disabled:Re("PM_TELEMETRY_DISABLED")||Re("PM_NO_TELEMETRY"),pm_no_telemetry:Re("PM_NO_TELEMETRY"),telemetry_otel_disabled:Re("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:Re("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:Wu()}}function Zu(e,t){return e.telemetry.enabled&&t.validEntries>0}function em(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function ya(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(ku)});return{probe_url:Ot(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let s of Tu){let i=n.headers.get(s)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:Ot(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function tm(e,t){let n=Q(process.cwd()),s=z.join(n,bu),i=z.join(n,wu),r=await $(s),o=r!==null,a=r?Buffer.byteLength(r,"utf8"):0,c=r?ha(r):zu(),d=await $(i),{runtimeState:l,stateParseFailed:u}=Hu(d),m=e.telemetry.endpoint.trim(),_=Ot(m),p=await Vu(e,t.checkTelemetry),f=[];u&&f.push("telemetry_state_invalid_json"),f.push(...Ku(e,c,l),...Yu(p),...Xu(p),...Ju(e,l));let y=Zu(e,c),b=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:f.length===0?"ok":"warn",details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:_,global_pm_root:n,queue_path:s,queue_exists:o,queue_entries:c.validEntries,queue_draining:em(y,f),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:a,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:ua,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:b,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:Qu()}},warnings:f}}async function nm(e){let t;try{t=await ea(e)}catch(s){let i=s instanceof Error?s.message:String(s);return{check:{name:"locks",status:"warn",details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function sm(e,t){let n="metadata",{missingStreams:s,unreadableStreams:i,hashMismatches:r,chainMismatches:o,driftedItems:a}=await vt(e,t,{cacheHitVerification:n}),c=[...s.map(d=>`history_drift_missing_stream:${d}`),...i.map(d=>`history_drift_unreadable_stream:${d}`),...r.map(d=>`history_drift_hash_mismatch:${d}`),...o.map(d=>`history_drift_chain_mismatch:${d}`)];return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,cache_hit_verification:n,drifted_items:a,counts:{drifted:a.length,missing_streams:s.length,unreadable_streams:i.length,hash_mismatches:r.length,chain_mismatches:o.length},missing_streams:s,unreadable_streams:i,hash_mismatches:r,chain_mismatches:o}},warnings:c}}function im(e,t){let n=Oi(e),s=Mi(n.settings),i=Di(n.settings,t),r=s.active?Fi(s.active.name,s.active.model):null;return{runtimeDefaults:n,providerResolution:s,vectorStoreResolution:i,runtimeEmbeddingIdentity:r,semanticRuntimeAvailable:!!(s.active&&i.active)}}function rm(){return{refreshed:[],skipped:[],warnings:[]}}async function om(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?rm():$i(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function am(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&ji(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function cm(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,s)=>n.localeCompare(s))}function dm(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function ba(e,t){let n=t.providerResolution.active?.name??null,s=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:_n(n,e.search?.provider??null),vector_store_active:s,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:_n(s,e.vector_store?.adapter??null)}}function lm(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function um(e,t,n){return e.enabled&&n.length>0&&t}async function mm(e,t,n,s,i){let r=im(t,e),o=await pn(e),a=r.semanticRuntimeAvailable?An(n,o.entries):[],c=await om({pmRoot:e,snapshot:r,refreshPolicy:s,staleBefore:a}),d=await pn(e),l=r.semanticRuntimeAvailable?An(n,d.entries):[],u=!r.runtimeDefaults.auto_ollama_defaults_applied,m=am({strictVectorizationWarnings:u,semanticRuntimeAvailable:r.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:r.runtimeEmbeddingIdentity}),_=cm({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:r.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=$n(a,i),f=$n(l,i),y=um(s,r.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:_.length===0?"ok":"warn",details:{semantic_runtime_available:r.semanticRuntimeAvailable,compatibility_mode_auto_defaults:r.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:r.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:r.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:r.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:lm(s),...ba(t,r),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:r.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:la,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:y,refresh_skipped_reason:dm(s,r.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:f.total,stale_items_after:f.values,stale_items_after_truncated:f.truncated}},warnings:_}}function _m(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function pm(e){let t=e.checkOnly===!0,n=e.noRefresh===!0||t,s=e.refreshVectors===!0;if(s&&t)throw new h("--check-only cannot be combined with --refresh-vectors",g.USAGE);if(s&&e.noRefresh===!0)throw new h("--no-refresh cannot be combined with --refresh-vectors",g.USAGE);return{enabled:s||!n,checkOnly:t,noRefresh:n,refreshVectors:s}}var fm=new Set(["extensions","locks","search"]);function gm(e){let t=new Set(Gs.filter(i=>i.length>0)),n=new Set,s=new Set(Object.values(qs));for(let i of e.folders)t.has(i)&&!s.has(i)||(t.delete(i),n.add(i));for(let i of fm)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,r)=>i.localeCompare(r)),optionalDirs:[...n].sort((i,r)=>i.localeCompare(r)),optionalDirSet:n}}async function hm(e,t,n){let{requiredDirs:s,optionalDirs:i,optionalDirSet:r}=gm(t),o=[],a=[],c=[];for(let d of[...s,...i]){let l=z.join(e,d);c.push(...await X({path:l,scope:"project"})),!await Un(l)&&(r.has(d)?a.push(d):o.push(d))}return{requiredDirs:s,optionalDirs:i,missingRequiredDirs:o,missingOptionalDirs:a,missingDirs:n?[...o,...a]:[...o],hookWarnings:c}}function wa(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,s=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||s)&&e.full!==!0,skipDrift:(e.skipDrift===!0||s)&&e.full!==!0,skipVectors:(e.skipVectors===!0||s)&&e.full!==!0}}async function ym(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Pi(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):Ce(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Dn(e){return{check:{name:e,status:"ok",details:{skipped:!0}},warnings:[]}}function bm(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function wm(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function km(e){return{name:"settings_values",status:e.length===0?"ok":"warn",details:{warnings:e}}}var Gn=e=>e.unknown_event_count??0,qn=e=>e.actionable_unknown_event_count??Gn(e);function vm(e,t,n,s,i){let r=Gn(s),o=qn(s),a=r>0,c=o>0,d=i.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!c&&!d?"ok":"warn",details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...a?{author_attribution:s}:{},...d?{stale_in_progress:i}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function ka(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function Tm(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function xm(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function Sm(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historySummary.over_threshold.map(t=>`history_stream_over_compact_threshold:${t}`),...e.authorAttributionWarnings,...e.staleInProgressWarnings],locks:e.locksCheck.warnings,integrity:e.integrityCheck.warnings,history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function Em(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-repair --all";if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function Cm(e){for(let t of e.checks){let n=Ln(e.remediationSources[t.name]);Em({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}function va(e,t,n){return n?Bu(e):t.brief===!0?qu(e):e}async function sk(e,t={}){let n=R(process.cwd(),e.path),s=O(n);if(!await x(s))throw new h(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let{settings:i,warnings:r}=await Ai(n),o=[...new Set(r)],a=V(i,W()),c=t.strictDirectories===!0,d=pm(t),l=await hm(n,a,c),u=_m(i),m=await tm(i,{checkTelemetry:t.checkTelemetry===!0}),_=await Fu(n,i,!!e.noExtensions),p=wa(t),f=[],y=await ym({pmRoot:n,settings:i,typeRegistry:a,skipPolicy:p,itemReadWarnings:f}),b=y,v=[...new Set(f)],C=p.skipDrift?{warnings:[]}:await ht({pmRoot:n,settings:i,itemIds:y.map(tn=>tn.id),commandLabel:"health"}),S=await Eu(n,i.history.compact_policy,await xu(n)),w=await Ve(n,20,t.verboseAuthorEvents===!0),A=qn(w),q=A>0?[`history_unknown_author_events:${A}`]:[],D=ka(await Ui(n,y,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),j=await nm(n),Y=p.skipIntegrity?Dn("integrity"):await Ru(n,a.type_to_folder,i.schema,t.requireMergeDrivers===!0),ce=p.skipDrift?Dn("history_drift"):await sm(n,b),T=p.skipVectors?Dn("vectorization"):await mm(n,i,b,d,t.verboseStaleItems===!0),B=[bm(s,i,o),wm(l,c),km(u),m.check,_.check,vm(y,i,S,w,D.scan),j.check,Y.check,ce.check,T.check],js=Tm({directoryState:l,normalizedSettingsReadWarnings:o,settingWarnings:u,normalizedItemReadWarnings:v,telemetryCheck:m,extensionCheck:_,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:q,staleInProgressWarnings:D.warnings,locksCheck:j,integrityCheck:Y,historyDriftCheck:ce,vectorizationCheck:T});Cm({checks:B,remediationSources:Sm({directoryState:l,normalizedSettingsReadWarnings:o,settingWarnings:u,telemetryCheck:m,extensionCheck:_,historySummary:S,authorAttributionWarnings:q,staleInProgressWarnings:D.warnings,locksCheck:j,integrityCheck:Y,historyDriftCheck:ce,vectorizationCheck:T}),historyDriftedCount:xm(ce),overThresholdCount:S.over_threshold.length});let Rl={ok:js.filter(tn=>!ma(tn,t.requireMergeDrivers===!0)).length===0,checks:B,warnings:js,generated_at:k()};return va(Rl,t,p.summaryMode)}var ik={buildExtensionHealthTriageSummary:fa,buildCapabilityContractMetadata:In,buildStaleInProgressHealthSummary:ka,buildVectorizationProviderDetails:ba,collectUnknownCapabilityGuidance:Cn,isAdvisoryHealthWarning:ma,isDirectory:Un,isExpectedUnmanagedExtension:Fn,listItemDocumentPaths:pa,normalizeEndpointForDisplay:Ot,normalizeExtensionNameForMatch:Oe,parseTelemetryQueue:ha,probeTelemetryEndpointHealth:ya,projectHealthResult:va,resolveActionableUnknownAuthorEventCount:qn,resolveHealthSkipPolicy:wa,resolveUnknownAuthorEventCount:Gn,selectStaleItemDetail:$n,summarizeHealthCheckDetails:ga,summarizeExtensionList:Rt,summarizeRecordList:ie,summarizeStringList:L,telemetryEnvFlagEnabled:Re,warningCode:_a};import Ne from"node:fs/promises";import Le from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function Im(e,t){let n=[...new Set(Object.values(t))],s=[];return await Promise.all(n.map(async i=>{let r;try{r=await Ne.readdir(Le.join(e,i))}catch{return}for(let o of r)for(let a of ge)if(o.toLowerCase().endsWith(a)){s.push({relativePath:`${i}/${o}`,id:o.slice(0,-a.length)});break}})),s.sort((i,r)=>i.relativePath.localeCompare(r.relativePath))}function Am(e,t){let{id:n,relativePath:s,liveItemIds:i,out:r}=e,o=Ee(t);if(o){r.conflictMarkers.push({id:n,path:s,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=null,c=t.split(/\r?\n/).map((d,l)=>({content:d.trim(),number:l+1})).filter(d=>d.content.length>0);for(let d of c)try{let l=JSON.parse(d.content);if(typeof l!="object"||l===null||Array.isArray(l))throw new TypeError("history entry must be an object");a=l}catch{r.unparseable.push({id:n,path:s,line:d.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&i.has(n)&&r.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(r.repairReconciliations+=1))}function Bn(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function Rm(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},s;try{s=await Ne.readdir(Le.join(e,"history"))}catch{return n}for(let i of s.sort((r,o)=>r.localeCompare(o))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let r;try{r=await Ne.readFile(Le.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Bn("history stream",o)});continue}Am({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},r)}return n}function Ta(e){let t=Ee(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function Om(e){let t=[],n=0,s=null;try{s=await $(O(e))}catch(r){n+=1,t.push({path:"settings.json",detail:Bn("configuration file",r)})}if(s!==null){n+=1;let r=Ta(s);r!==null&&t.push({path:"settings.json",detail:r})}let i;try{i=await Ne.readdir(Le.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let r of i.sort((o,a)=>o.localeCompare(a))){if(!r.endsWith(".json"))continue;n+=1;let o;try{o=await Ne.readFile(Le.join(e,"schema",r),"utf8")}catch(c){t.push({path:`schema/${r}`,detail:Bn("configuration file",c)});continue}let a=Ta(o);a!==null&&t.push({path:`schema/${r}`,detail:a})}return{scanned:n,unparseable:t}}async function xa(e,t,n,s={}){let i=await Im(e,n),r=new Set(i.map(u=>u.id)),o=new Map;for(let u of i){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((_,p)=>_.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Le.join(e,u.relativePath);return gt(await Ne.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:s.schema,extensionFieldNames:s.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await Rm(e,r),l=await Om(e);return{item_files_on_disk:i.length,item_ids_on_disk:r.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c4d45cf-6b97-5151-a325-db09d31962a7")}catch{}})();var Nm=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Wn=new Set(["--pm-path","--path","--author"]),Lm={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},Pm=new Set(["-p","--package"]),Mm=new Set(["-c","--call"]),zn=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Hn=new Set(["-C","--prefix","--userconfig","--cache"]),Sa=new Set(["--cwd"]),Ea=new Set(["--cwd"]),Dm=new Set(["exec","x"]),Ca=new Set(["run","run-script"]),Ia=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Pe(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function Nt(e){let t=Lt(e.split(" ").filter(r=>r.length>0));if(t.length===0)return null;let[n,...s]=t;if(Je(n)||Qe(n))return s;if(n==="node"&&s[0]&&Qe(s[0]))return s.slice(1);let i=n==="npx"||n==="bunx"?be(s):n==="pnpm"?Mt(s):n==="npm"?Dt(s):null;return i&&(Je(i.command)||Kn(i.command))?i.args:null}var Vn=(e,t="pm")=>{let n=t.trim().toLowerCase(),s=n.length;for(;s>0&&n[s-1]==="-";)s-=1;let i=n.slice(0,s);if(i.length===0)return[];let r=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of Pe(r)){let c=Nt(a),d=c?Yn(c):null,l=d&&Nm.has(d.subcommand)?jm(d.remaining,Lm[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&o.add(l)}return[...o].sort((a,c)=>a.localeCompare(c))};function Lt(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Pt(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Wn.has(n)){t+=2;continue}t+=1;continue}return n}}function Je(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function Fm(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let s=t.indexOf("@",n+1);return s===-1?t:t.slice(0,s)}function Kn(e){let t=Fm(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Qe(e){return e==="dist/cli.js"||e==="./dist/cli.js"||e.endsWith("/dist/cli.js")}function be(e){let t=0;for(;t<e.length;){let s=e[t];if(s==="--"){t+=1;break}if(!s.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(s);if(i){let r=i[1];return r?{command:r,args:e.slice(t+1)}:null}if(Mm.has(s)){t+=1;break}t+=Pm.has(s)&&!s.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function ue(e,t){let n=0;for(;n<e.length;){let s=e[n];if(s==="--"){n+=1;continue}if(s.startsWith("-")){if(s.includes("=")){n+=1;continue}if(t.has(s)){n+=2;continue}n+=1;continue}return{subcommand:s,args:e.slice(n+1)}}return null}function Mt(e){let t=ue(e,zn);return t?.subcommand!=="dlx"?null:be(t.args)}function Dt(e){let t=ue(e,Hn);return!t||!Dm.has(t.subcommand)?null:be(t.args)}function Yn(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Wn.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function jm(e,t=new Set){for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="--")return e[n+1];if(!s.startsWith("-"))return s;!s.includes("=")&&(Wn.has(s)||t.has(s))&&(n+=1)}}import ns from"node:fs/promises";import{realpathSync as zm}from"node:fs";import{execFile as Hm}from"node:child_process";import H from"node:path";import{promisify as Vm}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]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var $m=["metadata","resolution"],Xn=["metadata","resolution","estimates","lifecycle"],Um="completed";function Jn(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Aa(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Ra(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let s=Aa(n.close_reason)??Um;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:s,command:`pm update ${n.id} --resolution ${Jn(s)}`,gate:"resolution"})}return t}function Oa(e){let t=[];for(let n of e){let s=Aa(n.resolution);s!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:s,command:`pm update ${n.id} --close-reason ${Jn(s)}`,gate:"metadata"})}return t}function Na(e,t){return e.map(n=>{let s=Ii(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(s),command:`pm update ${n.id} --estimate ${s}`,gate:"estimates"}})}function La(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function Pa(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let s=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${s} ${n.item_id} --remove ${Jn(n.path)}`})}return t}function Ma(e){let t=(e??[]).flatMap(s=>s.split(",")).map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new h(`--fix-scope values must not be empty. Supported values: ${Xn.join(", ")}.`,g.USAGE);return new Set($m)}let n=new Set;for(let s of t){let i=s.toLowerCase().replaceAll("-","_");if(Xn.includes(i)){n.add(i);continue}throw new h(`Unknown --fix-scope value "${s}". Supported values: ${Xn.join(", ")}.`,g.USAGE)}return n}function Da(e,t){let n=[],s=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?s.push(i):n.push(i);return{applicable:n,gated:s}}function Ze(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var Gm=/^([A-Z][A-Z0-9]*-\d+)\b/;function qm(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=Gm.exec(t);return n?n[1]:null}function Fa(e){return typeof e=="string"&&e.trim().length>0}function ja(e){let t=new Map;for(let s of e){if(typeof s.title!="string"||Fa(s.duplicate_of))continue;let i=qm(s.title);if(i===null)continue;let r=t.get(i);r||(r=[],t.set(i,r)),r.some(o=>o.id===s.id)||r.push({id:s.id,title:s.title,parent:Fa(s.parent)?s.parent.trim():null})}let n=[];for(let[s,i]of t){if(i.length<2)continue;let r=new Set(i.map(c=>c.id.toLowerCase())),o=i.filter(c=>c.parent===null||!r.has(c.parent.toLowerCase()));if(o.length<2)continue;let a=[...o].sort((c,d)=>c.id.localeCompare(d.id));n.push({code:s,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return n.sort((s,i)=>s.code.localeCompare(i.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function $a(e){let t=new Map;for(let s of e){let i=t.get(s.item_type);i||(i=new Map,t.set(s.item_type,i)),i.set(s.field,(i.get(s.field)??0)+1)}let n={};for(let s of[...t.keys()].sort((i,r)=>i.localeCompare(r))){let i=t.get(s),r={};for(let o of[...i.keys()].sort((a,c)=>a.localeCompare(c)))r[o]=i.get(o);n[s]=r}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]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var Ua=3;function Ga(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function qa(e,t,n=Ua){let s=Number.isFinite(n)&&n>=1?Math.floor(n):Ua,i=new Map;for(let r of t){let o=Ga(r);if(o.length===0)continue;let a=i.get(o);a?a.push(r):i.set(o,[r])}return e.map(r=>{let o=(i.get(Ga(r))??[]).filter(a=>a!==r).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:r,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:r,classification:"moved",candidates:o.slice(0,s),candidates_truncated:o.length>s}})}function Ba(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function Bm(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function Wa(e){return`${e.item_id} ${e.link_kind}`}function za(e,t){let n=new Map;for(let s of e){let i=n.get(s.path);i?(i.classification=Bm(i.classification,s.classification),i.owners.set(Wa(s),s)):n.set(s.path,{classification:s.classification,owners:new Map([[Wa(s),s]])})}return[...n.entries()].sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>({path:s,classification:i.classification,items:[...i.owners.values()].map(r=>{let o=t(r.item_id);return{id:r.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:r.link_kind}}).sort((r,o)=>{let a=r.id.localeCompare(o.id);return a!==0?a:r.field.localeCompare(o.field)})}))}function Wm(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ha(e){let t=[];for(let n of e)for(let s of n.items)t.push(`${n.path}:${n.classification} owner=${s.id} status=${s.status} field=${s.field} title="${Wm(s.title)}"`);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]="f8048210-9e9f-585b-b0df-a34eca521cc3")}catch{}})();var Km=["src","tests","docs"],Ym=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],Xm=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),Jm=["resolution","expected_result","actual_result"],Qm=["default","tracked-all","tracked-all-strict"],Va=["core","strict","custom"],jt=["off","warn","error"];var Zn=["author","acceptance_criteria","estimated_minutes","close_reason"],Qa=[...Zn,"reviewer","risk","confidence","sprint","release"],ss=Array.from(new Set(Qa)),Zm={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"},e_={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},t_={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},n_={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},s_={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},i_=32*1024*1024,r_=1e4,Za=40,ae=5,o_=4096,a_=255,c_=Vm(Hm);function ec(e){let t={};for(let[n,s]of Object.entries(e))Array.isArray(s)||(t[n]=typeof s=="object"&&s!==null?ec(s):s);return t}function d_(e){return{...e,checks:e.checks.map(t=>({...t,details:ec(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function we(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Ka(e){return we(e).replace(/\/+$/,"")}function J(e){let t=P(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Ut(e,t){return ft(e,t)??e}function et(e,t){return t.terminal_statuses.has(Ut(e,t))}function me(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ft(e,t){return e.length!==t.length?!1:e.every((n,s)=>n===t[s])}function l_(e){let t=me(Bs),n={blocked_reason:me(ct.blocked_reason),resolution:me(ct.resolution),actual_result:me(ct.actual_result)},s=me(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:me(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:me(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:me(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:s,stale_blocker_reason_pattern_source:Ft(s,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Ft(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Ft(i.resolution,n.resolution)?"default":"settings",actual_result:Ft(i.actual_result,n.actual_result)?"default":"settings"}}}function tc(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Va.includes(t))return t;throw new h(`Unknown --metadata-profile value "${e}". Supported values: ${Va.join(", ")}.`,g.USAGE)}function nc(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(jt.includes(t))return t;throw new h(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${jt.join(", ")}.`,g.USAGE)}function sc(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(jt.includes(t))return t;throw new h(`Unknown --parent-cycle-severity value "${e}". Supported values: ${jt.join(", ")}.`,g.USAGE)}function u_(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>Zm[n]).filter(n=>n!==void 0).sort((n,s)=>n.localeCompare(s))}function m_(e,t,n){let s=u_(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Zn],configured_custom_fields:s,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Qa],configured_custom_fields:s,fallback_to_core:!1,warnings:[]}:s.length>0?{profile:e,profile_source:t,required_fields:s,configured_custom_fields:s,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Zn],configured_custom_fields:s,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var __=new Set(["acceptance_criteria","estimated_minutes"]);function ic(e,t,n,s){return!s&&__.has(t)&&et(e.status,n)?!1:t==="author"?!P(e.author):t==="acceptance_criteria"?!P(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ut(e.status,n)===n.close_status&&!P(e.close_reason):t==="reviewer"?!P(e.reviewer):t==="risk"?!P(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!P(e.confidence):t==="sprint"?!P(e.sprint):!P(e.release)}function rc(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new h(`Unknown --scan-mode value "${e}". Supported values: ${Qm.join(", ")}.`,g.USAGE)}function oc(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return H.resolve(t);let n=H.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return H.dirname(H.dirname(n));let i=H.resolve(process.cwd()),r=Ya(n),o=Ya(i),a=H.relative(r,o);return a.length===0||!a.startsWith("..")&&!H.isAbsolute(a)?n:i}function Ya(e){try{return zm.native(e)}catch{return H.resolve(e)}}function ac(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function is(e,t,n){let s=t.length>0?H.join(e,t):e,i;try{i=await ns.readdir(s,{withFileTypes:!0})}catch(r){if(ac(r,["ENOENT"]))return;throw r}for(let r of i){if(r.name.startsWith("."))continue;let o=t.length>0?H.join(t,r.name):r.name;if(r.isDirectory()){if(Xm.has(r.name))continue;await is(e,o,n);continue}r.isFile()&&n.push(we(o))}}async function es(e){let t=[];for(let n of Km)await is(e,n,t);for(let n of Ym){let s=H.join(e,n);try{(await ns.stat(s)).isFile()&&t.push(we(n))}catch{}}return[...new Set(t)].sort((n,s)=>n.localeCompare(s))}async function cc(e){try{let{stdout:t}=await c_("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:i_,windowsHide:!0,timeout:r_}),n=t.split("\0").map(s=>we(s)).filter(s=>s.length>0);return[...new Set(n)].sort((s,i)=>s.localeCompare(i))}catch{return null}}function p_(e,t){let n=new Set,s=Ka(Us);s.length>0&&n.add(s);let i=Ka(H.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((r,o)=>r.localeCompare(o))}function Xa(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function f_(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let s=await cc(e);if(s)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:s,candidateTotal:s.length,candidateScanned:s.length};let i=await es(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await es(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function M(e,t=ae){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function _e(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=M(e,Za);return{values:n.values,truncated:n.truncated,total:e.length}}var g_={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},h_={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function y_(e){let t=e.missing_fields.map(n=>`${g_[n]} "${h_[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function dc(e,t){let n=e.details?.missing_resolution_remediation_hints,s=Array.isArray(n)&&n.length>0,i=s?n.filter(o=>typeof o=="string"):aa(t);if(i.length===0)return;let r=s&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...r?{fix_hints_truncated:!0}:{}}}function lc(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var b_="validate_metadata_duplicate_issue_codes";function uc(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:ae,s=e.slice(0,n);return{rows:s.map(r=>({code:r.code,count:r.count,ids:r.ids,titles:r.titles,remediation_hint:`Items ${r.ids.join(", ")} share issue code "${r.code}"; rename or merge so each logical code maps to one item.`})),truncated:s.length<e.length,warnings:[`${b_}:${e.length}`]}}function w_(){return Object.fromEntries(ss.map(e=>[e,[]]))}function k_(e,t,n){let s=w_();for(let i of e)for(let r of ss)ic(i,r,t,n)&&s[r].push(i.id);return s}function v_(e,t,n){let s=[...e.warnings];for(let i of e.required_fields){let r=t[i];r.length>0&&s.push(`${e_[i]}:${r.length}`)}return s.push(...n),s}function mc(e,t){let n={};for(let s of e.required_fields){let i=t[s],r=i?i.length:0,o=t_[s];r>0&&o&&(n[o]=r)}return n}function _c(e,t,n){let s=[];for(let i of e.required_fields){let r=t[i];if(r)for(let o of r){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";s.push({item_type:c,field:i})}}return s}function T_(e,t,n,s){for(let i of t.required_fields){let r=n[i];if(!r||r.length===0)continue;let o=n_[i],a=s_[i];if(!o||!a)continue;let c=M(r,s?r.length:ae);e[o]=c.values,e[a]=c.truncated}}function pc(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let s=t.close_reason;return s?s.map(i=>({id:i,resolution:P(n.get(i)?.resolution)})):[]}function fc(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let s=t.estimated_minutes;return s?s.map(i=>({id:i,type:P(n.get(i)?.type)})):[]}function x_(e,t,n,s){let i=new Map(e.map(y=>[y.id,y])),r=t.profile==="strict",o=k_(e,n,r),a=ja(e),c=uc(a,s),d=v_(t,o,c.warnings),l=mc(t,o),u=_c(t,o,i),m=$a(u),_={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...ss],counts:l,missing_by_type:m,duplicate_issue_codes_count:a.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(_.configured_custom_required_fields=[...t.configured_custom_fields]),T_(_,t,o,s);let p=pc(t,o,i),f=fc(t,o,i);return{check:{name:"metadata",status:d.length===0?"ok":"warn",details:_},warnings:d,closeReasonBackfillRows:p,estimateBackfillRows:f}}function S_(e,t,n){let s=new Set(t.terminal_done_statuses);s.add(t.close_status);let i=e.filter(m=>s.has(Ut(m.status,t))),r=[],o=[];for(let m of i){let _=Jm.filter(p=>!P(m[p]));_.length!==0&&(r.push({id:m.id,missing_fields:_}),o.push({id:m.id,missing_fields:_,close_reason:P(m.close_reason)}))}let a=r.length>0?[`validate_resolution_missing_fields:${r.length}`]:[],c=n?Number.POSITIVE_INFINITY:ae,d=M(r.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),l=r.map(m=>y_(m)),u=M(l,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",details:{checked_closed_items:i.length,missing_resolution_items:r.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function gc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hc(e,t="pm",n=on()){let s=new Set(e.map(r=>r.id)),i=[...e].sort((r,o)=>r.id.localeCompare(o.id));return new Map(i.map(r=>{let o=new Set,a=J(r.blocked_by);a&&s.has(a)&&o.add(a),(r.dependencies??[]).filter(d=>{let l=J(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>J(d.id)).filter(d=>d!==void 0&&s.has(d)).forEach(d=>o.add(d));let c=J(r.definition_of_ready);return bc(c??"",t).filter(d=>s.has(d)).forEach(d=>o.add(d)),[r.id,[...o].sort((d,l)=>d.localeCompare(l))]}))}function yc(e,t,n){let s=Ro(e,n?l=>et(l,n):void 0),i=s.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),r=s.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),o=t?Number.POSITIVE_INFINITY:ae,a=M(i,o),c=M(r,o),d=M(s.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",details:{checked_items:e.length,dangling_reference_count:i.length+r.length,active_dangling_reference_count:i.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:r.length,legacy_closed_dangling_reference_count:s.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:s.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function bc(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),s=new RegExp(`(?:^|[^a-z0-9-])(${gc(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(s)].map(i=>i[1].toLowerCase()))].sort((i,r)=>i.localeCompare(r))}function rs(e){let t=0,n=new Map,s=new Map,i=[],r=new Set,o=[],a=l=>{n.set(l,t),s.set(l,t),t+=1,i.push(l),r.add(l);for(let m of e.get(l)??[])n.has(m)?r.has(m)&&s.set(l,Math.min(s.get(l),n.get(m))):(a(m),s.set(l,Math.min(s.get(l),s.get(m))));if(s.get(l)!==n.get(l))return;let u=[];for(;i.length>0;){let m=i.pop();if(r.delete(m),u.push(m),m===l)break}u.sort((m,_)=>m.localeCompare(_)),o.push(u)},c=[...e.keys()].sort((l,u)=>l.localeCompare(u));for(let l of c)n.has(l)||a(l);return o.filter(l=>{if(l.length>1)return!0;let u=l[0];return(e.get(u)??[]).includes(u)}).sort((l,u)=>l[0].localeCompare(u[0])||l.length-u.length||l.join(",").localeCompare(u.join(",")))}function os(e,t){let n=e[0];if(e.length===1)return[n,n];let s=new Set(e),i=[n],r=new Set([n]),o=a=>{let c=(t.get(a)??[]).filter(d=>s.has(d));for(let d of c){if(d===n&&i.length>1)return i.push(n),!0;if(!r.has(d)){if(r.add(d),i.push(d),o(d))return!0;i.pop(),r.delete(d)}}return!1};return o(n)?[...i]:[...e,n]}function wc(e,t="pm"){let n=hc(e,t),s=rs(n),i=[...new Set(s.flat())].sort((o,a)=>o.localeCompare(a)),r=s.map(o=>os(o,n).join("->"));return{cycle_count:s.length,cycle_item_ids:i,cycle_sample_paths:r}}function kc(e,t=on()){let n=new Map(e.map(r=>[r.id.toLowerCase(),r.id])),s=new Map(e.map(r=>[r.id,[]]));return[...e].sort((r,o)=>r.id.localeCompare(o.id)).forEach(r=>{let o=s.get(r.id),a=J(r.parent),c=a?n.get(a.toLowerCase()):void 0;c&&o.push(c),(r.dependencies??[]).forEach(d=>{let l=t.resolve(d.kind);if(!l?.hierarchy)return;let u=n.get(d.id.toLowerCase());u&&(l.hierarchyDirection==="source_parent"?s.get(u).push(r.id):o.push(u))})}),s.forEach((r,o)=>{s.set(o,[...new Set(r)].sort((a,c)=>a.localeCompare(c)))}),s}function vc(e){let t=kc(e),n=rs(t),s=[...new Set(n.flat())].sort((r,o)=>r.localeCompare(o)),i=n.map(r=>os(r,t).join("->"));return{cycle_count:n.length,cycle_item_ids:s,cycle_sample_paths:i}}function Tc(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function $t(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function xc(e,t){let n=$t(e).split("/").filter(Boolean),s=$t(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<s.length&&n[i]===s[i];)i+=1;return i}function E_(e,t){let n=$t(t),s=$t(e),i=t.endsWith("/")?t:`${t}/`,r=e.startsWith(i),o=n.length>0&&n===s,a=xc(e,t);return!r&&!o&&a===0?null:r?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function C_(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function I_(e,t,n){let s=t==="docs_unowned"?"docs":"files",i;return n.flatMap(r=>(s==="docs"?r.docs??[]:r.files??[]).map(o=>({item:r,link:o}))).forEach(({item:r,link:o})=>{if(o.scope!=="project")return;let a=we(o.path);if(a.length===0||a===e)return;let c=E_(e,a);c!==null&&C_(i,r,c.score)&&(i={item:r,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function Sc(e,t){return e.map(n=>{let s=Tc(n),i=s==="docs_unowned"?"docs":"files",r=I_(n,s,t),o=r?.id??"<id>";return{path:n,classification:s,owner_candidate:r,remediation_hint:`pm ${i} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Ec(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function A_(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,s])=>{let i=J(e[n]);return i?s.some(r=>i.toLowerCase().includes(r)):!1}).map(([n])=>n).sort((n,s)=>n.localeCompare(s))}function R_(e,t,n,s,i){let r=J(t.parent),o=r?n.get(s.get(r.toLowerCase())??r):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!et(o.status,i)}}function O_(e,t,n,s){let i=J(e.blocked_by),r=J(e.blocked_reason),o=r?.toLowerCase(),a=Ut(e.status,n),c=[];return t.has(a)?(!i&&!r&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&s.stale_blocker_reason_patterns.some(d=>o.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),r&&c.push("non_blocked_status_has_blocked_reason"),c)}function N_(e,t,n,s){let i=new Map(e.map(c=>[c.id,c])),r=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!et(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let d=A_(c,s);d.length>0&&a.closureLikeRows.push({id:c.id,fields:d});let l=J(c.parent),u=l?i.get(r.get(l.toLowerCase())??l):void 0;if(u&&et(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(R_(c,u,i,r,n))),t){let m=O_(c,o,n,s);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((_,p)=>_.localeCompare(p))})}}return a}function L_(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function Ja(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function P_(e,t,n,s,i,r){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=Ja("validate_lifecycle_dependency_cycles",n,i),c=Ja("validate_hierarchy_parent_cycle",s,r);return[...o,...a?[a]:[],...c?[c]:[]]}function Cc(e){let t=we(e);return t.length>o_||t.split(/[\\/]/).some(n=>n.length>a_)}async function M_(e,t){let n=H.isAbsolute(t)?t:H.resolve(e,t);if(Cc(n))return!1;try{let s=await ns.stat(n);return!s.isFile()&&!s.isDirectory()}catch(s){return ac(s,["ENOENT","ENOTDIR"])}}async function D_(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},s=e.flatMap(i=>[...(i.files??[]).map(r=>({item:i,artifact:r,link_kind:"files"})),...(i.docs??[]).map(r=>({item:i,artifact:r,link_kind:"docs"}))]);for(let{item:i,artifact:r,link_kind:o}of s){if(r.scope!=="project")continue;if(Wo(r.path)){n.remoteLinkedPaths.add(r.path.trim());continue}let a=we(r.path);a.length!==0&&(n.linkedProjectPaths.add(a),await M_(t,r.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:i.id,path:a,link_kind:o})))}return n}function F_(e,t,n,s,i,r){let o=s==="tracked-all-strict",a=o&&!i,c=i||o,d=c?[]:p_(t,n),l=d.length===0?[]:e.candidateFiles.filter(_=>Xa(_,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(_=>!Xa(_,d)),m={};if(l.length>0){let _=_e(l,r);m.pm_internals={count:l.length,paths:_.values,paths_truncated:_.truncated,paths_total:_.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:m}}function Ic(e,t,n,s,i,r,o,a="pm"){let c=N_(e,t,i,r);L_(c);let d=wc(c.activeItems,a),l=vc(e),u=P_(c,t,n,s,d.cycle_count,l.cycle_count),m=o?Number.POSITIVE_INFINITY:ae,_=M(c.closureLikeRows.map(w=>`${w.id}:${w.fields.join(",")}`),m),p=M(c.terminalParentRows.map(w=>`${w.id}:${w.parent_id}:${w.parent_status}`),m),f=M(c.staleBlockerRows.map(w=>`${w.id}:${w.status}:${w.reasons.join(",")}`),m),y=M(d.cycle_item_ids,m),b=M(d.cycle_sample_paths,m),v=M(l.cycle_item_ids,m),C=M(l.cycle_sample_paths,m);return{check:{name:"lifecycle",status:d.cycle_count>0&&n==="error"||l.cycle_count>0&&s==="error"?"error":u.length===0?"ok":"warn",details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:_.values,active_closure_like_metadata_rows_truncated:_.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:p.values,active_terminal_parent_rows_truncated:p.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:f.values,stale_blocker_rows_truncated:f.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:y.values,dependency_cycle_item_ids_truncated:y.truncated,dependency_cycle_sample_paths:b.values,dependency_cycle_sample_paths_truncated:b.truncated,parent_cycle_severity_policy:s,parent_cycle_count:l.cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:v.values,parent_cycle_item_ids_truncated:v.truncated,parent_cycle_sample_paths:C.values,parent_cycle_sample_paths_truncated:C.truncated,stale_blocker_reason_patterns:[...r.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:r.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...r.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:r.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...r.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:r.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...r.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:r.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function Ac(e,t,n,s,i,r){let o=await D_(e,t),a=new Map(e.map(T=>[T.id,T])),c=[...new Set(o.missingLinkedPaths)].sort((T,B)=>T.localeCompare(B)),d=await f_(t,s),l=F_(d,n,t,s,i,r),u=l.candidateFiles.filter(T=>!o.linkedProjectPaths.has(T)),m=Sc(u,e),_=qa(c,l.candidateFiles),p=new Map(_.map(T=>[T.path,T.classification])),f=_.filter(T=>T.classification==="moved").length,y=o.staleLinkRows.map(T=>({...T,classification:p.get(T.path)??"deleted"})).sort((T,B)=>T.item_id.localeCompare(B.item_id)||T.path.localeCompare(B.path)||T.link_kind.localeCompare(B.link_kind)),b=[];l.strictModeForcesPmInternals&&b.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&b.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&b.push(`validate_files_orphaned_paths:${u.length}`);let v=[...o.remoteLinkedPaths].sort((T,B)=>T.localeCompare(B)),C=_e(v,r),S=_e(c,r),w=_e(u,r),A=_e(m.map(T=>`${T.path}:${T.classification}:owner_candidate=${T.owner_candidate?.id??"unowned"}`),r),q=r?m:_e(Ec(m),!1).values,D=_e(Ba(_),r),j=y.map(T=>({item_id:T.item_id,path:T.path,link_kind:T.link_kind,classification:T.classification})),Y=za(j,T=>{let B=a.get(T);return B?{type:B.type,title:B.title,status:B.status}:void 0}),ce=r?Y:_e(Ha(Y),!1).values;return{check:{name:"files",status:b.length===0?"ok":"warn",details:{workspace_root:t,scan_mode_requested:d.requestedMode,scan_mode_applied:d.appliedMode,strict_tracked_all_mode:l.strictTrackedAllMode,strict_mode_forces_pm_internals:l.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:l.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:r?"full":"summary",file_list_summary_limit:Za,candidate_scan_source:d.source,include_pm_internals:l.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:l.pmInternalCandidatePrefixes,pm_internal_excluded_count:l.excludedPmInternalPaths.length,excluded_total:l.excludedPmInternalPaths.length,excluded_by_reason:l.excludedByReason,linked_project_paths:o.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:C.total,remote_linked_paths:C.values,remote_linked_paths_truncated:C.truncated,candidate_total_raw:d.candidateTotal,candidate_scanned_raw:d.candidateScanned,candidate_total:l.candidateFiles.length,candidate_scanned:l.candidateFiles.length,scanned_candidate_files:l.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:S.total,missing_linked_paths:S.values,missing_linked_paths_truncated:S.truncated,missing_linked_paths_moved_count:f,missing_linked_paths_deleted_count:c.length-f,missing_linked_path_classifications:D.values,missing_linked_path_classifications_truncated:D.truncated,missing_linked_path_rows_count:Y.length,missing_linked_path_rows:ce,orphaned_paths_count:u.length,orphaned_paths_total:w.total,orphaned_paths:w.values,orphaned_paths_truncated:w.truncated,orphaned_path_classifications:A.values,orphaned_path_classifications_truncated:A.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:q}},warnings:b,staleLinkPruneRows:y}}async function j_(e,t,n){let{missingStreams:s,unreadableStreams:i,hashMismatches:r,chainMismatches:o,driftedItems:a}=await vt(e,t),c=[];s.length>0&&c.push(`validate_history_drift_missing_streams:${s.length}`),i.length>0&&c.push(`validate_history_drift_unreadable_streams:${i.length}`),r.length>0&&c.push(`validate_history_drift_hash_mismatches:${r.length}`),o.length>0&&c.push(`validate_history_drift_chain_mismatches:${o.length}`);let d=n?Number.POSITIVE_INFINITY:ae,l=M(a,d);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,drifted_items_count:a.length,drifted_items:l.values,drifted_items_truncated:l.truncated,counts:{missing_streams:s.length,unreadable_streams:i.length,hash_mismatches:r.length,chain_mismatches:o.length}}},warnings:c}}function $_(e,t,n){let s=n.trim().replaceAll(/\s+/g," "),i=s.length>120?`${s.slice(0,117)}...`:s;return`${e}:${t}:${i}`}function Rc(e,t,n){let s=new Set(e.map(y=>y.id.toLowerCase())),i=0,r=0,o=new Set,a=[],c=e.flatMap(y=>(y.tests??[]).map(b=>({item:y,linkedTest:b})));for(let{item:y,linkedTest:b}of c){if(typeof b.command!="string"||b.command.trim().length===0)continue;i+=1;let v=Vn(b.command,t);if(v.length!==0){r+=v.length;for(let C of v)o.add(C),s.has(C.toLowerCase())||a.push($_(y.id,C,b.command))}}let d=[...new Set(a)].sort((y,b)=>y.localeCompare(b)),l=[...new Set(d.map(y=>y.split(":")[1]??""))].filter(y=>y.length>0).sort((y,b)=>y.localeCompare(b)),u=d.length>0?[`validate_command_references_stale_pm_ids:${d.length}`]:[],m=n?Number.POSITIVE_INFINITY:ae,_=M(d,m),p=M(l,m),f=M([...o].sort((y,b)=>y.localeCompare(b)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",details:{checked_items:e.length,linked_commands_scanned:i,referenced_pm_ids_count:r,unique_referenced_pm_ids_count:o.size,unique_referenced_pm_ids:f.values,unique_referenced_pm_ids_truncated:f.truncated,stale_pm_id_references_count:d.length,stale_pm_ids_count:l.length,stale_pm_ids:p.values,stale_pm_ids_truncated:p.truncated,stale_pm_id_reference_rows:_.values,stale_pm_id_reference_rows_truncated:_.truncated}},warnings:u}}function U_(e,t){let n=pt(e.map(c=>({ref:c.id,version:_t(c)}))),s=[];n.outdated.length>0&&s.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&s.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:ae,r=M(n.outdated,i),o=M(n.ahead,i);return{check:{name:"format_version",status:n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok",details:{checked_items:e.length,current_format_version:ui,outdated_items_count:n.outdated.length,outdated_items:r.values,outdated_items_truncated:r.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:s}}var ts="pm validate auto-fix";async function Oc(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let s={message:ts};if(e.kind==="set_resolution"?s.resolution=e.value:e.kind==="set_close_reason"?s.closeReason=e.value:e.kind==="set_estimate"?s.estimatedMinutes=e.value:e.kind==="reparent"?s.parent=e.parent_id:s.unset=["parent"],!n.runUpdate)throw new h("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.USAGE);await n.runUpdate(e.item_id,s,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Qn(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Nc(e,t,n){let s=[],i=[],r=new Map;for(let o of e.filter(a=>Qn(a)===null))try{await Oc(o,t,n),s.push(o)}catch(a){i.push({fix:o,error:a})}for(let o of e.filter(a=>Qn(a)!==null)){let a=Qn(o),c=r.get(a);c?c.push(o):r.set(a,[o])}for(let o of r.values()){let a=o[0];if(!a)continue;let c=o.map(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{a.kind==="prune_file_link"?await Ho(a.item_id,{remove:c,message:ts},t):await zo(a.item_id,{remove:c,message:ts},t),s.push(...o)}catch(d){i.push(...o.map(l=>({fix:l,error:d})))}}return{applied:s,failed:i}}var ov={applyValidateFix:Oc,applyValidateFixes:Nc,attachValidateFixHints:dc,buildCommandReferencesCheck:Rc,buildDependencyReferencesCheck:yc,buildCloseReasonBackfillRows:pc,buildFilesCheck:Ac,buildLifecycleCheck:Ic,buildLifecycleDependencyGraph:hc,buildLifecycleParentGraph:kc,buildEstimateBackfillRows:fc,buildMetadataCounts:mc,buildMissingFieldOccurrences:_c,buildOrphanedPathRows:Sc,classifyOrphanedPath:Tc,collectDefaultProjectFileCandidates:es,collectTrackedGitFileCandidates:cc,detectLifecycleDependencyCycles:wc,detectLifecycleParentCycles:vc,escapeRegExp:gc,extractItemIds:bc,findLifecycleDependencyCycleComponents:rs,isMetadataFieldMissing:ic,linkedArtifactPathExceedsFilesystemLimits:Cc,listFilesRecursive:is,resolveDependencyCycleSeverity:nc,resolveParentCycleSeverity:sc,resolveFileScanMode:rc,resolveLifecycleDependencyCycleSamplePath:os,resolveRequestedChecks:lc,resolveValidateMetadataProfile:tc,resolveWorkspaceRoot:oc,sharedDirectoryPrefixLength:xc,summarizeOrphanedPathRows:Ec,summarizeDuplicateIssueCodes:uc,toMeaningfulString:J};async function G_(e,t,n,s){let i=await xa(e,new Set(t.map(m=>m.id)),n,{schema:s.schema,extensionFieldNames:mt(W())}),r=[];i.unreadable_item_files.length>0&&r.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&r.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&r.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&r.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&r.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&r.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let o=r.length,a=await At(e);a.tracked_path_count>0&&r.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Go(e,Uo(s));c.status==="drift"&&r.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Ie(e),l=d===null?null:await kt(d);l!==null&&l.status!=="ok"&&r.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=d===null?[]:await Ye(d);return u.length>0&&r.push(`validate_merge_decisions_unreviewed:${u.length}`),{check:{name:"storage_integrity",status:o>0?"error":r.length>0?"warn":"ok",details:{...i,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:u.length,pending_merge_decision_items:[...new Set(u.map(m=>m.item_id))].sort((m,_)=>m.localeCompare(_)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:r}}function oe(e,t,n){n&&dc(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function q_(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,s=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let i=x_(e.items,e.metadataPolicy,e.statusRegistry,s);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,oe(t,i,n)}if(e.requestedChecks.has("resolution")){let i=S_(e.items,e.statusRegistry,s);t.resolutionBackfillRows=i.resolutionBackfillRows,oe(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=Ic(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,s,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,oe(t,i,n),oe(t,yc(e.items,s,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await Ac(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=i.staleLinkPruneRows,oe(t,i,n)}return e.requestedChecks.has("command_references")&&oe(t,Rc(e.items,e.settings.id_prefix,s),n),e.requestedChecks.has("history_drift")&&oe(t,await j_(e.pmRoot,e.items,s),n),e.requestedChecks.has("format_version")&&oe(t,U_(e.items,s),n),e.requestedChecks.has("storage_integrity")&&oe(t,await G_(e.pmRoot,e.items,V(e.settings,W()).type_to_folder,e.settings),n),t}function B_(e,t,n){let s=[];return e.autoFix===!0&&(s.push(...Oa(t.closeReasonBackfillRows)),s.push(...Ra(t.resolutionBackfillRows)),s.push(...Na(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),s.push(...La(t.terminalParentFixRows))),e.pruneMissing===!0&&s.push(...Pa(t.staleLinkPruneRows)),s}async function W_(e,t,n,s,i,r){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=B_(e,t,n),{applicable:a,gated:c}=Da(o,s),d=e.dryRun===!0,l=[],u=[];if(!d){let m=await Nc(a,i,r);l.push(...m.applied.map(Ze)),u.push(...m.failed.map(({fix:_,error:p})=>({...Ze(_),error:p instanceof Error?p.message:String(p)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...s].sort((m,_)=>m.localeCompare(_)),planned_count:o.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(Ze),applied_fixes:l,gated_fixes:c.map(m=>({...Ze(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function av(e,t,n={}){fi(e.counts===!0,e.full===!0,"--counts");let s=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!s)throw new h("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new h("--fix-scope requires --auto-fix.",g.USAGE);let i=Ma(e.fixScope),r=R(process.cwd(),t.path);if(!await x(O(r)))throw new h(`Tracker is not initialized at ${r}. Run pm init first.`,g.NOT_FOUND);let o=await N(r),a=Z(o.schema),c=V(o,W()),d=[],l=await Ce(r,o.item_format,c.type_to_folder,d,o.schema),u=lc(e);if(u.has("history_drift")){let j=await Ve(r);j.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${j.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",_=tc(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),p=m_(_,m,o.validation.metadata_required_fields),f=l_(o),y=nc(e.dependencyCycleSeverity),b=sc(e.parentCycleSeverity),v=rc(e.scanMode),C=oc(r),S=await q_({requestedChecks:u,options:e,global:t,pmRoot:r,workspaceRoot:C,settings:o,items:l,statusRegistry:a,metadataPolicy:p,lifecyclePatternPolicy:f,dependencyCycleSeverity:y,parentCycleSeverity:b,fileScanMode:v,initialWarnings:[...new Set(d)]}),w=s?await W_(e,S,o,i,t,n):void 0,A=[...new Set(S.warnings)].sort((j,Y)=>j.localeCompare(Y)),D={ok:!S.checks.some(j=>j.status==="error"),has_warnings:A.length>0,checks:S.checks,warnings:A,...w!==void 0?{fixes:w}:{},generated_at:k(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?D:{...d_(D),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32223457-5f57-5049-99cf-c5d766413fb6")}catch{}})();var z_="1h",H_="now",V_="+1d";function pe(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function Lc(e,t,n){return{type:e,title:t,schedulePreset:"lightweight",parent:n.parent,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message}}async function Pc(e,t,n,s){let i=Lc(e,t,n),r=[];return pe(r,"start",n.start??H_),n.end!==void 0?pe(r,"end",n.end):pe(r,"duration",n.duration??z_),pe(r,"location",n.location),pe(r,"timezone",n.timezone),n.allDay===!0&&pe(r,"all_day","true"),i.event=[r.join(",")],Sn(i,s)}function lv(e,t,n){return Pc("Meeting",e,t,n)}function uv(e,t,n){return Pc("Event",e,t,n)}function mv(e,t,n){let s=Lc("Reminder",e,t),i=[];return pe(i,"at",t.at??V_),pe(i,"text",t.text??e),s.reminder=[i.join(",")],Sn(s,n)}import nt from"node:crypto";import{cp as Mc,lstat as K_,mkdir as ke,readFile as Me,readdir as as,rename as jc,rm as ds,writeFile as Gt}from"node:fs/promises";import E 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]="3e32be7c-f8a4-547d-8c19-456b4567982e")}catch{}})();var $c="https://schema.unbrained.dev/pm/workspace-snapshot/v1",Uc=E.join("runtime","workspace-snapshots"),Y_=new Set(["checkpoints","locks","runtime","search","transactions"]),X_=/^[a-z0-9][a-z0-9._-]*$/,tt="sdk-workspace-transaction",Gc={renameEntry:jc,removeEntry:async e=>{await ds(e,{recursive:!0,force:!0})}},cs=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,s){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(s*1e3/3))}start(){this.timer=setInterval(()=>{this.refresh===void 0&&(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))},this.intervalMs),this.timer.unref()}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()}async renew(){let t=JSON.parse(await Me(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!==tt||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await se(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
5
+ `)}};async function qc(e,t=""){let n=await as(E.join(e,t),{withFileTypes:!0}),s=[];for(let i of n.sort((r,o)=>r.name.localeCompare(o.name))){if(t.length===0&&Y_.has(i.name))continue;let r=E.posix.join(t.replaceAll(E.sep,"/"),i.name);if(i.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${r}`);if(i.isDirectory())s.push(...await qc(e,r));else if(i.isFile())s.push(r);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${r}`)}return s}async function Bc(e){let t=await qc(e),n=nt.createHash("sha256"),s=[],i=0;for(let o of t){let a=await Me(E.join(e,o));s.push(a),i+=a.byteLength,n.update(o),n.update("\0"),n.update(String(a.byteLength)),n.update("\0"),n.update(a)}let r=n.digest("hex");return{manifest:{schema:$c,fingerprint:r,files:t,bytes:i},contents:s}}function Dc(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
6
+ `).filter(t=>t.trim().length>0).length}async function J_(e,t){let n=new Map;for(let s=0;s<t.length;s+=32){let i=t.slice(s,s+32),r=await Promise.all(i.map(async o=>[o,await Me(E.join(e,o))]));for(let[o,a]of r)n.set(o,a)}return n}function ls(e){if(!X_.test(e))throw new h("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",g.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"}})}function Wc(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function ve(e){return E.join(e,Uc)}function zc(e){return new h(`Unknown workspace snapshot: ${e}`,g.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 Hc(e,t){try{return JSON.parse(await Me(e,"utf8"))}catch(n){throw Wc(n,"ENOENT")?zc(t):n}}async function Fc(e,t,n){try{await ds(e,{recursive:n})}catch(s){throw Wc(s,"ENOENT")?zc(t):s}}async function Q_(e,t,n=Gc){try{return await n.renameEntry(e,t),!1}catch(s){if(!(s instanceof Error&&"code"in s&&(s.code==="EEXIST"||s.code==="ENOTEMPTY")))throw s;return await n.removeEntry(e),!0}}async function Z_(e,t,n,s,i){await s.renameEntry(t,n);try{await s.renameEntry(e,t),await i?.()}catch(r){throw await s.renameEntry(n,t),await s.removeEntry(e),r}await s.removeEntry(n)}async function ep(e,t){return ls(t),/^[a-f0-9]{64}$/.test(t)?t:(await Hc(E.join(ve(e),"refs",`${t}.json`),t)).fingerprint}async function tp(e,t={}){if(t.name!==void 0&&(ls(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new h("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",g.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:s}=await Bc(e),i=ve(e),r=E.join(i,"objects",n.fingerprint),o=!1;try{o=(await K_(r)).isDirectory()}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="ENOENT"))throw a}if(!o){let a=E.join(i,"objects",`.create-${process.pid}-${nt.randomUUID()}`);await ke(E.join(a,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let l=E.join(a,"files",d);await ke(E.dirname(l),{recursive:!0}),await Gt(l,s[c])}await Gt(E.join(a,"manifest.json"),`${JSON.stringify(n,null,2)}
7
+ `,"utf8"),await ke(E.dirname(r),{recursive:!0}),o=await Q_(a,r)}if(t.name!==void 0){let a={name:t.name,fingerprint:n.fingerprint},c=E.join(i,"refs");await ke(c,{recursive:!0});let d=E.join(c,`.ref-${process.pid}-${nt.randomUUID()}`);await Gt(d,`${JSON.stringify(a,null,2)}
8
+ `,"utf8"),await jc(d,E.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:o}}async function us(e,t){let n=await ep(e,t),s=await Hc(E.join(ve(e),"objects",n,"manifest.json"),t);if(s.schema!==$c||s.fingerprint!==n)throw new h(`Snapshot manifest identity mismatch: ${t}`,g.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 s}async function np(e){let t=ve(e),n=await as(E.join(t,"objects")).catch(i=>{if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i}),s=await as(E.join(t,"refs")).catch(i=>{if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return[];throw i});return{objects:await Promise.all(n.filter(i=>/^[a-f0-9]{64}$/.test(i)).sort().map(i=>us(e,i))),references:await Promise.all(s.filter(i=>i.endsWith(".json")).sort().map(async i=>JSON.parse(await Me(E.join(t,"refs",i),"utf8"))))}}async function sp(e,t){let n=await us(e,t),{manifest:s,contents:i}=await Bc(e),r=new Map(s.files.map((u,m)=>[u,i[m]])),o=await J_(E.join(ve(e),"objects",n.fingerprint,"files"),n.files),a=new Set(s.files),c=new Set(n.files),d=new Set([...a,...c]);for(let u of d){let m=r.get(u),_=o.get(u);m!==void 0&&_!==void 0&&m.equals(_)&&d.delete(u)}let l=s.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let m=Dc(r.get(u)),_=Dc(o.get(u));return{path:u,current_entries:m,target_entries:_,removed_entries:Math.max(0,m-_)}}).filter(u=>u.removed_entries>0).sort((u,m)=>u.path.localeCompare(m.path));return{target_fingerprint:n.fingerprint,current_fingerprint:s.fingerprint,changed_file_count:d.size,removed_file_count:[...a].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!a.has(u)).length,removed_item_count:[...a].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:l.length,removed_history_entry_count:l.reduce((u,m)=>u+m.removed_entries,0),affected_history_streams:l,changes_authoritative_state:s.fingerprint!==n.fingerprint}}async function ip(e,t,n={}){if(n.force!==!0)throw new h("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",g.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 s=n.author?.trim()||"pm-sdk",i=n.lockTtlSeconds??60,r=n.lockWaitMs??5e3,o=await Ei(e,tt,i,s,!1,!1,r),a=new cs(dt(e,tt),s,i);a.start();let c,d=!1,l=!1;try{let u=await sp(e,t),m=await us(e,t),_=await tp(e),p=m.fingerprint,f=ve(e),y=E.join(f,"objects",p,"files"),b=E.dirname(e),v=E.basename(e);c=E.join(b,`.${v}.restore-${nt.randomUUID()}`);let C=E.join(b,`.${v}.backup-${nt.randomUUID()}`);await ke(c,{recursive:!0}),await Mc(y,c,{recursive:!0,force:!1}),await ke(E.join(c,"runtime"),{recursive:!0}),await Mc(f,E.join(c,Uc),{recursive:!0,force:!1});let S=await yt({pmRoot:c,op:"workspace_snapshot_restore",author:s,message:n.message??`Restore workspace snapshot ${p}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:p,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:u.changed_file_count,removed_file_count:u.removed_file_count,removed_item_count:u.removed_item_count,affected_history_stream_count:u.affected_history_stream_count,removed_history_entry_count:u.removed_history_entry_count},lockTtlSeconds:i,lockWaitMs:r}),w=E.relative(c,S.historyPath).replaceAll("\\","/");await a.stop(),l=!0;let A=dt(c,tt);return await ke(E.dirname(A),{recursive:!0}),await Gt(A,await Me(dt(e,tt)),{flag:"wx"}),d=!0,await Z_(c,e,C,Gc,async()=>{a.start(),l=!1}),await a.stop(),l=!0,{manifest:m,plan:u,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:w,audit_operation:"workspace_snapshot_restore"}}catch(u){throw c!==void 0&&!d&&await Promise.allSettled([ds(c,{recursive:!0,force:!0})]),u}finally{try{l||await a.stop()}catch{}finally{await o()}}}async function Tv(e,t){return(await ip(e,t,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function xv(e,t){ls(t);let n=ve(e);if(!/^[a-f0-9]{64}$/.test(t))return await Fc(E.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:s}=await np(e);if(s.some(i=>i.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Fc(E.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]="3b72f4a5-9e0b-5f8e-8ee9-e45cd83d6f92")}catch{}})();var rp=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),op=new Set(["--add","--body","--comment","--dep","--description","--doc","--field","--file","--learning","--note","--remove","--test","--type-option"]),ap=new Set(["append","comments","create","docs","files","learnings","notes","test","update"]),cp=["--allow-","--check-","--dry-run","--explain","--filter-","--full","--has-","--include-","--json","--no-","--only","--quiet","--require-","--runtime-only","--schema-only","--stream","--strict-","--summary","--today","--verbose"];function dp(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:t.endsWith("-file")?["argv","file"]:op.has(t)&&ap.has(e)?["argv","stdin"]:["argv"]}function lp(e){let t=e.value_name!==void 0||e.value_type==="string"||e.value_type==="number"||e.list===!0||e.repeatable===!0,n=e.flag==="--stdin"||e.flag==="--stdin-json"||cp.some(s=>e.flag.startsWith(s));return t||!n}function up(e,t){let n=lp(t),s=dp(e,t.flag),i=t.description??rp[t.flag]??`${n?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:i,takes_value:n,value_required:n,...n?{value_name:t.value_name??"value"}:{},value_type:n?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:s,...s.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{}}}function Vc(e,t){return t.map(n=>up(e,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]="6fc2cd04-2fe4-5a0e-944d-fab0f86509e2")}catch{}})();var mp=new Set(["claim","close","context","create","get","help","list","next","plan","release","search","update","validate"]),_p=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),ms=Object.freeze([...he.map(e=>({command:e,tier:mp.has(e)?"core":_p.has(e)?"standard":"full"})),{command:"completion-statuses",tier:"internal"},{command:"completion-tags",tier:"internal"},{command:"completion-types",tier:"internal"},{command:"test-runs-worker",tier:"internal"}]),Kc={core:0,standard:1,full:2,internal:3},pp=new Map(ms.map(({command:e,tier:t})=>[e,t]));function Yc(e,t="standard"){return pp.get(e.trim().toLowerCase())??t}function fp(e){let t=Kc[e];return ms.filter(n=>n.tier!=="internal"&&Kc[n.tier]<=t).map(n=>n.command)}var gp=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function Iv(e,t){if(t==="full")return[...e];let n=new Set(fp(t));return e.filter(s=>{let i=gp[s];return i!==void 0&&n.has(i)})}var Av=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),Rv=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function Ov(){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_VISIBILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier |","| --- | --- |",...ms.map(({command:t,tier:n})=>`| \`${t}\` | ${n} |`),""].join(`
9
+ `)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="479dd590-7f54-54ae-bbaf-8f183fd6b6b4")}catch{}})();var hp=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],yp=new Map(hp.map(e=>[e.exit_code,e.class]));function Xc(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function Jc(e){let t=new Set,n=e.map(s=>{let i=s.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(i))throw new TypeError(`Invalid pm error code: ${JSON.stringify(s.code)}`);if(t.has(i))throw new TypeError(`Duplicate pm error code: ${i}`);t.add(i);let r=Xc(s.sources),o=Xc(s.emitting_commands);if(![1,2,3,4,5].includes(s.exit_code)||s.meaning.trim().length===0||s.recovery.trim().length===0||r.length===0||o.length===0||yp.get(s.exit_code)!==s.class)throw new TypeError(`Invalid pm error code contract: ${i}`);return Object.freeze({...s,code:i,meaning:s.meaning.trim(),recovery:s.recovery.trim(),sources:r,emitting_commands:o})});return Object.freeze(n.sort((s,i)=>s.code.localeCompare(i.code)))}function Lv(e,t){let n=e.trim(),s=t.find(i=>i.code===n);if(!s)throw new TypeError(`Unknown pm error code "${n}"`);return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a568064-a103-5b19-969d-6e58fc0cc5b7")}catch{}})();var Qc=Jc([{code:"acceptance_criteria_semicolon_forbidden",meaning:"Acceptance criteria semicolon forbidden condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"]},{code:"already_claimed_by",meaning:"Already claimed by condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"]},{code:"ambiguous_list_all",meaning:"Ambiguous list all condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-list-query.ts"],emitting_commands:["*"]},{code:"ambiguous_option_combination",meaning:"Ambiguous option combination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"annotation_flag_like_value",meaning:"Annotation flag like value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"]},{code:"annotation_message_without_text",meaning:"Annotation message without text condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"]},{code:"append_empty_body",meaning:"Append empty body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"]},{code:"body_file_conflicts_with_body",meaning:"Body file conflicts with body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"]},{code:"body_file_missing_path",meaning:"Body file missing path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"]},{code:"body_file_unreadable",meaning:"Body file unreadable condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"]},{code:"bundle_integrity_torn_install",meaning:"Bundle integrity torn install condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/bundle-integrity.ts"],emitting_commands:["*"]},{code:"capability_undeclared",meaning:"Capability undeclared condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"capability_unused",meaning:"Capability unused condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"child_projection_item_bound_exceeded",meaning:"Child projection item bound exceeded condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-children.ts"],emitting_commands:["*"]},{code:"close_reason_required",meaning:"Close reason required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"]},{code:"close_through_update",meaning:"Close through update condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"close_validation_missing_fields",meaning:"Close validation missing fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"collected_zero_items",meaning:"Collected zero items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"command_failed",meaning:"Command failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"command_namespace",meaning:"Command namespace condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"]},{code:"command_override_conflict",meaning:"Command override conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"config_duplicate",meaning:"Config duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"config_key_unknown",meaning:"Config key unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"config_value_invalid",meaning:"Config value invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"conflicting_lifecycle_owner",meaning:"Conflicting lifecycle owner condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-operations.ts"],emitting_commands:["*"]},{code:"context_takes_no_item_argument",meaning:"Context takes no item argument condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"core_item_field_requires_dedicated_flag",meaning:"Core item field requires dedicated flag condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"create_positional_type_without_title",meaning:"Create positional type without title condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts"],emitting_commands:["*"]},{code:"dependency_edge_not_allowed",meaning:"Dependency edge not allowed condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"]},{code:"duplicate_command",meaning:"Duplicate command condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"duplicate_edge",meaning:"Duplicate edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"]},{code:"duplicate_sweep_cost_limit",meaning:"Duplicate sweep cost limit condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/similarity.ts"],emitting_commands:["*"]},{code:"duplicate_target_circular",meaning:"Duplicate target circular condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_is_duplicate",meaning:"Duplicate target is duplicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_missing",meaning:"Duplicate target missing condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"duplicate_target_self",meaning:"Duplicate target self condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"]},{code:"empty_surface",meaning:"Empty surface condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"event_cursor_query_mismatch",meaning:"Event cursor query mismatch condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"event_index_unavailable",meaning:"Event index unavailable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"extension_command_activation_failed",meaning:"Extension command activation failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/commander-usage.ts"],emitting_commands:["*"]},{code:"extension_dependency_name_unsafe",meaning:"Extension dependency name unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"extension_dependency_spec_invalid",meaning:"Extension dependency spec invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"extension_dependency_version_unsafe",meaning:"Extension dependency version unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"extension_install_soft_failed",meaning:"Extension install soft failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"]},{code:"extension_install_source_contains_destination",meaning:"Extension install source contains destination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-runtime.ts"],emitting_commands:["*"]},{code:"extension_item_field_reserved",meaning:"Extension item field reserved condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"extension_item_field_type_conflict",meaning:"Extension item field type conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"extension_item_field_unknown",meaning:"Extension item field unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_failed",meaning:"Extension mutation guard failed condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_invalid_decision",meaning:"Extension mutation guard invalid decision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_invalid_denial",meaning:"Extension mutation guard invalid denial condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_mutation_guard_timed_out",meaning:"Extension mutation guard timed out condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"]},{code:"extension_update_health_partial_coverage",meaning:"Extension update health partial coverage condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"field_duplicate",meaning:"Field duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"field_invalid",meaning:"Field invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"field_mcp_input_collision",meaning:"Field mcp input collision condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"github_source_entry_unbuilt",meaning:"Github source entry unbuilt condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/shared.ts"],emitting_commands:["*"]},{code:"history_author_acknowledge_selector_required",meaning:"History author acknowledge selector required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-history-author.ts"],emitting_commands:["*"]},{code:"history_drift_chain_mismatch",meaning:"History drift chain mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_drift_hash_mismatch",meaning:"History drift hash mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_drift_missing_stream",meaning:"History drift missing stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_drift_unreadable_stream",meaning:"History drift unreadable stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_merge_conflict_markers_detected",meaning:"History merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"]},{code:"history_stream_over_compact_threshold",meaning:"History stream over compact threshold condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"history_target_out_of_range",meaning:"History target out of range condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"]},{code:"history_unknown_author_events",meaning:"History unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"init_existing_settings_requires_force",meaning:"Init existing settings requires force condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"init_gitignore_unwritable",meaning:"Init gitignore unwritable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace.ts"],emitting_commands:["*"]},{code:"init_id_prefix_conflict",meaning:"Init id prefix conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"init_id_prefix_path_like",meaning:"Init id prefix path like condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"integrity_history_conflict_marker",meaning:"Integrity history conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_history_invalid_json",meaning:"Integrity history invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_history_unreadable",meaning:"Integrity history unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_ahead_format_version",meaning:"Integrity item ahead format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_conflict_marker",meaning:"Integrity item conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_outdated_format_version",meaning:"Integrity item outdated format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_parse_failed",meaning:"Integrity item parse failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"integrity_item_unreadable",meaning:"Integrity item unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"invalid_argument_value",meaning:"Invalid argument value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts"],emitting_commands:["*","create"]},{code:"invalid_command_usage",meaning:"Invalid command usage condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"invalid_event_cursor",meaning:"Invalid event cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_event_follow_interval",meaning:"Invalid event follow interval condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_event_limit",meaning:"Invalid event limit condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_event_since",meaning:"Invalid event since condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"]},{code:"invalid_provenance_predicate",meaning:"Invalid provenance predicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"]},{code:"invalid_query_cursor",meaning:"Invalid query cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/pagination.ts"],emitting_commands:["*"]},{code:"invalid_workspace_snapshot_target",meaning:"Invalid workspace snapshot target condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"item_document_invalid",meaning:"Item document invalid condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"]},{code:"item_document_roundtrip_failed",meaning:"Item document roundtrip failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"]},{code:"item_id_collision",meaning:"Item id collision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"]},{code:"item_not_found",meaning:"Item not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"likely_duplicate",meaning:"Likely duplicate condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/similarity.ts"],emitting_commands:["*"]},{code:"linked_test_value_not_quoted",meaning:"Linked test value not quoted condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"list_source_incomplete",meaning:"List source incomplete condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/list.ts"],emitting_commands:["list"]},{code:"local_package_archive_unsafe",meaning:"Local package archive unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"local_source_not_found_bare_name",meaning:"Local source not found bare name condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"lock_conflict",meaning:"Lock conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"locks_stale_count",meaning:"Locks stale count condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"locks_unreadable",meaning:"Locks unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"malformed_plan_step_evidence",meaning:"Malformed plan step evidence condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"manifest_capabilities_absent",meaning:"Manifest capabilities absent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"merge_conflict_markers_detected",meaning:"Merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"]},{code:"merge_git_config_unwritable",meaning:"Merge git config unwritable condition.",stability:"stable",exit_code:5,class:"dependency_failed",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"]},{code:"merge_root_not_found",meaning:"Merge root not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"]},{code:"missing_directory",meaning:"Missing directory condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"missing_lifecycle_target",meaning:"Missing lifecycle target condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension.ts"],emitting_commands:["*"]},{code:"missing_required_argument",meaning:"Missing required argument condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","core/telemetry/observability.ts","sdk/history-redact.ts","sdk/invocation-author.ts"],emitting_commands:["*"]},{code:"missing_required_option",meaning:"Missing required option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"]},{code:"module_import_failed",meaning:"Module import failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"multi_target_github_install_ambiguous",meaning:"Multi target github install ambiguous condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"]},{code:"mutation_author_required",meaning:"Mutation author required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"]},{code:"mutation_secret_guard_blocked",meaning:"Mutation secret guard blocked condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"]},{code:"no_matching_tests",meaning:"No matching tests condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_projects_matched_filters",meaning:"No projects matched filters condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_test_files_found",meaning:"No test files found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_tests_found",meaning:"No tests found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"]},{code:"no_update_fields",meaning:"No update fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"npm_package_not_found",meaning:"Npm package not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"]},{code:"ownership_conflict",meaning:"Ownership conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"],emitting_commands:["*"]},{code:"ownership_dependency_bypass_restricted_options",meaning:"Ownership dependency bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"ownership_metadata_bypass_restricted_options",meaning:"Ownership metadata bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"]},{code:"package_spec_empty",meaning:"Package spec empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_name_empty",meaning:"Profile name empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_name_not_normalized",meaning:"Profile name not normalized condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_summary_empty",meaning:"Profile summary empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"profile_title_empty",meaning:"Profile title empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"redundant_edge",meaning:"Redundant edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"]},{code:"reindex_already_running",meaning:"Reindex already running condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/reindex.ts"],emitting_commands:["*"]},{code:"reserved_item_field",meaning:"Reserved item field condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"]},{code:"schema_migration_input_required",meaning:"Schema migration input required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/migration-gates.ts"],emitting_commands:["*"]},{code:"settings_read_fs_error",meaning:"Settings read fs error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"settings_read_invalid_json",meaning:"Settings read invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"settings_read_invalid_schema",meaning:"Settings read invalid schema condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"settings_read_merge_failed",meaning:"Settings read merge failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"status_duplicate",meaning:"Status duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"status_invalid",meaning:"Status invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"stdin_json_invalid",meaning:"Stdin json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"]},{code:"stdin_json_unknown_key",meaning:"Stdin json unknown key condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"]},{code:"structured_event_immutable",meaning:"Structured event immutable condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"]},{code:"structured_event_input_conflict",meaning:"Structured event input conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"structured_event_json_empty",meaning:"Structured event json empty condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"structured_event_json_invalid",meaning:"Structured event json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"structured_event_since_invalid",meaning:"Structured event since invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"]},{code:"telemetry_endpoint_probe_failed",meaning:"Telemetry endpoint probe failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_endpoint_probe_http_status",meaning:"Telemetry endpoint probe http status condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_otel_export_failing",meaning:"Telemetry otel export failing condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_queue_high_retries",meaning:"Telemetry queue high retries condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_queue_invalid_rows",meaning:"Telemetry queue invalid rows condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_queue_pending",meaning:"Telemetry queue pending condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_schema_version_behind",meaning:"Telemetry schema version behind condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"telemetry_state_invalid_json",meaning:"Telemetry state invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"template_type_unknown",meaning:"Template type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"terminal_plan_mutation",meaning:"Terminal plan mutation condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"terminal_state_conflict",meaning:"Terminal state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"tracked_runtime_cache_files",meaning:"Tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"tracker_not_initialized",meaning:"Tracker not initialized condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"tracker_root_missing",meaning:"Tracker root missing condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"]},{code:"tracker_root_not_directory",meaning:"Tracker root not directory condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"]},{code:"type_duplicate",meaning:"Type duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"type_invalid",meaning:"Type invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"unknown_command",meaning:"Unknown command condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"]},{code:"unknown_context_intent",meaning:"Unknown context intent condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-intent-contracts.ts"],emitting_commands:["*"]},{code:"unknown_error",meaning:"Unknown error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"unknown_field",meaning:"Unknown field condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"]},{code:"unknown_field_projection",meaning:"Unknown field projection condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts"],emitting_commands:["get","list"]},{code:"unknown_item_type",meaning:"Unknown item type condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"]},{code:"unknown_lifecycle_action",meaning:"Unknown lifecycle action condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension.ts"],emitting_commands:["*"]},{code:"unknown_option",meaning:"Unknown option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"]},{code:"unknown_plan_template",meaning:"Unknown plan template condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]},{code:"unknown_provenance_dimension",meaning:"Unknown provenance dimension condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"]},{code:"unknown_status",meaning:"Unknown status condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"]},{code:"unknown_subcommand",meaning:"Unknown subcommand condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts","cli/register-operations.ts","sdk/runtime-extended-actions.ts","sdk/telemetry.ts"],emitting_commands:["*"]},{code:"unsupported_update_option",meaning:"Unsupported update option condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"]},{code:"validate_command_references_stale_pm_ids",meaning:"Validate command references stale pm ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_files_missing_linked_paths",meaning:"Validate files missing linked paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_files_orphaned_paths",meaning:"Validate files orphaned paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_files_tracked_all_strict_forces_pm_internals",meaning:"Validate files tracked all strict forces pm internals condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_format_version_ahead_items",meaning:"Validate format version ahead items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_format_version_outdated_items",meaning:"Validate format version outdated items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_hierarchy_parent_cycle",meaning:"Validate hierarchy parent cycle condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_hierarchy_parent_cycle_error",meaning:"Validate hierarchy parent cycle error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_chain_mismatches",meaning:"Validate history drift chain mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_hash_mismatches",meaning:"Validate history drift hash mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_missing_streams",meaning:"Validate history drift missing streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_drift_unreadable_streams",meaning:"Validate history drift unreadable streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_history_unknown_author_events",meaning:"Validate history unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_active_closure_like_metadata",meaning:"Validate lifecycle active closure like metadata condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_active_terminal_parent",meaning:"Validate lifecycle active terminal parent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_dependency_cycles",meaning:"Validate lifecycle dependency cycles condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_dependency_cycles_error",meaning:"Validate lifecycle dependency cycles error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_lifecycle_stale_blockers",meaning:"Validate lifecycle stale blockers condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_merge_fence_drift",meaning:"Validate merge fence drift condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_custom_profile_missing_required_fields",meaning:"Validate metadata custom profile missing required fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_duplicate_issue_codes",meaning:"Validate metadata duplicate issue codes condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_acceptance_criteria",meaning:"Validate metadata missing acceptance criteria condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_close_reason",meaning:"Validate metadata missing close reason condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_confidence",meaning:"Validate metadata missing confidence condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_estimate",meaning:"Validate metadata missing estimate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_release",meaning:"Validate metadata missing release condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_reviewer",meaning:"Validate metadata missing reviewer condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_risk",meaning:"Validate metadata missing risk condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_metadata_missing_sprint",meaning:"Validate metadata missing sprint condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_resolution_missing_fields",meaning:"Validate resolution missing fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_duplicate_item_ids",meaning:"Validate storage duplicate item ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_history_conflict_markers",meaning:"Validate storage history conflict markers condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_resurrected_items",meaning:"Validate storage resurrected items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_tracked_runtime_cache_files",meaning:"Validate storage tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_unparseable_config",meaning:"Validate storage unparseable config condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_unparseable_history",meaning:"Validate storage unparseable history condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"validate_storage_unreadable_items",meaning:"Validate storage unreadable items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"vectorization_embedding_identity_changed",meaning:"Vectorization embedding identity changed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"vectorization_stale_items_remaining",meaning:"Vectorization stale items remaining condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"]},{code:"workflow_duplicate_type",meaning:"Workflow duplicate type condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_status_unknown",meaning:"Workflow status unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_transition_malformed",meaning:"Workflow transition malformed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_type_empty",meaning:"Workflow type empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workflow_type_unknown",meaning:"Workflow type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"]},{code:"workspace_history_state_conflict",meaning:"Workspace history state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"]},{code:"workspace_root_pm_path",meaning:"Workspace root pm path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_force_required",meaning:"Workspace snapshot force required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_manifest_mismatch",meaning:"Workspace snapshot manifest mismatch condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_name_reserved_fingerprint",meaning:"Workspace snapshot name reserved fingerprint condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"workspace_snapshot_not_found",meaning:"Workspace snapshot not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"]},{code:"wrong_item_type",meaning:"Wrong item type condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"]}]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af86d275-63a8-5205-a8b3-154efdbd8e2a")}catch{}})();var bp=["mutation_receipt","entity","collection","diagnostic","stream"],wp=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),kp=new Set(["close-many","update-many"]),vp=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),Tp=new Set(["aggregate","deps","graph","health","stats","validate"]);function st(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!bp.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function Zc(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return kp.has(n)?st({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):wp.has(n)?st({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):vp.has(n)?st({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):Tp.has(n)?st({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):st({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var xp=he.map(e=>Zc(e)),Sp=new Map(xp.map(e=>[e.command,e]));function ed(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=t.split(" "),s=Sp.get(n);return s?{...s,command:t}:Zc(t)}function Ep(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cp(e){return Ep(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function jv(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!Cp(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="89c1ac6d-c217-54ea-8728-5a58762f86d9")}catch{}})();var Ip={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:{type:"integer",minimum:1,description:"Universal estimated-token ceiling for a read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."}},td={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},F={type:"string",description:"pm item id, for example pm-abc1."},Ap=`Operation name (one of): ${qe.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,Rp={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."}},Op={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 I(e,t=[]){return{...td,properties:{...td.properties,...e},required:t}}var Np=[{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:I({action:{type:"string",enum:[...qe],description:Ap},id:F,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."},...Ip},["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:I({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:I({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:I({query:{type:"string"},options:{type:"object"},...Op},["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:I({options:{type:"object"},...Rp})},{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:I({id:F,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.",inputSchema:I({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"}})},{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:I({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:I({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:F,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:I({id:F,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:I({id:F,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:I({id:F,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:I({id:F,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:I({id:F,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:I({id:F,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:I({id:F,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:I({id:F,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:I({id:F,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:I({id:F,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:I({id:F,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:I({id:F,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:I({id:F,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:I({subcommand:{type:"string",enum:[...xi]},id:F,target:F,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:I({id:F,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:I({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:I({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:I({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:I({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:[...nn]},description:`Lifecycle roles for add-status: ${nn.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:I({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:I({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:I({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."}})}],Lp={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"},Pp=Np.map(e=>{let t=Lp[e.name];if(!t)return e;let n=e.inputSchema.properties,s=e.inputSchema.required.map(String);return{...e,inputSchema:bo(t,{properties:n,required:s})}});function nd(){return Pp.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(s=>String(s)).sort((s,i)=>s.localeCompare(i)):[];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]="e6dd81d6-95d6-51e6-a0c9-ba7bb5372457")}catch{}})();var Mp=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"]]]),Dp=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],_d=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Bt=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"]),it=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"]),pd=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"]]),fd=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"]]),gd=new Map([...fd.entries()].flatMap(([e,t])=>Te(t).map(n=>[n,e]))),hd=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages","install"]}],Fp=new Map(hd.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),jp=10,$p=20,sd=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["claim","Claim work."],["close","Close work."],["comments","Manage comments."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["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."],["learnings","Manage learnings."],["list","List work."],["next","Pick next work."],["notes","Manage notes."],["ops","Run operations."],["package","Manage packages."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["stats","Show stats."],["telemetry","Manage telemetry."],["test","Run linked tests."],["update","Update work."],["upgrade","Upgrade packages."],["validate","Validate data."],["workspace","Manage portable workspace primitives."]]),yd=[["init",wr],["install",vr],["uninstall",Tr],["explore",xr],["manage",Rr],["describe",Sr],["reload",Or],["doctor",Nr],["catalog",Lr],["adopt",Pr],["adopt-all",Er],["activate",Cr],["deactivate",Ir],["migrate",Ar]],Up=yd.map(([e,t])=>e==="init"?[e,kr]:[e,t]),Gp=[...yd.map(([e,t])=>[`extension ${e}`,t]),...Up.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",hr],["config",yr],["extension",br],["package",gn],["packages",gn],["install",Mr],["create",so],["item mutate",io],["item complete",ro],["update",oo],["update-many",ao],["upgrade",Dr],["calendar",hn],["cal",hn],["context",yn],["ctx",yn],["get",lo],["search",go],["eval",po],["workspace",le],["workspace snapshot",le],["workspace snapshot create",le],["workspace snapshot list",le],["workspace snapshot inspect",le],["workspace snapshot restore",le],["workspace snapshot delete",le],["next",fo],["aggregate",nr],["deps",mo],["graph",_o],["guide",uo],["reindex",Fr],["history",cr],["history-compact",_r],["history-redact",lr],["history-repair",ur],["history-author-acknowledge",mr],["merge",dr],["schema",pr],["profile",fr],["plan",gr],["restore",qr],["delete",Br],["close",jr],["close-many",$r],["append",Ur],["claim",Gr],["release",Wr],["start-task",zr],["pause-task",Hr],["close-task",Vr],["comments",sr],["notes",ir],["learnings",rr],["files",or],["docs",ar],["test",Kr],["test-all",Yr],["telemetry",Xr],["test-runs",Jr],["gc",Qr],["stats",Zr],["duplicates",eo],["validate",no],["health",to],["contracts",ho],["completion",yo],["activity",co],...[..._d].map(e=>[e,tr])],gs=new Map(Gp);function qp(e){let t=gd.get(e);return t||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function id(e){return he.includes(e)?K(e):e.startsWith("extension-")?K(`extension ${e.slice(10)}`):e.startsWith("package-")?K(`package ${e.slice(8)}`):e.startsWith("test-runs-")?K(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?K(`templates ${e.slice(10)}`):Bt.has(e)?fd.get(e)??K(e):null}function Bp(e,t){return e.command_path===null?!1:Te(e.command_path).some(n=>n===t?!0:n.startsWith(`${t} `))}function Te(e){return e.split("|").map(t=>K(t)).filter(t=>t.length>0)}function Wp(e,t){let n=new Set(t),s=new Set;for(let i of e)if(i.command_path)for(let r of Te(i.command_path)){let o=r.split(" ").filter(a=>a.length>0);if(o.length!==0)for(let a=o.length;a>0;a-=1){let c=o.slice(0,a).join(" ");if(n.has(c)){s.add(c);break}}}return[...s].sort((i,r)=>i.localeCompare(r))}function qt(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function rt(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function zp(e,t){if(!t)return{...e};let s=rt(e).filter(i=>{let r=i.properties;if(typeof r!="object"||r===null)return!1;let o=r.action;return typeof o!="object"||o===null?!1:o.const===t});return{...e,oneOf:s}}function _s(e,t){let s=rt(e).filter(i=>{let r=i.properties;if(typeof r!="object"||r===null)return!1;let o=r.action;if(typeof o!="object"||o===null)return!1;let a=o.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:s}}function K(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function rd(e){return e.replace(/\s+/g,"-")}function te(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function od(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let s of e){let i=te(s);!i||n.has(i)||(n.add(i),t.push(i))}return t}function ps(e,t,n){n&&(e[t]=!0)}function ad(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 Hp(e){let t=ad(e.long,"long"),n=ad(e.short,"short"),s=t??n;if(!s)return null;let i={flag:s};n&&t&&(i.short=n),ps(i,"required",e.required===!0),ps(i,"repeatable",e.repeatable===!0),ps(i,"list",e.list===!0);let r=te(e.description);r&&(i.description=r);let o=te(e.value_name);o&&(i.value_name=o);let a=[te(e.value_type),te(e.type),o?"string":null].find(c=>c==="string"||c==="number"||c==="boolean");return a&&(i.value_type=a),i}function bd(e){let t=new Map;for(let s of e){let i=K(s.target_command);if(i.length===0)continue;let r=t.get(i)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},o=`${s.layer}:${s.name}`;r.sourceDedupe.has(o)||(r.sourceDedupe.add(o),r.sources.push({layer:s.layer,name:s.name}));for(let a of s.flags){let c=Hp(a);if(!c)continue;let d=`${c.flag}|${c.short??""}`;r.dedupe.has(d)||(r.dedupe.add(d),r.flags.push(c))}t.set(i,r)}let n=new Map;for(let[s,i]of t.entries())n.set(s,{flags:i.flags,sources:i.sources.sort((r,o)=>{let a=r.layer.localeCompare(o.layer);return a!==0?a:(r.name??"").localeCompare(o.name??"")})});return n}function Vp(e){let t=bd(e.flagRegistrations),n=new Map;for(let r of e.commandDefinitions){let o=K(r.command);if(o.length===0)continue;let a=te(r.action)??rd(o),c=Array.isArray(r.arguments)?r.arguments.map(d=>{let l=te(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:te(d.description)}:null}).filter(d=>d!==null):[];n.set(o,{command:o,action:a,source:{layer:r.layer,name:r.name},description:te(r.description),intent:te(r.intent),arguments:c,flags:t.get(o)?.flags??[],examples:od(r.examples),failure_hints:od(r.failure_hints)})}let s=new Set;for(let r of e.handlers)s.add(K(r));for(let r of n.keys())s.add(r);for(let r of t.keys())s.add(r);let i=[];for(let r of[...s].sort((o,a)=>o.localeCompare(a))){let o=n.get(r);if(o){i.push({...o,flags:o.flags.length>0?o.flags:t.get(r)?.flags??[]});continue}i.push({command:r,action:rd(r),source:null,description:null,intent:null,arguments:[],flags:t.get(r)?.flags??[],examples:[],failure_hints:[]})}return i}function Kp(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let s=t.replace(/-([a-z0-9])/g,(i,r)=>r.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return s.length>0?s:null}function Yp(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 Xp(e,t){let n=e.value_type??"boolean",s=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",i=e.repeatable===!0||e.list===!0;return{type:i?"array":s,...i?{items:{type:s}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function Jp(e){let t=e.command.split("|").map(i=>i.trim()).filter(i=>i.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},s=["action"];for(let i of e.arguments)n[i.name]=Yp(i,e.action),i.required&&s.push(i.name);for(let i of e.flags){let r=Kp(i);!r||n[r]!==void 0||(n[r]=Xp(i,e.action),i.required===!0&&s.push(r))}return{type:"object",properties:n,required:s,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function Qp(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 Zp(e){let t=new Map;for(let n of e){let s=t.get(n.action);if(!s){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}s.command=[...new Set([s.command,n.command])].sort((r,o)=>r.localeCompare(o)).join("|"),s.arguments=s.arguments.length>=n.arguments.length?s.arguments:n.arguments;let i=new Set(s.flags.map(r=>`${r.flag}|${r.short??""}`));for(let r of n.flags){let o=`${r.flag}|${r.short??""}`;if(!i.has(o))i.add(o),s.flags.push(r);else{let a=s.flags.find(c=>`${c.flag}|${c.short??""}`===o);a&&Qp(a,r)}}s.examples=[...new Set([...s.examples,...n.examples])],s.failure_hints=[...new Set([...s.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,s)=>n.action.localeCompare(s.action))}async function ef(e,t=N){let n={mode:Ge.extensions.policy.mode,trust_mode:Ge.extensions.policy.trust_mode,default_sandbox_profile:Ge.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let s=R(process.cwd(),e.path);if(!await x(O(s)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let i=await t(s),r=await lt({pmRoot:s,settings:i,cwd:process.cwd(),noExtensions:!1}),o=await ut({...r,loaded:r.loaded});return{handlers:new Set(o.commands.handlers.map(c=>K(c.command))),disabledReason:null,commandDefinitions:o.registrations.commands,flagRegistrations:o.registrations.flags,registrations:o.registrations,policyState:{mode:r.policy.mode,trust_mode:r.policy.trust_mode,default_sandbox_profile:r.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function tf(e,t={}){let n=new Map;for(let s of qe){let i=Bt.has(s);if(i&&!t.includePackageOwnedActions)continue;let r=id(s);n.set(s,{action:s,provider:i?"extension":"core",requires_extension:i,command_path:r})}if(t.includePackageOwnedActions)for(let s of Bt)n.has(s)||n.set(s,{action:s,provider:"extension",requires_extension:!0,command_path:id(s)});for(let s of e)n.has(s.action)||n.set(s.action,{action:s.action,provider:"extension",requires_extension:!0,command_path:K(s.command)});return[...n.values()].sort((s,i)=>(s.action??"").localeCompare(i.action??""))}function nf(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?Te(e.command_path):[],s=n.some(o=>t.handlers.has(o)),i=n.map(o=>pd.get(o)).find(o=>typeof o=="string"),r=t.disabledReason===null&&s;return{action:e.action,invocable:r,available:r,requires_extension:!0,provider:"extension",disabled_reason:r?null:t.disabledReason??(i?`optional_package_not_installed:${i}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:s,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function wd(e){return gs.get(e)??er}function sf(e){return it.has(e)?!1:gs.has(e)}function rf(e){return _d.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function cd(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function of(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function af(e){let t=new Map;for(let s of e.definitions){let i=cd(s.cli_flag);if(!i)continue;let r=s.cli_aliases.map(a=>of(a)).find(a=>a!==null),o=s.cli_aliases.map(a=>cd(a)).filter(a=>a!==null&&a!==i);for(let a of s.commands){let c=t.get(a)??{flags:[],seen:new Set},d=r?{flag:i,short:r}:{flag:i},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of o){let m=`${u}|`;c.seen.has(m)||(c.seen.add(m),c.flags.push({flag:u}))}t.set(a,c)}}let n=new Map;for(let[s,i]of t.entries())n.set(s,fn(i.flags));return n}function dd(e,t){let n=[],s=new Set;for(let i of[...e,...t]){let r=`${i.flag}|${i.short??""}`;s.has(r)||(s.add(r),n.push(i))}return fn(n)}function cf(e,t,n,s){return e.map(i=>{let r=sf(i),o=r?wd(i):[],a=n.get(rf(i))??[],c=t.get(i),d=dd(o,a),l=dd(d,c?.flags??[]),u=o.length>0&&(c?.flags.length??0)>0?"mixed":r?"core":"extension";return{command:i,flags:l,...s?{canonical_command:fs(i),visibility:Yc(fs(i)),flag_invocations:Vc(i,l)}:{},provider:u,extension_sources:c?.sources}}).sort((i,r)=>i.command.localeCompare(r.command))}function df(e){let t=new Set(e);return hd.map(n=>({canonical:n.canonical,aliases:n.aliases.filter(s=>t.has(s))})).filter(n=>t.has(n.canonical)&&n.aliases.length>0)}function lf(){return{create_string_options:Xi,create_repeatable_options:Ji,update_string_options:Qi,update_repeatable_options:Zi,list_string_options:zi,search_string_options:Hi,calendar_string_options:Vi,context_string_options:Ki,activity_string_options:Yi}}function ld(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 s=Js(e,"create",n),i=[...new Set(s.required)].sort((a,c)=>a.localeCompare(c)),r=[...new Set(i.map(a=>Xs("create",a)))].sort((a,c)=>a.localeCompare(c)),o=[...new Set(e.options.filter(a=>a.required===!0).map(a=>a.key))].sort((a,c)=>a.localeCompare(c));return{required_option_keys:i,required_flags:r,required_type_options:o,policy_errors:[...new Set(s.errors)].sort((a,c)=>a.localeCompare(c))}}function uf(e){let t={},n={};for(let s of[...e.types].sort((i,r)=>i.localeCompare(r))){let i=e.by_type[s];t[s]=ld(i,"strict"),n[s]=ld(i,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function mf(e,t){let n=rt(e);if(n.length===0)return e;let s=!1,i=n.map(r=>{let o=r.properties;if(typeof o!="object"||o===null)return r;let a=o.action;return typeof a!="object"||a===null||a.const!=="create"?r:(s=!0,{...r,"x-create-required-options":t})});return s?{...e,oneOf:i}:e}function _f(e){let t=qt(e.action)!==void 0||qt(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,s=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,i=e.schemaOnly===!0,r=e.flagsOnly===!0,o=e.availabilityOnly===!0,a=e.runtimeOnly===!0,c=e.full===!0,d=qt(e.action),l=qt(e.command),u=!s&&!c&&!i&&!r&&!o&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:s,schemaOnly:i,flagsOnly:r,availabilityOnly:o,runtimeOnly:a,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u}}function pf(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(n=>n).length>1)throw new h("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",g.USAGE)}async function ff(e,t=N){try{return await t(e)}catch{return structuredClone(Ge)}}async function gf(e,t){let n=await ff(t),s=await ef(e),i=V(n,s.registrations??W()),r=di(n.schema),o=Vp(s);return{settings:n,runtimeProbe:s,typeRegistry:i,statusRegistry:Z(n.schema),runtimeFieldRegistry:r,runtimeFieldFlagMap:af(r),createRequiredOptionContracts:uf(i),extensionContracts:o,mergedExtensionContracts:Zp(o),extensionFlagMap:bd(s.flagRegistrations)}}function ud(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Bt.has(e.selectedAction)||e.selectedCommand!==void 0&&it.has(e.selectedCommand))}function hf(e,t){let n=tf(t,{includePackageOwnedActions:ud(e)});return ud(e)&&e.selectedCommand!==void 0&&it.has(e.selectedCommand)&&!n.some(s=>s.command_path===e.selectedCommand)&&n.push({action:qp(e.selectedCommand),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function yf(e,t){let n=new Set(t.map(s=>s.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new h(`Unknown action: "${e.selectedAction}".`,g.USAGE)}function bf(e,t){return[...new Set([...he.filter(n=>!it.has(n)),...[...gs.keys()].filter(n=>!it.has(n)),...e.flatMap(n=>n.command_path?Te(n.command_path):[]),...t.flatMap(n=>n.command.split("|"))])].map(n=>K(n)).filter(n=>n.length>0).sort((n,s)=>n.localeCompare(s))}function wf(e,t){let n=t.slice(0,jp),s=t.length-n.length,i=s>0?`${n.join(", ")}, and ${s} more`:n.join(", "),r=t.slice(0,$p),o=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),a=t[0];return new h(`Command "${e}" is a command namespace. Choose a concrete child command: ${i}.`,g.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:o,nextSteps:[`Retry with a child command, for example: ${o[0]}`],recovery:{suggested_retry:`pm contracts --command "${a}" --flags-only --json`,fallback_candidates:r.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function kf(e,t){return new h(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,g.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 vf(e){return new h(`Unknown command: "${e}".`,g.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 Tf(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let s=t.filter(r=>r.startsWith(`${e.selectedCommand} `));if(s.length>0)throw wf(e.selectedCommand,s);let i=pd.get(e.selectedCommand);throw i?kf(e.selectedCommand,i):vf(e.selectedCommand)}function xf(e,t){let n=hf(e,t.mergedExtensionContracts);yf(e,n);let s=bf(n,t.mergedExtensionContracts);Tf(e,s);let i=e.selectedCommand?gd.get(e.selectedCommand):void 0,r=e.selectedCommand?n.filter(d=>i?d.action===i:Bp(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!r.some(d=>d.action===e.selectedAction))throw new h(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,g.USAGE);let o=e.selectedAction?r.filter(d=>d.action===e.selectedAction):r,a=[...new Map(o.map(d=>nf(d,t.runtimeProbe)).map(d=>[i?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?a.filter(d=>d.invocable):a;return{actionDescriptors:n,commandCatalog:s,commandScopedDescriptors:r,scopedActionDescriptors:o,selectedPackageOwnedAction:i,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function Sf(e){return new Set(rt(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let s=n.action;if(typeof s!="object"||s===null)return null;let i=s.const;return typeof i=="string"?i:null}).filter(t=>t!==null))}function Ef(e){let t=wo,n=rt(t),s=Sf(t),i=e.filter(r=>!s.has(r.action)).map(r=>Jp(r));return i.length>0?{...t,oneOf:[...n,...i]}:t}function md(e,t,n){let s=new Set(t.actionDescriptors.map(r=>r.action)),i=e.selectedAction?zp(n,e.selectedAction):e.selectedCommand?_s(n,new Set(t.scopedActionDescriptors.map(r=>r.action))):_s(n,s);return e.runtimeOnly&&!e.selectedAction?_s(i,new Set(t.actions)):i}function Cf(e,t,n){let s=Ef(t.mergedExtensionContracts),r=!e.flagsOnly&&!e.availabilityOnly?mf(md(e,n,s),t.createRequiredOptionContracts):md(e,n,s);return{mergedSchema:s,filteredSchema:r}}function If(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?Wp(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function Af(e,t){return t}function Rf(e){let t=e.split(" ")[0];return sd.get(e)??sd.get(t)??"Inspect flags."}function fs(e){let t=e.split(" ")[0];return t.startsWith("list-")?"list":t.startsWith("history-")?"history":t==="ctx"?"context":t==="packages"?"package":Fp.get(t)??t}function Of(e){let t=new Map;for(let s of e){let i=s.split(" ")[0],r=fs(i),o=t.get(r)??new Set;o.add(i),t.set(r,o)}return[...t.keys()].filter(s=>s.length>0).sort((s,i)=>s.localeCompare(i)).map(s=>{let i=ln(s,{generateFallback:!0}),r=new Set(wd(s).map(c=>c.flag)),o=(Mp.get(s)??Dp).filter(c=>r.has(c)),a=[...t.get(s)].filter(c=>c!==s).sort((c,d)=>c.localeCompare(d));return{command:s,...a.length>0?{aliases:a}:{},intent:Rf(s),...o.length>0?{flags:o}:{},default_max_estimated_tokens:i.default_max_estimated_tokens}})}function Nf(e){return e.map(t=>({budget:ln(t,{generateFallback:!0}),envelope:ed(t)}))}function Lf(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(s=>Te(s.command).includes(e.selectedCommand));if(e.selectedAction){let s=new Set(n);return t.extensionContracts.filter(i=>Te(i.command).some(r=>s.has(r)))}return t.extensionContracts}function Pf(e,t,n,s){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?[]:s,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function Mf(e,t){e.runtime_schema={statuses:t.statusRegistry.definitions.map(n=>n.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()].map(([n,s])=>[n,[...new Set(s.map(i=>`--${i.cli_flag}`))].sort((i,r)=>i.localeCompare(r))]))},e.extension_contracts={capabilities:[...yi],services:[...bi],policy_modes:[...wi],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Ti],trust_modes:[...ki],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...vi],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...Hs],create_modes:[...Vs],close_validation_modes:[...Ks],workflow_enforcement_modes:[...Ys]}}function Df(e,t,n,s){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=s;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=s}}function Ff(e,t,n,s,i){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=cf(s,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0);let r=new Set(s);e.list_projections=Object.entries(Co).filter(([o])=>r.has(o)).map(([o,a])=>({command:o,default:a,brief_fields:[...Eo],compact_fields:[...So]}))}i.length>0&&(e.command_aliases=i)}}function jf(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=lf();return}e.commander_aliases_omitted_reason="unfiltered_default_brief"}}async function tT(e,t){let n=_f(e);pf(n);let s=R(process.cwd(),t.path),i=await gf(t,s),r=xf(n,i),o=Cf(n,i,r),a=If(n,r),c=Af(n,a),d=Pf(n,o,r,c);if(n.summary)return d.command_summaries=Of(c),d.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Si],allows_unbounded_opt_out:!0},d;let l=df(a),u=Lf(n,i,c);return n.flagsOnly&&!n.fullOutput||Mf(d,i),Df(d,n,o,u),Ff(d,n,i,c,l),jf(d,n),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=nd(),d.context_intents=hi(),d.read_output_dimensions=gi,d.error_codes=Qc,d.command_output_contracts=Nf(c)),d}import Uf from"node:fs/promises";import vd 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 Wt(e,t,n,s,i,r="min"){let o=i==="min"?e-t:t-e,a=r==="min"?n.localeCompare(s??n):(s??n).localeCompare(n);return o<0||o===0&&s!==null&&a<0}function $f(e,t){let n=Buffer.byteLength(t,"utf8"),s=0,i=null,r=null,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;s+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,m=Date.parse(u);Number.isNaN(m)||(Wt(m,o,u,i,"min")&&(o=m,i=u),Wt(m,a,u,r,"max","max")&&(a=m,r=u))}return{id:e,bytes:n,lines:s,oldest_ts:i,newest_ts:r}}function kd(e,t){let n=t?.topN??5,s=Math.max(0,Math.floor(n)),i=e.map(({id:_,raw:p})=>$f(_,p)),r=0,o=0,a=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let _ of i){if(r+=_.lines,o+=_.bytes,_.oldest_ts!==null){let p=Date.parse(_.oldest_ts);Wt(p,d,_.id,a?.id??null,"min")&&(d=p,a={id:_.id,ts:_.oldest_ts})}if(_.newest_ts!==null){let p=Date.parse(_.newest_ts);Wt(p,l,_.id,c?.id??null,"max")&&(l=p,c={id:_.id,ts:_.newest_ts})}}let u=s===0?[]:[...i].sort((_,p)=>p.bytes-_.bytes||_.id.localeCompare(p.id)).slice(0,s),m=s===0?[]:[...i].sort((_,p)=>p.lines-_.lines||_.id.localeCompare(p.id)).slice(0,s);return{total_streams:e.length,total_lines:r,total_bytes:o,largest_by_bytes:u,deepest_by_lines:m,oldest_entry:a,newest_entry:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e8916552-697e-565c-91e1-4829ecb584af")}catch{}})();function Gf(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function qf(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function Bf(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function Wf(e){let t=vd.join(e,"history");if(!await x(t))return[];await X({path:t,scope:"project"});let n=(await Uf.readdir(t)).filter(i=>i.endsWith(".jsonl")).sort((i,r)=>i.localeCompare(r)),s=[];for(let i of n){let r=vd.join(t,i),o=await $(r);o!==null&&(await X({path:r,scope:"project"}),s.push({id:i.slice(0,-6),raw:o}))}return s}async function wT(e,t={}){let n=R(process.cwd(),e.path);if(!await x(O(n)))throw new h(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let s=await N(n),i=V(s,W()),r=Z(s.schema),o=t.fieldUtilization?await Ce(n,s.item_format,i.type_to_folder,void 0,s.schema):await bt(n,s.item_format,i.type_to_folder,void 0,s.schema);await ht({pmRoot:n,settings:s,itemIds:o.map(b=>b.id),commandLabel:"stats"});let a=Gf(i.types),c=qf(r.definitions.map(b=>b.id));for(let b of o)a[b.type]+=1,c[b.status]+=1;let d=await Wf(n),l=0;for(let b of d)l+=Bf(b.raw);let u=t.storage?kd(d):void 0,m=vo(r),_=t.metadataCoverage?To(o,m):void 0,p={};t.byAssignee&&(p.assignee=wt(o,"assignee",m)),t.byTag&&(p.tag=wt(o,"tag",m,{tagPrefix:t.tagPrefix})),t.byPriority&&(p.priority=wt(o,"priority",m));let f=Object.keys(p).length>0,y=t.fieldUtilization?xo(o):void 0;return{totals:{items:o.length,history_streams:d.length,history_entries:l},by_type:a,by_status:c,..._?{metadata_coverage:_}:{},...f?{breakdowns:p}:{},...u?{storage:u}:{},...y?{field_utilization:y}:{},generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6152efa9-8338-57f0-b3de-5707befed019")}catch{}})();async function xT(e,t={}){let n=await Oo({pmRoot:R(process.cwd(),e.path),...t.status===void 0?{}:{statuses:t.status.flatMap(s=>s.split(",").map(i=>i.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(s=>{let i=s.id;return{...s,canonical_id:i,close_command:`pm close <duplicate-id> --duplicate-of ${i}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import zf from"node:fs/promises";import fe 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]="150c6ff7-cfb5-542f-bd3d-3c8088d1086a")}catch{}})();var Cd=fe.join("runtime","telemetry","events.jsonl"),Id=fe.join("runtime","telemetry","state.json"),Hf=fe.join("runtime","telemetry"),Vf=20,Td=["status","flush","stats","clear"],xd=(e,t)=>{let n=Math.ceil(t*e.length),s=Math.min(e.length-1,Math.max(0,n-1));return e[s]},hs=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Sd=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},Kf=e=>({command:hs(e.event.command,"<unknown>"),eventType:hs(e.event.event_type,"unknown"),eventSchemaVersion:Sd(e.event.schema_version),clientSchemaVersion:Sd(e.client_schema_version)}),Yf=()=>({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:{}}),Xf=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},Jf=e=>{let t=e?.command_resolution;return hs(t,"")||void 0},Ad=(e,t)=>{e[t]=(e[t]??0)+1},Qf=(e,t)=>{let n=Xf(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let s=Jf(t);s!==void 0&&Ad(e.resolution_counts,s)},Zf=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Ed=(e,t)=>{t!==void 0&&e.add(t)},eg=(e,t)=>{let n=Kf(t),s=e.get(n.command)??Yf();s.count+=1,s.max_attempts=Math.max(s.max_attempts,Zf(t.attempts)),Ad(s.event_type_counts,n.eventType),Ed(s.event_schema_versions,n.eventSchemaVersion),Ed(s.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&Qf(s,t.event.payload),e.set(n.command,s)},tg=(e,t)=>{let n=t.ok_count+t.error_count,s=[...t.finish_durations_ms].sort((r,o)=>r-o),i=Object.entries(t.resolution_counts).sort((r,o)=>r[0].localeCompare(o[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((r,o)=>r[0].localeCompare(o[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((r,o)=>r-o),client_schema_versions:[...t.client_schema_versions].sort((r,o)=>r-o),...s.length>0?{duration_p50_ms:xd(s,.5),duration_p95_ms:xd(s,.95),duration_max_ms:s[s.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...i.length>0?{command_resolution_counts:Object.fromEntries(i)}:{}}},ng=e=>{let t=(e??"status").trim().toLowerCase();if(Td.includes(t))return t;throw new h(`Unknown pm telemetry subcommand "${e}". Allowed: ${Td.join(", ")}`,g.USAGE,{code:"unknown_subcommand",examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},ys=()=>{throw new h("--limit must be a positive integer",g.USAGE)},Rd=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?ys():e,sg=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?ys():Rd(Number.parseInt(t,10))},ig=e=>e===void 0?Vf:typeof e=="number"?Rd(e):typeof e=="string"?sg(e):ys(),rg=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},og=e=>{try{let t=JSON.parse(e);return rg(t)?t:void 0}catch{return}},ag=e=>e===null?[]:e.split(`
10
+ `).map(t=>t.trim()).filter(t=>t.length>0),Od=e=>{let t=ag(e),n=[],s=0;for(let i of t){let r=og(i);r===void 0?s+=1:n.push(r)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:s,entries:n}},cg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dg=e=>{try{let t=JSON.parse(e);return cg(t)?t:{}}catch{return{}}},lg=async e=>{let t=await $(e);return t===null||t.trim().length===0?{}:dg(t)},zt=e=>e??null,Ht=async e=>{let t=await N(e),n=fe.join(e,Cd),s=fe.join(e,Id),i=await $(n),r=Od(i),o=await lg(s);return{enabled:t.telemetry.enabled,endpoint:t.telemetry.endpoint,queue_path:n,state_path:s,queue_rows_total:r.rows_total,queue_entries:r.valid_entries,queue_invalid_rows:r.invalid_rows,queue_size_bytes:Buffer.byteLength(i??"","utf8"),last_attempted_flush_at:zt(o.last_attempted_flush_at),last_successful_flush_at:zt(o.last_successful_flush_at),last_failed_flush_at:zt(o.last_failed_flush_at),last_failed_flush_error:zt(o.last_failed_flush_error)}},ug=e=>{let t=new Map;for(let n of e)eg(t,n);return[...t.entries()].map(([n,s])=>tg(n,s)).sort((n,s)=>s.count-n.count||n.command.localeCompare(s.command))},mg=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Ht(t.globalPmRoot),generated_at:k()}),_g=async(e,t)=>{let n=await Ht(t.globalPmRoot);await Wi(t.globalPmRoot);let s=await Ht(t.globalPmRoot),i=Math.max(0,n.queue_entries-s.queue_entries),r=s.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:s.queue_entries,queue_entries_drained:i,queue_progressed:i>0,queue_empty:r,queue_drained:r,status:s,generated_at:k()}},pg=async(e,t)=>{let n=ig(e.limit),s=await $(t.queuePath),i=Od(s),r=ug(i.entries),o=r.slice(0,n);return{action:"telemetry",subcommand:"stats",limit:n,total_commands:r.length,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_rows_total:i.rows_total,truncated:r.length>o.length,stats:o,generated_at:k()}},fg=async(e,t)=>{let n=await N(t.globalPmRoot),s=[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="",s&&await Ri(t.globalPmRoot,n,"telemetry:clear");let i=fe.join(t.globalPmRoot,Hf),r=await x(i);return await zf.rm(i,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:s,runtime_dir_removed:r&&!await x(i),queue_exists_after:await x(t.queuePath),state_exists_after:await x(t.statePath),status:await Ht(t.globalPmRoot),generated_at:k()}},gg={status:mg,flush:_g,stats:pg,clear:fg};async function MT(e,t){let n=ng(e.subcommand),s=Q(process.cwd());return gg[n](e,{globalPmRoot:s,queuePath:fe.join(s,Cd),statePath:fe.join(s,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]="6e840281-a386-57db-bee0-c9b93b27deb1")}catch{}})();var hg=32;function yg(e){let t=[];for(let n of e??[]){let s=[];for(let i of n.split(",")){let r=i.slice(0,i.indexOf("=")).trim();s.length>0&&r!=="unit"&&r!=="threshold"&&(t.push(s.join(",")),s=[]),s.push(i)}t.push(s.join(","))}return t}function bs(e,t){let n=yg(e).map(i=>{let[r,...o]=i.split(","),a=r.indexOf("="),c=r.slice(0,a).trim(),d=r.slice(a+1).trim(),l=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(l))throw new h(`Invalid --measure "${i}"; expected name=value[,unit=...][,threshold=...]`,g.USAGE);let u,m;for(let _ of o){let p=_.indexOf("="),f=_.slice(0,p).trim(),y=_.slice(p+1).trim();if(f==="unit"&&y.length>0)u=y;else if(f==="threshold"&&y.length>0&&Number.isFinite(Number(y)))m=Number(y);else throw new h(`Invalid --measure attribute "${_}"`,g.USAGE)}return{name:c,value:l,unit:u,threshold:m,recorded_at:t}});return[...new Map(n.map(i=>[i.name,i])).values()].sort((i,r)=>i.name.localeCompare(r.name)).slice(0,hg)}function Nd(e,t,n){return e.flatMap(s=>(s.measurements??[]).filter(i=>i.name===t&&i.value<n).map(i=>({...i,run_id:s.run_id})))}function Ld(e,t){let n=e.flatMap(r=>r.measurements??[]).filter(r=>r.name===t).sort((r,o)=>o.recorded_at.localeCompare(r.recorded_at)),s=n[0],i=n[1];return{name:t,latest:s?.value??null,previous:i?.value??null,delta:s!==void 0&&i!==void 0?s.value-i.value:null,unit:s?.unit}}import{spawn as Qd}from"node:child_process";import{cp as jd,mkdir as Tg,mkdtemp as Zd,open as Ts,readdir as xs,rm as el}from"node:fs/promises";import{tmpdir as tl}from"node:os";import G 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 Pd=20;function bg(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return Pd;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?Pd:t}function ws(e){let t=[...e].filter(s=>s.run_id.trim().length>0&&s.started_at.trim().length>0&&s.finished_at.trim().length>0&&s.recorded_at.trim().length>0).sort((s,i)=>{let r=Ws(s.recorded_at,i.recorded_at);if(r!==0)return r;let o=s.run_id.localeCompare(i.run_id);return o!==0?o:s.kind.localeCompare(i.kind)}),n=bg();return t.length>n?t.slice(t.length-n):t}async function Vt(e){await ye({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=ws([...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 Md=100;function ks(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new h(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,g.USAGE);return n}function wg(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Md?n:`${n.slice(0,Md-3)}...`}function Dd(e){return e.map((t,n)=>`${n+1}. ${wg(t)}`).join("; ")}function kg(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 vg(e,t){let n=e.command?.toLowerCase()??"",s=e.path?.toLowerCase()??"";return n.includes(t)||s.includes(t)}function Fd(e,t){let n=kg(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((i,r)=>r+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new h(`Combine at most one linked-test selector per run: ${n.map(i=>`--${i}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,g.USAGE);let s=n[0];if(e.length===0)throw new h(`--${s} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,g.USAGE);if(s==="match"){let i=t.match.trim().toLowerCase();if(i.length===0)throw new h("--match requires a non-empty substring to match against linked-test command/path values",g.USAGE);let r=[],o=[];for(let a=0;a<e.length;a+=1)vg(e[a],i)&&(o.push(e[a]),r.push(a+1));if(o.length===0)throw new h(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Dd(e)}`,g.USAGE);return{selector:"match",requested:t.match,selected:o,selected_indexes:r,selected_count:o.length,skipped_count:e.length-o.length}}if(s==="only-index"){let i=ks(t.onlyIndex);if(i>e.length)throw new h(`--only-index ${i} is out of range: this item has ${e.length} linked test(s). Available entries: ${Dd(e)}`,g.USAGE);return{selector:"only-index",requested:String(i),selected:[e[i-1]],selected_indexes:[i],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]="7d05534b-3cf7-506c-8626-4bd4a42cbc80")}catch{}})();var Yt=20*1024*1024,xg=3e3,Sg=1e4,Eg=5e3,$d=120,Cg=new Set(["locks","extensions","runtime"]),Ig=new Set(["history","index","search","extensions","locks","runtime"]),Ag=[/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],Rg=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,Og=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,Ng=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 Cs(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let s=Number.parseInt(n,10);return!Number.isFinite(s)||s<=0?t:s}function Lg(){return Cs("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",xg)}function Pg(){return Cs("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",Sg)}function Mg(){return Cs("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",Eg)}function Dg(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 Fg(e){let t=0,n=0,s=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"){n+=1;continue}s+=1}return{passed:t,failed:n,skipped:s}}function Is(e){let t=0,n=0,s=0,i=0;for(let r of e){let o=r.execution_context;!o||o.is_pm_command!==!0||(t+=1,o.is_pm_tracker_read_command===!0&&(n+=1),o.mismatch_detected===!0&&(s+=1),o.auto_pm_context_applied===!0&&(i+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:s,auto_remediated:i}}function jg(e){let t=e??"project";if(!zs.includes(t))throw new h(`Invalid scope "${e}"`,g.USAGE);return t}function Xt(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(wn.includes(t))return t;throw new h(`Invalid --pm-context value "${e}". Expected one of: ${wn.join(", ")}`,g.USAGE)}function $g(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Xt(e.pm_context_mode)}function Ug(e,t){return e==="auto"?t?"tracker":"schema":e}function Gg(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 qg(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:s}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&s==="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 Bg(e,t){let n={};if(!e)return n;for(let s of e){let i=kn(s,t);if(i)for(let[r,o]of Object.entries(i))n[r]=o}return n}function Wg(e,t){if(!e)return[];let n=[];for(let s of e){let i=vn(s,t);i&&n.push(...i)}return[...new Set(n)]}function zg(e){let t=Jt(e);return Pe(t).some(n=>Nt(n)!==null)}function Hg(e){let t=Jt(e);return Pe(t).some(n=>{let s=Nt(n);if(!s)return!1;let i=Yn(s);return i?Ng.has(i.subcommand):!1})}function Kt(e){if(e)return Ca.has(e.subcommand)?ue(e.args,Ia)?.subcommand:e.subcommand}function Ud(e,t){if(e==="npx"||e==="bunx")return be(t)?.command;if(e==="pnpm")return Kt(ue(t,zn));if(e==="npm")return Kt(ue(t,Hn));if(e==="yarn")return Kt(ue(t,Sa));if(e==="bun")return Kt(ue(t,Ea))}function Gd(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function vs(e){return!e||!Je(e.command)&&!Kn(e.command)?!1:Pt(e.args)==="test-all"}var Vg=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])]),Kg=new Set(["npx","bunx"]);function nl(e){let t=e.split(" ").filter(o=>o.length>0),n=Lt(t);if(n.length===0)return!1;let[s,...i]=n,r=Vg.get(s);if(r){let o=i.findIndex(a=>r.test(a));return o>=0?nl(i.slice(o+1).join(" ")):!1}return Je(s)||Qe(s)?Pt(i)==="test-all":s==="node"&&i.length>0&&Qe(i[0])?Pt(i.slice(1))==="test-all":Kg.has(s)?vs(be(i)):s==="pnpm"?vs(Mt(i)):s==="npm"?vs(Dt(i)):!1}function sl(e){let t=Jt(e);return Pe(t).some(n=>nl(n))}function il(e){if(sl(e))throw new h('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',g.USAGE)}function Jt(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function Yg(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 Xg(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 Jg(e){let t=e.split(" ").filter(r=>r.length>0),n=Lt(t);if(n.length===0)return!1;let[s,...i]=n;return s==="vitest"||s.endsWith("/vitest")||s.endsWith("/vitest.mjs")?!0:s==="node"?Qg(i):Zg(s,i)}function Qg(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function Zg(e,t){return e==="npx"||e==="bunx"?Gd(be(t)?.command):e==="pnpm"||e==="npm"?Gd((e==="pnpm"?Mt(t):Dt(t))?.command)||Ud(e,t)==="vitest":(e==="yarn"||e==="bun")&&Ud(e,t)==="vitest"}function rl(e){let t=Jt(e);if(Pe(t).some(i=>!Yg(i)&&Jg(i)&&!Xg(i)))throw new h('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".',g.USAGE)}function eh(e){if(sl(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function th(e){return e?e.map(nh):[]}function nh(e){let t=e.trim(),n=No(t)?Lo(un(e,"--add"),"--add"):{command:t},s=U(n.command);if(!s)throw new h("--add requires command=<value> or a bare command (path=<value> is optional metadata)",g.USAGE);return il(s),rl(s),{command:s,path:U(n.path),scope:jg(n.scope),timeout_seconds:sh(U(n.timeout_seconds),U(n.timeout)),pm_context_mode:Mo(U(n.pm_context_mode),"--add"),env_set:kn(U(n.env_set),"--add"),env_clear:vn(U(n.env_clear),"--add"),shared_host_safe:Po(U(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Tn(U(n.assert_stdout_contains)),assert_stdout_regex:xn(U(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Tn(U(n.assert_stderr_contains)),assert_stderr_regex:xn(U(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Do(U(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Fo(U(n.assert_json_field_equals),"--add"),assert_json_field_gte:jo(U(n.assert_json_field_gte),"--add"),note:U(n.note)}}function U(e){let t=e?.trim();return t&&t.length>0?t:void 0}function sh(e,t){if(e&&t&&e!==t)throw new h("--add timeout and timeout_seconds must match when both are provided",g.USAGE);let n=e??t;if(n===void 0)return;let s=Math.floor(Be(n,"timeout_seconds"));if(s<=0)throw new h("--add timeout_seconds must be a positive integer",g.USAGE);return s}function ih(e){return e?e.flatMap(t=>{let n=$o(t,"--add-json");for(let s of n){let i=s.command;if(!i)throw new h("--add-json requires a non-empty command string",g.USAGE);il(i),rl(i)}return n}):[]}function rh(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new h("--remove requires command or path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:path|command)\s*[:=]/i.test(n)||n.startsWith("```")){let s=un(n,"--remove"),i=s.path??s.command;if(!i?.trim())throw new h("--remove requires command=<value> and/or path=<value>",g.USAGE);return i.trim()}return n}):[]}function oh(e){try{e.stdin?.end()}catch{}}function ol(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=$d?t:`${t.slice(0,$d-3)}...`}function al(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Ss(e){try{process.stderr.write(`${e}
11
+ `)}catch{}}function ah(e,t){if(!al(t))return null;let n=ol(e.command),s=Date.now();Ss(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let i=setInterval(()=>{let r=Date.now()-s;Ss(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${r} command="${n}"`)},Pg());return i.unref?.(),i}function ch(e,t,n,s){if(!al(s))return;let i=ol(e.command),r=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 d=t.exitCode===null?"null":String(t.exitCode),l=c.length>0?` ${c.join(" ")}`:"";Ss(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${d} elapsed_ms=${r}${l} command="${i}"`)}async function qd(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Qd("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 dh(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function lh(e,t){let n=!1;return async()=>{if(n)return;n=!0;let s=e.pid;if(!s||s<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await qd(s);return}try{process.kill(-s,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{qd(s)},Lg()),t.forceKillTimer.unref?.()}}function uh(e){return new Promise(t=>{let n=!1,s=null,i=(r,o=!1)=>{n||(n=!0,s&&(clearTimeout(s),s=null),o&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(r))};e.on("exit",(r,o)=>{n||(s=setTimeout(()=>{i({code:r,signal:o},!0)},Mg()),s.unref?.())}),e.on("close",(r,o)=>{i({code:r,signal:o})})})}function mh(e,t,n,s){return Qd(e,{cwd:process.cwd(),env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,s]})}async function Bd(e){let t=await Ts(e,"r");try{let n=(await t.stat()).size,s=Math.min(n,Yt),i=Buffer.alloc(s);return s>0&&await t.read(i,0,s,0),{text:i.toString("utf8"),truncated:n>Yt}}finally{await t.close()}}async function _h(e,t,n,s,i){let r=Date.now(),o=await Zd(G.join(tl(),"pm-linked-test-output-"));try{let a=G.join(o,"stdout.log"),c=G.join(o,"stderr.log"),[d,l]=await Promise.all([Ts(a,"w"),Ts(c,"w")]),u;try{u=mh(e,n,d.fd,l.fd)}finally{await Promise.all([d.close(),l.close()])}oh(u);let m={heartbeat:ah(s,i),forceKillTimer:null,timedOutTimer:null},_=lh(u,m),p=!1,f;u.on("error",q=>{f=q.message}),m.timedOutTimer=setTimeout(()=>{p=!0,_()},t),m.timedOutTimer.unref?.();let{code:y,signal:b}=await uh(u);dh(m);let[v,C]=await Promise.all([Bd(a),Bd(c)]),S=v.truncated||C.truncated,w=S?`
12
12
  [pm linked-test output truncated at ${Yt} bytes per stream; the child process continued to completion]
13
- `:"",A={stdout:`${v.text}${w}`,stderr:E.text,exitCode:y,signal:b,timedOut:p,maxBufferExceeded:!1,outputTruncated:S,spawnError:f};return oh(s,A,r,i),A}finally{await Qd(o,{recursive:!0,force:!0})}}function mh(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Yt} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let s=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,i=e.spawnError?.trim()||s||"Linked test command failed.";return n.length===0?i:`${i} ${n.join(" ")}`}function _h(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
14
- `);return Eg.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>Ig.test(n)&&Ag.test(n))}function ph(e){return _h(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function fh(){return{infra_collision:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function Qt(e){let t=fh();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function qd(e,t){for(let[n,s]of Object.entries(t.env_set))bn.has(n.toUpperCase())||(e[n]=s);for(let n of t.env_clear)bn.has(n.toUpperCase())||delete e[n]}function gh(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 hh(e,t){let n={...e.env_set,...t.env_set},s=[...new Set([...e.env_clear,...t.env_clear??[]])],i=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:s,shared_host_safe:i}}function yh(e,t,n){return{env_set:Gg(e,"--env-set"),env_clear:qg(t,"--env-clear"),shared_host_safe:n===!0}}async function Fe(e,t,n=!1){if(await x(e)){await kg(G.dirname(t),{recursive:!0});try{if(n){await Dd(e,t,{recursive:!0,force:!0});return}await Dd(e,t,{force:!0})}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")return;throw s}}}async function Bd(e,t,n){await Fe(O(n.projectPmRoot),O(e)),await Fe(G.join(n.projectPmRoot,"extensions"),G.join(e,"extensions"),!0),await Fe(O(n.globalPmRoot),O(t)),await Fe(G.join(n.globalPmRoot,"extensions"),G.join(t,"extensions"),!0)}async function Wd(e,t){if(!await x(e))return;let n=await xs(e,{withFileTypes:!0});for(let s of n){if(Sg.has(s.name))continue;let i=G.join(e,s.name),r=G.join(t,s.name);if(s.isDirectory()){await Fe(i,r,!0);continue}s.isFile()&&await Fe(i,r)}}async function De(e){if(!await x(e))return 0;let t=0,n=await xs(e,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||Cg.has(s.name))continue;let i=G.join(e,s.name),r;try{r=await xs(i,{withFileTypes:!0})}catch{continue}for(let o of r)o.isFile()&&ge.some(a=>o.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function bh(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function wh(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let s of n){if(s.startsWith("[")&&s.endsWith("]")){let i=Number.parseInt(s.slice(1,-1),10);if(!Number.isInteger(i)||i<0)return[];t.push(i);continue}t.push(s)}return t}function zd(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let s=wh(n);if(s.length===0)return{found:!1,value:void 0};let i=e;for(let r of s){if(typeof r=="number"){if(!Array.isArray(i)||r>=i.length)return{found:!1,value:void 0};i=i[r];continue}if(typeof i!="object"||i===null||!Object.prototype.hasOwnProperty.call(i,r))return{found:!1,value:void 0};i=i[r]}return{found:!0,value:i}}function kh(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 vh(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?cn(e,t):Object.is(e,t)}function Th(e,t,n){let s=[];s.push(...Hd("stdout",t,e.assert_stdout_contains)),s.push(...Vd("stdout",t,e.assert_stdout_regex)),s.push(...Hd("stderr",n,e.assert_stderr_contains)),s.push(...Vd("stderr",n,e.assert_stderr_regex)),s.push(...xh(t,e.assert_stdout_min_lines));let i=e.assert_json_field_equals??{},r=e.assert_json_field_gte??{};if(!(Object.keys(i).length>0||Object.keys(r).length>0))return s;let a;try{a=JSON.parse(t)}catch(c){return s.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),s}for(let[c,d]of Object.entries(i)){let l=zd(a,c);if(!l.found){s.push(`assert_json_field_equals missing path "${c}"`);continue}let u=kh(d);vh(l.value,u)||s.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(u)} actual=${JSON.stringify(l.value)})`)}for(let[c,d]of Object.entries(r)){let l=zd(a,c);if(!l.found){s.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof l.value!="number"||!Number.isFinite(l.value)){s.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}l.value<d&&s.push(`assert_json_field_gte failed at "${c}" (expected >= ${d}, actual ${l.value})`)}return s}function Hd(e,t,n){let s=[];for(let i of n??[])t.includes(i)||s.push(`${e} missing required text: "${i}"`);return s}function Vd(e,t,n){let s=[];for(let i of n??[])try{new RegExp(i,"m").test(t)||s.push(`${e} failed regex assertion: /${i}/m`)}catch(r){s.push(`${e} regex assertion is invalid: /${i}/ (${r instanceof Error?r.message:String(r)})`)}return s}function xh(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var Sh=[{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 Ch(e,t){let n=`${e}
15
- ${t}`;for(let s of Sh)if(s.regex.test(n))return s.code;return null}function Eh(e){return{root:e,schemaProjectPmPath:G.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:G.join(e,"schema","global"),trackerProjectPmPath:G.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:G.join(e,"tracker","global")}}async function Ih(e,t=zo){let n={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},n),await t(void 0,{path:e.schemaGlobalPmPath},n),await t(void 0,{path:e.trackerProjectPmPath},n),await t(void 0,{path:e.trackerGlobalPmPath},n)}async function Ah(e,t){t&&(await Bd(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),await Bd(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Wd(t.projectPmRoot,e.trackerProjectPmPath),await Wd(t.globalPmRoot,e.trackerGlobalPmPath))}async function Rh(e,t){return{sourceProjectItemCount:t?await De(t.projectPmRoot):0,sourceGlobalItemCount:t?await De(t.globalPmRoot):0,schemaProjectItemCount:await De(e.schemaProjectPmPath),schemaGlobalItemCount:await De(e.schemaGlobalPmPath),trackerProjectItemCount:await De(e.trackerProjectPmPath),trackerGlobalItemCount:await De(e.trackerGlobalPmPath)}}function Oh(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,s=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,i=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,r=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:s,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:i,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:r,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==i||e.counts.sourceGlobalItemCount!==r),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots}}function Nh(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Xt(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,s=n?Bg(n):!1,i=s&&n?Wg(n):!1,r=e.options?.autoPmContext===!0&&i,o=r?"auto":Fg(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=jg(o,i);return{linkedOverridePmContextMode:t,executionContext:Oh({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:s,isPmTrackerReadCommand:i,requestedPmContextMode:o,effectivePmContextMode:a,autoPmContextApplied:r})}}function Kd(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Cs(e,t,n,s){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...s?{stdout:s.stdout,stderr:s.stderr}:{},error:n}}function Lh(e){if(!e.linkedTest.command)return Kd(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=Qg(e.linkedTest.command);if(t)return Kd(e.linkedTest,e.executionContext,t);let n=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,s=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(n||s){let i=Ug({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),r=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Cs(e.linkedTest,e.executionContext,`${r} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${i}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!$g(e.linkedTest)?Cs(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function Ph(e){let t=hh(e.runtimeDirectives,e.linkedTest),n={...process.env};return qd(n,e.runtimeDirectives),qd(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&gh(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,n.PM_SOURCE_WORKSPACE_ROOT=process.env.PM_SOURCE_WORKSPACE_ROOT??process.cwd(),n.PM_SOURCE_PM_PATH=e.executionContext.source_project_pm_path,n}function Mh(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 Dh(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 Fh(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:bh(e.execution),failure_category:ph(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:mh(e.execution,e.timeoutMs)}}function jh(e){if(e.options?.failOnEmptyTestRun===!0){let n=Ch(e.execution.stdout,e.execution.stderr);if(n)return Dh({...e,emptyRunSignal:n})}let t=Th(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Cs(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):Mh(e.linkedTest,e.executionContext,e.execution)}async function $h(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,s=await uh(t,n,Ph(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode);return s.exitCode===0&&!s.timedOut&&!s.maxBufferExceeded?jh({...e,execution:s}):Fh({...e,execution:s,timeoutMs:n})}async function As(e,t,n){let s=[],i=await Jd(G.join(Zd(),"pm-linked-test-")),r=Eh(i),o=Xt(n?.pmContext),a=n?.progress===!0?"always":"auto",c=yh(n?.envSet,n?.envClear,n?.sharedHostSafe),d=n?.sourceRoots;try{await Ih(r),await Ah(r,d);let l=await Rh(r,d);for(let u=0;u<e.length;u+=1){let m=e[u],_=Nh({linkedTest:m,layout:r,counts:l,sourceRoots:d,runLevelPmContextMode:o,options:n}),p=Lh({linkedTest:m,executionContext:_.executionContext,runLevelPmContextMode:o,linkedOverridePmContextMode:_.linkedOverridePmContextMode,options:n});if(p){s.push(p);continue}s.push(await $h({linkedTest:m,index:u,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:c,progressMode:a,executionContext:_.executionContext,options:n}))}}finally{await Qd(r.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return s}async function Uh(e){let{id:t,pmRoot:n,settings:s,typeToFolder:i}=e,r=await Ni(n,t,s.id_prefix,s.item_format,i);if(!r)throw new h(`Item ${t} not found`,g.NOT_FOUND);let o=await Li(r,{schema:s.schema});return{itemId:r.id,tests:o.document.metadata.tests??[],testRuns:o.document.metadata.test_runs??[],changed:!1}}function Gh(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode}function qh(e,t){let n=[...e];for(let s of t)n.some(i=>Gh(i,s))||n.push(s);return n}function Bh(e,t){return t.length===0?e:e.filter(n=>!t.includes(n.path??"")&&!t.includes(n.command??""))}function Wh(e,t,n){return Bh(qh(e,t),n)}function zh(e){return(e.envSet?.length??0)>0||(e.envClear?.length??0)>0||e.sharedHostSafe===!0||e.pmContext!==void 0||e.overrideLinkedPmContext===!0||e.failOnContextMismatch===!0||e.failOnSkipped===!0||e.failOnEmptyTestRun===!0||e.requireAssertionsForPm===!0||e.checkContext===!0||e.autoPmContext===!0}function Hh(e){if(zh(e)&&e.run!==!0)throw new h("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",g.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new h("--match, --only-index, and --only-last require --run",g.USAGE)}async function Vh(e){let{id:t,options:n,pmRoot:s,settings:i,typeToFolder:r,adds:o,removes:a}=e;if(o.length===0&&a.length===0)return Uh({id:t,pmRoot:s,settings:i,typeToFolder:r});let c=await ye({pmRoot:s,settings:i,id:t,op:"tests_add",author:ee(n.author,i.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(d){let l=d.metadata.tests??[],u=Wh(l,o,a);return d.metadata.tests=u,{changedFields:cn(l,u)?[]:["tests"]}}});return{itemId:c.item.id,tests:c.item.tests??[],testRuns:c.item.test_runs??[],changed:c.changedFields.length>0}}function Kh(e,t){Hh(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:ks(e.onlyIndex),onlyLast:e.onlyLast},s=e.run===!0?Md(t,n):void 0,i=e.timeout===void 0?void 0:Be(e.timeout,"timeout");if(i!==void 0&&i<=0)throw new h("Test timeout must be a positive number",g.USAGE);return{defaultTimeoutSeconds:i,pmContextMode:Xt(e.pmContext),runSelection:s,testsToRun:s?.selected??t}}async function Yh(e){let{options:t,runOptions:n,pmRoot:s}=e;return t.run!==!0?[]:await As(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,sourceRoots:{projectPmRoot:s,globalPmRoot:Q(process.cwd())}})}function Xh(e,t,n){let s=[];if(t&&t.selector!==null&&s.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 i=Is(n);s.push(`context_preflight:checked_pm_commands=${i.checked_pm_commands};tracker_read_commands=${i.tracker_read_commands};mismatches=${i.mismatches};auto_remediated=${i.auto_remediated}`)}return s}function Jh(e){let t=Mg(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),s=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),i=k(),r=bs(e.options.measure,i);return{run_id:Pg("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:i,recorded_at:i,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:s&&s.length>0?s:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:r.length>0?r:void 0}}async function Qh(e){let{options:t,pmRoot:n,settings:s,itemId:i,runStartedAt:r,runResults:o,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!r)return;let d=Jh({options:t,runStartedAt:r,runResults:o,failOnSkippedTriggered:a});if(s.testing.record_results_to_items!==!0)return d;try{return await Vt({pmRoot:n,settings:s,itemId:i,author:ee(t.author,s.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),d}catch(l){return c.push(`test_result_tracking_failed:${i}:${l instanceof Error?l.message:String(l)}`),d}}function Yd(e,t,n){let s;if(e.metricBelow!==void 0){let i=e.metricBelow.indexOf("="),r=e.metricBelow.slice(0,i).trim(),o=e.metricBelow.slice(i+1).trim(),a=Number(o);if(i<=0||r.length===0||o.length===0||!Number.isFinite(a))throw new h("--metric-below must use name=value",g.USAGE);s=Rd(t,r,a)}return{measurements:n?.measurements,metric_below:s,metric_diff:e.metricDiff===void 0?void 0:Od(t,e.metricDiff)}}async function ol(e,t,n){let s=Ei(),i=R(process.cwd(),n.path);if(!await x(O(i)))throw new h(`Tracker is not initialized at ${i}. Run pm init first.`,g.NOT_FOUND);let r=await N(i);if((t.measure?.length??0)>0&&t.run!==!0)throw new h("--measure requires --run",g.USAGE);bs(t.measure,"validation"),Yd(t,[],void 0);let o=V(r,W()),a=await s.resolveList(t.add,"--add"),c=await s.resolveList(t.addJson,"--add-json"),d=await s.resolveList(t.remove,"--remove"),l=[...Zg(a),...nh(c)],u=sh(d),m=await Vh({id:e,options:t,pmRoot:i,settings:r,typeToFolder:o.type_to_folder,adds:l,removes:u}),_=Kh(t,m.tests),p=t.run===!0?k():void 0,f=await Yh({options:t,runOptions:_,pmRoot:i}),y=Qt(f),b=t.run===!0&&t.failOnSkipped===!0&&f.some(A=>A.status==="skipped"),v=Xh(t,_.runSelection,f),E=await Qh({options:t,pmRoot:i,settings:r,itemId:m.itemId,runStartedAt:p,runResults:f,failOnSkippedTriggered:b,warnings:v}),S=E?ws([...m.testRuns,E]):m.testRuns,w=Yd(t,S,E);return{ok:f.every(A=>A.status!=="failed")&&b!==!0,id:m.itemId,tests:m.tests,run_results:f,failure_categories:y,selection:_.runSelection?{selector:_.runSelection.selector,requested:_.runSelection.requested,selected_indexes:_.runSelection.selected_indexes,selected_count:_.runSelection.selected_count,skipped_count:_.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:b?!0:void 0,warnings:v.length>0?v:void 0,changed:m.changed,count:m.tests.length,...w}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7fea0ecb-35e2-5d40-931f-ffdd1a465fdc")}catch{}})();var Zh=(e,t)=>{if(e===void 0)return;let n=ft(e,t);if(!n){let s=t.definitions.map(i=>i.id);throw new h(`Invalid --status value "${e}". Allowed: ${s.join(", ")}`,g.USAGE)}return n},ey=e=>{if(e===void 0)return;let t=Be(e,"timeout");if(t<=0)throw new h("timeout must be a positive number",g.USAGE);return t},al=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new h(`${t} must be a non-negative integer`,g.USAGE);return n},ty=e=>e instanceof Error?e.message:String(e),ny=()=>{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)}`},sy=e=>e.trim().replaceAll(/\s+/g," "),iy=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),ry=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),oy=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},Zt=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),cl=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),ay=e=>typeof e=="number"?e:void 0,cy=e=>{let t={assert_stdout_contains:Zt(e.assert_stdout_contains),assert_stdout_regex:Zt(e.assert_stdout_regex),assert_stderr_contains:Zt(e.assert_stderr_contains),assert_stderr_regex:Zt(e.assert_stderr_regex),assert_stdout_min_lines:ay(e.assert_stdout_min_lines),assert_json_field_equals:cl(e.assert_json_field_equals),assert_json_field_gte:cl(e.assert_json_field_gte)};return JSON.stringify(t)},dy=e=>{let t=Rs(e.command);return t!==void 0?`command:${e.scope}:${sy(t)}`:`path:${e.scope}:${Rs(e.path)??""}`},dl=e=>{let t=iy(e.env_set),n=ry(e.env_clear),s=oy(e.pm_context_mode),i=e.shared_host_safe===!0?"true":"false",r=cy(e);return`${dy(e)}:${t}:${n}:${s}:${i}:${r}`},ly=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,uy=e=>{let t=0,n=0,s=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"){n+=1;continue}s+=1}return{passed:t,failed:n,skipped:s}},my=(e,t)=>{for(let[n,s]of Object.entries(t))e[n]+=s},en=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
16
- `)}catch{}},_y=async(e,t,n)=>{let s=[],i=0;for(let r of e){let o=await ol(r.id,{run:!1},{...t,path:n});i+=o.tests.length,s.push({item:r,tests:o.tests})}return{itemTests:s,linkedTests:i}},py=async e=>{let t=Z(e.settings.schema),n=V(e.settings,W()),s=Zh(e.options.status,t),i=al(e.options.limit,"--limit"),r=al(e.options.offset,"--offset")??0,a=(await bt(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>s?d.status===s:!0).sort((d,l)=>d.id.localeCompare(l.id));return{filteredItems:i===void 0?a.slice(r):a.slice(r,r+i),statusFilter:s,limitFilter:i,offsetFilter:r}},fy=e=>{let t=new Map;for(let{tests:n}of e)for(let s of n){let i=dl(s);if(!t.has(i)){t.set(i,s.timeout_seconds);continue}t.set(i,ly(t.get(i),s.timeout_seconds))}return t},gy=async(e,t)=>{let n=[],s=e.tests.map(l=>{let u=dl(l),m=t.seenTestKeys.has(u);if(!m){t.seenTestKeys.add(u);let _=t.effectiveTimeoutByKey.get(u);n.push(_===void 0?l:{...l,timeout_seconds:_})}return{test:l,key:u,duplicate:m}}),i=n.length>0?await As(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}):[],r=0,o=s.map(({test:l,key:u,duplicate:m})=>{if(!m){let _=i[r];return r+=1,_}return{command:l.command,path:l.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),a=uy(o),c=Qt(o),d=await by(e,a,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:d,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:o,failure_categories:c}}},hy=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),yy=e=>e?!0:void 0,by=async(e,t,n)=>{if(!n.trackingEnabled)return[];try{let s=hy(t,n.options);await Vt({pmRoot:n.pmRoot,settings:n.settings,itemId:e.item.id,author:n.trackingAuthor,message:`Track test-all run summary (${n.trackingRunId})`,entry:{run_id:n.trackingRunId,kind:"test-all",status:s?"failed":"passed",started_at:n.runStartedAt,finished_at:k(),recorded_at:k(),attempt:n.trackingAttempt,resumed_from:n.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:yy(n.options.failOnSkipped===!0&&t.skipped>0)}})}catch(s){return[`test_result_tracking_failed:${e.item.id}:${ty(s)}`]}return[]},wy=()=>{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},Rs=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},ky=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:Q(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:fy(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:ee(e.options.author,e.settings.author_default),trackingRunId:ny(),trackingAttempt:wy(),trackingResumedFrom:Rs(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),vy=(e,t,n)=>{let s={results:[],passed:0,failed:0,skipped:0,failureCategories:Qt([]),trackingWarnings:[]},i=e.failOnEmptyTestRun===!0&&t===0;return i&&(s.failed+=1,s.failureCategories.empty_run+=1,s.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:s,failOnEmptyTestRunTriggered:i}},Ty=async(e,t,n)=>{for(let[s,i]of e.entries()){en(t.options,`item ${s+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let r=await gy(i,t);my(n.failureCategories,r.failureCategories),n.passed+=r.passed,n.failed+=r.failed,n.skipped+=r.skipped,n.trackingWarnings.push(...r.trackingWarnings),n.results.push(r.result),en(t.options,`item ${s+1}/${e.length} end id=${i.item.id} status=${r.failed===0?"passed":"failed"} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`)}},xy=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(i=>i.run_results),s=Is(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${s.checked_pm_commands};tracker_read_commands=${s.tracker_read_commands};mismatches=${s.mismatches};auto_remediated=${s.auto_remediated}`)},Sy=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}),Cy=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(" "),Ey=async(e,t)=>{let n=R(process.cwd(),t.path);if(!await x(O(n)))throw new h(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let s=await N(n),i=await py({pmRoot:n,settings:s,options:e}),r=ey(e.timeout),o=k(),a=await _y(i.filteredItems,t,n);return en(e,Cy({...i,linkedTests:a.linkedTests})),{pmRoot:n,settings:s,filteredItems:i.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:r,runStartedAt:o}},Iy=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}},Ax=async(e,t)=>{let n=await Ey(e,t),{accumulation:s,failOnEmptyTestRunTriggered:i}=vy(e,n.linkedTests,n.filteredItems),r=ky({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await Ty(n.itemTests,r,s),xy(e,s);let o=Iy({options:e,accumulation:s,failOnEmptyTestRunTriggered:i});return en(e,`end status=${o.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`),Sy({ok:o.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:s,failOnSkippedTriggered:o.failOnSkippedTriggered,failOnEmptyTestRunTriggered: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]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function Nx(e){return ci("in_progress",e)??e.open_status}import ib from"node:os";import je from"node:fs/promises";import{spawn as pl}from"node:child_process";import{createHash as Ay,randomBytes as Ry}from"node:crypto";import ot from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0224a672-e326-5555-a4b4-1fa3550d9e61")}catch{}})();var fl=new Set(["queued","running"]),Ps=new Set(["passed","failed","stopped","canceled"]),Oy=3e3,Ny=3e3,Ly=3e4,gl=100,ll=100;function hl(){return Date.now()}function yl(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function Py(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function My(){let e=Date.now().toString(36),t=Ry(3).toString("hex");return`tr-${e}-${t}`}function Dy(e,t,n){let s={kind:e,command:yl(t),pm_root:ot.resolve(n)};return Ay("sha256").update(JSON.stringify(s)).digest("hex")}function $e(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function Fy(e){await de(ei(e)),await de(sn(e)),await de(ti(e)),await de(ni(e)),await de(ri(e))}async function bl(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new h(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,g.GENERIC_FAILURE)}}async function ne(e,t){let n={...t,updated_at:k()};await se(rn(e,t.id),`${JSON.stringify(n,null,2)}
17
- `)}async function Ue(e,t){let n=rn(e,t),s=await $(n);return s?bl(s,n):null}async function jy(e){let t=sn(e);return await x(t)?(await je.readdir(t,{withFileTypes:!0})).filter(s=>s.isFile()&&s.name.endsWith(".json")).map(s=>ot.join(t,s.name)).sort((s,i)=>i.localeCompare(s)):[]}function $y(e){let t=e.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(t)return Number.parseInt(t[1],10)*1024}async function Uy(e){if(process.platform==="linux")try{let t=await je.readFile(`/proc/${e}/status`,"utf8");return $y(t)}catch{return}}function Gy(e){let t=e.lastIndexOf(")");if(t<0)return{};let s=e.slice(t+2).trim().split(/\s+/),i=Number.parseInt(s[11],10),r=Number.parseInt(s[12],10);return!Number.isFinite(i)||!Number.isFinite(r)?{}:{cpu_user_seconds:i/ll,cpu_system_seconds:r/ll}}async function qy(e){if(process.platform!=="linux")return{};try{let t=await je.readFile(`/proc/${e}/stat`,"utf8");return Gy(t)}catch{return{}}}async function Ns(e){let t=e.child_pid??e.worker_pid;if(!$e(t))return;let n=await Uy(t),s=await qy(t),i=e.started_at?Date.parse(e.started_at):Number.NaN,r=Number.isFinite(i)?Math.max(0,(hl()-i)/1e3):void 0;return{recorded_at:k(),rss_bytes:n,cpu_user_seconds:s.cpu_user_seconds,cpu_system_seconds:s.cpu_system_seconds,uptime_seconds:r}}function Os(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function By(e,t){if(!t||typeof t!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};let n=t;if(e==="test-all"){let a=n.totals??{};return{summary:{items:typeof a.items=="number"?a.items:void 0,linked_tests:typeof a.linked_tests=="number"?a.linked_tests:void 0,passed:Os(a.passed),failed:Os(a.failed),skipped:Os(a.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}let s=Array.isArray(n.run_results)?n.run_results:[],i=0,r=0,o=0;for(let a of s){if(!a||typeof a!="object")continue;let c=a.status;if(c==="passed"){i+=1;continue}if(c==="failed"){r+=1;continue}o+=1}return{summary:{passed:i,failed:r,skipped:o,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}function Wy(e){let t=e.trim();if(t.length===0)return null;let n=t.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){let d=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:d,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:k(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}let s=t.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!s)return null;let i=Number.parseInt(s[1],10),r=Number.parseInt(s[2],10),o=s[4]?Number.parseInt(s[4],10):void 0,a=t.match(/\scommand="((?:\\.|[^"\\])*)"/),c=a?a[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:i,linked_test_total:r,current_command:c,elapsed_ms:Number.isFinite(o)?o:void 0,heartbeat_at:k(),phase:s[3]?.toLowerCase()==="end"?"finished":"running"}}function zy(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.length>0)}function Ls(e,t){if(t<=0)return[];let n=zy(e);return n.length<=t?n:n.slice(n.length-t)}async function wl(e){let t=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(t&&t.length>0){let i=ot.resolve(e,t);if(await x(i))return i}let n=ot.resolve(e,"dist","cli.js");if(await x(n))return n;let s=process.argv[1]?.trim();if(s&&s.length>0){let i=ot.resolve(e,s);if(await x(i))return i}throw new h("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",g.GENERIC_FAILURE)}async function at(e,t){if(!fl.has(t.status)||$e(t.worker_pid)||t.finished_at)return t;let s={...t,status:"failed",finished_at:k(),error:t.error??"Background test run worker exited before writing terminal status."};return await ne(e,s),s}async function Ms(e){await Fy(e.pmRoot);let t=yl(e.commandArgs);if(t.length===0)throw new h("Background test run requires command arguments.",g.USAGE);let n=Dy(e.kind,t,e.pmRoot),s=await Fs(e.pmRoot,{});for(let l of s){let u=await at(e.pmRoot,l);if(u.fingerprint===n&&!(!fl.has(u.status)||!$e(u.worker_pid)))return{started:!1,run:{...u,duplicate_of:u.id},duplicate_of:u.id}}let i=My(),r=k(),o=si(e.pmRoot,i),a=ii(e.pmRoot,i),c=oi(e.pmRoot,i);await je.writeFile(o,"","utf8"),await je.writeFile(a,"","utf8");let d={id:i,kind:e.kind,status:"queued",created_at:r,updated_at:r,requested_by:e.requestedBy,fingerprint:n,command_args:t,command_label:Py(t),pm_root:e.pmRoot,global_pm_root:e.globalPmRoot,target_id:e.targetId,status_filter:e.statusFilter,attempt:typeof e.attempt=="number"&&Number.isFinite(e.attempt)&&e.attempt>=1?Math.floor(e.attempt):1,resumed_from:e.resumedFrom,resumed_by:e.resumedBy,stdout_path:o,stderr_path:a,result_path:c,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:r}};return await ne(e.pmRoot,d),{started:!0,run:d}}async function Ds(e){let t=await Ue(e.pmRoot,e.runId);if(!t)throw new h(`Background test run ${e.runId} not found`,g.NOT_FOUND);if(Ps.has(t.status))throw new h(`Background test run ${t.id} is already terminal (${t.status}).`,g.CONFLICT);let n=await wl(process.cwd()),s=[];e.noExtensions===!0&&s.push("--no-extensions"),s.push("--path",t.pm_root,"test-runs-worker",t.id);let i={...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:t.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(t.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:t.resumed_from??"",FORCE_COLOR:"0"},r=pl(process.execPath,[n,...s],{cwd:process.cwd(),env:i,detached:!0,stdio:"ignore",windowsHide:!0});r.unref();let o={...t,status:"queued",worker_pid:r.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:k()}};return await ne(e.pmRoot,o),o}async function ul(e,t,n){await e,await je.appendFile(t,n,"utf8")}function kl(e,t){let n=Number.parseInt(process.env[e]??"",10);return Number.isFinite(n)&&n>0?n:t}function Hy(e){return{...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,FORCE_COLOR:"0"}}function Vy(e,t){return t?["--no-extensions",...e.command_args]:[...e.command_args]}function Ky(e,t){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await ne(e,t)}catch{}})},async flush(){await n}}}function ml(e,t){try{e.kill(t)}catch{}}async function Yy(e,t,n,s){if(n.stopRequested)return;n.stopRequested=!0,e.stop_requested_at=k(),e.progress={...e.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:k()},s(),ml(t,"SIGTERM"),setTimeout(()=>ml(t,"SIGKILL"),kl("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",Ny)).unref?.()}function Xy(e,t,n){return{phase:n,message:e,heartbeat_at:k(),item_index:t.item_index,item_total:t.item_total,item_id:t.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function Jy(e,t,n,s){return{phase:s,message:e,heartbeat_at:k(),item_index:n.item_index??t.progress?.item_index,item_total:n.item_total??t.progress?.item_total,item_id:n.item_id??t.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function _l(e,t,n){let s=Wy(t);if(!s)return!1;let i=e.progress?.phase==="stopping"?"stopping":"running";return e.progress=s.item_id?Xy(t,s,i):Jy(t,e,s,i),s.phase==="finished"&&!n&&(e.progress.phase="running"),!0}function Qy(e){if(e.trim().length===0)return null;try{return JSON.parse(e)}catch{return null}}function Zy(e,t){return t?"stopped":e.exit_code===0&&(e.summary?.failed??0)===0&&e.summary?.fail_on_skipped_triggered!==!0?"passed":"failed"}function eb(e,t){return{phase:"finished",message:t?"Background run stopped.":`Background run finished with status=${e.status}.`,heartbeat_at:k(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function tb(e,t,n){if(t!==null){await se(e.result_path,`${JSON.stringify(t,null,2)}
18
- `);return}await se(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:Ls(n,gl)},null,2)}
19
- `)}async function vl(e,t,n=!1){let s=await Ue(e,t);if(!s)throw new h(`Background test run ${t} not found`,g.NOT_FOUND);let i={...s,status:"running",started_at:s.started_at??k(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:k()}},r=await wl(process.cwd()),o=Hy(i);await ne(e,i);let a=Vy(i,n),c=pl(process.execPath,[r,...a],{cwd:process.cwd(),env:o,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});i.child_pid=c.pid;let d=Ky(e,i),l=d.schedule,u=Promise.resolve(),m=Promise.resolve(),_="",p="",f={stopRequested:!1},y=()=>{Yy(i,c,f,l)};process.on("SIGTERM",y),process.on("SIGINT",y);let b=setInterval(()=>{(async()=>(i.resource=await Ns(i),i.progress.heartbeat_at=k(),l()))()},kl("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",Oy));b.unref?.(),c.stdout?.on("data",q=>{let D=q.toString("utf8");_+=D,u=ul(u,i.stdout_path,D)}),c.stderr?.on("data",q=>{let D=q.toString("utf8");m=ul(m,i.stderr_path,D),p+=D;let j=p.split(/\r?\n/);p=j.pop();let Y=!1;for(let ce of j){let T=ce.trimEnd();T.length>0&&_l(i,T,f.stopRequested)&&(Y=!0)}Y&&l()});let v=null,E=null;try{({code:v,signal:E}=await new Promise(q=>{c.on("close",(D,j)=>{q({code:D,signal:j})})}))}finally{clearInterval(b),process.off("SIGTERM",y),process.off("SIGINT",y)}await u,await m;let S=p.trimEnd();S.length>0&&_l(i,S,f.stopRequested)&&l(),p="";let w=Qy(_),A=By(i.kind,w);return i.summary=A.summary,i.exit_code=typeof v=="number"?v:void 0,i.signal=E??void 0,i.finished_at=k(),i.status=Zy(i,f.stopRequested),i.progress=eb(i,f.stopRequested),i.resource=await Ns(i),await tb(i,w,_),await ne(e,i),await d.flush(),i}async function Fs(e,t){let n=await jy(e),s=[];for(let c of n){let d=await $(c);if(!d)continue;let l=await bl(d,c);s.push(l)}let i=[];for(let c of s)i.push(await at(e,c));let o=(t.status?i.filter(c=>c.status===t.status):i).sort((c,d)=>{let l=Date.parse(d.updated_at)-Date.parse(c.updated_at);return Number.isFinite(l)&&l!==0?l:d.id.localeCompare(c.id)}),a=typeof t.limit=="number"&&t.limit>=0?t.limit:void 0;return a===void 0?o:o.slice(0,a)}async function Tl(e,t){let n=await Ue(e,t);if(!n)throw new h(`Background test run ${t} not found`,g.NOT_FOUND);let s=await at(e,n),i=$e(s.worker_pid),r=$e(s.child_pid);s.status==="running"&&!r&&!s.finished_at&&!i&&(s.status="failed",s.finished_at=k(),s.error=s.error??"Background run process exited unexpectedly.",await ne(e,s)),s.status==="running"&&(s.resource=await Ns(s),await ne(e,s));let o=s.progress?.heartbeat_at,a=o?Date.parse(o):Number.NaN,c=Number.isFinite(a)?Math.max(0,hl()-a):void 0,d=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(d)&&d>0?d:Ly,u=s.status==="running"?c!==void 0&&c>l?"stale":"healthy":"inactive";return{run:s,health:{state:u,last_heartbeat_at:o,heartbeat_lag_ms:c,worker_alive:i,child_alive:r}}}function nb(e,t){let n=t?"SIGKILL":"SIGTERM";if(!$e(e.worker_pid)||!e.worker_pid)return"none";try{return process.kill(e.worker_pid,n),n}catch{return"none"}}function sb(e,t){return{phase:"stopping",message:t==="none"?"Run marked stopped.":`Stop requested via ${t}.`,heartbeat_at:k(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function xl(e,t,n=!1){let s=await Ue(e,t);if(!s)throw new h(`Background test run ${t} not found`,g.NOT_FOUND);let i=await at(e,s);if(Ps.has(i.status))return{run:i,signal_sent:"none"};let r=nb(i,n);return r==="none"&&(i.status="stopped",i.finished_at=i.finished_at??k()),i.stop_requested_at=k(),i.progress=sb(i,r),await ne(e,i),{run:i,signal_sent:r}}async function Sl(e,t,n,s=!1){let i=await Ue(e,t);if(!i)throw new h(`Background test run ${t} not found`,g.NOT_FOUND);let r=await at(e,i);if(!Ps.has(r.status))throw new h(`Background test run ${t} is not terminal and cannot be resumed.`,g.CONFLICT);let o=await Ms({pmRoot:r.pm_root,globalPmRoot:r.global_pm_root,kind:r.kind,commandArgs:r.command_args,requestedBy:n,targetId:r.target_id,statusFilter:r.status_filter,resumedFrom:r.id,resumedBy:n,attempt:r.attempt+1});if(!o.started)return o.run;let a=await Ds({pmRoot:e,runId:o.run.id,noExtensions:s}),c={...r,resumed_by:a.id};return await ne(e,c),a}async function Cl(e,t,n,s){let i=await Ue(e,t);if(!i)throw new h(`Background test run ${t} not found`,g.NOT_FOUND);let r=typeof s=="number"&&Number.isFinite(s)&&s>=0?Math.floor(s):gl,o=n==="stdout"||n==="both"?await $(i.stdout_path)??"":"",a=n==="stderr"||n==="both"?await $(i.stderr_path)??"":"";return{run:i,stream:n,tail:r,stdout:n==="stdout"||n==="both"?Ls(o,r):[],stderr:n==="stderr"||n==="both"?Ls(a,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]="8f02f498-5cee-59fa-9f4e-fd882c58d401")}catch{}})();var rb=["queued","running","passed","failed","stopped","canceled"],ob=["stdout","stderr","both"];function ab(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(rb.includes(t))return t;throw new h(`Invalid --status value "${e}"`,g.USAGE)}function cb(e){if(e===void 0||e.trim().length===0)return"stderr";let t=e.trim().toLowerCase();if(ob.includes(t))return t;throw new h(`Invalid --stream value "${e}"`,g.USAGE)}function db(){try{let e=ib.userInfo().username.trim();if(e.length>0)return e}catch{}}function El(e,t){let n=[e,mi(),t,process.env.USER,process.env.LOGNAME,process.env.USERNAME,db()];for(let s of n){if(typeof s!="string")continue;let i=s.trim();if(i.length>0)return i}return"unknown"}async function xe(e){if(!await x(O(e)))throw new h(`Tracker is not initialized at ${e}. Run pm init first.`,g.NOT_FOUND)}async function Zx(e,t){let n=R(process.cwd(),t.path),s=Q(process.cwd());await xe(n);let i=await N(n),r=El(e.author,i.author_default),o=await Ms({pmRoot:n,globalPmRoot:s,kind:e.kind,commandArgs:e.commandArgs,requestedBy:r,targetId:e.targetId,statusFilter:e.statusFilter});return o.started?{started:!0,run:await Ds({pmRoot:n,runId:o.run.id,noExtensions:e.noExtensions===!0})}:{started:!1,duplicate_of:o.duplicate_of,run:o.run}}async function eS(e,t){let n=R(process.cwd(),t.path);await xe(n);let s=ab(e.status),i=mn(e.limit,"limit"),r=await Fs(n,{status:s,limit:i});return{runs:r,count:r.length,filters:{status:s,limit:i}}}async function tS(e,t){let n=R(process.cwd(),t.path);await xe(n);let s=await Tl(n,e);return{run:s.run,health:s.health}}async function nS(e,t,n){let s=R(process.cwd(),n.path);await xe(s);let i=cb(t.stream),r=mn(t.tail,"tail"),o=await Cl(s,e,i,r);return{run:o.run,stream:o.stream,tail:o.tail,stdout:o.stdout,stderr:o.stderr}}async function sS(e,t,n){let s=R(process.cwd(),n.path);await xe(s);let i=await xl(s,e,t.force===!0);return{run:i.run,signal_sent:i.signal_sent}}async function iS(e,t,n){let s=R(process.cwd(),n.path);await xe(s);let i=await N(s),r=El(t.author,i.author_default),o=await Sl(s,e,r,t.noExtensions===!0);return{resumed_from:e,run:o}}async function rS(e,t){let n=R(process.cwd(),t.path);await xe(n);let s=await vl(n,e,t.noExtensions===!0);return{id:s.id,status:s.status,exit_code:s.exit_code}}export{Ho as a,Rl as b,bb as c,wb as d,Yo as e,Bb as f,Yl as g,na as h,Yb as i,Ve as j,Xb as k,ow as l,aw as m,Ye as n,cw as o,dw as p,ek as q,tk as r,va as s,Vn as t,a_ as u,sv as v,iv as w,av as x,cv as y,dv as z,Fc as A,Z_ as B,us as C,ep as D,tp as E,np as F,wv as G,kv as H,dp as I,zc as J,ms as K,Vc as L,_p as M,pp as N,Sv as O,Cv as P,Ev as Q,Iv as R,fp as S,Yc as T,Rv as U,Xc as V,hp as W,st as X,vp as Y,Qc as Z,Sp as _,Mv as $,Qv as aa,hT as ba,kT as ca,kd as da,NT as ea,fg as fa,bs as ga,Rd as ha,Od as ia,Is as ja,ph as ka,Qt as la,bh as ma,As as na,ol as oa,Ax as pa,Nx as qa,Zx as ra,eS as sa,tS as ta,nS as ua,sS as va,iS as wa,rS as xa};
20
- //# sourceMappingURL=chunk-WRL4KNDL.js.map
13
+ `:"",A={stdout:`${v.text}${w}`,stderr:C.text,exitCode:y,signal:b,timedOut:p,maxBufferExceeded:!1,outputTruncated:S,spawnError:f};return ch(s,A,r,i),A}finally{await el(o,{recursive:!0,force:!0})}}function ph(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Yt} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let s=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,i=e.spawnError?.trim()||s||"Linked test command failed.";return n.length===0?i:`${i} ${n.join(" ")}`}function fh(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
14
+ `);return Ag.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>Rg.test(n)&&Og.test(n))}function gh(e){return fh(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function hh(){return{infra_collision:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function Qt(e){let t=hh();for(let n of e)n.status!=="failed"||!n.failure_category||(t[n.failure_category]+=1);return t}function Wd(e,t){for(let[n,s]of Object.entries(t.env_set))bn.has(n.toUpperCase())||(e[n]=s);for(let n of t.env_clear)bn.has(n.toUpperCase())||delete e[n]}function yh(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 bh(e,t){let n={...e.env_set,...t.env_set},s=[...new Set([...e.env_clear,...t.env_clear??[]])],i=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:s,shared_host_safe:i}}function wh(e,t,n){return{env_set:Bg(e,"--env-set"),env_clear:Wg(t,"--env-clear"),shared_host_safe:n===!0}}async function Fe(e,t,n=!1){if(await x(e)){await Tg(G.dirname(t),{recursive:!0});try{if(n){await jd(e,t,{recursive:!0,force:!0});return}await jd(e,t,{force:!0})}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")return;throw s}}}async function zd(e,t,n){await Fe(O(n.projectPmRoot),O(e)),await Fe(G.join(n.projectPmRoot,"extensions"),G.join(e,"extensions"),!0),await Fe(O(n.globalPmRoot),O(t)),await Fe(G.join(n.globalPmRoot,"extensions"),G.join(t,"extensions"),!0)}async function Hd(e,t){if(!await x(e))return;let n=await xs(e,{withFileTypes:!0});for(let s of n){if(Cg.has(s.name))continue;let i=G.join(e,s.name),r=G.join(t,s.name);if(s.isDirectory()){await Fe(i,r,!0);continue}s.isFile()&&await Fe(i,r)}}async function De(e){if(!await x(e))return 0;let t=0,n=await xs(e,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||Ig.has(s.name))continue;let i=G.join(e,s.name),r;try{r=await xs(i,{withFileTypes:!0})}catch{continue}for(let o of r)o.isFile()&&ge.some(a=>o.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function kh(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function vh(e){let t=[],n=e.match(/[^.[\]]+|\[\d+\]/g)??[];for(let s of n){if(s.startsWith("[")&&s.endsWith("]")){let i=Number.parseInt(s.slice(1,-1),10);if(!Number.isInteger(i)||i<0)return[];t.push(i);continue}t.push(s)}return t}function Vd(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let s=vh(n);if(s.length===0)return{found:!1,value:void 0};let i=e;for(let r of s){if(typeof r=="number"){if(!Array.isArray(i)||r>=i.length)return{found:!1,value:void 0};i=i[r];continue}if(typeof i!="object"||i===null||!Object.prototype.hasOwnProperty.call(i,r))return{found:!1,value:void 0};i=i[r]}return{found:!0,value:i}}function Th(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 xh(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?cn(e,t):Object.is(e,t)}function Sh(e,t,n){let s=[];s.push(...Kd("stdout",t,e.assert_stdout_contains)),s.push(...Yd("stdout",t,e.assert_stdout_regex)),s.push(...Kd("stderr",n,e.assert_stderr_contains)),s.push(...Yd("stderr",n,e.assert_stderr_regex)),s.push(...Eh(t,e.assert_stdout_min_lines));let i=e.assert_json_field_equals??{},r=e.assert_json_field_gte??{};if(!(Object.keys(i).length>0||Object.keys(r).length>0))return s;let a;try{a=JSON.parse(t)}catch(c){return s.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),s}for(let[c,d]of Object.entries(i)){let l=Vd(a,c);if(!l.found){s.push(`assert_json_field_equals missing path "${c}"`);continue}let u=Th(d);xh(l.value,u)||s.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(u)} actual=${JSON.stringify(l.value)})`)}for(let[c,d]of Object.entries(r)){let l=Vd(a,c);if(!l.found){s.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof l.value!="number"||!Number.isFinite(l.value)){s.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}l.value<d&&s.push(`assert_json_field_gte failed at "${c}" (expected >= ${d}, actual ${l.value})`)}return s}function Kd(e,t,n){let s=[];for(let i of n??[])t.includes(i)||s.push(`${e} missing required text: "${i}"`);return s}function Yd(e,t,n){let s=[];for(let i of n??[])try{new RegExp(i,"m").test(t)||s.push(`${e} failed regex assertion: /${i}/m`)}catch(r){s.push(`${e} regex assertion is invalid: /${i}/ (${r instanceof Error?r.message:String(r)})`)}return s}function Eh(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}var Ch=[{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 Ih(e,t){let n=`${e}
15
+ ${t}`;for(let s of Ch)if(s.regex.test(n))return s.code;return null}function Ah(e){return{root:e,schemaProjectPmPath:G.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:G.join(e,"schema","global"),trackerProjectPmPath:G.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:G.join(e,"tracker","global")}}async function Rh(e,t=Vo){let n={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},n),await t(void 0,{path:e.schemaGlobalPmPath},n),await t(void 0,{path:e.trackerProjectPmPath},n),await t(void 0,{path:e.trackerGlobalPmPath},n)}async function Oh(e,t){t&&(await zd(e.schemaProjectPmPath,e.schemaGlobalPmPath,t),await zd(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Hd(t.projectPmRoot,e.trackerProjectPmPath),await Hd(t.globalPmRoot,e.trackerGlobalPmPath))}async function Nh(e,t){return{sourceProjectItemCount:t?await De(t.projectPmRoot):0,sourceGlobalItemCount:t?await De(t.globalPmRoot):0,schemaProjectItemCount:await De(e.schemaProjectPmPath),schemaGlobalItemCount:await De(e.schemaGlobalPmPath),trackerProjectItemCount:await De(e.trackerProjectPmPath),trackerGlobalItemCount:await De(e.trackerGlobalPmPath)}}function Lh(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,s=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,i=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,r=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:s,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:i,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:r,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==i||e.counts.sourceGlobalItemCount!==r),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots}}function Ph(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Xt(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,s=n?zg(n):!1,i=s&&n?Hg(n):!1,r=e.options?.autoPmContext===!0&&i,o=r?"auto":$g(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=Ug(o,i);return{linkedOverridePmContextMode:t,executionContext:Lh({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:s,isPmTrackerReadCommand:i,requestedPmContextMode:o,effectivePmContextMode:a,autoPmContextApplied:r})}}function Xd(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Es(e,t,n,s){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...s?{stdout:s.stdout,stderr:s.stderr}:{},error:n}}function Mh(e){if(!e.linkedTest.command)return Xd(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=eh(e.linkedTest.command);if(t)return Xd(e.linkedTest,e.executionContext,t);let n=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,s=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(n||s){let i=qg({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),r=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return Es(e.linkedTest,e.executionContext,`${r} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${i}`)}return e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!Gg(e.linkedTest)?Es(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null}function Dh(e){let t=bh(e.runtimeDirectives,e.linkedTest),n={...process.env};return Wd(n,e.runtimeDirectives),Wd(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&yh(n),n.FORCE_COLOR="0",n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,n.PM_SOURCE_WORKSPACE_ROOT=process.env.PM_SOURCE_WORKSPACE_ROOT??process.cwd(),n.PM_SOURCE_PM_PATH=e.executionContext.source_project_pm_path,n}function Fh(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 jh(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 $h(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:kh(e.execution),failure_category:gh(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:ph(e.execution,e.timeoutMs)}}function Uh(e){if(e.options?.failOnEmptyTestRun===!0){let n=Ih(e.execution.stdout,e.execution.stderr);if(n)return jh({...e,emptyRunSignal:n})}let t=Sh(e.linkedTest,e.execution.stdout,e.execution.stderr);return t.length>0?Es(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${t.join("; ")}`,e.execution):Fh(e.linkedTest,e.executionContext,e.execution)}async function Gh(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,s=await _h(t,n,Dh(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode);return s.exitCode===0&&!s.timedOut&&!s.maxBufferExceeded?Uh({...e,execution:s}):$h({...e,execution:s,timeoutMs:n})}async function As(e,t,n){let s=[],i=await Zd(G.join(tl(),"pm-linked-test-")),r=Ah(i),o=Xt(n?.pmContext),a=n?.progress===!0?"always":"auto",c=wh(n?.envSet,n?.envClear,n?.sharedHostSafe),d=n?.sourceRoots;try{await Rh(r),await Oh(r,d);let l=await Nh(r,d);for(let u=0;u<e.length;u+=1){let m=e[u],_=Ph({linkedTest:m,layout:r,counts:l,sourceRoots:d,runLevelPmContextMode:o,options:n}),p=Mh({linkedTest:m,executionContext:_.executionContext,runLevelPmContextMode:o,linkedOverridePmContextMode:_.linkedOverridePmContextMode,options:n});if(p){s.push(p);continue}s.push(await Gh({linkedTest:m,index:u,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:c,progressMode:a,executionContext:_.executionContext,options:n}))}}finally{await el(r.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return s}async function qh(e){let{id:t,pmRoot:n,settings:s,typeToFolder:i}=e,r=await Ni(n,t,s.id_prefix,s.item_format,i);if(!r)throw new h(`Item ${t} not found`,g.NOT_FOUND);let o=await Li(r,{schema:s.schema});return{itemId:r.id,tests:o.document.metadata.tests??[],testRuns:o.document.metadata.test_runs??[],changed:!1}}function Bh(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode}function Wh(e,t){let n=[...e];for(let s of t)n.some(i=>Bh(i,s))||n.push(s);return n}function zh(e,t){return t.length===0?e:e.filter(n=>!t.includes(n.path??"")&&!t.includes(n.command??""))}function Hh(e,t,n){return zh(Wh(e,t),n)}function Vh(e){return(e.envSet?.length??0)>0||(e.envClear?.length??0)>0||e.sharedHostSafe===!0||e.pmContext!==void 0||e.overrideLinkedPmContext===!0||e.failOnContextMismatch===!0||e.failOnSkipped===!0||e.failOnEmptyTestRun===!0||e.requireAssertionsForPm===!0||e.checkContext===!0||e.autoPmContext===!0}function Kh(e){if(Vh(e)&&e.run!==!0)throw new h("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",g.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new h("--match, --only-index, and --only-last require --run",g.USAGE)}async function Yh(e){let{id:t,options:n,pmRoot:s,settings:i,typeToFolder:r,adds:o,removes:a}=e;if(o.length===0&&a.length===0)return qh({id:t,pmRoot:s,settings:i,typeToFolder:r});let c=await ye({pmRoot:s,settings:i,id:t,op:"tests_add",author:ee(n.author,i.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(d){let l=d.metadata.tests??[],u=Hh(l,o,a);return d.metadata.tests=u,{changedFields:cn(l,u)?[]:["tests"]}}});return{itemId:c.item.id,tests:c.item.tests??[],testRuns:c.item.test_runs??[],changed:c.changedFields.length>0}}function Xh(e,t){Kh(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:ks(e.onlyIndex),onlyLast:e.onlyLast},s=e.run===!0?Fd(t,n):void 0,i=e.timeout===void 0?void 0:Be(e.timeout,"timeout");if(i!==void 0&&i<=0)throw new h("Test timeout must be a positive number",g.USAGE);return{defaultTimeoutSeconds:i,pmContextMode:Xt(e.pmContext),runSelection:s,testsToRun:s?.selected??t}}async function Jh(e){let{options:t,runOptions:n,pmRoot:s}=e;return t.run!==!0?[]:await As(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,sourceRoots:{projectPmRoot:s,globalPmRoot:Q(process.cwd())}})}function Qh(e,t,n){let s=[];if(t&&t.selector!==null&&s.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 i=Is(n);s.push(`context_preflight:checked_pm_commands=${i.checked_pm_commands};tracker_read_commands=${i.tracker_read_commands};mismatches=${i.mismatches};auto_remediated=${i.auto_remediated}`)}return s}function Zh(e){let t=Fg(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),s=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),i=k(),r=bs(e.options.measure,i);return{run_id:Dg("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:i,recorded_at:i,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:s&&s.length>0?s:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:r.length>0?r:void 0}}async function ey(e){let{options:t,pmRoot:n,settings:s,itemId:i,runStartedAt:r,runResults:o,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!r)return;let d=Zh({options:t,runStartedAt:r,runResults:o,failOnSkippedTriggered:a});if(s.testing.record_results_to_items!==!0)return d;try{return await Vt({pmRoot:n,settings:s,itemId:i,author:ee(t.author,s.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),d}catch(l){return c.push(`test_result_tracking_failed:${i}:${l instanceof Error?l.message:String(l)}`),d}}function Jd(e,t,n){let s;if(e.metricBelow!==void 0){let i=e.metricBelow.indexOf("="),r=e.metricBelow.slice(0,i).trim(),o=e.metricBelow.slice(i+1).trim(),a=Number(o);if(i<=0||r.length===0||o.length===0||!Number.isFinite(a))throw new h("--metric-below must use name=value",g.USAGE);s=Nd(t,r,a)}return{measurements:n?.measurements,metric_below:s,metric_diff:e.metricDiff===void 0?void 0:Ld(t,e.metricDiff)}}async function cl(e,t,n){let s=Ci(),i=R(process.cwd(),n.path);if(!await x(O(i)))throw new h(`Tracker is not initialized at ${i}. Run pm init first.`,g.NOT_FOUND);let r=await N(i);if((t.measure?.length??0)>0&&t.run!==!0)throw new h("--measure requires --run",g.USAGE);bs(t.measure,"validation"),Jd(t,[],void 0);let o=V(r,W()),a=await s.resolveList(t.add,"--add"),c=await s.resolveList(t.addJson,"--add-json"),d=await s.resolveList(t.remove,"--remove"),l=[...th(a),...ih(c)],u=rh(d),m=await Yh({id:e,options:t,pmRoot:i,settings:r,typeToFolder:o.type_to_folder,adds:l,removes:u}),_=Xh(t,m.tests),p=t.run===!0?k():void 0,f=await Jh({options:t,runOptions:_,pmRoot:i}),y=Qt(f),b=t.run===!0&&t.failOnSkipped===!0&&f.some(A=>A.status==="skipped"),v=Qh(t,_.runSelection,f),C=await ey({options:t,pmRoot:i,settings:r,itemId:m.itemId,runStartedAt:p,runResults:f,failOnSkippedTriggered:b,warnings:v}),S=C?ws([...m.testRuns,C]):m.testRuns,w=Jd(t,S,C);return{ok:f.every(A=>A.status!=="failed")&&b!==!0,id:m.itemId,tests:m.tests,run_results:f,failure_categories:y,selection:_.runSelection?{selector:_.runSelection.selector,requested:_.runSelection.requested,selected_indexes:_.runSelection.selected_indexes,selected_count:_.runSelection.selected_count,skipped_count:_.runSelection.skipped_count}:void 0,fail_on_skipped_triggered:b?!0:void 0,warnings:v.length>0?v:void 0,changed:m.changed,count:m.tests.length,...w}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7fea0ecb-35e2-5d40-931f-ffdd1a465fdc")}catch{}})();var ty=(e,t)=>{if(e===void 0)return;let n=ft(e,t);if(!n){let s=t.definitions.map(i=>i.id);throw new h(`Invalid --status value "${e}". Allowed: ${s.join(", ")}`,g.USAGE)}return n},ny=e=>{if(e===void 0)return;let t=Be(e,"timeout");if(t<=0)throw new h("timeout must be a positive number",g.USAGE);return t},dl=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new h(`${t} must be a non-negative integer`,g.USAGE);return n},sy=e=>e instanceof Error?e.message:String(e),iy=()=>{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)}`},ry=e=>e.trim().replaceAll(/\s+/g," "),oy=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),ay=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),cy=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},Zt=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),ll=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),dy=e=>typeof e=="number"?e:void 0,ly=e=>{let t={assert_stdout_contains:Zt(e.assert_stdout_contains),assert_stdout_regex:Zt(e.assert_stdout_regex),assert_stderr_contains:Zt(e.assert_stderr_contains),assert_stderr_regex:Zt(e.assert_stderr_regex),assert_stdout_min_lines:dy(e.assert_stdout_min_lines),assert_json_field_equals:ll(e.assert_json_field_equals),assert_json_field_gte:ll(e.assert_json_field_gte)};return JSON.stringify(t)},uy=e=>{let t=Rs(e.command);return t!==void 0?`command:${e.scope}:${ry(t)}`:`path:${e.scope}:${Rs(e.path)??""}`},ul=e=>{let t=oy(e.env_set),n=ay(e.env_clear),s=cy(e.pm_context_mode),i=e.shared_host_safe===!0?"true":"false",r=ly(e);return`${uy(e)}:${t}:${n}:${s}:${i}:${r}`},my=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,_y=e=>{let t=0,n=0,s=0;for(let i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"){n+=1;continue}s+=1}return{passed:t,failed:n,skipped:s}},py=(e,t)=>{for(let[n,s]of Object.entries(t))e[n]+=s},en=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
16
+ `)}catch{}},fy=async(e,t,n)=>{let s=[],i=0;for(let r of e){let o=await cl(r.id,{run:!1},{...t,path:n});i+=o.tests.length,s.push({item:r,tests:o.tests})}return{itemTests:s,linkedTests:i}},gy=async e=>{let t=Z(e.settings.schema),n=V(e.settings,W()),s=ty(e.options.status,t),i=dl(e.options.limit,"--limit"),r=dl(e.options.offset,"--offset")??0,a=(await bt(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(d=>s?d.status===s:!0).sort((d,l)=>d.id.localeCompare(l.id));return{filteredItems:i===void 0?a.slice(r):a.slice(r,r+i),statusFilter:s,limitFilter:i,offsetFilter:r}},hy=e=>{let t=new Map;for(let{tests:n}of e)for(let s of n){let i=ul(s);if(!t.has(i)){t.set(i,s.timeout_seconds);continue}t.set(i,my(t.get(i),s.timeout_seconds))}return t},yy=async(e,t)=>{let n=[],s=e.tests.map(l=>{let u=ul(l),m=t.seenTestKeys.has(u);if(!m){t.seenTestKeys.add(u);let _=t.effectiveTimeoutByKey.get(u);n.push(_===void 0?l:{...l,timeout_seconds:_})}return{test:l,key:u,duplicate:m}}),i=n.length>0?await As(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}):[],r=0,o=s.map(({test:l,key:u,duplicate:m})=>{if(!m){let _=i[r];return r+=1,_}return{command:l.command,path:l.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),a=_y(o),c=Qt(o),d=await ky(e,a,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:d,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:o,failure_categories:c}}},by=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),wy=e=>e?!0:void 0,ky=async(e,t,n)=>{if(!n.trackingEnabled)return[];try{let s=by(t,n.options);await Vt({pmRoot:n.pmRoot,settings:n.settings,itemId:e.item.id,author:n.trackingAuthor,message:`Track test-all run summary (${n.trackingRunId})`,entry:{run_id:n.trackingRunId,kind:"test-all",status:s?"failed":"passed",started_at:n.runStartedAt,finished_at:k(),recorded_at:k(),attempt:n.trackingAttempt,resumed_from:n.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:wy(n.options.failOnSkipped===!0&&t.skipped>0)}})}catch(s){return[`test_result_tracking_failed:${e.item.id}:${sy(s)}`]}return[]},vy=()=>{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},Rs=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},Ty=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:Q(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:hy(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:ee(e.options.author,e.settings.author_default),trackingRunId:iy(),trackingAttempt:vy(),trackingResumedFrom:Rs(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),xy=(e,t,n)=>{let s={results:[],passed:0,failed:0,skipped:0,failureCategories:Qt([]),trackingWarnings:[]},i=e.failOnEmptyTestRun===!0&&t===0;return i&&(s.failed+=1,s.failureCategories.empty_run+=1,s.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:s,failOnEmptyTestRunTriggered:i}},Sy=async(e,t,n)=>{for(let[s,i]of e.entries()){en(t.options,`item ${s+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let r=await yy(i,t);py(n.failureCategories,r.failureCategories),n.passed+=r.passed,n.failed+=r.failed,n.skipped+=r.skipped,n.trackingWarnings.push(...r.trackingWarnings),n.results.push(r.result),en(t.options,`item ${s+1}/${e.length} end id=${i.item.id} status=${r.failed===0?"passed":"failed"} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`)}},Ey=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(i=>i.run_results),s=Is(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${s.checked_pm_commands};tracker_read_commands=${s.tracker_read_commands};mismatches=${s.mismatches};auto_remediated=${s.auto_remediated}`)},Cy=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}),Iy=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(" "),Ay=async(e,t)=>{let n=R(process.cwd(),t.path);if(!await x(O(n)))throw new h(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let s=await N(n),i=await gy({pmRoot:n,settings:s,options:e}),r=ny(e.timeout),o=k(),a=await fy(i.filteredItems,t,n);return en(e,Iy({...i,linkedTests:a.linkedTests})),{pmRoot:n,settings:s,filteredItems:i.filteredItems,itemTests:a.itemTests,linkedTests:a.linkedTests,defaultTimeoutSeconds:r,runStartedAt:o}},Ry=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}},Nx=async(e,t)=>{let n=await Ay(e,t),{accumulation:s,failOnEmptyTestRunTriggered:i}=xy(e,n.linkedTests,n.filteredItems),r=Ty({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await Sy(n.itemTests,r,s),Ey(e,s);let o=Ry({options:e,accumulation:s,failOnEmptyTestRunTriggered:i});return en(e,`end status=${o.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`),Cy({ok:o.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:s,failOnSkippedTriggered:o.failOnSkippedTriggered,failOnEmptyTestRunTriggered: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]="d1930c5a-6849-5f78-8090-a436f61711ae")}catch{}})();function Mx(e){return ci("in_progress",e)??e.open_status}import ob from"node:os";import je from"node:fs/promises";import{spawn as gl}from"node:child_process";import{createHash as Oy,randomBytes as Ny}from"node:crypto";import ot from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0224a672-e326-5555-a4b4-1fa3550d9e61")}catch{}})();var hl=new Set(["queued","running"]),Ps=new Set(["passed","failed","stopped","canceled"]),Ly=3e3,Py=3e3,My=3e4,yl=100,ml=100;function bl(){return Date.now()}function wl(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function Dy(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function Fy(){let e=Date.now().toString(36),t=Ny(3).toString("hex");return`tr-${e}-${t}`}function jy(e,t,n){let s={kind:e,command:wl(t),pm_root:ot.resolve(n)};return Oy("sha256").update(JSON.stringify(s)).digest("hex")}function $e(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function $y(e){await de(ei(e)),await de(sn(e)),await de(ti(e)),await de(ni(e)),await de(ri(e))}async function kl(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new h(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,g.GENERIC_FAILURE)}}async function ne(e,t){let n={...t,updated_at:k()};await se(rn(e,t.id),`${JSON.stringify(n,null,2)}
17
+ `)}async function Ue(e,t){let n=rn(e,t),s=await $(n);return s?kl(s,n):null}async function Uy(e){let t=sn(e);return await x(t)?(await je.readdir(t,{withFileTypes:!0})).filter(s=>s.isFile()&&s.name.endsWith(".json")).map(s=>ot.join(t,s.name)).sort((s,i)=>i.localeCompare(s)):[]}function Gy(e){let t=e.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(t)return Number.parseInt(t[1],10)*1024}async function qy(e){if(process.platform==="linux")try{let t=await je.readFile(`/proc/${e}/status`,"utf8");return Gy(t)}catch{return}}function By(e){let t=e.lastIndexOf(")");if(t<0)return{};let s=e.slice(t+2).trim().split(/\s+/),i=Number.parseInt(s[11],10),r=Number.parseInt(s[12],10);return!Number.isFinite(i)||!Number.isFinite(r)?{}:{cpu_user_seconds:i/ml,cpu_system_seconds:r/ml}}async function Wy(e){if(process.platform!=="linux")return{};try{let t=await je.readFile(`/proc/${e}/stat`,"utf8");return By(t)}catch{return{}}}async function Ns(e){let t=e.child_pid??e.worker_pid;if(!$e(t))return;let n=await qy(t),s=await Wy(t),i=e.started_at?Date.parse(e.started_at):Number.NaN,r=Number.isFinite(i)?Math.max(0,(bl()-i)/1e3):void 0;return{recorded_at:k(),rss_bytes:n,cpu_user_seconds:s.cpu_user_seconds,cpu_system_seconds:s.cpu_system_seconds,uptime_seconds:r}}function Os(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function zy(e,t){if(!t||typeof t!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};let n=t;if(e==="test-all"){let a=n.totals??{};return{summary:{items:typeof a.items=="number"?a.items:void 0,linked_tests:typeof a.linked_tests=="number"?a.linked_tests:void 0,passed:Os(a.passed),failed:Os(a.failed),skipped:Os(a.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}let s=Array.isArray(n.run_results)?n.run_results:[],i=0,r=0,o=0;for(let a of s){if(!a||typeof a!="object")continue;let c=a.status;if(c==="passed"){i+=1;continue}if(c==="failed"){r+=1;continue}o+=1}return{summary:{passed:i,failed:r,skipped:o,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}function Hy(e){let t=e.trim();if(t.length===0)return null;let n=t.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){let d=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:d,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:k(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}let s=t.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!s)return null;let i=Number.parseInt(s[1],10),r=Number.parseInt(s[2],10),o=s[4]?Number.parseInt(s[4],10):void 0,a=t.match(/\scommand="((?:\\.|[^"\\])*)"/),c=a?a[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:i,linked_test_total:r,current_command:c,elapsed_ms:Number.isFinite(o)?o:void 0,heartbeat_at:k(),phase:s[3]?.toLowerCase()==="end"?"finished":"running"}}function Vy(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.length>0)}function Ls(e,t){if(t<=0)return[];let n=Vy(e);return n.length<=t?n:n.slice(n.length-t)}async function vl(e){let t=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(t&&t.length>0){let i=ot.resolve(e,t);if(await x(i))return i}let n=ot.resolve(e,"dist","cli.js");if(await x(n))return n;let s=process.argv[1]?.trim();if(s&&s.length>0){let i=ot.resolve(e,s);if(await x(i))return i}throw new h("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",g.GENERIC_FAILURE)}async function at(e,t){if(!hl.has(t.status)||$e(t.worker_pid)||t.finished_at)return t;let s={...t,status:"failed",finished_at:k(),error:t.error??"Background test run worker exited before writing terminal status."};return await ne(e,s),s}async function Ms(e){await $y(e.pmRoot);let t=wl(e.commandArgs);if(t.length===0)throw new h("Background test run requires command arguments.",g.USAGE);let n=jy(e.kind,t,e.pmRoot),s=await Fs(e.pmRoot,{});for(let l of s){let u=await at(e.pmRoot,l);if(u.fingerprint===n&&!(!hl.has(u.status)||!$e(u.worker_pid)))return{started:!1,run:{...u,duplicate_of:u.id},duplicate_of:u.id}}let i=Fy(),r=k(),o=si(e.pmRoot,i),a=ii(e.pmRoot,i),c=oi(e.pmRoot,i);await je.writeFile(o,"","utf8"),await je.writeFile(a,"","utf8");let d={id:i,kind:e.kind,status:"queued",created_at:r,updated_at:r,requested_by:e.requestedBy,fingerprint:n,command_args:t,command_label:Dy(t),pm_root:e.pmRoot,global_pm_root:e.globalPmRoot,target_id:e.targetId,status_filter:e.statusFilter,attempt:typeof e.attempt=="number"&&Number.isFinite(e.attempt)&&e.attempt>=1?Math.floor(e.attempt):1,resumed_from:e.resumedFrom,resumed_by:e.resumedBy,stdout_path:o,stderr_path:a,result_path:c,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:r}};return await ne(e.pmRoot,d),{started:!0,run:d}}async function Ds(e){let t=await Ue(e.pmRoot,e.runId);if(!t)throw new h(`Background test run ${e.runId} not found`,g.NOT_FOUND);if(Ps.has(t.status))throw new h(`Background test run ${t.id} is already terminal (${t.status}).`,g.CONFLICT);let n=await vl(process.cwd()),s=[];e.noExtensions===!0&&s.push("--no-extensions"),s.push("--path",t.pm_root,"test-runs-worker",t.id);let i={...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:t.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(t.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:t.resumed_from??"",FORCE_COLOR:"0"},r=gl(process.execPath,[n,...s],{cwd:process.cwd(),env:i,detached:!0,stdio:"ignore",windowsHide:!0});r.unref();let o={...t,status:"queued",worker_pid:r.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:k()}};return await ne(e.pmRoot,o),o}async function _l(e,t,n){await e,await je.appendFile(t,n,"utf8")}function Tl(e,t){let n=Number.parseInt(process.env[e]??"",10);return Number.isFinite(n)&&n>0?n:t}function Ky(e){return{...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,FORCE_COLOR:"0"}}function Yy(e,t){return t?["--no-extensions",...e.command_args]:[...e.command_args]}function Xy(e,t){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await ne(e,t)}catch{}})},async flush(){await n}}}function pl(e,t){try{e.kill(t)}catch{}}async function Jy(e,t,n,s){if(n.stopRequested)return;n.stopRequested=!0,e.stop_requested_at=k(),e.progress={...e.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:k()},s(),pl(t,"SIGTERM"),setTimeout(()=>pl(t,"SIGKILL"),Tl("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",Py)).unref?.()}function Qy(e,t,n){return{phase:n,message:e,heartbeat_at:k(),item_index:t.item_index,item_total:t.item_total,item_id:t.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function Zy(e,t,n,s){return{phase:s,message:e,heartbeat_at:k(),item_index:n.item_index??t.progress?.item_index,item_total:n.item_total??t.progress?.item_total,item_id:n.item_id??t.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function fl(e,t,n){let s=Hy(t);if(!s)return!1;let i=e.progress?.phase==="stopping"?"stopping":"running";return e.progress=s.item_id?Qy(t,s,i):Zy(t,e,s,i),s.phase==="finished"&&!n&&(e.progress.phase="running"),!0}function eb(e){if(e.trim().length===0)return null;try{return JSON.parse(e)}catch{return null}}function tb(e,t){return t?"stopped":e.exit_code===0&&(e.summary?.failed??0)===0&&e.summary?.fail_on_skipped_triggered!==!0?"passed":"failed"}function nb(e,t){return{phase:"finished",message:t?"Background run stopped.":`Background run finished with status=${e.status}.`,heartbeat_at:k(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function sb(e,t,n){if(t!==null){await se(e.result_path,`${JSON.stringify(t,null,2)}
18
+ `);return}await se(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:Ls(n,yl)},null,2)}
19
+ `)}async function xl(e,t,n=!1){let s=await Ue(e,t);if(!s)throw new h(`Background test run ${t} not found`,g.NOT_FOUND);let i={...s,status:"running",started_at:s.started_at??k(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:k()}},r=await vl(process.cwd()),o=Ky(i);await ne(e,i);let a=Yy(i,n),c=gl(process.execPath,[r,...a],{cwd:process.cwd(),env:o,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});i.child_pid=c.pid;let d=Xy(e,i),l=d.schedule,u=Promise.resolve(),m=Promise.resolve(),_="",p="",f={stopRequested:!1},y=()=>{Jy(i,c,f,l)};process.on("SIGTERM",y),process.on("SIGINT",y);let b=setInterval(()=>{(async()=>(i.resource=await Ns(i),i.progress.heartbeat_at=k(),l()))()},Tl("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",Ly));b.unref?.(),c.stdout?.on("data",q=>{let D=q.toString("utf8");_+=D,u=_l(u,i.stdout_path,D)}),c.stderr?.on("data",q=>{let D=q.toString("utf8");m=_l(m,i.stderr_path,D),p+=D;let j=p.split(/\r?\n/);p=j.pop();let Y=!1;for(let ce of j){let T=ce.trimEnd();T.length>0&&fl(i,T,f.stopRequested)&&(Y=!0)}Y&&l()});let v=null,C=null;try{({code:v,signal:C}=await new Promise(q=>{c.on("close",(D,j)=>{q({code:D,signal:j})})}))}finally{clearInterval(b),process.off("SIGTERM",y),process.off("SIGINT",y)}await u,await m;let S=p.trimEnd();S.length>0&&fl(i,S,f.stopRequested)&&l(),p="";let w=eb(_),A=zy(i.kind,w);return i.summary=A.summary,i.exit_code=typeof v=="number"?v:void 0,i.signal=C??void 0,i.finished_at=k(),i.status=tb(i,f.stopRequested),i.progress=nb(i,f.stopRequested),i.resource=await Ns(i),await sb(i,w,_),await ne(e,i),await d.flush(),i}async function Fs(e,t){let n=await Uy(e),s=[];for(let c of n){let d=await $(c);if(!d)continue;let l=await kl(d,c);s.push(l)}let i=[];for(let c of s)i.push(await at(e,c));let o=(t.status?i.filter(c=>c.status===t.status):i).sort((c,d)=>{let l=Date.parse(d.updated_at)-Date.parse(c.updated_at);return Number.isFinite(l)&&l!==0?l:d.id.localeCompare(c.id)}),a=typeof t.limit=="number"&&t.limit>=0?t.limit:void 0;return a===void 0?o:o.slice(0,a)}async function Sl(e,t){let n=await Ue(e,t);if(!n)throw new h(`Background test run ${t} not found`,g.NOT_FOUND);let s=await at(e,n),i=$e(s.worker_pid),r=$e(s.child_pid);s.status==="running"&&!r&&!s.finished_at&&!i&&(s.status="failed",s.finished_at=k(),s.error=s.error??"Background run process exited unexpectedly.",await ne(e,s)),s.status==="running"&&(s.resource=await Ns(s),await ne(e,s));let o=s.progress?.heartbeat_at,a=o?Date.parse(o):Number.NaN,c=Number.isFinite(a)?Math.max(0,bl()-a):void 0,d=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(d)&&d>0?d:My,u=s.status==="running"?c!==void 0&&c>l?"stale":"healthy":"inactive";return{run:s,health:{state:u,last_heartbeat_at:o,heartbeat_lag_ms:c,worker_alive:i,child_alive:r}}}function ib(e,t){let n=t?"SIGKILL":"SIGTERM";if(!$e(e.worker_pid)||!e.worker_pid)return"none";try{return process.kill(e.worker_pid,n),n}catch{return"none"}}function rb(e,t){return{phase:"stopping",message:t==="none"?"Run marked stopped.":`Stop requested via ${t}.`,heartbeat_at:k(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function El(e,t,n=!1){let s=await Ue(e,t);if(!s)throw new h(`Background test run ${t} not found`,g.NOT_FOUND);let i=await at(e,s);if(Ps.has(i.status))return{run:i,signal_sent:"none"};let r=ib(i,n);return r==="none"&&(i.status="stopped",i.finished_at=i.finished_at??k()),i.stop_requested_at=k(),i.progress=rb(i,r),await ne(e,i),{run:i,signal_sent:r}}async function Cl(e,t,n,s=!1){let i=await Ue(e,t);if(!i)throw new h(`Background test run ${t} not found`,g.NOT_FOUND);let r=await at(e,i);if(!Ps.has(r.status))throw new h(`Background test run ${t} is not terminal and cannot be resumed.`,g.CONFLICT);let o=await Ms({pmRoot:r.pm_root,globalPmRoot:r.global_pm_root,kind:r.kind,commandArgs:r.command_args,requestedBy:n,targetId:r.target_id,statusFilter:r.status_filter,resumedFrom:r.id,resumedBy:n,attempt:r.attempt+1});if(!o.started)return o.run;let a=await Ds({pmRoot:e,runId:o.run.id,noExtensions:s}),c={...r,resumed_by:a.id};return await ne(e,c),a}async function Il(e,t,n,s){let i=await Ue(e,t);if(!i)throw new h(`Background test run ${t} not found`,g.NOT_FOUND);let r=typeof s=="number"&&Number.isFinite(s)&&s>=0?Math.floor(s):yl,o=n==="stdout"||n==="both"?await $(i.stdout_path)??"":"",a=n==="stderr"||n==="both"?await $(i.stderr_path)??"":"";return{run:i,stream:n,tail:r,stdout:n==="stdout"||n==="both"?Ls(o,r):[],stderr:n==="stderr"||n==="both"?Ls(a,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]="8f02f498-5cee-59fa-9f4e-fd882c58d401")}catch{}})();var ab=["queued","running","passed","failed","stopped","canceled"],cb=["stdout","stderr","both"];function db(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(ab.includes(t))return t;throw new h(`Invalid --status value "${e}"`,g.USAGE)}function lb(e){if(e===void 0||e.trim().length===0)return"stderr";let t=e.trim().toLowerCase();if(cb.includes(t))return t;throw new h(`Invalid --stream value "${e}"`,g.USAGE)}function ub(){try{let e=ob.userInfo().username.trim();if(e.length>0)return e}catch{}}function Al(e,t){let n=[e,mi(),t,process.env.USER,process.env.LOGNAME,process.env.USERNAME,ub()];for(let s of n){if(typeof s!="string")continue;let i=s.trim();if(i.length>0)return i}return"unknown"}async function xe(e){if(!await x(O(e)))throw new h(`Tracker is not initialized at ${e}. Run pm init first.`,g.NOT_FOUND)}async function nS(e,t){let n=R(process.cwd(),t.path),s=Q(process.cwd());await xe(n);let i=await N(n),r=Al(e.author,i.author_default),o=await Ms({pmRoot:n,globalPmRoot:s,kind:e.kind,commandArgs:e.commandArgs,requestedBy:r,targetId:e.targetId,statusFilter:e.statusFilter});return o.started?{started:!0,run:await Ds({pmRoot:n,runId:o.run.id,noExtensions:e.noExtensions===!0})}:{started:!1,duplicate_of:o.duplicate_of,run:o.run}}async function sS(e,t){let n=R(process.cwd(),t.path);await xe(n);let s=db(e.status),i=mn(e.limit,"limit"),r=await Fs(n,{status:s,limit:i});return{runs:r,count:r.length,filters:{status:s,limit:i}}}async function iS(e,t){let n=R(process.cwd(),t.path);await xe(n);let s=await Sl(n,e);return{run:s.run,health:s.health}}async function rS(e,t,n){let s=R(process.cwd(),n.path);await xe(s);let i=lb(t.stream),r=mn(t.tail,"tail"),o=await Il(s,e,i,r);return{run:o.run,stream:o.stream,tail:o.tail,stdout:o.stdout,stderr:o.stderr}}async function oS(e,t,n){let s=R(process.cwd(),n.path);await xe(s);let i=await El(s,e,t.force===!0);return{run:i.run,signal_sent:i.signal_sent}}async function aS(e,t,n){let s=R(process.cwd(),n.path);await xe(s);let i=await N(s),r=Al(t.author,i.author_default),o=await Cl(s,e,r,t.noExtensions===!0);return{resumed_from:e,run:o}}async function cS(e,t){let n=R(process.cwd(),t.path);await xe(n);let s=await xl(n,e,t.noExtensions===!0);return{id:s.id,status:s.status,exit_code:s.exit_code}}export{Ko as a,Nl as b,kb as c,vb as d,Jo as e,zb as f,Jl as g,ia as h,Jb as i,Ve as j,Qb as k,cw as l,dw as m,Ye as n,lw as o,uw as p,sk as q,ik as r,xa as s,Vn as t,d_ as u,ov as v,av as w,lv as x,uv as y,mv as z,$c as A,tp as B,us as C,np as D,sp as E,ip as F,Tv as G,xv as H,up as I,Vc as J,ms as K,Yc as L,fp as M,gp as N,Iv as O,Av as P,Rv as Q,Ov as R,hp as S,Jc as T,Lv as U,Qc as V,bp as W,st as X,xp as Y,ed as Z,Cp as _,jv as $,tT as aa,wT as ba,xT as ca,Td as da,MT as ea,hg as fa,bs as ga,Nd as ha,Ld as ia,Is as ja,gh as ka,Qt as la,kh as ma,As as na,cl as oa,Nx as pa,Mx as qa,nS as ra,sS as sa,iS as ta,rS as ua,oS as va,aS as wa,cS as xa};
20
+ //# sourceMappingURL=chunk-V663653R.js.map